blob: 8fd3a701163efaf6939d4f667ea11390a3e50f3f [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregore8381c02008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000019#include "clang/AST/TypeOrdering.h"
Chris Lattner58258242008-04-10 02:22:51 +000020#include "clang/AST/StmtVisitor.h"
Anders Carlssond624e162009-08-26 23:45:07 +000021#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000022#include "clang/Lex/Preprocessor.h"
Daniel Dunbar34fb6722008-08-11 03:27:53 +000023#include "clang/Parse/DeclSpec.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Chris Lattner58258242008-04-10 02:22:51 +000025#include "llvm/Support/Compiler.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000026#include <algorithm> // for std::equal
Douglas Gregor29a92472008-10-22 17:49:05 +000027#include <map>
Chris Lattner199abbc2008-04-08 05:04:30 +000028
29using namespace clang;
30
Chris Lattner58258242008-04-10 02:22:51 +000031//===----------------------------------------------------------------------===//
32// CheckDefaultArgumentVisitor
33//===----------------------------------------------------------------------===//
34
Chris Lattnerb0d38442008-04-12 23:52:44 +000035namespace {
36 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
37 /// the default argument of a parameter to determine whether it
38 /// contains any ill-formed subexpressions. For example, this will
39 /// diagnose the use of local variables or parameters within the
40 /// default argument expression.
Mike Stump11289f42009-09-09 15:08:12 +000041 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000042 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000043 Expr *DefaultArg;
44 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000045
Chris Lattnerb0d38442008-04-12 23:52:44 +000046 public:
Mike Stump11289f42009-09-09 15:08:12 +000047 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000048 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000049
Chris Lattnerb0d38442008-04-12 23:52:44 +000050 bool VisitExpr(Expr *Node);
51 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000052 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000053 };
Chris Lattner58258242008-04-10 02:22:51 +000054
Chris Lattnerb0d38442008-04-12 23:52:44 +000055 /// VisitExpr - Visit all of the children of this expression.
56 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
57 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000058 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000059 E = Node->child_end(); I != E; ++I)
60 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000062 }
63
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 /// VisitDeclRefExpr - Visit a reference to a declaration, to
65 /// determine whether this declaration can be used in the default
66 /// argument expression.
67 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000068 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000069 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
70 // C++ [dcl.fct.default]p9
71 // Default arguments are evaluated each time the function is
72 // called. The order of evaluation of function arguments is
73 // unspecified. Consequently, parameters of a function shall not
74 // be used in default argument expressions, even if they are not
75 // evaluated. Parameters of a function declared before a default
76 // argument expression are in scope and can hide namespace and
77 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000078 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000079 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000080 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000081 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000082 // C++ [dcl.fct.default]p7
83 // Local variables shall not be used in default argument
84 // expressions.
Steve Naroff08899ff2008-04-15 22:42:06 +000085 if (VDecl->isBlockVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000088 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000089 }
Chris Lattner58258242008-04-10 02:22:51 +000090
Douglas Gregor8e12c382008-11-04 13:41:56 +000091 return false;
92 }
Chris Lattnerb0d38442008-04-12 23:52:44 +000093
Douglas Gregor97a9c812008-11-04 14:32:21 +000094 /// VisitCXXThisExpr - Visit a C++ "this" expression.
95 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
96 // C++ [dcl.fct.default]p8:
97 // The keyword this shall not be used in a default argument of a
98 // member function.
99 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000100 diag::err_param_default_argument_references_this)
101 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000102 }
Chris Lattner58258242008-04-10 02:22:51 +0000103}
104
Anders Carlssonc80a1272009-08-25 02:29:20 +0000105bool
106Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump11289f42009-09-09 15:08:12 +0000107 SourceLocation EqualLoc) {
Anders Carlssonc80a1272009-08-25 02:29:20 +0000108 QualType ParamType = Param->getType();
109
Anders Carlsson114056f2009-08-25 13:46:13 +0000110 if (RequireCompleteType(Param->getLocation(), Param->getType(),
111 diag::err_typecheck_decl_incomplete_type)) {
112 Param->setInvalidDecl();
113 return true;
114 }
115
Anders Carlssonc80a1272009-08-25 02:29:20 +0000116 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump11289f42009-09-09 15:08:12 +0000117
Anders Carlssonc80a1272009-08-25 02:29:20 +0000118 // C++ [dcl.fct.default]p5
119 // A default argument expression is implicitly converted (clause
120 // 4) to the parameter type. The default argument expression has
121 // the same semantic constraints as the initializer expression in
122 // a declaration of a variable of the parameter type, using the
123 // copy-initialization semantics (8.5).
Mike Stump11289f42009-09-09 15:08:12 +0000124 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssonc80a1272009-08-25 02:29:20 +0000125 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000126 return true;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000127
128 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump11289f42009-09-09 15:08:12 +0000129
Anders Carlssonc80a1272009-08-25 02:29:20 +0000130 // Okay: add the default argument to the parameter
131 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000132
Anders Carlssonc80a1272009-08-25 02:29:20 +0000133 DefaultArg.release();
Mike Stump11289f42009-09-09 15:08:12 +0000134
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000135 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000136}
137
Chris Lattner58258242008-04-10 02:22:51 +0000138/// ActOnParamDefaultArgument - Check whether the default argument
139/// provided for a function parameter is well-formed. If so, attach it
140/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000141void
Mike Stump11289f42009-09-09 15:08:12 +0000142Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000143 ExprArg defarg) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000144 if (!param || !defarg.get())
145 return;
Mike Stump11289f42009-09-09 15:08:12 +0000146
Chris Lattner83f095c2009-03-28 19:18:32 +0000147 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson84613c42009-06-12 16:51:40 +0000148 UnparsedDefaultArgLocs.erase(Param);
149
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000150 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner199abbc2008-04-08 05:04:30 +0000151 QualType ParamType = Param->getType();
152
153 // Default arguments are only permitted in C++
154 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000155 Diag(EqualLoc, diag::err_param_default_argument)
156 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000157 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000158 return;
159 }
160
Anders Carlssonf1c26952009-08-25 01:02:06 +0000161 // Check that the default argument is well-formed
162 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
163 if (DefaultArgChecker.Visit(DefaultArg.get())) {
164 Param->setInvalidDecl();
165 return;
166 }
Mike Stump11289f42009-09-09 15:08:12 +0000167
Anders Carlssonc80a1272009-08-25 02:29:20 +0000168 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000169}
170
Douglas Gregor58354032008-12-24 00:01:03 +0000171/// ActOnParamUnparsedDefaultArgument - We've seen a default
172/// argument for a function parameter, but we can't parse it yet
173/// because we're inside a class definition. Note that this default
174/// argument will be parsed later.
Mike Stump11289f42009-09-09 15:08:12 +0000175void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000176 SourceLocation EqualLoc,
177 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000178 if (!param)
179 return;
Mike Stump11289f42009-09-09 15:08:12 +0000180
Chris Lattner83f095c2009-03-28 19:18:32 +0000181 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000182 if (Param)
183 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000184
Anders Carlsson84613c42009-06-12 16:51:40 +0000185 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000186}
187
Douglas Gregor4d87df52008-12-16 21:30:33 +0000188/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
189/// the default argument for the parameter param failed.
Chris Lattner83f095c2009-03-28 19:18:32 +0000190void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000191 if (!param)
192 return;
Mike Stump11289f42009-09-09 15:08:12 +0000193
Anders Carlsson84613c42009-06-12 16:51:40 +0000194 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +0000195
Anders Carlsson84613c42009-06-12 16:51:40 +0000196 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000197
Anders Carlsson84613c42009-06-12 16:51:40 +0000198 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000199}
200
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000201/// CheckExtraCXXDefaultArguments - Check for any extra default
202/// arguments in the declarator, which is not a function declaration
203/// or definition and therefore is not permitted to have default
204/// arguments. This routine should be invoked for every declarator
205/// that is not a function declaration or definition.
206void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
207 // C++ [dcl.fct.default]p3
208 // A default argument expression shall be specified only in the
209 // parameter-declaration-clause of a function declaration or in a
210 // template-parameter (14.1). It shall not be specified for a
211 // parameter pack. If it is specified in a
212 // parameter-declaration-clause, it shall not occur within a
213 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000214 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000215 DeclaratorChunk &chunk = D.getTypeObject(i);
216 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000217 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
218 ParmVarDecl *Param =
219 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000220 if (Param->hasUnparsedDefaultArg()) {
221 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000222 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
223 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
224 delete Toks;
225 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000226 } else if (Param->getDefaultArg()) {
227 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
228 << Param->getDefaultArg()->getSourceRange();
229 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000230 }
231 }
232 }
233 }
234}
235
Chris Lattner199abbc2008-04-08 05:04:30 +0000236// MergeCXXFunctionDecl - Merge two declarations of the same C++
237// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000238// type. Subroutine of MergeFunctionDecl. Returns true if there was an
239// error, false otherwise.
240bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
241 bool Invalid = false;
242
Chris Lattner199abbc2008-04-08 05:04:30 +0000243 // C++ [dcl.fct.default]p4:
244 //
245 // For non-template functions, default arguments can be added in
246 // later declarations of a function in the same
247 // scope. Declarations in different scopes have completely
248 // distinct sets of default arguments. That is, declarations in
249 // inner scopes do not acquire default arguments from
250 // declarations in outer scopes, and vice versa. In a given
251 // function declaration, all parameters subsequent to a
252 // parameter with a default argument shall have default
253 // arguments supplied in this or previous declarations. A
254 // default argument shall not be redefined by a later
255 // declaration (not even to the same value).
256 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
257 ParmVarDecl *OldParam = Old->getParamDecl(p);
258 ParmVarDecl *NewParam = New->getParamDecl(p);
259
Mike Stump11289f42009-09-09 15:08:12 +0000260 if (OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
261 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000262 diag::err_param_default_argument_redefinition)
263 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner0369c572008-11-23 23:12:31 +0000264 Diag(OldParam->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000265 Invalid = true;
Chris Lattner199abbc2008-04-08 05:04:30 +0000266 } else if (OldParam->getDefaultArg()) {
267 // Merge the old default argument into the new parameter
268 NewParam->setDefaultArg(OldParam->getDefaultArg());
269 }
270 }
271
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000272 if (CheckEquivalentExceptionSpec(
273 Old->getType()->getAsFunctionProtoType(), Old->getLocation(),
274 New->getType()->getAsFunctionProtoType(), New->getLocation())) {
275 Invalid = true;
276 }
277
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000278 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000279}
280
281/// CheckCXXDefaultArguments - Verify that the default arguments for a
282/// function declaration are well-formed according to C++
283/// [dcl.fct.default].
284void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
285 unsigned NumParams = FD->getNumParams();
286 unsigned p;
287
288 // Find first parameter with a default argument
289 for (p = 0; p < NumParams; ++p) {
290 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000291 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000292 break;
293 }
294
295 // C++ [dcl.fct.default]p4:
296 // In a given function declaration, all parameters
297 // subsequent to a parameter with a default argument shall
298 // have default arguments supplied in this or previous
299 // declarations. A default argument shall not be redefined
300 // by a later declaration (not even to the same value).
301 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000302 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000303 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000304 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000305 if (Param->isInvalidDecl())
306 /* We already complained about this parameter. */;
307 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000308 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000309 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000310 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000311 else
Mike Stump11289f42009-09-09 15:08:12 +0000312 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000313 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000314
Chris Lattner199abbc2008-04-08 05:04:30 +0000315 LastMissingDefaultArg = p;
316 }
317 }
318
319 if (LastMissingDefaultArg > 0) {
320 // Some default arguments were missing. Clear out all of the
321 // default arguments up to (and including) the last missing
322 // default argument, so that we leave the function parameters
323 // in a semantically valid state.
324 for (p = 0; p <= LastMissingDefaultArg; ++p) {
325 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000326 if (Param->hasDefaultArg()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000327 if (!Param->hasUnparsedDefaultArg())
328 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000329 Param->setDefaultArg(0);
330 }
331 }
332 }
333}
Douglas Gregor556877c2008-04-13 21:30:24 +0000334
Douglas Gregor61956c42008-10-31 09:07:45 +0000335/// isCurrentClassName - Determine whether the identifier II is the
336/// name of the class type currently being defined. In the case of
337/// nested classes, this will only return true if II is the name of
338/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000339bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
340 const CXXScopeSpec *SS) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000341 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000342 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000343 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000344 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
345 } else
346 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
347
348 if (CurDecl)
Douglas Gregor61956c42008-10-31 09:07:45 +0000349 return &II == CurDecl->getIdentifier();
350 else
351 return false;
352}
353
Mike Stump11289f42009-09-09 15:08:12 +0000354/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000355///
356/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
357/// and returns NULL otherwise.
358CXXBaseSpecifier *
359Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
360 SourceRange SpecifierRange,
361 bool Virtual, AccessSpecifier Access,
Mike Stump11289f42009-09-09 15:08:12 +0000362 QualType BaseType,
Douglas Gregor463421d2009-03-03 04:44:36 +0000363 SourceLocation BaseLoc) {
364 // C++ [class.union]p1:
365 // A union shall not have base classes.
366 if (Class->isUnion()) {
367 Diag(Class->getLocation(), diag::err_base_clause_on_union)
368 << SpecifierRange;
369 return 0;
370 }
371
372 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000373 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor463421d2009-03-03 04:44:36 +0000374 Class->getTagKind() == RecordDecl::TK_class,
375 Access, BaseType);
376
377 // Base specifiers must be record types.
378 if (!BaseType->isRecordType()) {
379 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
380 return 0;
381 }
382
383 // C++ [class.union]p1:
384 // A union shall not be used as a base class.
385 if (BaseType->isUnionType()) {
386 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
387 return 0;
388 }
389
390 // C++ [class.derived]p2:
391 // The class-name in a base-specifier shall not be an incompletely
392 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000393 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000394 PDiag(diag::err_incomplete_base_class)
395 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000396 return 0;
397
Eli Friedmanc96d4962009-08-15 21:55:26 +0000398 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000399 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000400 assert(BaseDecl && "Record type has no declaration");
401 BaseDecl = BaseDecl->getDefinition(Context);
402 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000403 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
404 assert(CXXBaseDecl && "Base type is not a C++ type");
405 if (!CXXBaseDecl->isEmpty())
406 Class->setEmpty(false);
407 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor463421d2009-03-03 04:44:36 +0000408 Class->setPolymorphic(true);
409
410 // C++ [dcl.init.aggr]p1:
411 // An aggregate is [...] a class with [...] no base classes [...].
412 Class->setAggregate(false);
413 Class->setPOD(false);
414
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000415 if (Virtual) {
416 // C++ [class.ctor]p5:
417 // A constructor is trivial if its class has no virtual base classes.
418 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000419
420 // C++ [class.copy]p6:
421 // A copy constructor is trivial if its class has no virtual base classes.
422 Class->setHasTrivialCopyConstructor(false);
423
424 // C++ [class.copy]p11:
425 // A copy assignment operator is trivial if its class has no virtual
426 // base classes.
427 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000428
429 // C++0x [meta.unary.prop] is_empty:
430 // T is a class type, but not a union type, with ... no virtual base
431 // classes
432 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000433 } else {
434 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000435 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000436 // class have trivial constructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000437 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
438 Class->setHasTrivialConstructor(false);
439
440 // C++ [class.copy]p6:
441 // A copy constructor is trivial if all the direct base classes of its
442 // class have trivial copy constructors.
443 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
444 Class->setHasTrivialCopyConstructor(false);
445
446 // C++ [class.copy]p11:
447 // A copy assignment operator is trivial if all the direct base classes
448 // of its class have trivial copy assignment operators.
449 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
450 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000451 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000452
453 // C++ [class.ctor]p3:
454 // A destructor is trivial if all the direct base classes of its class
455 // have trivial destructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000456 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
457 Class->setHasTrivialDestructor(false);
Mike Stump11289f42009-09-09 15:08:12 +0000458
Douglas Gregor463421d2009-03-03 04:44:36 +0000459 // Create the base specifier.
460 // FIXME: Allocate via ASTContext?
Mike Stump11289f42009-09-09 15:08:12 +0000461 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
462 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor463421d2009-03-03 04:44:36 +0000463 Access, BaseType);
464}
465
Douglas Gregor556877c2008-04-13 21:30:24 +0000466/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
467/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000468/// example:
469/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000470/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000471Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000472Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000473 bool Virtual, AccessSpecifier Access,
474 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000475 if (!classdecl)
476 return true;
477
Douglas Gregorc40290e2009-03-09 23:48:35 +0000478 AdjustDeclIfTemplate(classdecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000479 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000480 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000481 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
482 Virtual, Access,
483 BaseType, BaseLoc))
484 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000485
Douglas Gregor463421d2009-03-03 04:44:36 +0000486 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000487}
Douglas Gregor556877c2008-04-13 21:30:24 +0000488
Douglas Gregor463421d2009-03-03 04:44:36 +0000489/// \brief Performs the actual work of attaching the given base class
490/// specifiers to a C++ class.
491bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
492 unsigned NumBases) {
493 if (NumBases == 0)
494 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000495
496 // Used to keep track of which base types we have already seen, so
497 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000498 // that the key is always the unqualified canonical type of the base
499 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000500 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
501
502 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000503 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000504 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000505 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000506 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000507 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000508 NewBaseType = NewBaseType.getUnqualifiedType();
509
Douglas Gregor29a92472008-10-22 17:49:05 +0000510 if (KnownBaseTypes[NewBaseType]) {
511 // C++ [class.mi]p3:
512 // A class shall not be specified as a direct base class of a
513 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000514 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000515 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000516 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000517 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000518
519 // Delete the duplicate base class specifier; we're going to
520 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000521 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000522
523 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000524 } else {
525 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000526 KnownBaseTypes[NewBaseType] = Bases[idx];
527 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000528 }
529 }
530
531 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian9fa077c2009-07-02 18:26:15 +0000532 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000533
534 // Delete the remaining (good) base class specifiers, since their
535 // data has been copied into the CXXRecordDecl.
536 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000537 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000538
539 return Invalid;
540}
541
542/// ActOnBaseSpecifiers - Attach the given base specifiers to the
543/// class, after checking whether there are any duplicate base
544/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000545void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000546 unsigned NumBases) {
547 if (!ClassDecl || !Bases || !NumBases)
548 return;
549
550 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000551 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000552 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000553}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000554
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000555//===----------------------------------------------------------------------===//
556// C++ class member Handling
557//===----------------------------------------------------------------------===//
558
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000559/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
560/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
561/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000562/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000563Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000564Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000565 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000566 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000567 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000568 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000569 Expr *BitWidth = static_cast<Expr*>(BW);
570 Expr *Init = static_cast<Expr*>(InitExpr);
571 SourceLocation Loc = D.getIdentifierLoc();
572
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000573 bool isFunc = D.isFunctionDeclarator();
574
John McCall07e91c02009-08-06 02:15:43 +0000575 assert(!DS.isFriendSpecified());
576
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000577 // C++ 9.2p6: A member shall not be declared to have automatic storage
578 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000579 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
580 // data members and cannot be applied to names declared const or static,
581 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000582 switch (DS.getStorageClassSpec()) {
583 case DeclSpec::SCS_unspecified:
584 case DeclSpec::SCS_typedef:
585 case DeclSpec::SCS_static:
586 // FALL THROUGH.
587 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000588 case DeclSpec::SCS_mutable:
589 if (isFunc) {
590 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000591 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000592 else
Chris Lattner3b054132008-11-19 05:08:23 +0000593 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000594
Sebastian Redl8071edb2008-11-17 23:24:37 +0000595 // FIXME: It would be nicer if the keyword was ignored only for this
596 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000597 D.getMutableDeclSpec().ClearStorageClassSpecs();
598 } else {
599 QualType T = GetTypeForDeclarator(D, S);
600 diag::kind err = static_cast<diag::kind>(0);
601 if (T->isReferenceType())
602 err = diag::err_mutable_reference;
603 else if (T.isConstQualified())
604 err = diag::err_mutable_const;
605 if (err != 0) {
606 if (DS.getStorageClassSpecLoc().isValid())
607 Diag(DS.getStorageClassSpecLoc(), err);
608 else
609 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000610 // FIXME: It would be nicer if the keyword was ignored only for this
611 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000612 D.getMutableDeclSpec().ClearStorageClassSpecs();
613 }
614 }
615 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000616 default:
617 if (DS.getStorageClassSpecLoc().isValid())
618 Diag(DS.getStorageClassSpecLoc(),
619 diag::err_storageclass_invalid_for_member);
620 else
621 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
622 D.getMutableDeclSpec().ClearStorageClassSpecs();
623 }
624
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000625 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000626 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000627 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000628 // Check also for this case:
629 //
630 // typedef int f();
631 // f a;
632 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000633 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000634 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000635 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000636
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000637 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
638 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000639 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000640
641 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000642 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000643 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000644 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
645 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000646 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000647 } else {
Douglas Gregor3447e762009-08-20 22:52:58 +0000648 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
649 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000650 if (!Member) {
651 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000652 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000653 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000654
655 // Non-instance-fields can't have a bitfield.
656 if (BitWidth) {
657 if (Member->isInvalidDecl()) {
658 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000659 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000660 // C++ 9.6p3: A bit-field shall not be a static member.
661 // "static member 'A' cannot be a bit-field"
662 Diag(Loc, diag::err_static_not_bitfield)
663 << Name << BitWidth->getSourceRange();
664 } else if (isa<TypedefDecl>(Member)) {
665 // "typedef member 'x' cannot be a bit-field"
666 Diag(Loc, diag::err_typedef_not_bitfield)
667 << Name << BitWidth->getSourceRange();
668 } else {
669 // A function typedef ("typedef int f(); f a;").
670 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
671 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000672 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000673 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000674 }
Mike Stump11289f42009-09-09 15:08:12 +0000675
Chris Lattnerd26760a2009-03-05 23:01:03 +0000676 DeleteExpr(BitWidth);
677 BitWidth = 0;
678 Member->setInvalidDecl();
679 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000680
681 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000682
Douglas Gregor3447e762009-08-20 22:52:58 +0000683 // If we have declared a member function template, set the access of the
684 // templated declaration as well.
685 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
686 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000687 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000688
Douglas Gregor92751d42008-11-17 22:58:34 +0000689 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000690
Douglas Gregor0c880302009-03-11 23:00:04 +0000691 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000692 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000693 if (Deleted) // FIXME: Source location is not very good.
694 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000695
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000696 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000697 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000698 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000699 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000700 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000701}
702
Douglas Gregore8381c02008-11-05 04:29:56 +0000703/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +0000704Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000705Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +0000706 Scope *S,
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000707 const CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +0000708 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000709 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +0000710 SourceLocation IdLoc,
711 SourceLocation LParenLoc,
712 ExprTy **Args, unsigned NumArgs,
713 SourceLocation *CommaLocs,
714 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000715 if (!ConstructorD)
716 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000717
Douglas Gregorc8c277a2009-08-24 11:57:43 +0000718 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +0000719
720 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +0000721 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +0000722 if (!Constructor) {
723 // The user wrote a constructor initializer on a function that is
724 // not a C++ constructor. Ignore the error for now, because we may
725 // have more member initializers coming; we'll diagnose it just
726 // once in ActOnMemInitializers.
727 return true;
728 }
729
730 CXXRecordDecl *ClassDecl = Constructor->getParent();
731
732 // C++ [class.base.init]p2:
733 // Names in a mem-initializer-id are looked up in the scope of the
734 // constructor’s class and, if not found in that scope, are looked
735 // up in the scope containing the constructor’s
736 // definition. [Note: if the constructor’s class contains a member
737 // with the same name as a direct or virtual base class of the
738 // class, a mem-initializer-id naming the member or base class and
739 // composed of a single identifier refers to the class member. A
740 // mem-initializer-id for the hidden base class may be specified
741 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000742 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000743 // Look for a member, first.
744 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000745 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000746 = ClassDecl->lookup(MemberOrBase);
747 if (Result.first != Result.second)
748 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +0000749
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000750 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +0000751
Eli Friedman8e1433b2009-07-29 19:44:27 +0000752 if (Member)
753 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
754 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +0000755 }
Douglas Gregore8381c02008-11-05 04:29:56 +0000756 // It didn't name a member, so see if it names a class.
Mike Stump11289f42009-09-09 15:08:12 +0000757 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000758 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregore8381c02008-11-05 04:29:56 +0000759 if (!BaseTy)
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000760 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
761 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000762
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000763 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregore8381c02008-11-05 04:29:56 +0000764
Eli Friedman8e1433b2009-07-29 19:44:27 +0000765 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
766 RParenLoc, ClassDecl);
767}
768
769Sema::MemInitResult
770Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
771 unsigned NumArgs, SourceLocation IdLoc,
772 SourceLocation RParenLoc) {
773 bool HasDependentArg = false;
774 for (unsigned i = 0; i < NumArgs; i++)
775 HasDependentArg |= Args[i]->isTypeDependent();
776
777 CXXConstructorDecl *C = 0;
778 QualType FieldType = Member->getType();
779 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
780 FieldType = Array->getElementType();
781 if (FieldType->isDependentType()) {
782 // Can't check init for dependent type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000783 } else if (FieldType->getAs<RecordType>()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000784 if (!HasDependentArg) {
785 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
786
787 C = PerformInitializationByConstructor(FieldType,
788 MultiExprArg(*this,
789 (void**)Args,
790 NumArgs),
791 IdLoc,
792 SourceRange(IdLoc, RParenLoc),
793 Member->getDeclName(), IK_Direct,
794 ConstructorArgs);
795
796 if (C) {
797 // Take over the constructor arguments as our own.
798 NumArgs = ConstructorArgs.size();
799 Args = (Expr **)ConstructorArgs.take();
800 }
801 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +0000802 } else if (NumArgs != 1 && NumArgs != 0) {
Mike Stump11289f42009-09-09 15:08:12 +0000803 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman8e1433b2009-07-29 19:44:27 +0000804 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
805 } else if (!HasDependentArg) {
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +0000806 Expr *NewExp;
807 if (NumArgs == 0) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000808 if (FieldType->isReferenceType()) {
809 Diag(IdLoc, diag::err_null_intialized_reference_member)
810 << Member->getDeclName();
811 return Diag(Member->getLocation(), diag::note_declared_at);
812 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +0000813 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
814 NumArgs = 1;
815 }
816 else
817 NewExp = (Expr*)Args[0];
Eli Friedman8e1433b2009-07-29 19:44:27 +0000818 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
819 return true;
820 Args[0] = NewExp;
Douglas Gregore8381c02008-11-05 04:29:56 +0000821 }
Eli Friedman8e1433b2009-07-29 19:44:27 +0000822 // FIXME: Perform direct initialization of the member.
Mike Stump11289f42009-09-09 15:08:12 +0000823 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson1e172e02009-08-29 01:31:33 +0000824 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +0000825}
826
827Sema::MemInitResult
828Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
829 unsigned NumArgs, SourceLocation IdLoc,
830 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
831 bool HasDependentArg = false;
832 for (unsigned i = 0; i < NumArgs; i++)
833 HasDependentArg |= Args[i]->isTypeDependent();
834
835 if (!BaseType->isDependentType()) {
836 if (!BaseType->isRecordType())
837 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
838 << BaseType << SourceRange(IdLoc, RParenLoc);
839
840 // C++ [class.base.init]p2:
841 // [...] Unless the mem-initializer-id names a nonstatic data
842 // member of the constructor’s class or a direct or virtual base
843 // of that class, the mem-initializer is ill-formed. A
844 // mem-initializer-list can initialize a base class using any
845 // name that denotes that base class type.
Mike Stump11289f42009-09-09 15:08:12 +0000846
Eli Friedman8e1433b2009-07-29 19:44:27 +0000847 // First, check for a direct base class.
848 const CXXBaseSpecifier *DirectBaseSpec = 0;
849 for (CXXRecordDecl::base_class_const_iterator Base =
850 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Mike Stump11289f42009-09-09 15:08:12 +0000851 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
Eli Friedman8e1433b2009-07-29 19:44:27 +0000852 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
853 // We found a direct base of this type. That's what we're
854 // initializing.
855 DirectBaseSpec = &*Base;
856 break;
857 }
858 }
Mike Stump11289f42009-09-09 15:08:12 +0000859
Eli Friedman8e1433b2009-07-29 19:44:27 +0000860 // Check for a virtual base class.
861 // FIXME: We might be able to short-circuit this if we know in advance that
862 // there are no virtual bases.
863 const CXXBaseSpecifier *VirtualBaseSpec = 0;
864 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
865 // We haven't found a base yet; search the class hierarchy for a
866 // virtual base class.
867 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
868 /*DetectVirtual=*/false);
869 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Mike Stump11289f42009-09-09 15:08:12 +0000870 for (BasePaths::paths_iterator Path = Paths.begin();
Eli Friedman8e1433b2009-07-29 19:44:27 +0000871 Path != Paths.end(); ++Path) {
872 if (Path->back().Base->isVirtual()) {
873 VirtualBaseSpec = Path->back().Base;
874 break;
875 }
Douglas Gregore8381c02008-11-05 04:29:56 +0000876 }
877 }
878 }
Eli Friedman8e1433b2009-07-29 19:44:27 +0000879
880 // C++ [base.class.init]p2:
881 // If a mem-initializer-id is ambiguous because it designates both
882 // a direct non-virtual base class and an inherited virtual base
883 // class, the mem-initializer is ill-formed.
884 if (DirectBaseSpec && VirtualBaseSpec)
885 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
886 << BaseType << SourceRange(IdLoc, RParenLoc);
887 // C++ [base.class.init]p2:
888 // Unless the mem-initializer-id names a nonstatic data membeer of the
889 // constructor's class ot a direst or virtual base of that class, the
890 // mem-initializer is ill-formed.
891 if (!DirectBaseSpec && !VirtualBaseSpec)
892 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
893 << BaseType << ClassDecl->getNameAsCString()
894 << SourceRange(IdLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +0000895 }
896
Fariborz Jahanian0228bc12009-07-23 00:42:24 +0000897 CXXConstructorDecl *C = 0;
Eli Friedman8e1433b2009-07-29 19:44:27 +0000898 if (!BaseType->isDependentType() && !HasDependentArg) {
899 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
900 Context.getCanonicalType(BaseType));
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000901 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
902
903 C = PerformInitializationByConstructor(BaseType,
904 MultiExprArg(*this,
905 (void**)Args, NumArgs),
Mike Stump11289f42009-09-09 15:08:12 +0000906 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000907 Name, IK_Direct,
908 ConstructorArgs);
909 if (C) {
910 // Take over the constructor arguments as our own.
911 NumArgs = ConstructorArgs.size();
912 Args = (Expr **)ConstructorArgs.take();
913 }
Eli Friedman8e1433b2009-07-29 19:44:27 +0000914 }
915
Mike Stump11289f42009-09-09 15:08:12 +0000916 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson1e172e02009-08-29 01:31:33 +0000917 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +0000918}
919
Fariborz Jahanianca2f0852009-07-23 23:32:59 +0000920void
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000921Sema::setBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
922 CXXBaseOrMemberInitializer **Initializers,
923 unsigned NumInitializers,
Mike Stump11289f42009-09-09 15:08:12 +0000924 llvm::SmallVectorImpl<CXXBaseSpecifier *>& Bases,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000925 llvm::SmallVectorImpl<FieldDecl *>&Fields) {
926 // We need to build the initializer AST according to order of construction
927 // and not what user specified in the Initializers list.
928 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
929 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
930 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
931 bool HasDependentBaseInit = false;
Mike Stump11289f42009-09-09 15:08:12 +0000932
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000933 for (unsigned i = 0; i < NumInitializers; i++) {
934 CXXBaseOrMemberInitializer *Member = Initializers[i];
935 if (Member->isBaseInitializer()) {
936 if (Member->getBaseClass()->isDependentType())
937 HasDependentBaseInit = true;
938 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
939 } else {
940 AllBaseFields[Member->getMember()] = Member;
941 }
942 }
Mike Stump11289f42009-09-09 15:08:12 +0000943
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000944 if (HasDependentBaseInit) {
945 // FIXME. This does not preserve the ordering of the initializers.
946 // Try (with -Wreorder)
947 // template<class X> struct A {};
Mike Stump11289f42009-09-09 15:08:12 +0000948 // template<class X> struct B : A<X> {
949 // B() : x1(10), A<X>() {}
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000950 // int x1;
951 // };
952 // B<int> x;
953 // On seeing one dependent type, we should essentially exit this routine
954 // while preserving user-declared initializer list. When this routine is
955 // called during instantiatiation process, this routine will rebuild the
956 // oderdered initializer list correctly.
Mike Stump11289f42009-09-09 15:08:12 +0000957
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000958 // If we have a dependent base initialization, we can't determine the
959 // association between initializers and bases; just dump the known
960 // initializers into the list, and don't try to deal with other bases.
961 for (unsigned i = 0; i < NumInitializers; i++) {
962 CXXBaseOrMemberInitializer *Member = Initializers[i];
963 if (Member->isBaseInitializer())
964 AllToInit.push_back(Member);
965 }
966 } else {
967 // Push virtual bases before others.
968 for (CXXRecordDecl::base_class_iterator VBase =
969 ClassDecl->vbases_begin(),
970 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
971 if (VBase->getType()->isDependentType())
972 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000973 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +0000974 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Mike Stump11289f42009-09-09 15:08:12 +0000975 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +0000976 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
977 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
978 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
979 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000980 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +0000981 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000982 else {
Mike Stump11289f42009-09-09 15:08:12 +0000983 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000984 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
985 assert(VBaseDecl && "setBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +0000986 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
987 if (!Ctor)
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000988 Bases.push_back(VBase);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +0000989 else
990 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
991
Mike Stump11289f42009-09-09 15:08:12 +0000992 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000993 new (Context) CXXBaseOrMemberInitializer(VBase->getType(), 0, 0,
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +0000994 Ctor,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000995 SourceLocation(),
996 SourceLocation());
997 AllToInit.push_back(Member);
998 }
999 }
Mike Stump11289f42009-09-09 15:08:12 +00001000
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001001 for (CXXRecordDecl::base_class_iterator Base =
1002 ClassDecl->bases_begin(),
1003 E = ClassDecl->bases_end(); Base != E; ++Base) {
1004 // Virtuals are in the virtual base list and already constructed.
1005 if (Base->isVirtual())
1006 continue;
1007 // Skip dependent types.
1008 if (Base->getType()->isDependentType())
1009 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001010 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001011 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Mike Stump11289f42009-09-09 15:08:12 +00001012 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001013 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1014 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
1015 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1016 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001017 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001018 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001019 else {
Mike Stump11289f42009-09-09 15:08:12 +00001020 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001021 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001022 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001023 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
1024 if (!Ctor)
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001025 Bases.push_back(Base);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001026 else
1027 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1028
Mike Stump11289f42009-09-09 15:08:12 +00001029 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001030 new (Context) CXXBaseOrMemberInitializer(Base->getType(), 0, 0,
1031 BaseDecl->getDefaultConstructor(Context),
1032 SourceLocation(),
1033 SourceLocation());
1034 AllToInit.push_back(Member);
1035 }
1036 }
1037 }
Mike Stump11289f42009-09-09 15:08:12 +00001038
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001039 // non-static data members.
1040 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1041 E = ClassDecl->field_end(); Field != E; ++Field) {
1042 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001043 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001044 Field->getType()->getAs<RecordType>()) {
1045 CXXRecordDecl *FieldClassDecl
1046 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001047 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001048 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1049 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1050 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1051 // set to the anonymous union data member used in the initializer
1052 // list.
1053 Value->setMember(*Field);
1054 Value->setAnonUnionMember(*FA);
1055 AllToInit.push_back(Value);
1056 break;
1057 }
1058 }
1059 }
1060 continue;
1061 }
1062 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001063 QualType FT = (*Field)->getType();
1064 if (const RecordType* RT = FT->getAs<RecordType>()) {
1065 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl());
1066 assert(FieldRecDecl && "setBaseOrMemberInitializers - BaseDecl null");
Mike Stump11289f42009-09-09 15:08:12 +00001067 if (CXXConstructorDecl *Ctor =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001068 FieldRecDecl->getDefaultConstructor(Context))
1069 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
1070 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001071 AllToInit.push_back(Value);
1072 continue;
1073 }
Mike Stump11289f42009-09-09 15:08:12 +00001074
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001075 QualType FT = Context.getBaseElementType((*Field)->getType());
1076 if (const RecordType* RT = FT->getAs<RecordType>()) {
1077 CXXConstructorDecl *Ctor =
1078 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
1079 if (!Ctor && !FT->isDependentType())
1080 Fields.push_back(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001081 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001082 new (Context) CXXBaseOrMemberInitializer((*Field), 0, 0,
1083 Ctor,
1084 SourceLocation(),
1085 SourceLocation());
1086 AllToInit.push_back(Member);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001087 if (Ctor)
1088 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001089 if (FT.isConstQualified() && (!Ctor || Ctor->isTrivial())) {
1090 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1091 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1092 Diag((*Field)->getLocation(), diag::note_declared_at);
1093 }
1094 }
1095 else if (FT->isReferenceType()) {
1096 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1097 << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getDeclName();
1098 Diag((*Field)->getLocation(), diag::note_declared_at);
1099 }
1100 else if (FT.isConstQualified()) {
1101 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1102 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1103 Diag((*Field)->getLocation(), diag::note_declared_at);
1104 }
1105 }
Mike Stump11289f42009-09-09 15:08:12 +00001106
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001107 NumInitializers = AllToInit.size();
1108 if (NumInitializers > 0) {
1109 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1110 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1111 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump11289f42009-09-09 15:08:12 +00001112
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001113 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1114 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1115 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1116 }
1117}
1118
1119void
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001120Sema::BuildBaseOrMemberInitializers(ASTContext &C,
1121 CXXConstructorDecl *Constructor,
1122 CXXBaseOrMemberInitializer **Initializers,
1123 unsigned NumInitializers
1124 ) {
1125 llvm::SmallVector<CXXBaseSpecifier *, 4>Bases;
1126 llvm::SmallVector<FieldDecl *, 4>Members;
Mike Stump11289f42009-09-09 15:08:12 +00001127
1128 setBaseOrMemberInitializers(Constructor,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001129 Initializers, NumInitializers, Bases, Members);
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001130 for (unsigned int i = 0; i < Bases.size(); i++)
Mike Stump11289f42009-09-09 15:08:12 +00001131 Diag(Bases[i]->getSourceRange().getBegin(),
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001132 diag::err_missing_default_constructor) << 0 << Bases[i]->getType();
1133 for (unsigned int i = 0; i < Members.size(); i++)
Mike Stump11289f42009-09-09 15:08:12 +00001134 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor)
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001135 << 1 << Members[i]->getType();
1136}
1137
Eli Friedman952c15d2009-07-21 19:28:10 +00001138static void *GetKeyForTopLevelField(FieldDecl *Field) {
1139 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001140 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001141 if (RT->getDecl()->isAnonymousStructOrUnion())
1142 return static_cast<void *>(RT->getDecl());
1143 }
1144 return static_cast<void *>(Field);
1145}
1146
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001147static void *GetKeyForBase(QualType BaseType) {
1148 if (const RecordType *RT = BaseType->getAs<RecordType>())
1149 return (void *)RT;
Mike Stump11289f42009-09-09 15:08:12 +00001150
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001151 assert(0 && "Unexpected base type!");
1152 return 0;
1153}
1154
Mike Stump11289f42009-09-09 15:08:12 +00001155static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001156 bool MemberMaybeAnon = false) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001157 // For fields injected into the class via declaration of an anonymous union,
1158 // use its anonymous union class declaration as the unique key.
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001159 if (Member->isMemberInitializer()) {
1160 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001161
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001162 // After BuildBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump11289f42009-09-09 15:08:12 +00001163 // data member of the class. Data member used in the initializer list is
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001164 // in AnonUnionMember field.
1165 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1166 Field = Member->getAnonUnionMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00001167 if (Field->getDeclContext()->isRecord()) {
1168 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1169 if (RD->isAnonymousStructOrUnion())
1170 return static_cast<void *>(RD);
1171 }
1172 return static_cast<void *>(Field);
1173 }
Mike Stump11289f42009-09-09 15:08:12 +00001174
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001175 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman952c15d2009-07-21 19:28:10 +00001176}
1177
Mike Stump11289f42009-09-09 15:08:12 +00001178void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001179 SourceLocation ColonLoc,
1180 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001181 if (!ConstructorDecl)
1182 return;
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001183
1184 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001185
1186 CXXConstructorDecl *Constructor
Douglas Gregor71a57182009-06-22 23:20:33 +00001187 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001188
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001189 if (!Constructor) {
1190 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1191 return;
1192 }
Mike Stump11289f42009-09-09 15:08:12 +00001193
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001194 if (!Constructor->isDependentContext()) {
1195 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1196 bool err = false;
1197 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001198 CXXBaseOrMemberInitializer *Member =
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001199 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1200 void *KeyToMember = GetKeyForMember(Member);
1201 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1202 if (!PrevMember) {
1203 PrevMember = Member;
1204 continue;
1205 }
1206 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001207 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001208 diag::error_multiple_mem_initialization)
1209 << Field->getNameAsString();
1210 else {
1211 Type *BaseClass = Member->getBaseClass();
1212 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump11289f42009-09-09 15:08:12 +00001213 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001214 diag::error_multiple_base_initialization)
1215 << BaseClass->getDesugaredType(true);
1216 }
1217 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1218 << 0;
1219 err = true;
1220 }
Mike Stump11289f42009-09-09 15:08:12 +00001221
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001222 if (err)
1223 return;
1224 }
Mike Stump11289f42009-09-09 15:08:12 +00001225
Anders Carlssone0eebb32009-08-27 05:45:01 +00001226 BuildBaseOrMemberInitializers(Context, Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00001227 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001228 NumMemInits);
Mike Stump11289f42009-09-09 15:08:12 +00001229
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001230 if (Constructor->isDependentContext())
1231 return;
Mike Stump11289f42009-09-09 15:08:12 +00001232
1233 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001234 Diagnostic::Ignored &&
Mike Stump11289f42009-09-09 15:08:12 +00001235 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001236 Diagnostic::Ignored)
1237 return;
Mike Stump11289f42009-09-09 15:08:12 +00001238
Anders Carlssone0eebb32009-08-27 05:45:01 +00001239 // Also issue warning if order of ctor-initializer list does not match order
1240 // of 1) base class declarations and 2) order of non-static data members.
1241 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump11289f42009-09-09 15:08:12 +00001242
Anders Carlssone0eebb32009-08-27 05:45:01 +00001243 CXXRecordDecl *ClassDecl
1244 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1245 // Push virtual bases before others.
1246 for (CXXRecordDecl::base_class_iterator VBase =
1247 ClassDecl->vbases_begin(),
1248 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001249 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001250
Anders Carlssone0eebb32009-08-27 05:45:01 +00001251 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1252 E = ClassDecl->bases_end(); Base != E; ++Base) {
1253 // Virtuals are alread in the virtual base list and are constructed
1254 // first.
1255 if (Base->isVirtual())
1256 continue;
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001257 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001258 }
Mike Stump11289f42009-09-09 15:08:12 +00001259
Anders Carlssone0eebb32009-08-27 05:45:01 +00001260 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1261 E = ClassDecl->field_end(); Field != E; ++Field)
1262 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001263
Anders Carlssone0eebb32009-08-27 05:45:01 +00001264 int Last = AllBaseOrMembers.size();
1265 int curIndex = 0;
1266 CXXBaseOrMemberInitializer *PrevMember = 0;
1267 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001268 CXXBaseOrMemberInitializer *Member =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001269 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1270 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman952c15d2009-07-21 19:28:10 +00001271
Anders Carlssone0eebb32009-08-27 05:45:01 +00001272 for (; curIndex < Last; curIndex++)
1273 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1274 break;
1275 if (curIndex == Last) {
1276 assert(PrevMember && "Member not in member list?!");
1277 // Initializer as specified in ctor-initializer list is out of order.
1278 // Issue a warning diagnostic.
1279 if (PrevMember->isBaseInitializer()) {
1280 // Diagnostics is for an initialized base class.
1281 Type *BaseClass = PrevMember->getBaseClass();
1282 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001283 diag::warn_base_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001284 << BaseClass->getDesugaredType(true);
1285 } else {
1286 FieldDecl *Field = PrevMember->getMember();
1287 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001288 diag::warn_field_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001289 << Field->getNameAsString();
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001290 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001291 // Also the note!
1292 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001293 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001294 diag::note_fieldorbase_initialized_here) << 0
1295 << Field->getNameAsString();
1296 else {
1297 Type *BaseClass = Member->getBaseClass();
Mike Stump11289f42009-09-09 15:08:12 +00001298 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001299 diag::note_fieldorbase_initialized_here) << 1
1300 << BaseClass->getDesugaredType(true);
1301 }
1302 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump11289f42009-09-09 15:08:12 +00001303 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001304 break;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001305 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001306 PrevMember = Member;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001307 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001308}
1309
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001310void
1311Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) {
1312 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext());
1313 llvm::SmallVector<uintptr_t, 32> AllToDestruct;
Mike Stump11289f42009-09-09 15:08:12 +00001314
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001315 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1316 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1317 if (VBase->getType()->isDependentType())
1318 continue;
1319 // Skip over virtual bases which have trivial destructors.
1320 CXXRecordDecl *BaseClassDecl
1321 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1322 if (BaseClassDecl->hasTrivialDestructor())
1323 continue;
1324 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001325 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001326 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump11289f42009-09-09 15:08:12 +00001327
1328 uintptr_t Member =
1329 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001330 | CXXDestructorDecl::VBASE;
1331 AllToDestruct.push_back(Member);
1332 }
1333 for (CXXRecordDecl::base_class_iterator Base =
1334 ClassDecl->bases_begin(),
1335 E = ClassDecl->bases_end(); Base != E; ++Base) {
1336 if (Base->isVirtual())
1337 continue;
1338 if (Base->getType()->isDependentType())
1339 continue;
1340 // Skip over virtual bases which have trivial destructors.
1341 CXXRecordDecl *BaseClassDecl
1342 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1343 if (BaseClassDecl->hasTrivialDestructor())
1344 continue;
1345 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001346 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001347 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump11289f42009-09-09 15:08:12 +00001348 uintptr_t Member =
1349 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001350 | CXXDestructorDecl::DRCTNONVBASE;
1351 AllToDestruct.push_back(Member);
1352 }
Mike Stump11289f42009-09-09 15:08:12 +00001353
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001354 // non-static data members.
1355 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1356 E = ClassDecl->field_end(); Field != E; ++Field) {
1357 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001358
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001359 if (const RecordType* RT = FieldType->getAs<RecordType>()) {
1360 // Skip over virtual bases which have trivial destructors.
1361 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1362 if (FieldClassDecl->hasTrivialDestructor())
1363 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001364 if (const CXXDestructorDecl *Dtor =
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001365 FieldClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001366 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001367 const_cast<CXXDestructorDecl*>(Dtor));
1368 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field);
1369 AllToDestruct.push_back(Member);
1370 }
1371 }
Mike Stump11289f42009-09-09 15:08:12 +00001372
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001373 unsigned NumDestructions = AllToDestruct.size();
1374 if (NumDestructions > 0) {
1375 Destructor->setNumBaseOrMemberDestructions(NumDestructions);
Mike Stump11289f42009-09-09 15:08:12 +00001376 uintptr_t *BaseOrMemberDestructions =
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001377 new (Context) uintptr_t [NumDestructions];
1378 // Insert in reverse order.
1379 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx)
1380 BaseOrMemberDestructions[i++] = AllToDestruct[Idx];
1381 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions);
1382 }
1383}
1384
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001385void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001386 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001387 return;
Mike Stump11289f42009-09-09 15:08:12 +00001388
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001389 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001390
1391 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001392 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001393 BuildBaseOrMemberInitializers(Context,
1394 Constructor,
1395 (CXXBaseOrMemberInitializer **)0, 0);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001396}
1397
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001398namespace {
1399 /// PureVirtualMethodCollector - traverses a class and its superclasses
1400 /// and determines if it has any pure virtual methods.
1401 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1402 ASTContext &Context;
1403
Sebastian Redlb7d64912009-03-22 21:28:55 +00001404 public:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001405 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redlb7d64912009-03-22 21:28:55 +00001406
1407 private:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001408 MethodList Methods;
Mike Stump11289f42009-09-09 15:08:12 +00001409
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001410 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump11289f42009-09-09 15:08:12 +00001411
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001412 public:
Mike Stump11289f42009-09-09 15:08:12 +00001413 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001414 : Context(Ctx) {
Mike Stump11289f42009-09-09 15:08:12 +00001415
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001416 MethodList List;
1417 Collect(RD, List);
Mike Stump11289f42009-09-09 15:08:12 +00001418
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001419 // Copy the temporary list to methods, and make sure to ignore any
1420 // null entries.
1421 for (size_t i = 0, e = List.size(); i != e; ++i) {
1422 if (List[i])
1423 Methods.push_back(List[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001424 }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001425 }
Mike Stump11289f42009-09-09 15:08:12 +00001426
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001427 bool empty() const { return Methods.empty(); }
Mike Stump11289f42009-09-09 15:08:12 +00001428
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001429 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1430 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001431 };
Mike Stump11289f42009-09-09 15:08:12 +00001432
1433 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001434 MethodList& Methods) {
1435 // First, collect the pure virtual methods for the base classes.
1436 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1437 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001438 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner85e2e142009-03-29 05:01:10 +00001439 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001440 if (BaseDecl && BaseDecl->isAbstract())
1441 Collect(BaseDecl, Methods);
1442 }
1443 }
Mike Stump11289f42009-09-09 15:08:12 +00001444
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001445 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson3c012712009-05-17 00:00:05 +00001446 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump11289f42009-09-09 15:08:12 +00001447
Anders Carlsson3c012712009-05-17 00:00:05 +00001448 MethodSetTy OverriddenMethods;
1449 size_t MethodsSize = Methods.size();
1450
Mike Stump11289f42009-09-09 15:08:12 +00001451 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson3c012712009-05-17 00:00:05 +00001452 i != e; ++i) {
1453 // Traverse the record, looking for methods.
1454 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl86be8542009-07-07 20:29:57 +00001455 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson3c012712009-05-17 00:00:05 +00001456 if (MD->isPure()) {
1457 Methods.push_back(MD);
1458 continue;
1459 }
Mike Stump11289f42009-09-09 15:08:12 +00001460
Anders Carlsson3c012712009-05-17 00:00:05 +00001461 // Otherwise, record all the overridden methods in our set.
1462 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1463 E = MD->end_overridden_methods(); I != E; ++I) {
1464 // Keep track of the overridden methods.
1465 OverriddenMethods.insert(*I);
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001466 }
1467 }
1468 }
Mike Stump11289f42009-09-09 15:08:12 +00001469
1470 // Now go through the methods and zero out all the ones we know are
Anders Carlsson3c012712009-05-17 00:00:05 +00001471 // overridden.
1472 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1473 if (OverriddenMethods.count(Methods[i]))
1474 Methods[i] = 0;
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001475 }
Mike Stump11289f42009-09-09 15:08:12 +00001476
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001477 }
1478}
Douglas Gregore8381c02008-11-05 04:29:56 +00001479
Anders Carlssoneabf7702009-08-27 00:13:57 +00001480
Mike Stump11289f42009-09-09 15:08:12 +00001481bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001482 unsigned DiagID, AbstractDiagSelID SelID,
1483 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00001484 if (SelID == -1)
1485 return RequireNonAbstractType(Loc, T,
1486 PDiag(DiagID), CurrentRD);
1487 else
1488 return RequireNonAbstractType(Loc, T,
1489 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001490}
1491
Anders Carlssoneabf7702009-08-27 00:13:57 +00001492bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1493 const PartialDiagnostic &PD,
1494 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001495 if (!getLangOptions().CPlusPlus)
1496 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001497
Anders Carlssoneb0c5322009-03-23 19:10:31 +00001498 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001499 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001500 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001501
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001502 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001503 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001504 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001505 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00001506
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001507 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001508 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001509 }
Mike Stump11289f42009-09-09 15:08:12 +00001510
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001511 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001512 if (!RT)
1513 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001514
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001515 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1516 if (!RD)
1517 return false;
1518
Anders Carlssonb57738b2009-03-24 17:23:42 +00001519 if (CurrentRD && CurrentRD != RD)
1520 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001521
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001522 if (!RD->isAbstract())
1523 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001524
Anders Carlssoneabf7702009-08-27 00:13:57 +00001525 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00001526
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001527 // Check if we've already emitted the list of pure virtual functions for this
1528 // class.
1529 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1530 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001531
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001532 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001533
1534 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001535 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1536 const CXXMethodDecl *MD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001537
1538 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001539 MD->getDeclName();
1540 }
1541
1542 if (!PureVirtualClassDiagSet)
1543 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1544 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00001545
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001546 return true;
1547}
1548
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001549namespace {
Mike Stump11289f42009-09-09 15:08:12 +00001550 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001551 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1552 Sema &SemaRef;
1553 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00001554
Anders Carlssonb57738b2009-03-24 17:23:42 +00001555 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001556 bool Invalid = false;
1557
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001558 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1559 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001560 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00001561
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001562 return Invalid;
1563 }
Mike Stump11289f42009-09-09 15:08:12 +00001564
Anders Carlssonb57738b2009-03-24 17:23:42 +00001565 public:
1566 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1567 : SemaRef(SemaRef), AbstractClass(ac) {
1568 Visit(SemaRef.Context.getTranslationUnitDecl());
1569 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001570
Anders Carlssonb57738b2009-03-24 17:23:42 +00001571 bool VisitFunctionDecl(const FunctionDecl *FD) {
1572 if (FD->isThisDeclarationADefinition()) {
1573 // No need to do the check if we're in a definition, because it requires
1574 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00001575 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00001576 return VisitDeclContext(FD);
1577 }
Mike Stump11289f42009-09-09 15:08:12 +00001578
Anders Carlssonb57738b2009-03-24 17:23:42 +00001579 // Check the return type.
1580 QualType RTy = FD->getType()->getAsFunctionType()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001581 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00001582 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1583 diag::err_abstract_type_in_decl,
1584 Sema::AbstractReturnType,
1585 AbstractClass);
1586
Mike Stump11289f42009-09-09 15:08:12 +00001587 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00001588 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001589 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001590 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001591 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001592 VD->getOriginalType(),
1593 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001594 Sema::AbstractParamType,
1595 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001596 }
1597
1598 return Invalid;
1599 }
Mike Stump11289f42009-09-09 15:08:12 +00001600
Anders Carlssonb57738b2009-03-24 17:23:42 +00001601 bool VisitDecl(const Decl* D) {
1602 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1603 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001604
Anders Carlssonb57738b2009-03-24 17:23:42 +00001605 return false;
1606 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001607 };
1608}
1609
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001610void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00001611 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001612 SourceLocation LBrac,
1613 SourceLocation RBrac) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001614 if (!TagDecl)
1615 return;
Mike Stump11289f42009-09-09 15:08:12 +00001616
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001617 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001618 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00001619 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar15619c72008-10-03 02:03:53 +00001620 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor463421d2009-03-03 04:44:36 +00001621
Chris Lattner83f095c2009-03-28 19:18:32 +00001622 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001623 if (!RD->isAbstract()) {
1624 // Collect all the pure virtual methods and see if this is an abstract
1625 // class after all.
1626 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001627 if (!Collector.empty())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001628 RD->setAbstract(true);
1629 }
Mike Stump11289f42009-09-09 15:08:12 +00001630
1631 if (RD->isAbstract())
Anders Carlssonb57738b2009-03-24 17:23:42 +00001632 AbstractClassUsageDiagnoser(*this, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001633
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001634 if (!RD->isDependentType())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001635 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001636}
1637
Douglas Gregor05379422008-11-03 17:51:48 +00001638/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1639/// special functions, such as the default constructor, copy
1640/// constructor, or destructor, to the given C++ class (C++
1641/// [special]p1). This routine can only be executed just before the
1642/// definition of the class is complete.
1643void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00001644 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00001645 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00001646
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001647 // FIXME: Implicit declarations have exception specifications, which are
1648 // the union of the specifications of the implicitly called functions.
1649
Douglas Gregor05379422008-11-03 17:51:48 +00001650 if (!ClassDecl->hasUserDeclaredConstructor()) {
1651 // C++ [class.ctor]p5:
1652 // A default constructor for a class X is a constructor of class X
1653 // that can be called without an argument. If there is no
1654 // user-declared constructor for class X, a default constructor is
1655 // implicitly declared. An implicitly-declared default constructor
1656 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00001657 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00001658 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00001659 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00001660 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00001661 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00001662 Context.getFunctionType(Context.VoidTy,
1663 0, 0, false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001664 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00001665 /*isExplicit=*/false,
1666 /*isInline=*/true,
1667 /*isImplicitlyDeclared=*/true);
1668 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00001669 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00001670 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001671 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00001672 }
1673
1674 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1675 // C++ [class.copy]p4:
1676 // If the class definition does not explicitly declare a copy
1677 // constructor, one is declared implicitly.
1678
1679 // C++ [class.copy]p5:
1680 // The implicitly-declared copy constructor for a class X will
1681 // have the form
1682 //
1683 // X::X(const X&)
1684 //
1685 // if
1686 bool HasConstCopyConstructor = true;
1687
1688 // -- each direct or virtual base class B of X has a copy
1689 // constructor whose first parameter is of type const B& or
1690 // const volatile B&, and
1691 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1692 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1693 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001694 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001695 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00001696 = BaseClassDecl->hasConstCopyConstructor(Context);
1697 }
1698
1699 // -- for all the nonstatic data members of X that are of a
1700 // class type M (or array thereof), each such class type
1701 // has a copy constructor whose first parameter is of type
1702 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001703 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1704 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001705 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00001706 QualType FieldType = (*Field)->getType();
1707 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1708 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001709 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001710 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00001711 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001712 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00001713 = FieldClassDecl->hasConstCopyConstructor(Context);
1714 }
1715 }
1716
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001717 // Otherwise, the implicitly declared copy constructor will have
1718 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00001719 //
1720 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001721 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00001722 if (HasConstCopyConstructor)
1723 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001724 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00001725
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001726 // An implicitly-declared copy constructor is an inline public
1727 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00001728 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00001729 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00001730 CXXConstructorDecl *CopyConstructor
1731 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00001732 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00001733 Context.getFunctionType(Context.VoidTy,
1734 &ArgType, 1,
1735 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001736 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00001737 /*isExplicit=*/false,
1738 /*isInline=*/true,
1739 /*isImplicitlyDeclared=*/true);
1740 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00001741 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00001742 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00001743
1744 // Add the parameter to the constructor.
1745 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1746 ClassDecl->getLocation(),
1747 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001748 ArgType, /*DInfo=*/0,
1749 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00001750 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001751 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00001752 }
1753
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001754 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1755 // Note: The following rules are largely analoguous to the copy
1756 // constructor rules. Note that virtual bases are not taken into account
1757 // for determining the argument type of the operator. Note also that
1758 // operators taking an object instead of a reference are allowed.
1759 //
1760 // C++ [class.copy]p10:
1761 // If the class definition does not explicitly declare a copy
1762 // assignment operator, one is declared implicitly.
1763 // The implicitly-defined copy assignment operator for a class X
1764 // will have the form
1765 //
1766 // X& X::operator=(const X&)
1767 //
1768 // if
1769 bool HasConstCopyAssignment = true;
1770
1771 // -- each direct base class B of X has a copy assignment operator
1772 // whose parameter is of type const B&, const volatile B& or B,
1773 // and
1774 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1775 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1776 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001777 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001778 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001779 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001780 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001781 }
1782
1783 // -- for all the nonstatic data members of X that are of a class
1784 // type M (or array thereof), each such class type has a copy
1785 // assignment operator whose parameter is of type const M&,
1786 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001787 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1788 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001789 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001790 QualType FieldType = (*Field)->getType();
1791 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1792 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001793 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001794 const CXXRecordDecl *FieldClassDecl
1795 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001796 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001797 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001798 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001799 }
1800 }
1801
1802 // Otherwise, the implicitly declared copy assignment operator will
1803 // have the form
1804 //
1805 // X& X::operator=(X&)
1806 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001807 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001808 if (HasConstCopyAssignment)
1809 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001810 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001811
1812 // An implicitly-declared copy assignment operator is an inline public
1813 // member of its class.
1814 DeclarationName Name =
1815 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1816 CXXMethodDecl *CopyAssignment =
1817 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1818 Context.getFunctionType(RetType, &ArgType, 1,
1819 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001820 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001821 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00001822 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00001823 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001824 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001825
1826 // Add the parameter to the operator.
1827 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1828 ClassDecl->getLocation(),
1829 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001830 ArgType, /*DInfo=*/0,
1831 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00001832 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001833
1834 // Don't call addedAssignmentOperator. There is no way to distinguish an
1835 // implicit from an explicit assignment operator.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001836 ClassDecl->addDecl(CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001837 }
1838
Douglas Gregor1349b452008-12-15 21:24:18 +00001839 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00001840 // C++ [class.dtor]p2:
1841 // If a class has no user-declared destructor, a destructor is
1842 // declared implicitly. An implicitly-declared destructor is an
1843 // inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00001844 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00001845 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00001846 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00001847 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00001848 ClassDecl->getLocation(), Name,
Douglas Gregor831c93f2008-11-05 20:51:48 +00001849 Context.getFunctionType(Context.VoidTy,
1850 0, 0, false, 0),
1851 /*isInline=*/true,
1852 /*isImplicitlyDeclared=*/true);
1853 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00001854 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00001855 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001856 ClassDecl->addDecl(Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00001857 }
Douglas Gregor05379422008-11-03 17:51:48 +00001858}
1859
Douglas Gregore44a2ad2009-05-27 23:11:45 +00001860void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
1861 TemplateDecl *Template = TemplateD.getAs<TemplateDecl>();
1862 if (!Template)
1863 return;
1864
1865 TemplateParameterList *Params = Template->getTemplateParameters();
1866 for (TemplateParameterList::iterator Param = Params->begin(),
1867 ParamEnd = Params->end();
1868 Param != ParamEnd; ++Param) {
1869 NamedDecl *Named = cast<NamedDecl>(*Param);
1870 if (Named->getDeclName()) {
1871 S->AddDecl(DeclPtrTy::make(Named));
1872 IdResolver.AddDecl(Named);
1873 }
1874 }
1875}
1876
Douglas Gregor4d87df52008-12-16 21:30:33 +00001877/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1878/// parsing a top-level (non-nested) C++ class, and we are now
1879/// parsing those parts of the given Method declaration that could
1880/// not be parsed earlier (C++ [class.mem]p2), such as default
1881/// arguments. This action should enter the scope of the given
1882/// Method declaration as if we had just parsed the qualified method
1883/// name. However, it should not bring the parameters into scope;
1884/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00001885void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001886 if (!MethodD)
1887 return;
Mike Stump11289f42009-09-09 15:08:12 +00001888
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001889 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00001890
Douglas Gregor4d87df52008-12-16 21:30:33 +00001891 CXXScopeSpec SS;
Chris Lattner83f095c2009-03-28 19:18:32 +00001892 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001893 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00001894 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1895 SS.setScopeRep(
1896 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00001897 ActOnCXXEnterDeclaratorScope(S, SS);
1898}
1899
1900/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1901/// C++ method declaration. We're (re-)introducing the given
1902/// function parameter into scope for use in parsing later parts of
1903/// the method declaration. For example, we could see an
1904/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00001905void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001906 if (!ParamD)
1907 return;
Mike Stump11289f42009-09-09 15:08:12 +00001908
Chris Lattner83f095c2009-03-28 19:18:32 +00001909 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00001910
1911 // If this parameter has an unparsed default argument, clear it out
1912 // to make way for the parsed default argument.
1913 if (Param->hasUnparsedDefaultArg())
1914 Param->setDefaultArg(0);
1915
Chris Lattner83f095c2009-03-28 19:18:32 +00001916 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00001917 if (Param->getDeclName())
1918 IdResolver.AddDecl(Param);
1919}
1920
1921/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1922/// processing the delayed method declaration for Method. The method
1923/// declaration is now considered finished. There may be a separate
1924/// ActOnStartOfFunctionDef action later (not necessarily
1925/// immediately!) for this method, if it was also defined inside the
1926/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00001927void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001928 if (!MethodD)
1929 return;
Mike Stump11289f42009-09-09 15:08:12 +00001930
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001931 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00001932
Chris Lattner83f095c2009-03-28 19:18:32 +00001933 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00001934 CXXScopeSpec SS;
Mike Stump11289f42009-09-09 15:08:12 +00001935 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00001936 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1937 SS.setScopeRep(
1938 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00001939 ActOnCXXExitDeclaratorScope(S, SS);
1940
1941 // Now that we have our default arguments, check the constructor
1942 // again. It could produce additional diagnostics or affect whether
1943 // the class has implicitly-declared destructors, among other
1944 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00001945 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
1946 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00001947
1948 // Check the default arguments, which we may have added.
1949 if (!Method->isInvalidDecl())
1950 CheckCXXDefaultArguments(Method);
1951}
1952
Douglas Gregor831c93f2008-11-05 20:51:48 +00001953/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00001954/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00001955/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00001956/// emit diagnostics and set the invalid bit to true. In any case, the type
1957/// will be updated to reflect a well-formed type for the constructor and
1958/// returned.
1959QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
1960 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00001961 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00001962
1963 // C++ [class.ctor]p3:
1964 // A constructor shall not be virtual (10.3) or static (9.4). A
1965 // constructor can be invoked for a const, volatile or const
1966 // volatile object. A constructor shall not be declared const,
1967 // volatile, or const volatile (9.3.2).
1968 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00001969 if (!D.isInvalidType())
1970 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1971 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1972 << SourceRange(D.getIdentifierLoc());
1973 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00001974 }
1975 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00001976 if (!D.isInvalidType())
1977 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1978 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1979 << SourceRange(D.getIdentifierLoc());
1980 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00001981 SC = FunctionDecl::None;
1982 }
Mike Stump11289f42009-09-09 15:08:12 +00001983
Chris Lattner38378bf2009-04-25 08:28:21 +00001984 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1985 if (FTI.TypeQuals != 0) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00001986 if (FTI.TypeQuals & QualType::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00001987 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1988 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00001989 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00001990 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1991 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00001992 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00001993 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1994 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00001995 }
Mike Stump11289f42009-09-09 15:08:12 +00001996
Douglas Gregor831c93f2008-11-05 20:51:48 +00001997 // Rebuild the function type "R" without any type qualifiers (in
1998 // case any of the errors above fired) and with "void" as the
1999 // return type, since constructors don't have return types. We
2000 // *always* have to do this, because GetTypeForDeclarator will
2001 // put in a result type of "int" when none was specified.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002002 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Chris Lattner38378bf2009-04-25 08:28:21 +00002003 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2004 Proto->getNumArgs(),
2005 Proto->isVariadic(), 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002006}
2007
Douglas Gregor4d87df52008-12-16 21:30:33 +00002008/// CheckConstructor - Checks a fully-formed constructor for
2009/// well-formedness, issuing any diagnostics required. Returns true if
2010/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002011void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002012 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002013 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2014 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002015 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002016
2017 // C++ [class.copy]p3:
2018 // A declaration of a constructor for a class X is ill-formed if
2019 // its first parameter is of type (optionally cv-qualified) X and
2020 // either there are no other parameters or else all other
2021 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002022 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002023 ((Constructor->getNumParams() == 1) ||
2024 (Constructor->getNumParams() > 1 &&
Anders Carlsson85446472009-06-06 04:14:07 +00002025 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002026 QualType ParamType = Constructor->getParamDecl(0)->getType();
2027 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2028 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002029 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2030 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor578dae52009-04-02 01:08:08 +00002031 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002032 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002033 }
2034 }
Mike Stump11289f42009-09-09 15:08:12 +00002035
Douglas Gregor4d87df52008-12-16 21:30:33 +00002036 // Notify the class that we've added a constructor.
2037 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002038}
2039
Mike Stump11289f42009-09-09 15:08:12 +00002040static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002041FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2042 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2043 FTI.ArgInfo[0].Param &&
2044 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2045}
2046
Douglas Gregor831c93f2008-11-05 20:51:48 +00002047/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2048/// the well-formednes of the destructor declarator @p D with type @p
2049/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002050/// emit diagnostics and set the declarator to invalid. Even if this happens,
2051/// will be updated to reflect a well-formed type for the destructor and
2052/// returned.
2053QualType Sema::CheckDestructorDeclarator(Declarator &D,
2054 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002055 // C++ [class.dtor]p1:
2056 // [...] A typedef-name that names a class is a class-name
2057 // (7.1.3); however, a typedef-name that names a class shall not
2058 // be used as the identifier in the declarator for a destructor
2059 // declaration.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00002060 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType());
Chris Lattner38378bf2009-04-25 08:28:21 +00002061 if (isa<TypedefType>(DeclaratorType)) {
2062 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002063 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002064 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002065 }
2066
2067 // C++ [class.dtor]p2:
2068 // A destructor is used to destroy objects of its class type. A
2069 // destructor takes no parameters, and no return type can be
2070 // specified for it (not even void). The address of a destructor
2071 // shall not be taken. A destructor shall not be static. A
2072 // destructor can be invoked for a const, volatile or const
2073 // volatile object. A destructor shall not be declared const,
2074 // volatile or const volatile (9.3.2).
2075 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002076 if (!D.isInvalidType())
2077 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2078 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2079 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002080 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002081 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002082 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002083 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002084 // Destructors don't have return types, but the parser will
2085 // happily parse something like:
2086 //
2087 // class X {
2088 // float ~X();
2089 // };
2090 //
2091 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002092 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2093 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2094 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002095 }
Mike Stump11289f42009-09-09 15:08:12 +00002096
Chris Lattner38378bf2009-04-25 08:28:21 +00002097 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2098 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002099 if (FTI.TypeQuals & QualType::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002100 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2101 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002102 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002103 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2104 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002105 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002106 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2107 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002108 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002109 }
2110
2111 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002112 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002113 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2114
2115 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002116 FTI.freeArgs();
2117 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002118 }
2119
Mike Stump11289f42009-09-09 15:08:12 +00002120 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002121 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002122 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002123 D.setInvalidType();
2124 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002125
2126 // Rebuild the function type "R" without any type qualifiers or
2127 // parameters (in case any of the errors above fired) and with
2128 // "void" as the return type, since destructors don't have return
2129 // types. We *always* have to do this, because GetTypeForDeclarator
2130 // will put in a result type of "int" when none was specified.
Chris Lattner38378bf2009-04-25 08:28:21 +00002131 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002132}
2133
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002134/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2135/// well-formednes of the conversion function declarator @p D with
2136/// type @p R. If there are any errors in the declarator, this routine
2137/// will emit diagnostics and return true. Otherwise, it will return
2138/// false. Either way, the type @p R will be updated to reflect a
2139/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002140void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002141 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002142 // C++ [class.conv.fct]p1:
2143 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00002144 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00002145 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002146 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002147 if (!D.isInvalidType())
2148 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2149 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2150 << SourceRange(D.getIdentifierLoc());
2151 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002152 SC = FunctionDecl::None;
2153 }
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002154 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002155 // Conversion functions don't have return types, but the parser will
2156 // happily parse something like:
2157 //
2158 // class X {
2159 // float operator bool();
2160 // };
2161 //
2162 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00002163 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2164 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2165 << SourceRange(D.getIdentifierLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002166 }
2167
2168 // Make sure we don't have any parameters.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002169 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002170 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2171
2172 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00002173 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002174 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002175 }
2176
Mike Stump11289f42009-09-09 15:08:12 +00002177 // Make sure the conversion function isn't variadic.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002178 if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002179 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002180 D.setInvalidType();
2181 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002182
2183 // C++ [class.conv.fct]p4:
2184 // The conversion-type-id shall not represent a function type nor
2185 // an array type.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00002186 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002187 if (ConvType->isArrayType()) {
2188 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2189 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002190 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002191 } else if (ConvType->isFunctionType()) {
2192 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2193 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002194 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002195 }
2196
2197 // Rebuild the function type "R" without any parameters (in case any
2198 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00002199 // return type.
2200 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002201 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002202
Douglas Gregor5fb53972009-01-14 15:45:31 +00002203 // C++0x explicit conversion operators.
2204 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00002205 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002206 diag::warn_explicit_conversion_functions)
2207 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002208}
2209
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002210/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2211/// the declaration of the given C++ conversion function. This routine
2212/// is responsible for recording the conversion function in the C++
2213/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00002214Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002215 assert(Conversion && "Expected to receive a conversion function declaration");
2216
Douglas Gregor4287b372008-12-12 08:25:50 +00002217 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002218
2219 // Make sure we aren't redeclaring the conversion function.
2220 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002221
2222 // C++ [class.conv.fct]p1:
2223 // [...] A conversion function is never used to convert a
2224 // (possibly cv-qualified) object to the (possibly cv-qualified)
2225 // same object type (or a reference to it), to a (possibly
2226 // cv-qualified) base class of that type (or a reference to it),
2227 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00002228 // FIXME: Suppress this warning if the conversion function ends up being a
2229 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00002230 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002231 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002232 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002233 ConvType = ConvTypeRef->getPointeeType();
2234 if (ConvType->isRecordType()) {
2235 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2236 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002237 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002238 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002239 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002240 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002241 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002242 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002243 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002244 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002245 }
2246
Douglas Gregor1dc98262008-12-26 15:00:45 +00002247 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002248 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump11289f42009-09-09 15:08:12 +00002249 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002250 = Conversion->getDescribedFunctionTemplate())
2251 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor1dc98262008-12-26 15:00:45 +00002252 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00002253 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor1dc98262008-12-26 15:00:45 +00002254 Conv = Conversions->function_begin(),
2255 ConvEnd = Conversions->function_end();
2256 Conv != ConvEnd; ++Conv) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002257 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor1dc98262008-12-26 15:00:45 +00002258 *Conv = Conversion;
Chris Lattner83f095c2009-03-28 19:18:32 +00002259 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00002260 }
2261 }
2262 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00002263 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002264 = Conversion->getDescribedFunctionTemplate())
2265 ClassDecl->addConversionFunction(Context, ConversionTemplate);
2266 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Douglas Gregor1dc98262008-12-26 15:00:45 +00002267 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002268
Chris Lattner83f095c2009-03-28 19:18:32 +00002269 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002270}
2271
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002272//===----------------------------------------------------------------------===//
2273// Namespace Handling
2274//===----------------------------------------------------------------------===//
2275
2276/// ActOnStartNamespaceDef - This is called at the start of a namespace
2277/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00002278Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2279 SourceLocation IdentLoc,
2280 IdentifierInfo *II,
2281 SourceLocation LBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002282 NamespaceDecl *Namespc =
2283 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2284 Namespc->setLBracLoc(LBrace);
2285
2286 Scope *DeclRegionScope = NamespcScope->getParent();
2287
2288 if (II) {
2289 // C++ [namespace.def]p2:
2290 // The identifier in an original-namespace-definition shall not have been
2291 // previously defined in the declarative region in which the
2292 // original-namespace-definition appears. The identifier in an
2293 // original-namespace-definition is the name of the namespace. Subsequently
2294 // in that declarative region, it is treated as an original-namespace-name.
2295
Douglas Gregor2ada0482009-02-04 17:27:36 +00002296 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
2297 true);
Mike Stump11289f42009-09-09 15:08:12 +00002298
Douglas Gregor91f84212008-12-11 16:49:14 +00002299 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2300 // This is an extended namespace definition.
2301 // Attach this namespace decl to the chain of extended namespace
2302 // definitions.
2303 OrigNS->setNextNamespace(Namespc);
2304 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002305
Mike Stump11289f42009-09-09 15:08:12 +00002306 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002307 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00002308 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00002309 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002310 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002311 } else if (PrevDecl) {
2312 // This is an invalid name redefinition.
2313 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2314 << Namespc->getDeclName();
2315 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2316 Namespc->setInvalidDecl();
2317 // Continue on to push Namespc as current DeclContext and return it.
Mike Stump11289f42009-09-09 15:08:12 +00002318 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002319
2320 PushOnScopeChains(Namespc, DeclRegionScope);
2321 } else {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002322 // FIXME: Handle anonymous namespaces
2323 }
2324
2325 // Although we could have an invalid decl (i.e. the namespace name is a
2326 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00002327 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2328 // for the namespace has the declarations that showed up in that particular
2329 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00002330 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002331 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002332}
2333
2334/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2335/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00002336void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2337 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002338 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2339 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2340 Namespc->setRBracLoc(RBrace);
2341 PopDeclContext();
2342}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002343
Chris Lattner83f095c2009-03-28 19:18:32 +00002344Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2345 SourceLocation UsingLoc,
2346 SourceLocation NamespcLoc,
2347 const CXXScopeSpec &SS,
2348 SourceLocation IdentLoc,
2349 IdentifierInfo *NamespcName,
2350 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00002351 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2352 assert(NamespcName && "Invalid NamespcName.");
2353 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002354 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00002355
Douglas Gregor889ceb72009-02-03 19:21:40 +00002356 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00002357
Douglas Gregor34074322009-01-14 22:20:51 +00002358 // Lookup namespace name.
Douglas Gregor889ceb72009-02-03 19:21:40 +00002359 LookupResult R = LookupParsedName(S, &SS, NamespcName,
2360 LookupNamespaceName, false);
2361 if (R.isAmbiguous()) {
2362 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002363 return DeclPtrTy();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002364 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00002365 if (NamedDecl *NS = R) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00002366 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002367 // C++ [namespace.udir]p1:
2368 // A using-directive specifies that the names in the nominated
2369 // namespace can be used in the scope in which the
2370 // using-directive appears after the using-directive. During
2371 // unqualified name lookup (3.4.1), the names appear as if they
2372 // were declared in the nearest enclosing namespace which
2373 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00002374 // namespace. [Note: in this context, "contains" means "contains
2375 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00002376
2377 // Find enclosing context containing both using-directive and
2378 // nominated namespace.
2379 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2380 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2381 CommonAncestor = CommonAncestor->getParent();
2382
Mike Stump11289f42009-09-09 15:08:12 +00002383 UDir = UsingDirectiveDecl::Create(Context,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002384 CurContext, UsingLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002385 NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002386 SS.getRange(),
2387 (NestedNameSpecifier *)SS.getScopeRep(),
2388 IdentLoc,
Douglas Gregor889ceb72009-02-03 19:21:40 +00002389 cast<NamespaceDecl>(NS),
2390 CommonAncestor);
2391 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00002392 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00002393 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00002394 }
2395
Douglas Gregor889ceb72009-02-03 19:21:40 +00002396 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00002397 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00002398 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002399}
2400
2401void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2402 // If scope has associated entity, then using directive is at namespace
2403 // or translation unit scope. We add UsingDirectiveDecls, into
2404 // it's lookup structure.
2405 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002406 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002407 else
2408 // Otherwise it is block-sope. using-directives will affect lookup
2409 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002410 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00002411}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002412
Douglas Gregorfec52632009-06-20 00:51:54 +00002413
2414Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00002415 AccessSpecifier AS,
Anders Carlsson59140b32009-08-28 03:16:11 +00002416 SourceLocation UsingLoc,
2417 const CXXScopeSpec &SS,
2418 SourceLocation IdentLoc,
2419 IdentifierInfo *TargetName,
2420 OverloadedOperatorKind Op,
2421 AttributeList *AttrList,
2422 bool IsTypeName) {
Eli Friedman173e0b7a2009-06-27 05:59:59 +00002423 assert((TargetName || Op) && "Invalid TargetName.");
Douglas Gregorfec52632009-06-20 00:51:54 +00002424 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00002425
Anders Carlsson74d7f0d2009-06-27 00:27:47 +00002426 DeclarationName Name;
2427 if (TargetName)
2428 Name = TargetName;
2429 else
2430 Name = Context.DeclarationNames.getCXXOperatorName(Op);
Mike Stump11289f42009-09-09 15:08:12 +00002431
2432 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS, IdentLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00002433 Name, AttrList, IsTypeName);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002434 if (UD) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00002435 PushOnScopeChains(UD, S);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002436 UD->setAccess(AS);
2437 }
Mike Stump11289f42009-09-09 15:08:12 +00002438
Anders Carlsson696a3f12009-08-28 05:40:36 +00002439 return DeclPtrTy::make(UD);
2440}
2441
2442NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2443 const CXXScopeSpec &SS,
2444 SourceLocation IdentLoc,
2445 DeclarationName Name,
2446 AttributeList *AttrList,
2447 bool IsTypeName) {
2448 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2449 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00002450
Anders Carlssonf038fc22009-08-28 05:49:21 +00002451 // FIXME: We ignore attributes for now.
2452 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00002453
Anders Carlsson59140b32009-08-28 03:16:11 +00002454 if (SS.isEmpty()) {
2455 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00002456 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002457 }
Mike Stump11289f42009-09-09 15:08:12 +00002458
2459 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00002460 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2461
Anders Carlssonf038fc22009-08-28 05:49:21 +00002462 if (isUnknownSpecialization(SS)) {
2463 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2464 SS.getRange(), NNS,
2465 IdentLoc, Name, IsTypeName);
2466 }
Mike Stump11289f42009-09-09 15:08:12 +00002467
Anders Carlsson59140b32009-08-28 03:16:11 +00002468 DeclContext *LookupContext = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002469
Anders Carlsson59140b32009-08-28 03:16:11 +00002470 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2471 // C++0x N2914 [namespace.udecl]p3:
2472 // A using-declaration used as a member-declaration shall refer to a member
2473 // of a base class of the class being defined, shall refer to a member of an
2474 // anonymous union that is a member of a base class of the class being
Mike Stump11289f42009-09-09 15:08:12 +00002475 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlsson59140b32009-08-28 03:16:11 +00002476 // a member of a base class of the class being defined.
2477 const Type *Ty = NNS->getAsType();
2478 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) {
2479 Diag(SS.getRange().getBegin(),
2480 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2481 << NNS << RD->getDeclName();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002482 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002483 }
Anders Carlsson4bd78752009-08-28 15:18:15 +00002484
2485 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0));
2486 LookupContext = BaseTy->getAs<RecordType>()->getDecl();
Anders Carlsson59140b32009-08-28 03:16:11 +00002487 } else {
2488 // C++0x N2914 [namespace.udecl]p8:
2489 // A using-declaration for a class member shall be a member-declaration.
2490 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002491 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlsson59140b32009-08-28 03:16:11 +00002492 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002493 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002494 }
Mike Stump11289f42009-09-09 15:08:12 +00002495
Anders Carlsson59140b32009-08-28 03:16:11 +00002496 // C++0x N2914 [namespace.udecl]p9:
2497 // In a using-declaration, a prefix :: refers to the global namespace.
2498 if (NNS->getKind() == NestedNameSpecifier::Global)
2499 LookupContext = Context.getTranslationUnitDecl();
2500 else
2501 LookupContext = NNS->getAsNamespace();
2502 }
2503
2504
Douglas Gregorfec52632009-06-20 00:51:54 +00002505 // Lookup target name.
Mike Stump11289f42009-09-09 15:08:12 +00002506 LookupResult R = LookupQualifiedName(LookupContext,
Anders Carlsson59140b32009-08-28 03:16:11 +00002507 Name, LookupOrdinaryName);
Mike Stump11289f42009-09-09 15:08:12 +00002508
Anders Carlsson59140b32009-08-28 03:16:11 +00002509 if (!R) {
Anders Carlsson5167a462009-08-30 00:58:45 +00002510 DiagnoseMissingMember(IdentLoc, Name, NNS, SS.getRange());
Anders Carlsson696a3f12009-08-28 05:40:36 +00002511 return 0;
Douglas Gregorfec52632009-06-20 00:51:54 +00002512 }
2513
Anders Carlsson59140b32009-08-28 03:16:11 +00002514 NamedDecl *ND = R.getAsDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002515
Anders Carlsson59140b32009-08-28 03:16:11 +00002516 if (IsTypeName && !isa<TypeDecl>(ND)) {
2517 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlsson696a3f12009-08-28 05:40:36 +00002518 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002519 }
2520
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002521 // C++0x N2914 [namespace.udecl]p6:
2522 // A using-declaration shall not name a namespace.
2523 if (isa<NamespaceDecl>(ND)) {
2524 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2525 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002526 return 0;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002527 }
Mike Stump11289f42009-09-09 15:08:12 +00002528
Anders Carlsson696a3f12009-08-28 05:40:36 +00002529 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2530 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregorfec52632009-06-20 00:51:54 +00002531}
2532
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002533/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2534/// is a namespace alias, returns the namespace it points to.
2535static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2536 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2537 return AD->getNamespace();
2538 return dyn_cast_or_null<NamespaceDecl>(D);
2539}
2540
Mike Stump11289f42009-09-09 15:08:12 +00002541Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00002542 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00002543 SourceLocation AliasLoc,
2544 IdentifierInfo *Alias,
2545 const CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00002546 SourceLocation IdentLoc,
2547 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00002548
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002549 // Lookup the namespace name.
2550 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
2551
Anders Carlssondca83c42009-03-28 06:23:46 +00002552 // Check if we have a previous declaration with the same name.
Anders Carlsson36949352009-03-28 23:49:35 +00002553 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002554 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00002555 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002556 // namespace, so don't create a new one.
2557 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
2558 return DeclPtrTy();
2559 }
Mike Stump11289f42009-09-09 15:08:12 +00002560
Anders Carlssondca83c42009-03-28 06:23:46 +00002561 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2562 diag::err_redefinition_different_kind;
2563 Diag(AliasLoc, DiagID) << Alias;
2564 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00002565 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00002566 }
2567
Anders Carlssonac2c9652009-03-28 06:42:02 +00002568 if (R.isAmbiguous()) {
Anders Carlsson47952ae2009-03-28 22:53:22 +00002569 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002570 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00002571 }
Mike Stump11289f42009-09-09 15:08:12 +00002572
Anders Carlssonac2c9652009-03-28 06:42:02 +00002573 if (!R) {
2574 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00002575 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00002576 }
Mike Stump11289f42009-09-09 15:08:12 +00002577
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002578 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00002579 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2580 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00002581 (NestedNameSpecifier *)SS.getScopeRep(),
Anders Carlssonff25fdf2009-03-28 22:58:02 +00002582 IdentLoc, R);
Mike Stump11289f42009-09-09 15:08:12 +00002583
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002584 CurContext->addDecl(AliasDecl);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00002585 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00002586}
2587
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002588void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2589 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00002590 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2591 !Constructor->isUsed()) &&
2592 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00002593
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002594 CXXRecordDecl *ClassDecl
2595 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002596 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Mike Stump11289f42009-09-09 15:08:12 +00002597 // Before the implicitly-declared default constructor for a class is
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002598 // implicitly defined, all the implicitly-declared default constructors
2599 // for its base class and its non-static data members shall have been
2600 // implicitly defined.
2601 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00002602 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2603 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002604 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002605 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002606 if (!BaseClassDecl->hasTrivialConstructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00002607 if (CXXConstructorDecl *BaseCtor =
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00002608 BaseClassDecl->getDefaultConstructor(Context))
2609 MarkDeclarationReferenced(CurrentLocation, BaseCtor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002610 else {
Mike Stump11289f42009-09-09 15:08:12 +00002611 Diag(CurrentLocation, diag::err_defining_default_ctor)
2612 << Context.getTagDeclType(ClassDecl) << 1
Fariborz Jahanian1c9d5d92009-06-20 20:23:38 +00002613 << Context.getTagDeclType(BaseClassDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002614 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian1c9d5d92009-06-20 20:23:38 +00002615 << Context.getTagDeclType(BaseClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002616 err = true;
2617 }
2618 }
2619 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00002620 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2621 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002622 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2623 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2624 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002625 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002626 CXXRecordDecl *FieldClassDecl
2627 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Duncan Sands323fc2a2009-06-25 09:03:06 +00002628 if (!FieldClassDecl->hasTrivialConstructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00002629 if (CXXConstructorDecl *FieldCtor =
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00002630 FieldClassDecl->getDefaultConstructor(Context))
2631 MarkDeclarationReferenced(CurrentLocation, FieldCtor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002632 else {
Mike Stump11289f42009-09-09 15:08:12 +00002633 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian1c9d5d92009-06-20 20:23:38 +00002634 << Context.getTagDeclType(ClassDecl) << 0 <<
2635 Context.getTagDeclType(FieldClassDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002636 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian1c9d5d92009-06-20 20:23:38 +00002637 << Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002638 err = true;
2639 }
2640 }
Mike Stump12b8ce12009-08-04 21:02:39 +00002641 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002642 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson52b91802009-07-09 17:37:12 +00002643 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002644 Diag((*Field)->getLocation(), diag::note_declared_at);
2645 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002646 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00002647 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson52b91802009-07-09 17:37:12 +00002648 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002649 Diag((*Field)->getLocation(), diag::note_declared_at);
2650 err = true;
2651 }
2652 }
2653 if (!err)
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00002654 Constructor->setUsed();
2655 else
2656 Constructor->setInvalidDecl();
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002657}
2658
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002659void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00002660 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002661 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2662 "DefineImplicitDestructor - call it for implicit default dtor");
Mike Stump11289f42009-09-09 15:08:12 +00002663
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002664 CXXRecordDecl *ClassDecl
2665 = cast<CXXRecordDecl>(Destructor->getDeclContext());
2666 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2667 // C++ [class.dtor] p5
Mike Stump11289f42009-09-09 15:08:12 +00002668 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002669 // implicitly defined, all the implicitly-declared default destructors
2670 // for its base class and its non-static data members shall have been
2671 // implicitly defined.
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00002672 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2673 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002674 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002675 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002676 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00002677 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002678 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2679 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2680 else
Mike Stump11289f42009-09-09 15:08:12 +00002681 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002682 "DefineImplicitDestructor - missing dtor in a base class");
2683 }
2684 }
Mike Stump11289f42009-09-09 15:08:12 +00002685
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00002686 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2687 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002688 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2689 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2690 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002691 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002692 CXXRecordDecl *FieldClassDecl
2693 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2694 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00002695 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002696 const_cast<CXXDestructorDecl*>(
2697 FieldClassDecl->getDestructor(Context)))
2698 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
2699 else
Mike Stump11289f42009-09-09 15:08:12 +00002700 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002701 "DefineImplicitDestructor - missing dtor in class of a data member");
2702 }
2703 }
2704 }
2705 Destructor->setUsed();
2706}
2707
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002708void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
2709 CXXMethodDecl *MethodDecl) {
2710 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
2711 MethodDecl->getOverloadedOperator() == OO_Equal &&
2712 !MethodDecl->isUsed()) &&
2713 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump11289f42009-09-09 15:08:12 +00002714
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002715 CXXRecordDecl *ClassDecl
2716 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00002717
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00002718 // C++[class.copy] p12
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002719 // Before the implicitly-declared copy assignment operator for a class is
2720 // implicitly defined, all implicitly-declared copy assignment operators
2721 // for its direct base classes and its nonstatic data members shall have
2722 // been implicitly defined.
2723 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00002724 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2725 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002726 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002727 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002728 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002729 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
2730 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
2731 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00002732 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2733 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002734 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2735 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2736 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002737 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002738 CXXRecordDecl *FieldClassDecl
2739 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002740 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002741 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
2742 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump12b8ce12009-08-04 21:02:39 +00002743 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002744 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00002745 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
2746 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002747 Diag(CurrentLocation, diag::note_first_required_here);
2748 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002749 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00002750 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00002751 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
2752 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002753 Diag(CurrentLocation, diag::note_first_required_here);
2754 err = true;
2755 }
2756 }
2757 if (!err)
Mike Stump11289f42009-09-09 15:08:12 +00002758 MethodDecl->setUsed();
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002759}
2760
2761CXXMethodDecl *
2762Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
2763 CXXRecordDecl *ClassDecl) {
2764 QualType LHSType = Context.getTypeDeclType(ClassDecl);
2765 QualType RHSType(LHSType);
2766 // If class's assignment operator argument is const/volatile qualified,
Mike Stump11289f42009-09-09 15:08:12 +00002767 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002768 // operator = (B&).
2769 if (ParmDecl->getType().isConstQualified())
2770 RHSType.addConst();
2771 if (ParmDecl->getType().isVolatileQualified())
2772 RHSType.addVolatile();
Mike Stump11289f42009-09-09 15:08:12 +00002773 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
2774 LHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002775 SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00002776 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
2777 RHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002778 SourceLocation()));
2779 Expr *Args[2] = { &*LHS, &*RHS };
2780 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00002781 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002782 CandidateSet);
2783 OverloadCandidateSet::iterator Best;
Mike Stump11289f42009-09-09 15:08:12 +00002784 if (BestViableFunction(CandidateSet,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002785 ClassDecl->getLocation(), Best) == OR_Success)
2786 return cast<CXXMethodDecl>(Best->Function);
2787 assert(false &&
2788 "getAssignOperatorMethod - copy assignment operator method not found");
2789 return 0;
2790}
2791
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002792void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2793 CXXConstructorDecl *CopyConstructor,
2794 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00002795 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002796 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
2797 !CopyConstructor->isUsed()) &&
2798 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00002799
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002800 CXXRecordDecl *ClassDecl
2801 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
2802 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00002803 // C++ [class.copy] p209
Mike Stump11289f42009-09-09 15:08:12 +00002804 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002805 // implicitly defined, all the implicitly-declared copy constructors
2806 // for its base class and its non-static data members shall have been
2807 // implicitly defined.
2808 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2809 Base != ClassDecl->bases_end(); ++Base) {
2810 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002811 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002812 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002813 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00002814 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002815 }
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002816 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2817 FieldEnd = ClassDecl->field_end();
2818 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002819 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2820 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2821 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002822 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002823 CXXRecordDecl *FieldClassDecl
2824 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002825 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002826 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00002827 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002828 }
2829 }
2830 CopyConstructor->setUsed();
2831}
2832
Anders Carlsson6eb55572009-08-25 05:12:04 +00002833Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00002834Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00002835 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00002836 MultiExprArg ExprArgs) {
Anders Carlsson250aada2009-08-16 05:13:48 +00002837 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00002838
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002839 // C++ [class.copy]p15:
2840 // Whenever a temporary class object is copied using a copy constructor, and
2841 // this object and the copy have the same cv-unqualified type, an
2842 // implementation is permitted to treat the original and the copy as two
2843 // different ways of referring to the same object and not perform a copy at
2844 // all, even if the class copy constructor or destructor have side effects.
Mike Stump11289f42009-09-09 15:08:12 +00002845
Anders Carlsson250aada2009-08-16 05:13:48 +00002846 // FIXME: Is this enough?
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002847 if (Constructor->isCopyConstructor(Context)) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00002848 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson250aada2009-08-16 05:13:48 +00002849 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2850 E = BE->getSubExpr();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002851 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2852 if (ICE->getCastKind() == CastExpr::CK_NoOp)
2853 E = ICE->getSubExpr();
2854
Anders Carlsson250aada2009-08-16 05:13:48 +00002855 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
2856 Elidable = true;
2857 }
Mike Stump11289f42009-09-09 15:08:12 +00002858
2859 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00002860 Elidable, move(ExprArgs));
Anders Carlsson250aada2009-08-16 05:13:48 +00002861}
2862
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00002863/// BuildCXXConstructExpr - Creates a complete call to a constructor,
2864/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00002865Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00002866Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2867 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00002868 MultiExprArg ExprArgs) {
2869 unsigned NumExprs = ExprArgs.size();
2870 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00002871
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002872 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
2873 Elidable, Exprs, NumExprs));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00002874}
2875
Anders Carlsson574315a2009-08-27 05:08:22 +00002876Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00002877Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
2878 QualType Ty,
2879 SourceLocation TyBeginLoc,
Anders Carlsson574315a2009-08-27 05:08:22 +00002880 MultiExprArg Args,
2881 SourceLocation RParenLoc) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002882 unsigned NumExprs = Args.size();
2883 Expr **Exprs = (Expr **)Args.release();
Mike Stump11289f42009-09-09 15:08:12 +00002884
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002885 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
2886 TyBeginLoc, Exprs,
2887 NumExprs, RParenLoc));
Anders Carlsson574315a2009-08-27 05:08:22 +00002888}
2889
2890
Mike Stump11289f42009-09-09 15:08:12 +00002891bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00002892 CXXConstructorDecl *Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00002893 QualType DeclInitType,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00002894 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00002895 OwningExprResult TempResult =
2896 BuildCXXConstructExpr(VD->getLocation(), DeclInitType, Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00002897 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00002898 if (TempResult.isInvalid())
2899 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002900
Anders Carlsson6eb55572009-08-25 05:12:04 +00002901 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00002902 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniand460cb42009-08-05 18:17:32 +00002903 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00002904 VD->setInit(Context, Temp);
Mike Stump11289f42009-09-09 15:08:12 +00002905
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00002906 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00002907}
2908
Mike Stump11289f42009-09-09 15:08:12 +00002909void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002910 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002911 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002912 if (!ClassDecl->hasTrivialDestructor())
Mike Stump11289f42009-09-09 15:08:12 +00002913 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002914 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahanian67828442009-08-03 19:13:25 +00002915 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002916}
2917
Mike Stump11289f42009-09-09 15:08:12 +00002918/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002919/// ActOnDeclarator, when a C++ direct initializer is present.
2920/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00002921void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
2922 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002923 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002924 SourceLocation *CommaLocs,
2925 SourceLocation RParenLoc) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002926 unsigned NumExprs = Exprs.size();
2927 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00002928 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002929
2930 // If there is no declaration, there was an error parsing it. Just ignore
2931 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00002932 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002933 return;
Mike Stump11289f42009-09-09 15:08:12 +00002934
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002935 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2936 if (!VDecl) {
2937 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
2938 RealDecl->setInvalidDecl();
2939 return;
2940 }
2941
Douglas Gregor402250f2009-08-26 21:14:46 +00002942 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00002943 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002944 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
2945 //
2946 // Clients that want to distinguish between the two forms, can check for
2947 // direct initializer using VarDecl::hasCXXDirectInitializer().
2948 // A major benefit is that clients that don't particularly care about which
2949 // exactly form was it (like the CodeGen) can handle both cases without
2950 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00002951
Douglas Gregor402250f2009-08-26 21:14:46 +00002952 // If either the declaration has a dependent type or if any of the expressions
2953 // is type-dependent, we represent the initialization via a ParenListExpr for
2954 // later use during template instantiation.
2955 if (VDecl->getType()->isDependentType() ||
2956 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
2957 // Let clients know that initialization was done with a direct initializer.
2958 VDecl->setCXXDirectInitializer(true);
Mike Stump11289f42009-09-09 15:08:12 +00002959
Douglas Gregor402250f2009-08-26 21:14:46 +00002960 // Store the initialization expressions as a ParenListExpr.
2961 unsigned NumExprs = Exprs.size();
Mike Stump11289f42009-09-09 15:08:12 +00002962 VDecl->setInit(Context,
Douglas Gregor402250f2009-08-26 21:14:46 +00002963 new (Context) ParenListExpr(Context, LParenLoc,
2964 (Expr **)Exprs.release(),
2965 NumExprs, RParenLoc));
2966 return;
2967 }
Mike Stump11289f42009-09-09 15:08:12 +00002968
Douglas Gregor402250f2009-08-26 21:14:46 +00002969
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002970 // C++ 8.5p11:
2971 // The form of initialization (using parentheses or '=') is generally
2972 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00002973 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00002974 QualType DeclInitType = VDecl->getType();
2975 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
2976 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00002977
Douglas Gregor4044d992009-03-24 16:43:20 +00002978 // FIXME: This isn't the right place to complete the type.
2979 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
2980 diag::err_typecheck_decl_incomplete_type)) {
2981 VDecl->setInvalidDecl();
2982 return;
2983 }
2984
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00002985 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002986 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2987
Douglas Gregorc28b57d2008-11-03 20:45:27 +00002988 CXXConstructorDecl *Constructor
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002989 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002990 move(Exprs),
Douglas Gregor6f543152008-11-05 15:29:30 +00002991 VDecl->getLocation(),
2992 SourceRange(VDecl->getLocation(),
2993 RParenLoc),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002994 VDecl->getDeclName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002995 IK_Direct,
2996 ConstructorArgs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002997 if (!Constructor)
Douglas Gregorc28b57d2008-11-03 20:45:27 +00002998 RealDecl->setInvalidDecl();
Anders Carlsson332ef552009-04-15 21:48:18 +00002999 else {
Anders Carlsson332ef552009-04-15 21:48:18 +00003000 VDecl->setCXXDirectInitializer(true);
Mike Stump11289f42009-09-09 15:08:12 +00003001 if (InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003002 move_arg(ConstructorArgs)))
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003003 RealDecl->setInvalidDecl();
Fariborz Jahanian67828442009-08-03 19:13:25 +00003004 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlsson332ef552009-04-15 21:48:18 +00003005 }
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003006 return;
3007 }
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003008
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003009 if (NumExprs > 1) {
Chris Lattnerf490e152008-11-19 05:27:50 +00003010 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3011 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003012 RealDecl->setInvalidDecl();
3013 return;
3014 }
3015
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003016 // Let clients know that initialization was done with a direct initializer.
3017 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003018
3019 assert(NumExprs == 1 && "Expected 1 expression");
3020 // Set the init expression, handles conversions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003021 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3022 /*DirectInit=*/true);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003023}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003024
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003025/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3026/// may occur as part of direct-initialization or copy-initialization.
3027///
3028/// \param ClassType the type of the object being initialized, which must have
3029/// class type.
3030///
3031/// \param ArgsPtr the arguments provided to initialize the object
3032///
3033/// \param Loc the source location where the initialization occurs
3034///
3035/// \param Range the source range that covers the entire initialization
3036///
3037/// \param InitEntity the name of the entity being initialized, if known
3038///
3039/// \param Kind the type of initialization being performed
3040///
3041/// \param ConvertedArgs a vector that will be filled in with the
3042/// appropriately-converted arguments to the constructor (if initialization
3043/// succeeded).
3044///
3045/// \returns the constructor used to initialize the object, if successful.
3046/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003047CXXConstructorDecl *
Douglas Gregor6f543152008-11-05 15:29:30 +00003048Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003049 MultiExprArg ArgsPtr,
Douglas Gregor6f543152008-11-05 15:29:30 +00003050 SourceLocation Loc, SourceRange Range,
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003051 DeclarationName InitEntity,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003052 InitializationKind Kind,
3053 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003054 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003055 assert(ClassRec && "Can only initialize a class type here");
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003056 Expr **Args = (Expr **)ArgsPtr.get();
3057 unsigned NumArgs = ArgsPtr.size();
3058
Mike Stump11289f42009-09-09 15:08:12 +00003059 // C++ [dcl.init]p14:
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003060 // If the initialization is direct-initialization, or if it is
3061 // copy-initialization where the cv-unqualified version of the
3062 // source type is the same class as, or a derived class of, the
3063 // class of the destination, constructors are considered. The
3064 // applicable constructors are enumerated (13.3.1.3), and the
3065 // best one is chosen through overload resolution (13.3). The
3066 // constructor so selected is called to initialize the object,
3067 // with the initializer expression(s) as its argument(s). If no
3068 // constructor applies, or the overload resolution is ambiguous,
3069 // the initialization is ill-formed.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003070 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3071 OverloadCandidateSet CandidateSet;
Douglas Gregor6f543152008-11-05 15:29:30 +00003072
3073 // Add constructors to the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00003074 DeclarationName ConstructorName
Douglas Gregor1349b452008-12-15 21:24:18 +00003075 = Context.DeclarationNames.getCXXConstructorName(
3076 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor55297ac2008-12-23 00:26:44 +00003077 DeclContext::lookup_const_iterator Con, ConEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003078 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor55297ac2008-12-23 00:26:44 +00003079 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003080 // Find the constructor (which may be a template).
3081 CXXConstructorDecl *Constructor = 0;
3082 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3083 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003084 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003085 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3086 else
3087 Constructor = cast<CXXConstructorDecl>(*Con);
3088
Douglas Gregor6f543152008-11-05 15:29:30 +00003089 if ((Kind == IK_Direct) ||
Mike Stump11289f42009-09-09 15:08:12 +00003090 (Kind == IK_Copy &&
Anders Carlssond20e7952009-08-28 16:57:08 +00003091 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003092 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
3093 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003094 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003095 Args, NumArgs, CandidateSet);
3096 else
3097 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3098 }
Douglas Gregor6f543152008-11-05 15:29:30 +00003099 }
3100
Douglas Gregor1349b452008-12-15 21:24:18 +00003101 // FIXME: When we decide not to synthesize the implicitly-declared
3102 // constructors, we'll need to make them appear here.
3103
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003104 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003105 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003106 case OR_Success:
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003107 // We found a constructor. Break out so that we can convert the arguments
3108 // appropriately.
3109 break;
Mike Stump11289f42009-09-09 15:08:12 +00003110
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003111 case OR_No_Viable_Function:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003112 if (InitEntity)
3113 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003114 << InitEntity << Range;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003115 else
3116 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003117 << ClassType << Range;
Sebastian Redl15b02d22008-11-22 13:44:36 +00003118 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003119 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003120
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003121 case OR_Ambiguous:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003122 if (InitEntity)
3123 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3124 else
3125 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003126 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3127 return 0;
Douglas Gregor171c45a2009-02-18 21:56:37 +00003128
3129 case OR_Deleted:
3130 if (InitEntity)
3131 Diag(Loc, diag::err_ovl_deleted_init)
3132 << Best->Function->isDeleted()
3133 << InitEntity << Range;
3134 else
3135 Diag(Loc, diag::err_ovl_deleted_init)
3136 << Best->Function->isDeleted()
3137 << InitEntity << Range;
3138 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3139 return 0;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003140 }
Mike Stump11289f42009-09-09 15:08:12 +00003141
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003142 // Convert the arguments, fill in default arguments, etc.
3143 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3144 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3145 return 0;
3146
3147 return Constructor;
3148}
3149
3150/// \brief Given a constructor and the set of arguments provided for the
3151/// constructor, convert the arguments and add any required default arguments
3152/// to form a proper call to this constructor.
3153///
3154/// \returns true if an error occurred, false otherwise.
3155bool
3156Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3157 MultiExprArg ArgsPtr,
3158 SourceLocation Loc,
3159 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3160 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3161 unsigned NumArgs = ArgsPtr.size();
3162 Expr **Args = (Expr **)ArgsPtr.get();
3163
3164 const FunctionProtoType *Proto
3165 = Constructor->getType()->getAs<FunctionProtoType>();
3166 assert(Proto && "Constructor without a prototype?");
3167 unsigned NumArgsInProto = Proto->getNumArgs();
3168 unsigned NumArgsToCheck = NumArgs;
3169
3170 // If too few arguments are available, we'll fill in the rest with defaults.
3171 if (NumArgs < NumArgsInProto) {
3172 NumArgsToCheck = NumArgsInProto;
3173 ConvertedArgs.reserve(NumArgsInProto);
3174 } else {
3175 ConvertedArgs.reserve(NumArgs);
3176 if (NumArgs > NumArgsInProto)
3177 NumArgsToCheck = NumArgsInProto;
3178 }
3179
3180 // Convert arguments
3181 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3182 QualType ProtoArgType = Proto->getArgType(i);
3183
3184 Expr *Arg;
3185 if (i < NumArgs) {
3186 Arg = Args[i];
3187
3188 // Pass the argument.
3189 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3190 return true;
3191
3192 Args[i] = 0;
3193 } else {
3194 ParmVarDecl *Param = Constructor->getParamDecl(i);
3195
3196 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3197 if (DefArg.isInvalid())
3198 return true;
3199
3200 Arg = DefArg.takeAs<Expr>();
3201 }
3202
3203 ConvertedArgs.push_back(Arg);
3204 }
3205
3206 // If this is a variadic call, handle args passed through "...".
3207 if (Proto->isVariadic()) {
3208 // Promote the arguments (C99 6.5.2.2p7).
3209 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3210 Expr *Arg = Args[i];
3211 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3212 return true;
3213
3214 ConvertedArgs.push_back(Arg);
3215 Args[i] = 0;
3216 }
3217 }
3218
3219 return false;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003220}
3221
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003222/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3223/// determine whether they are reference-related,
3224/// reference-compatible, reference-compatible with added
3225/// qualification, or incompatible, for use in C++ initialization by
3226/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3227/// type, and the first type (T1) is the pointee type of the reference
3228/// type being initialized.
Mike Stump11289f42009-09-09 15:08:12 +00003229Sema::ReferenceCompareResult
3230Sema::CompareReferenceRelationship(QualType T1, QualType T2,
Douglas Gregor786ab212008-10-29 02:00:59 +00003231 bool& DerivedToBase) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003232 assert(!T1->isReferenceType() &&
3233 "T1 must be the pointee type of the reference type");
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003234 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
3235
3236 T1 = Context.getCanonicalType(T1);
3237 T2 = Context.getCanonicalType(T2);
3238 QualType UnqualT1 = T1.getUnqualifiedType();
3239 QualType UnqualT2 = T2.getUnqualifiedType();
3240
3241 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003242 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump11289f42009-09-09 15:08:12 +00003243 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003244 // T1 is a base class of T2.
Douglas Gregor786ab212008-10-29 02:00:59 +00003245 if (UnqualT1 == UnqualT2)
3246 DerivedToBase = false;
3247 else if (IsDerivedFrom(UnqualT2, UnqualT1))
3248 DerivedToBase = true;
3249 else
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003250 return Ref_Incompatible;
3251
3252 // At this point, we know that T1 and T2 are reference-related (at
3253 // least).
3254
3255 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003256 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003257 // reference-related to T2 and cv1 is the same cv-qualification
3258 // as, or greater cv-qualification than, cv2. For purposes of
3259 // overload resolution, cases for which cv1 is greater
3260 // cv-qualification than cv2 are identified as
3261 // reference-compatible with added qualification (see 13.3.3.2).
3262 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3263 return Ref_Compatible;
3264 else if (T1.isMoreQualifiedThan(T2))
3265 return Ref_Compatible_With_Added_Qualification;
3266 else
3267 return Ref_Related;
3268}
3269
3270/// CheckReferenceInit - Check the initialization of a reference
3271/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3272/// the initializer (either a simple initializer or an initializer
Douglas Gregor23a1f192008-10-29 23:31:03 +00003273/// list), and DeclType is the type of the declaration. When ICS is
3274/// non-null, this routine will compute the implicit conversion
3275/// sequence according to C++ [over.ics.ref] and will not produce any
3276/// diagnostics; when ICS is null, it will emit diagnostics when any
3277/// errors are found. Either way, a return value of true indicates
3278/// that there was a failure, a return value of false indicates that
3279/// the reference initialization succeeded.
Douglas Gregor2fe98832008-11-03 19:09:14 +00003280///
3281/// When @p SuppressUserConversions, user-defined conversions are
3282/// suppressed.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003283/// When @p AllowExplicit, we also permit explicit user-defined
3284/// conversion functions.
Sebastian Redl42e92c42009-04-12 17:16:29 +00003285/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Mike Stump11289f42009-09-09 15:08:12 +00003286bool
Sebastian Redl1a99f442009-04-16 17:51:27 +00003287Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003288 bool SuppressUserConversions,
Anders Carlsson271e3a42009-08-27 17:30:43 +00003289 bool AllowExplicit, bool ForceRValue,
3290 ImplicitConversionSequence *ICS) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003291 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3292
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003293 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003294 QualType T2 = Init->getType();
3295
Douglas Gregorcd695e52008-11-10 20:40:00 +00003296 // If the initializer is the address of an overloaded function, try
3297 // to resolve the overloaded function. If all goes well, T2 is the
3298 // type of the resulting function.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003299 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump11289f42009-09-09 15:08:12 +00003300 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003301 ICS != 0);
3302 if (Fn) {
3303 // Since we're performing this reference-initialization for
3304 // real, update the initializer with the resulting function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003305 if (!ICS) {
3306 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
3307 return true;
3308
Douglas Gregorcd695e52008-11-10 20:40:00 +00003309 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor171c45a2009-02-18 21:56:37 +00003310 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003311
3312 T2 = Fn->getType();
3313 }
3314 }
3315
Douglas Gregor786ab212008-10-29 02:00:59 +00003316 // Compute some basic properties of the types and the initializer.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003317 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor786ab212008-10-29 02:00:59 +00003318 bool DerivedToBase = false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00003319 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3320 Init->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003321 ReferenceCompareResult RefRelationship
Douglas Gregor786ab212008-10-29 02:00:59 +00003322 = CompareReferenceRelationship(T1, T2, DerivedToBase);
3323
3324 // Most paths end in a failed conversion.
3325 if (ICS)
3326 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003327
3328 // C++ [dcl.init.ref]p5:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003329 // A reference to type "cv1 T1" is initialized by an expression
3330 // of type "cv2 T2" as follows:
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003331
3332 // -- If the initializer expression
3333
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003334 // Rvalue references cannot bind to lvalues (N2812).
3335 // There is absolutely no situation where they can. In particular, note that
3336 // this is ill-formed, even if B has a user-defined conversion to A&&:
3337 // B b;
3338 // A&& r = b;
3339 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3340 if (!ICS)
3341 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
3342 << Init->getSourceRange();
3343 return true;
3344 }
3345
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003346 bool BindsDirectly = false;
Eli Friedman44b83ee2009-08-05 19:21:58 +00003347 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3348 // reference-compatible with "cv2 T2," or
Douglas Gregor786ab212008-10-29 02:00:59 +00003349 //
3350 // Note that the bit-field check is skipped if we are just computing
3351 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor71235ec2009-05-02 02:18:30 +00003352 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003353 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003354 BindsDirectly = true;
3355
Douglas Gregor786ab212008-10-29 02:00:59 +00003356 if (ICS) {
3357 // C++ [over.ics.ref]p1:
3358 // When a parameter of reference type binds directly (8.5.3)
3359 // to an argument expression, the implicit conversion sequence
3360 // is the identity conversion, unless the argument expression
3361 // has a type that is a derived class of the parameter type,
3362 // in which case the implicit conversion sequence is a
3363 // derived-to-base Conversion (13.3.3.1).
3364 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3365 ICS->Standard.First = ICK_Identity;
3366 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3367 ICS->Standard.Third = ICK_Identity;
3368 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3369 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003370 ICS->Standard.ReferenceBinding = true;
3371 ICS->Standard.DirectBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003372 ICS->Standard.RRefBinding = false;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003373 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00003374
3375 // Nothing more to do: the inaccessibility/ambiguity check for
3376 // derived-to-base conversions is suppressed when we're
3377 // computing the implicit conversion sequence (C++
3378 // [over.best.ics]p2).
3379 return false;
3380 } else {
3381 // Perform the conversion.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003382 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3383 if (DerivedToBase)
3384 CK = CastExpr::CK_DerivedToBase;
3385 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003386 }
3387 }
3388
3389 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman44b83ee2009-08-05 19:21:58 +00003390 // implicitly converted to an lvalue of type "cv3 T3,"
3391 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003392 // 92) (this conversion is selected by enumerating the
3393 // applicable conversion functions (13.3.1.6) and choosing
3394 // the best one through overload resolution (13.3)),
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003395 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
3396 !RequireCompleteType(SourceLocation(), T2, 0)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003397 // FIXME: Look for conversions in base classes!
Mike Stump11289f42009-09-09 15:08:12 +00003398 CXXRecordDecl *T2RecordDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003399 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003400
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003401 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003402 OverloadedFunctionDecl *Conversions
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003403 = T2RecordDecl->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00003404 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003405 = Conversions->function_begin();
3406 Func != Conversions->function_end(); ++Func) {
Mike Stump11289f42009-09-09 15:08:12 +00003407 FunctionTemplateDecl *ConvTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00003408 = dyn_cast<FunctionTemplateDecl>(*Func);
3409 CXXConversionDecl *Conv;
3410 if (ConvTemplate)
3411 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3412 else
3413 Conv = cast<CXXConversionDecl>(*Func);
Sebastian Redlb7d64912009-03-22 21:28:55 +00003414
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003415 // If the conversion function doesn't return a reference type,
3416 // it can't be considered for this conversion.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003417 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor05155d82009-08-21 23:19:43 +00003418 (AllowExplicit || !Conv->isExplicit())) {
3419 if (ConvTemplate)
Mike Stump11289f42009-09-09 15:08:12 +00003420 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003421 CandidateSet);
3422 else
3423 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3424 }
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003425 }
3426
3427 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003428 switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003429 case OR_Success:
3430 // This is a direct binding.
3431 BindsDirectly = true;
3432
3433 if (ICS) {
3434 // C++ [over.ics.ref]p1:
3435 //
3436 // [...] If the parameter binds directly to the result of
3437 // applying a conversion function to the argument
3438 // expression, the implicit conversion sequence is a
3439 // user-defined conversion sequence (13.3.3.1.2), with the
3440 // second standard conversion sequence either an identity
3441 // conversion or, if the conversion function returns an
3442 // entity of a type that is a derived class of the parameter
3443 // type, a derived-to-base Conversion.
3444 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3445 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3446 ICS->UserDefined.After = Best->FinalConversion;
3447 ICS->UserDefined.ConversionFunction = Best->Function;
3448 assert(ICS->UserDefined.After.ReferenceBinding &&
3449 ICS->UserDefined.After.DirectBinding &&
3450 "Expected a direct reference binding!");
3451 return false;
3452 } else {
3453 // Perform the conversion.
Mike Stump87c57ac2009-05-16 07:39:55 +00003454 // FIXME: Binding to a subobject of the lvalue is going to require more
3455 // AST annotation than this.
Anders Carlssona076d142009-07-31 01:23:52 +00003456 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003457 }
3458 break;
3459
3460 case OR_Ambiguous:
3461 assert(false && "Ambiguous reference binding conversions not implemented.");
3462 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003463
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003464 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003465 case OR_Deleted:
3466 // There was no suitable conversion, or we found a deleted
3467 // conversion; continue with other checks.
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003468 break;
3469 }
3470 }
Mike Stump11289f42009-09-09 15:08:12 +00003471
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003472 if (BindsDirectly) {
3473 // C++ [dcl.init.ref]p4:
3474 // [...] In all cases where the reference-related or
3475 // reference-compatible relationship of two types is used to
3476 // establish the validity of a reference binding, and T1 is a
3477 // base class of T2, a program that necessitates such a binding
3478 // is ill-formed if T1 is an inaccessible (clause 11) or
3479 // ambiguous (10.2) base class of T2.
3480 //
3481 // Note that we only check this condition when we're allowed to
3482 // complain about errors, because we should not be checking for
3483 // ambiguity (or inaccessibility) unless the reference binding
3484 // actually happens.
Mike Stump11289f42009-09-09 15:08:12 +00003485 if (DerivedToBase)
3486 return CheckDerivedToBaseConversion(T2, T1,
Douglas Gregor786ab212008-10-29 02:00:59 +00003487 Init->getSourceRange().getBegin(),
3488 Init->getSourceRange());
3489 else
3490 return false;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003491 }
3492
3493 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003494 // type (i.e., cv1 shall be const), or the reference shall be an
3495 // rvalue reference and the initializer expression shall be an rvalue.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003496 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor786ab212008-10-29 02:00:59 +00003497 if (!ICS)
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003498 Diag(Init->getSourceRange().getBegin(),
Chris Lattner377d1f82008-11-18 22:52:51 +00003499 diag::err_not_reference_to_const_init)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003500 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3501 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003502 return true;
3503 }
3504
3505 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman44b83ee2009-08-05 19:21:58 +00003506 // class type, and "cv1 T1" is reference-compatible with
3507 // "cv2 T2," the reference is bound in one of the
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003508 // following ways (the choice is implementation-defined):
3509 //
3510 // -- The reference is bound to the object represented by
3511 // the rvalue (see 3.10) or to a sub-object within that
3512 // object.
3513 //
Eli Friedman44b83ee2009-08-05 19:21:58 +00003514 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003515 // a constructor is called to copy the entire rvalue
3516 // object into the temporary. The reference is bound to
3517 // the temporary or to a sub-object within the
3518 // temporary.
3519 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003520 // The constructor that would be used to make the copy
3521 // shall be callable whether or not the copy is actually
3522 // done.
3523 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003524 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003525 // freedom, so we will always take the first option and never build
3526 // a temporary in this case. FIXME: We will, however, have to check
3527 // for the presence of a copy constructor in C++98/03 mode.
3528 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003529 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3530 if (ICS) {
3531 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3532 ICS->Standard.First = ICK_Identity;
3533 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3534 ICS->Standard.Third = ICK_Identity;
3535 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3536 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003537 ICS->Standard.ReferenceBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003538 ICS->Standard.DirectBinding = false;
3539 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003540 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00003541 } else {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003542 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3543 if (DerivedToBase)
3544 CK = CastExpr::CK_DerivedToBase;
3545 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003546 }
3547 return false;
3548 }
3549
Eli Friedman44b83ee2009-08-05 19:21:58 +00003550 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003551 // initialized from the initializer expression using the
3552 // rules for a non-reference copy initialization (8.5). The
3553 // reference is then bound to the temporary. If T1 is
3554 // reference-related to T2, cv1 must be the same
3555 // cv-qualification as, or greater cv-qualification than,
3556 // cv2; otherwise, the program is ill-formed.
3557 if (RefRelationship == Ref_Related) {
3558 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3559 // we would be reference-compatible or reference-compatible with
3560 // added qualification. But that wasn't the case, so the reference
3561 // initialization fails.
Douglas Gregor786ab212008-10-29 02:00:59 +00003562 if (!ICS)
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003563 Diag(Init->getSourceRange().getBegin(),
Chris Lattner377d1f82008-11-18 22:52:51 +00003564 diag::err_reference_init_drops_quals)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003565 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3566 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003567 return true;
3568 }
3569
Douglas Gregor576e98c2009-01-30 23:27:23 +00003570 // If at least one of the types is a class type, the types are not
3571 // related, and we aren't allowed any user conversions, the
3572 // reference binding fails. This case is important for breaking
3573 // recursion, since TryImplicitConversion below will attempt to
3574 // create a temporary through the use of a copy constructor.
3575 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3576 (T1->isRecordType() || T2->isRecordType())) {
3577 if (!ICS)
3578 Diag(Init->getSourceRange().getBegin(),
3579 diag::err_typecheck_convert_incompatible)
3580 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3581 return true;
3582 }
3583
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003584 // Actually try to convert the initializer to T1.
Douglas Gregor786ab212008-10-29 02:00:59 +00003585 if (ICS) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003586 // C++ [over.ics.ref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00003587 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003588 // When a parameter of reference type is not bound directly to
3589 // an argument expression, the conversion sequence is the one
3590 // required to convert the argument expression to the
3591 // underlying type of the reference according to
3592 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3593 // to copy-initializing a temporary of the underlying type with
3594 // the argument expression. Any difference in top-level
3595 // cv-qualification is subsumed by the initialization itself
3596 // and does not constitute a conversion.
Anders Carlssonef4c7212009-08-27 17:24:15 +00003597 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
3598 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00003599 /*ForceRValue=*/false,
3600 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003601
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003602 // Of course, that's still a reference binding.
3603 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3604 ICS->Standard.ReferenceBinding = true;
3605 ICS->Standard.RRefBinding = isRValRef;
Mike Stump11289f42009-09-09 15:08:12 +00003606 } else if (ICS->ConversionKind ==
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003607 ImplicitConversionSequence::UserDefinedConversion) {
3608 ICS->UserDefined.After.ReferenceBinding = true;
3609 ICS->UserDefined.After.RRefBinding = isRValRef;
3610 }
Douglas Gregor786ab212008-10-29 02:00:59 +00003611 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3612 } else {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003613 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor786ab212008-10-29 02:00:59 +00003614 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003615}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003616
3617/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3618/// of this overloaded operator is well-formed. If so, returns false;
3619/// otherwise, emits appropriate diagnostics and returns true.
3620bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00003621 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003622 "Expected an overloaded operator declaration");
3623
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003624 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
3625
Mike Stump11289f42009-09-09 15:08:12 +00003626 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003627 // The allocation and deallocation functions, operator new,
3628 // operator new[], operator delete and operator delete[], are
3629 // described completely in 3.7.3. The attributes and restrictions
3630 // found in the rest of this subclause do not apply to them unless
3631 // explicitly stated in 3.7.3.
Mike Stump87c57ac2009-05-16 07:39:55 +00003632 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003633 if (Op == OO_New || Op == OO_Array_New ||
3634 Op == OO_Delete || Op == OO_Array_Delete)
3635 return false;
3636
3637 // C++ [over.oper]p6:
3638 // An operator function shall either be a non-static member
3639 // function or be a non-member function and have at least one
3640 // parameter whose type is a class, a reference to a class, an
3641 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00003642 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
3643 if (MethodDecl->isStatic())
3644 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003645 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003646 } else {
3647 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00003648 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
3649 ParamEnd = FnDecl->param_end();
3650 Param != ParamEnd; ++Param) {
3651 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00003652 if (ParamType->isDependentType() || ParamType->isRecordType() ||
3653 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003654 ClassOrEnumParam = true;
3655 break;
3656 }
3657 }
3658
Douglas Gregord69246b2008-11-17 16:14:12 +00003659 if (!ClassOrEnumParam)
3660 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00003661 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003662 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003663 }
3664
3665 // C++ [over.oper]p8:
3666 // An operator function cannot have default arguments (8.3.6),
3667 // except where explicitly stated below.
3668 //
Mike Stump11289f42009-09-09 15:08:12 +00003669 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003670 // (C++ [over.call]p1).
3671 if (Op != OO_Call) {
3672 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
3673 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor58354032008-12-24 00:01:03 +00003674 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00003675 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00003676 diag::err_operator_overload_default_arg)
3677 << FnDecl->getDeclName();
3678 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregord69246b2008-11-17 16:14:12 +00003679 return Diag((*Param)->getLocation(),
Chris Lattner29e812b2008-11-20 06:06:08 +00003680 diag::err_operator_overload_default_arg)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003681 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003682 }
3683 }
3684
Douglas Gregor6cf08062008-11-10 13:38:07 +00003685 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
3686 { false, false, false }
3687#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3688 , { Unary, Binary, MemberOnly }
3689#include "clang/Basic/OperatorKinds.def"
3690 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003691
Douglas Gregor6cf08062008-11-10 13:38:07 +00003692 bool CanBeUnaryOperator = OperatorUses[Op][0];
3693 bool CanBeBinaryOperator = OperatorUses[Op][1];
3694 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003695
3696 // C++ [over.oper]p8:
3697 // [...] Operator functions cannot have more or fewer parameters
3698 // than the number required for the corresponding operator, as
3699 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00003700 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00003701 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003702 if (Op != OO_Call &&
3703 ((NumParams == 1 && !CanBeUnaryOperator) ||
3704 (NumParams == 2 && !CanBeBinaryOperator) ||
3705 (NumParams < 1) || (NumParams > 2))) {
3706 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00003707 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00003708 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00003709 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00003710 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00003711 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00003712 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00003713 assert(CanBeBinaryOperator &&
3714 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00003715 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00003716 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003717
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00003718 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003719 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003720 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003721
Douglas Gregord69246b2008-11-17 16:14:12 +00003722 // Overloaded operators other than operator() cannot be variadic.
3723 if (Op != OO_Call &&
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003724 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00003725 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003726 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003727 }
3728
3729 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00003730 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
3731 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00003732 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003733 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003734 }
3735
3736 // C++ [over.inc]p1:
3737 // The user-defined function called operator++ implements the
3738 // prefix and postfix ++ operator. If this function is a member
3739 // function with no parameters, or a non-member function with one
3740 // parameter of class or enumeration type, it defines the prefix
3741 // increment operator ++ for objects of that type. If the function
3742 // is a member function with one parameter (which shall be of type
3743 // int) or a non-member function with two parameters (the second
3744 // of which shall be of type int), it defines the postfix
3745 // increment operator ++ for objects of that type.
3746 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
3747 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
3748 bool ParamIsInt = false;
3749 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
3750 ParamIsInt = BT->getKind() == BuiltinType::Int;
3751
Chris Lattner2b786902008-11-21 07:50:02 +00003752 if (!ParamIsInt)
3753 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003754 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003755 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003756 }
3757
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003758 // Notify the class if it got an assignment operator.
3759 if (Op == OO_Equal) {
3760 // Would have returned earlier otherwise.
3761 assert(isa<CXXMethodDecl>(FnDecl) &&
3762 "Overloaded = not member, but not filtered.");
3763 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Fariborz Jahanian4985b332009-08-13 21:09:41 +00003764 Method->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003765 Method->getParent()->addedAssignmentOperator(Context, Method);
3766 }
3767
Douglas Gregord69246b2008-11-17 16:14:12 +00003768 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003769}
Chris Lattner3b024a32008-12-17 07:09:26 +00003770
Douglas Gregor07665a62009-01-05 19:45:36 +00003771/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
3772/// linkage specification, including the language and (if present)
3773/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
3774/// the location of the language string literal, which is provided
3775/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
3776/// the '{' brace. Otherwise, this linkage specification does not
3777/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00003778Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
3779 SourceLocation ExternLoc,
3780 SourceLocation LangLoc,
3781 const char *Lang,
3782 unsigned StrSize,
3783 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00003784 LinkageSpecDecl::LanguageIDs Language;
3785 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3786 Language = LinkageSpecDecl::lang_c;
3787 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3788 Language = LinkageSpecDecl::lang_cxx;
3789 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00003790 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00003791 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00003792 }
Mike Stump11289f42009-09-09 15:08:12 +00003793
Chris Lattner438e5012008-12-17 07:13:27 +00003794 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00003795
Douglas Gregor07665a62009-01-05 19:45:36 +00003796 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00003797 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00003798 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003799 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00003800 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00003801 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00003802}
3803
Douglas Gregor07665a62009-01-05 19:45:36 +00003804/// ActOnFinishLinkageSpecification - Completely the definition of
3805/// the C++ linkage specification LinkageSpec. If RBraceLoc is
3806/// valid, it's the position of the closing '}' brace in a linkage
3807/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00003808Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
3809 DeclPtrTy LinkageSpec,
3810 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00003811 if (LinkageSpec)
3812 PopDeclContext();
3813 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00003814}
3815
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003816/// \brief Perform semantic analysis for the variable declaration that
3817/// occurs within a C++ catch clause, returning the newly-created
3818/// variable.
3819VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00003820 DeclaratorInfo *DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003821 IdentifierInfo *Name,
3822 SourceLocation Loc,
3823 SourceRange Range) {
3824 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00003825
3826 // Arrays and functions decay.
3827 if (ExDeclType->isArrayType())
3828 ExDeclType = Context.getArrayDecayedType(ExDeclType);
3829 else if (ExDeclType->isFunctionType())
3830 ExDeclType = Context.getPointerType(ExDeclType);
3831
3832 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
3833 // The exception-declaration shall not denote a pointer or reference to an
3834 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00003835 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00003836 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003837 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00003838 Invalid = true;
3839 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003840
Sebastian Redl54c04d42008-12-22 19:15:10 +00003841 QualType BaseType = ExDeclType;
3842 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00003843 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003844 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003845 BaseType = Ptr->getPointeeType();
3846 Mode = 1;
Douglas Gregordd430f72009-01-19 19:26:10 +00003847 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00003848 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00003849 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00003850 BaseType = Ref->getPointeeType();
3851 Mode = 2;
Douglas Gregordd430f72009-01-19 19:26:10 +00003852 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00003853 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00003854 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003855 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00003856 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00003857
Mike Stump11289f42009-09-09 15:08:12 +00003858 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003859 RequireNonAbstractType(Loc, ExDeclType,
3860 diag::err_abstract_type_in_decl,
3861 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00003862 Invalid = true;
3863
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003864 // FIXME: Need to test for ability to copy-construct and destroy the
3865 // exception variable.
3866
Sebastian Redl9b244a82008-12-22 21:35:02 +00003867 // FIXME: Need to check for abstract classes.
3868
Mike Stump11289f42009-09-09 15:08:12 +00003869 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003870 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003871
3872 if (Invalid)
3873 ExDecl->setInvalidDecl();
3874
3875 return ExDecl;
3876}
3877
3878/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
3879/// handler.
3880Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00003881 DeclaratorInfo *DInfo = 0;
3882 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003883
3884 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00003885 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor2ada0482009-02-04 17:27:36 +00003886 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003887 // The scope should be freshly made just for us. There is just no way
3888 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00003889 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00003890 if (PrevDecl->isTemplateParameter()) {
3891 // Maybe we will complain about the shadowed template parameter.
3892 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003893 }
3894 }
3895
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003896 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003897 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
3898 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003899 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00003900 }
3901
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00003902 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003903 D.getIdentifier(),
3904 D.getIdentifierLoc(),
3905 D.getDeclSpec().getSourceRange());
3906
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003907 if (Invalid)
3908 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003909
Sebastian Redl54c04d42008-12-22 19:15:10 +00003910 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00003911 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003912 PushOnScopeChains(ExDecl, S);
3913 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003914 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003915
Douglas Gregor758a8692009-06-17 21:51:59 +00003916 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00003917 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003918}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00003919
Mike Stump11289f42009-09-09 15:08:12 +00003920Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00003921 ExprArg assertexpr,
3922 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00003923 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00003924 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00003925 cast<StringLiteral>((Expr *)assertmessageexpr.get());
3926
Anders Carlsson54b26982009-03-14 00:33:21 +00003927 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
3928 llvm::APSInt Value(32);
3929 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
3930 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
3931 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00003932 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00003933 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00003934
Anders Carlsson54b26982009-03-14 00:33:21 +00003935 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00003936 std::string str(AssertMessage->getStrData(),
Anders Carlsson54b26982009-03-14 00:33:21 +00003937 AssertMessage->getByteLength());
Mike Stump11289f42009-09-09 15:08:12 +00003938 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson27de6a52009-03-15 18:44:04 +00003939 << str << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00003940 }
3941 }
Mike Stump11289f42009-09-09 15:08:12 +00003942
Anders Carlsson78e2bc02009-03-15 17:35:16 +00003943 assertexpr.release();
3944 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00003945 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00003946 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00003947
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003948 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00003949 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00003950}
Sebastian Redlf769df52009-03-24 22:27:57 +00003951
John McCall07e91c02009-08-06 02:15:43 +00003952Sema::DeclPtrTy Sema::ActOnFriendDecl(Scope *S,
John McCalld1e9d832009-08-11 06:59:38 +00003953 llvm::PointerUnion<const DeclSpec*,Declarator*> DU,
3954 bool IsDefinition) {
John McCallaa74a0c2009-08-28 07:59:38 +00003955 if (DU.is<Declarator*>())
3956 return ActOnFriendFunctionDecl(S, *DU.get<Declarator*>(), IsDefinition);
3957 else
3958 return ActOnFriendTypeDecl(S, *DU.get<const DeclSpec*>(), IsDefinition);
3959}
3960
3961Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S,
3962 const DeclSpec &DS,
3963 bool IsDefinition) {
3964 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00003965
3966 assert(DS.isFriendSpecified());
3967 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
3968
John McCalld8fe9af2009-09-08 17:47:29 +00003969 // Try to convert the decl specifier to a type.
3970 bool invalid = false;
3971 QualType T = ConvertDeclSpecToType(DS, Loc, invalid);
3972 if (invalid) return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00003973
John McCallaa74a0c2009-08-28 07:59:38 +00003974 // C++ [class.friend]p2:
3975 // An elaborated-type-specifier shall be used in a friend declaration
3976 // for a class.*
3977 // * The class-key of the elaborated-type-specifier is required.
John McCalld8fe9af2009-09-08 17:47:29 +00003978 // This is one of the rare places in Clang where it's legitimate to
3979 // ask about the "spelling" of the type.
3980 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
3981 // If we evaluated the type to a record type, suggest putting
3982 // a tag in front.
John McCallaa74a0c2009-08-28 07:59:38 +00003983 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00003984 RecordDecl *RD = RT->getDecl();
3985
3986 std::string InsertionText = std::string(" ") + RD->getKindName();
3987
3988 Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type)
3989 << (RD->isUnion())
3990 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
3991 InsertionText);
John McCallaa74a0c2009-08-28 07:59:38 +00003992 return DeclPtrTy();
3993 }else {
John McCalld8fe9af2009-09-08 17:47:29 +00003994 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
3995 << DS.getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003996 return DeclPtrTy();
John McCallaa74a0c2009-08-28 07:59:38 +00003997 }
3998 }
3999
John McCalld8fe9af2009-09-08 17:47:29 +00004000 FriendDecl::FriendUnion FU = T.getTypePtr();
4001
4002 // The parser doesn't quite handle
4003 // friend class A { ... }
4004 // optimally, because it might have been the (valid) prefix of
4005 // friend class A { ... } foo();
4006 // So in a very particular set of circumstances, we need to adjust
4007 // IsDefinition.
4008 //
4009 // Also, if we made a RecordDecl in ActOnTag, we want that to be the
4010 // object of our friend declaration.
4011 switch (DS.getTypeSpecType()) {
4012 default: break;
4013 case DeclSpec::TST_class:
4014 case DeclSpec::TST_struct:
4015 case DeclSpec::TST_union:
4016 CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep());
4017 if (RD) {
4018 IsDefinition |= RD->isDefinition();
4019 FU = RD;
4020 }
4021 break;
4022 }
John McCallaa74a0c2009-08-28 07:59:38 +00004023
4024 // C++ [class.friend]p2: A class shall not be defined inside
4025 // a friend declaration.
4026 if (IsDefinition) {
4027 Diag(DS.getFriendSpecLoc(), diag::err_friend_decl_defines_class)
4028 << DS.getSourceRange();
4029 return DeclPtrTy();
4030 }
4031
4032 // C++98 [class.friend]p1: A friend of a class is a function
4033 // or class that is not a member of the class . . .
4034 // But that's a silly restriction which nobody implements for
4035 // inner classes, and C++0x removes it anyway, so we only report
4036 // this (as a warning) if we're being pedantic.
John McCalld8fe9af2009-09-08 17:47:29 +00004037 if (!getLangOptions().CPlusPlus0x)
4038 if (const RecordType *RT = T->getAs<RecordType>())
4039 if (RT->getDecl()->getDeclContext() == CurContext)
4040 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCallaa74a0c2009-08-28 07:59:38 +00004041
4042 FriendDecl *FD = FriendDecl::Create(Context, CurContext, Loc, FU,
4043 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00004044 FD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00004045 CurContext->addDecl(FD);
4046
4047 return DeclPtrTy::make(FD);
4048}
4049
4050Sema::DeclPtrTy Sema::ActOnFriendFunctionDecl(Scope *S,
4051 Declarator &D,
4052 bool IsDefinition) {
4053 const DeclSpec &DS = D.getDeclSpec();
4054
4055 assert(DS.isFriendSpecified());
4056 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4057
4058 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004059 DeclaratorInfo *DInfo = 0;
John McCallaa74a0c2009-08-28 07:59:38 +00004060 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall07e91c02009-08-06 02:15:43 +00004061
4062 // C++ [class.friend]p1
4063 // A friend of a class is a function or class....
4064 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00004065 // It *doesn't* see through dependent types, which is correct
4066 // according to [temp.arg.type]p3:
4067 // If a declaration acquires a function type through a
4068 // type dependent on a template-parameter and this causes
4069 // a declaration that does not use the syntactic form of a
4070 // function declarator to have a function type, the program
4071 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00004072 if (!T->isFunctionType()) {
4073 Diag(Loc, diag::err_unexpected_friend);
4074
4075 // It might be worthwhile to try to recover by creating an
4076 // appropriate declaration.
4077 return DeclPtrTy();
4078 }
4079
4080 // C++ [namespace.memdef]p3
4081 // - If a friend declaration in a non-local class first declares a
4082 // class or function, the friend class or function is a member
4083 // of the innermost enclosing namespace.
4084 // - The name of the friend is not found by simple name lookup
4085 // until a matching declaration is provided in that namespace
4086 // scope (either before or after the class declaration granting
4087 // friendship).
4088 // - If a friend function is called, its name may be found by the
4089 // name lookup that considers functions from namespaces and
4090 // classes associated with the types of the function arguments.
4091 // - When looking for a prior declaration of a class or a function
4092 // declared as a friend, scopes outside the innermost enclosing
4093 // namespace scope are not considered.
4094
John McCallaa74a0c2009-08-28 07:59:38 +00004095 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4096 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00004097 assert(Name);
4098
4099 // The existing declaration we found.
4100 FunctionDecl *FD = NULL;
4101
4102 // The context we found the declaration in, or in which we should
4103 // create the declaration.
4104 DeclContext *DC;
4105
4106 // FIXME: handle local classes
4107
4108 // Recover from invalid scope qualifiers as if they just weren't there.
4109 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
4110 DC = computeDeclContext(ScopeQual);
4111
4112 // FIXME: handle dependent contexts
4113 if (!DC) return DeclPtrTy();
4114
4115 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
4116
4117 // If searching in that context implicitly found a declaration in
4118 // a different context, treat it like it wasn't found at all.
4119 // TODO: better diagnostics for this case. Suggesting the right
4120 // qualified scope would be nice...
4121 if (!Dec || Dec->getDeclContext() != DC) {
John McCallaa74a0c2009-08-28 07:59:38 +00004122 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00004123 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4124 return DeclPtrTy();
4125 }
4126
4127 // C++ [class.friend]p1: A friend of a class is a function or
4128 // class that is not a member of the class . . .
4129 if (DC == CurContext)
4130 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4131
4132 FD = cast<FunctionDecl>(Dec);
4133
4134 // Otherwise walk out to the nearest namespace scope looking for matches.
4135 } else {
4136 // TODO: handle local class contexts.
4137
4138 DC = CurContext;
4139 while (true) {
4140 // Skip class contexts. If someone can cite chapter and verse
4141 // for this behavior, that would be nice --- it's what GCC and
4142 // EDG do, and it seems like a reasonable intent, but the spec
4143 // really only says that checks for unqualified existing
4144 // declarations should stop at the nearest enclosing namespace,
4145 // not that they should only consider the nearest enclosing
4146 // namespace.
4147 while (DC->isRecord()) DC = DC->getParent();
4148
4149 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
4150
4151 // TODO: decide what we think about using declarations.
4152 if (Dec) {
4153 FD = cast<FunctionDecl>(Dec);
4154 break;
4155 }
4156 if (DC->isFileContext()) break;
4157 DC = DC->getParent();
4158 }
4159
4160 // C++ [class.friend]p1: A friend of a class is a function or
4161 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00004162 // C++0x changes this for both friend types and functions.
4163 // Most C++ 98 compilers do seem to give an error here, so
4164 // we do, too.
4165 if (FD && DC == CurContext && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00004166 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4167 }
4168
John McCalld1e9d832009-08-11 06:59:38 +00004169 bool Redeclaration = (FD != 0);
4170
4171 // If we found a match, create a friend function declaration with
4172 // that function as the previous declaration.
4173 if (Redeclaration) {
4174 // Create it in the semantic context of the original declaration.
4175 DC = FD->getDeclContext();
4176
John McCall07e91c02009-08-06 02:15:43 +00004177 // If we didn't find something matching the type exactly, create
4178 // a declaration. This declaration should only be findable via
4179 // argument-dependent lookup.
John McCalld1e9d832009-08-11 06:59:38 +00004180 } else {
John McCall07e91c02009-08-06 02:15:43 +00004181 assert(DC->isFileContext());
4182
4183 // This implies that it has to be an operator or function.
John McCallaa74a0c2009-08-28 07:59:38 +00004184 if (D.getKind() == Declarator::DK_Constructor ||
4185 D.getKind() == Declarator::DK_Destructor ||
4186 D.getKind() == Declarator::DK_Conversion) {
John McCall07e91c02009-08-06 02:15:43 +00004187 Diag(Loc, diag::err_introducing_special_friend) <<
John McCallaa74a0c2009-08-28 07:59:38 +00004188 (D.getKind() == Declarator::DK_Constructor ? 0 :
4189 D.getKind() == Declarator::DK_Destructor ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00004190 return DeclPtrTy();
4191 }
John McCall07e91c02009-08-06 02:15:43 +00004192 }
4193
John McCallaa74a0c2009-08-28 07:59:38 +00004194 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo,
John McCalld1e9d832009-08-11 06:59:38 +00004195 /* PrevDecl = */ FD,
4196 MultiTemplateParamsArg(*this),
4197 IsDefinition,
4198 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00004199 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00004200
4201 assert(cast<FunctionDecl>(ND)->getPreviousDeclaration() == FD &&
4202 "lost reference to previous declaration");
4203
John McCallaa74a0c2009-08-28 07:59:38 +00004204 FD = cast<FunctionDecl>(ND);
John McCalld1e9d832009-08-11 06:59:38 +00004205
John McCall5ed6e8f2009-08-18 00:00:49 +00004206 assert(FD->getDeclContext() == DC);
4207 assert(FD->getLexicalDeclContext() == CurContext);
4208
John McCall759e32b2009-08-31 22:39:49 +00004209 // Add the function declaration to the appropriate lookup tables,
4210 // adjusting the redeclarations list as necessary. We don't
4211 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00004212 //
John McCall759e32b2009-08-31 22:39:49 +00004213 // Also update the scope-based lookup if the target context's
4214 // lookup context is in lexical scope.
4215 if (!CurContext->isDependentContext()) {
4216 DC = DC->getLookupContext();
4217 DC->makeDeclVisibleInContext(FD, /* Recoverable=*/ false);
4218 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4219 PushOnScopeChains(FD, EnclosingScope, /*AddToContext=*/ false);
4220 }
John McCallaa74a0c2009-08-28 07:59:38 +00004221
4222 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
4223 D.getIdentifierLoc(), FD,
4224 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00004225 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00004226 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00004227
4228 return DeclPtrTy::make(FD);
Anders Carlsson38811702009-05-11 22:55:49 +00004229}
4230
Chris Lattner83f095c2009-03-28 19:18:32 +00004231void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004232 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004233
Chris Lattner83f095c2009-03-28 19:18:32 +00004234 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00004235 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4236 if (!Fn) {
4237 Diag(DelLoc, diag::err_deleted_non_function);
4238 return;
4239 }
4240 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4241 Diag(DelLoc, diag::err_deleted_decl_not_first);
4242 Diag(Prev->getLocation(), diag::note_previous_declaration);
4243 // If the declaration wasn't the first, we delete the function anyway for
4244 // recovery.
4245 }
4246 Fn->setDeleted();
4247}
Sebastian Redl4c018662009-04-27 21:33:24 +00004248
4249static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4250 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4251 ++CI) {
4252 Stmt *SubStmt = *CI;
4253 if (!SubStmt)
4254 continue;
4255 if (isa<ReturnStmt>(SubStmt))
4256 Self.Diag(SubStmt->getSourceRange().getBegin(),
4257 diag::err_return_in_constructor_handler);
4258 if (!isa<Expr>(SubStmt))
4259 SearchForReturnInStmt(Self, SubStmt);
4260 }
4261}
4262
4263void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4264 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4265 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4266 SearchForReturnInStmt(*this, Handler);
4267 }
4268}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004269
Mike Stump11289f42009-09-09 15:08:12 +00004270bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004271 const CXXMethodDecl *Old) {
4272 QualType NewTy = New->getType()->getAsFunctionType()->getResultType();
4273 QualType OldTy = Old->getType()->getAsFunctionType()->getResultType();
4274
4275 QualType CNewTy = Context.getCanonicalType(NewTy);
4276 QualType COldTy = Context.getCanonicalType(OldTy);
4277
Mike Stump11289f42009-09-09 15:08:12 +00004278 if (CNewTy == COldTy &&
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004279 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
4280 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004281
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004282 // Check if the return types are covariant
4283 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00004284
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004285 /// Both types must be pointers or references to classes.
4286 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4287 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4288 NewClassTy = NewPT->getPointeeType();
4289 OldClassTy = OldPT->getPointeeType();
4290 }
4291 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4292 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4293 NewClassTy = NewRT->getPointeeType();
4294 OldClassTy = OldRT->getPointeeType();
4295 }
4296 }
Mike Stump11289f42009-09-09 15:08:12 +00004297
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004298 // The return types aren't either both pointers or references to a class type.
4299 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00004300 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004301 diag::err_different_return_type_for_overriding_virtual_function)
4302 << New->getDeclName() << NewTy << OldTy;
4303 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00004304
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004305 return true;
4306 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004307
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004308 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
4309 // Check if the new class derives from the old class.
4310 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4311 Diag(New->getLocation(),
4312 diag::err_covariant_return_not_derived)
4313 << New->getDeclName() << NewTy << OldTy;
4314 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4315 return true;
4316 }
Mike Stump11289f42009-09-09 15:08:12 +00004317
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004318 // Check if we the conversion from derived to base is valid.
Mike Stump11289f42009-09-09 15:08:12 +00004319 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004320 diag::err_covariant_return_inaccessible_base,
4321 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4322 // FIXME: Should this point to the return type?
4323 New->getLocation(), SourceRange(), New->getDeclName())) {
4324 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4325 return true;
4326 }
4327 }
Mike Stump11289f42009-09-09 15:08:12 +00004328
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004329 // The qualifiers of the return types must be the same.
4330 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
4331 Diag(New->getLocation(),
4332 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004333 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004334 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4335 return true;
4336 };
Mike Stump11289f42009-09-09 15:08:12 +00004337
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004338
4339 // The new class type must have the same or less qualifiers as the old type.
4340 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4341 Diag(New->getLocation(),
4342 diag::err_covariant_return_type_class_type_more_qualified)
4343 << New->getDeclName() << NewTy << OldTy;
4344 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4345 return true;
4346 };
Mike Stump11289f42009-09-09 15:08:12 +00004347
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004348 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004349}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004350
Sebastian Redl86be8542009-07-07 20:29:57 +00004351bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
Mike Stump11289f42009-09-09 15:08:12 +00004352 const CXXMethodDecl *Old) {
Sebastian Redl86be8542009-07-07 20:29:57 +00004353 return CheckExceptionSpecSubset(diag::err_override_exception_spec,
4354 diag::note_overridden_virtual_function,
4355 Old->getType()->getAsFunctionProtoType(),
4356 Old->getLocation(),
4357 New->getType()->getAsFunctionProtoType(),
4358 New->getLocation());
4359}
4360
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004361/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4362/// initializer for the declaration 'Dcl'.
4363/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4364/// static data member of class X, names should be looked up in the scope of
4365/// class X.
4366void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004367 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004368
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004369 Decl *D = Dcl.getAs<Decl>();
4370 // If there is no declaration, there was an error parsing it.
4371 if (D == 0)
4372 return;
4373
4374 // Check whether it is a declaration with a nested name specifier like
4375 // int foo::bar;
4376 if (!D->isOutOfLine())
4377 return;
Mike Stump11289f42009-09-09 15:08:12 +00004378
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004379 // C++ [basic.lookup.unqual]p13
4380 //
4381 // A name used in the definition of a static data member of class X
4382 // (after the qualified-id of the static member) is looked up as if the name
4383 // was used in a member function of X.
Mike Stump11289f42009-09-09 15:08:12 +00004384
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004385 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004386 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004387}
4388
4389/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4390/// initializer for the declaration 'Dcl'.
4391void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004392 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004393
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004394 Decl *D = Dcl.getAs<Decl>();
4395 // If there is no declaration, there was an error parsing it.
4396 if (D == 0)
4397 return;
4398
4399 // Check whether it is a declaration with a nested name specifier like
4400 // int foo::bar;
4401 if (!D->isOutOfLine())
4402 return;
4403
4404 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004405 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004406}