blob: 3e832025752ac9cf90e0ffb7fcf4b38086649e79 [file] [log] [blame]
Chris Lattner3d1cee32008-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 Gregor7ad83902008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregor02189362008-10-22 21:13:31 +000019#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000020#include "clang/AST/StmtVisitor.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000021#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000022#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000023#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Chris Lattner8123a952008-04-10 02:22:51 +000025#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000026#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000027#include <map>
Chris Lattner3d1cee32008-04-08 05:04:30 +000028
29using namespace clang;
30
Chris Lattner8123a952008-04-10 02:22:51 +000031//===----------------------------------------------------------------------===//
32// CheckDefaultArgumentVisitor
33//===----------------------------------------------------------------------===//
34
Chris Lattner9e979552008-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 Stump1eb44332009-09-09 15:08:12 +000041 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000042 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000043 Expr *DefaultArg;
44 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000045
Chris Lattner9e979552008-04-12 23:52:44 +000046 public:
Mike Stump1eb44332009-09-09 15:08:12 +000047 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000048 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000049
Chris Lattner9e979552008-04-12 23:52:44 +000050 bool VisitExpr(Expr *Node);
51 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000052 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000053 };
Chris Lattner8123a952008-04-10 02:22:51 +000054
Chris Lattner9e979552008-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 Stump1eb44332009-09-09 15:08:12 +000058 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000059 E = Node->child_end(); I != E; ++I)
60 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000061 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000062 }
63
Chris Lattner9e979552008-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 Gregor8e9bebd2008-10-21 16:13:35 +000068 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-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 Stump1eb44332009-09-09 15:08:12 +000078 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000079 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000080 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000081 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000082 // C++ [dcl.fct.default]p7
83 // Local variables shall not be used in default argument
84 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000085 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000088 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000089 }
Chris Lattner8123a952008-04-10 02:22:51 +000090
Douglas Gregor3996f232008-11-04 13:41:56 +000091 return false;
92 }
Chris Lattner9e979552008-04-12 23:52:44 +000093
Douglas Gregor796da182008-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 Lattnerfa25bbb2008-11-19 05:08:23 +0000100 diag::err_param_default_argument_references_this)
101 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000102 }
Chris Lattner8123a952008-04-10 02:22:51 +0000103}
104
Anders Carlssoned961f92009-08-25 02:29:20 +0000105bool
106Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000107 SourceLocation EqualLoc) {
Anders Carlssoned961f92009-08-25 02:29:20 +0000108 QualType ParamType = Param->getType();
109
Anders Carlsson5653ca52009-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 Carlssoned961f92009-08-25 02:29:20 +0000116 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000117
Anders Carlssoned961f92009-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 Stump1eb44332009-09-09 15:08:12 +0000124 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssoned961f92009-08-25 02:29:20 +0000125 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson9351c172009-08-25 03:18:48 +0000126 return true;
Anders Carlssoned961f92009-08-25 02:29:20 +0000127
128 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Anders Carlssoned961f92009-08-25 02:29:20 +0000130 // Okay: add the default argument to the parameter
131 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000132
Anders Carlssoned961f92009-08-25 02:29:20 +0000133 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000134
Anders Carlsson9351c172009-08-25 03:18:48 +0000135 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000136}
137
Chris Lattner8123a952008-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 Lattner3d1cee32008-04-08 05:04:30 +0000141void
Mike Stump1eb44332009-09-09 15:08:12 +0000142Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000143 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000144 if (!param || !defarg.get())
145 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Chris Lattnerb28317a2009-03-28 19:18:32 +0000147 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000148 UnparsedDefaultArgLocs.erase(Param);
149
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000150 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000151 QualType ParamType = Param->getType();
152
153 // Default arguments are only permitted in C++
154 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000155 Diag(EqualLoc, diag::err_param_default_argument)
156 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000157 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000158 return;
159 }
160
Anders Carlsson66e30672009-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 Stump1eb44332009-09-09 15:08:12 +0000167
Anders Carlssoned961f92009-08-25 02:29:20 +0000168 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000169}
170
Douglas Gregor61366e92008-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 Stump1eb44332009-09-09 15:08:12 +0000175void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000176 SourceLocation EqualLoc,
177 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000178 if (!param)
179 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Chris Lattnerb28317a2009-03-28 19:18:32 +0000181 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000182 if (Param)
183 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Anders Carlsson5e300d12009-06-12 16:51:40 +0000185 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000186}
187
Douglas Gregor72b505b2008-12-16 21:30:33 +0000188/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
189/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000190void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000191 if (!param)
192 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000193
Anders Carlsson5e300d12009-06-12 16:51:40 +0000194 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Anders Carlsson5e300d12009-06-12 16:51:40 +0000196 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Anders Carlsson5e300d12009-06-12 16:51:40 +0000198 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000199}
200
Douglas Gregor6d6eb572008-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 Lattnerb28317a2009-03-28 19:18:32 +0000214 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000215 DeclaratorChunk &chunk = D.getTypeObject(i);
216 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-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 Gregor61366e92008-12-24 00:01:03 +0000220 if (Param->hasUnparsedDefaultArg()) {
221 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-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 Gregor61366e92008-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 Gregor6d6eb572008-05-07 04:49:29 +0000230 }
231 }
232 }
233 }
234}
235
Chris Lattner3d1cee32008-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 Gregorcda9c672009-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 Lattner3d1cee32008-04-08 05:04:30 +0000243 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000244 // For non-template functions, default arguments can be added in
245 // later declarations of a function in the same
246 // scope. Declarations in different scopes have completely
247 // distinct sets of default arguments. That is, declarations in
248 // inner scopes do not acquire default arguments from
249 // declarations in outer scopes, and vice versa. In a given
250 // function declaration, all parameters subsequent to a
251 // parameter with a default argument shall have default
252 // arguments supplied in this or previous declarations. A
253 // default argument shall not be redefined by a later
254 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000255 //
256 // C++ [dcl.fct.default]p6:
257 // Except for member functions of class templates, the default arguments
258 // in a member function definition that appears outside of the class
259 // definition are added to the set of default arguments provided by the
260 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000261 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
262 ParmVarDecl *OldParam = Old->getParamDecl(p);
263 ParmVarDecl *NewParam = New->getParamDecl(p);
264
Douglas Gregor6cc15182009-09-11 18:44:32 +0000265 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000266 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000267 diag::err_param_default_argument_redefinition)
Douglas Gregor6cc15182009-09-11 18:44:32 +0000268 << NewParam->getDefaultArgRange();
269
270 // Look for the function declaration where the default argument was
271 // actually written, which may be a declaration prior to Old.
272 for (FunctionDecl *Older = Old->getPreviousDeclaration();
273 Older; Older = Older->getPreviousDeclaration()) {
274 if (!Older->getParamDecl(p)->hasDefaultArg())
275 break;
276
277 OldParam = Older->getParamDecl(p);
278 }
279
280 Diag(OldParam->getLocation(), diag::note_previous_definition)
281 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000282 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000283 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000284 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000285 if (OldParam->hasUninstantiatedDefaultArg())
286 NewParam->setUninstantiatedDefaultArg(
287 OldParam->getUninstantiatedDefaultArg());
288 else
289 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000290 } else if (NewParam->hasDefaultArg()) {
291 if (New->getDescribedFunctionTemplate()) {
292 // Paragraph 4, quoted above, only applies to non-template functions.
293 Diag(NewParam->getLocation(),
294 diag::err_param_default_argument_template_redecl)
295 << NewParam->getDefaultArgRange();
296 Diag(Old->getLocation(), diag::note_template_prev_declaration)
297 << false;
298 } else if (New->getDeclContext()->isDependentContext()) {
299 // C++ [dcl.fct.default]p6 (DR217):
300 // Default arguments for a member function of a class template shall
301 // be specified on the initial declaration of the member function
302 // within the class template.
303 //
304 // Reading the tea leaves a bit in DR217 and its reference to DR205
305 // leads me to the conclusion that one cannot add default function
306 // arguments for an out-of-line definition of a member function of a
307 // dependent type.
308 int WhichKind = 2;
309 if (CXXRecordDecl *Record
310 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
311 if (Record->getDescribedClassTemplate())
312 WhichKind = 0;
313 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
314 WhichKind = 1;
315 else
316 WhichKind = 2;
317 }
318
319 Diag(NewParam->getLocation(),
320 diag::err_param_default_argument_member_template_redecl)
321 << WhichKind
322 << NewParam->getDefaultArgRange();
323 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000324 }
325 }
326
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000327 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000328 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
329 New->getType()->getAs<FunctionProtoType>(), New->getLocation())) {
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000330 Invalid = true;
331 }
332
Douglas Gregorcda9c672009-02-16 17:45:42 +0000333 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000334}
335
336/// CheckCXXDefaultArguments - Verify that the default arguments for a
337/// function declaration are well-formed according to C++
338/// [dcl.fct.default].
339void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
340 unsigned NumParams = FD->getNumParams();
341 unsigned p;
342
343 // Find first parameter with a default argument
344 for (p = 0; p < NumParams; ++p) {
345 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000346 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000347 break;
348 }
349
350 // C++ [dcl.fct.default]p4:
351 // In a given function declaration, all parameters
352 // subsequent to a parameter with a default argument shall
353 // have default arguments supplied in this or previous
354 // declarations. A default argument shall not be redefined
355 // by a later declaration (not even to the same value).
356 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000357 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000358 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000359 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000360 if (Param->isInvalidDecl())
361 /* We already complained about this parameter. */;
362 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000363 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000364 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000365 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000366 else
Mike Stump1eb44332009-09-09 15:08:12 +0000367 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000368 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Chris Lattner3d1cee32008-04-08 05:04:30 +0000370 LastMissingDefaultArg = p;
371 }
372 }
373
374 if (LastMissingDefaultArg > 0) {
375 // Some default arguments were missing. Clear out all of the
376 // default arguments up to (and including) the last missing
377 // default argument, so that we leave the function parameters
378 // in a semantically valid state.
379 for (p = 0; p <= LastMissingDefaultArg; ++p) {
380 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000381 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000382 if (!Param->hasUnparsedDefaultArg())
383 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000384 Param->setDefaultArg(0);
385 }
386 }
387 }
388}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000389
Douglas Gregorb48fe382008-10-31 09:07:45 +0000390/// isCurrentClassName - Determine whether the identifier II is the
391/// name of the class type currently being defined. In the case of
392/// nested classes, this will only return true if II is the name of
393/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000394bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
395 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000396 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000397 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000398 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000399 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
400 } else
401 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
402
403 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000404 return &II == CurDecl->getIdentifier();
405 else
406 return false;
407}
408
Mike Stump1eb44332009-09-09 15:08:12 +0000409/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000410///
411/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
412/// and returns NULL otherwise.
413CXXBaseSpecifier *
414Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
415 SourceRange SpecifierRange,
416 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000417 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000418 SourceLocation BaseLoc) {
419 // C++ [class.union]p1:
420 // A union shall not have base classes.
421 if (Class->isUnion()) {
422 Diag(Class->getLocation(), diag::err_base_clause_on_union)
423 << SpecifierRange;
424 return 0;
425 }
426
427 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000428 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000429 Class->getTagKind() == RecordDecl::TK_class,
430 Access, BaseType);
431
432 // Base specifiers must be record types.
433 if (!BaseType->isRecordType()) {
434 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
435 return 0;
436 }
437
438 // C++ [class.union]p1:
439 // A union shall not be used as a base class.
440 if (BaseType->isUnionType()) {
441 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
442 return 0;
443 }
444
445 // C++ [class.derived]p2:
446 // The class-name in a base-specifier shall not be an incompletely
447 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000448 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000449 PDiag(diag::err_incomplete_base_class)
450 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000451 return 0;
452
Eli Friedman1d954f62009-08-15 21:55:26 +0000453 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000454 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000455 assert(BaseDecl && "Record type has no declaration");
456 BaseDecl = BaseDecl->getDefinition(Context);
457 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000458 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
459 assert(CXXBaseDecl && "Base type is not a C++ type");
460 if (!CXXBaseDecl->isEmpty())
461 Class->setEmpty(false);
462 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor2943aed2009-03-03 04:44:36 +0000463 Class->setPolymorphic(true);
464
465 // C++ [dcl.init.aggr]p1:
466 // An aggregate is [...] a class with [...] no base classes [...].
467 Class->setAggregate(false);
468 Class->setPOD(false);
469
Anders Carlsson347ba892009-04-16 00:08:20 +0000470 if (Virtual) {
471 // C++ [class.ctor]p5:
472 // A constructor is trivial if its class has no virtual base classes.
473 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000474
475 // C++ [class.copy]p6:
476 // A copy constructor is trivial if its class has no virtual base classes.
477 Class->setHasTrivialCopyConstructor(false);
478
479 // C++ [class.copy]p11:
480 // A copy assignment operator is trivial if its class has no virtual
481 // base classes.
482 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000483
484 // C++0x [meta.unary.prop] is_empty:
485 // T is a class type, but not a union type, with ... no virtual base
486 // classes
487 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000488 } else {
489 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000490 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000491 // class have trivial constructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000492 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
493 Class->setHasTrivialConstructor(false);
494
495 // C++ [class.copy]p6:
496 // A copy constructor is trivial if all the direct base classes of its
497 // class have trivial copy constructors.
498 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
499 Class->setHasTrivialCopyConstructor(false);
500
501 // C++ [class.copy]p11:
502 // A copy assignment operator is trivial if all the direct base classes
503 // of its class have trivial copy assignment operators.
504 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
505 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000506 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000507
508 // C++ [class.ctor]p3:
509 // A destructor is trivial if all the direct base classes of its class
510 // have trivial destructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000511 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
512 Class->setHasTrivialDestructor(false);
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Douglas Gregor2943aed2009-03-03 04:44:36 +0000514 // Create the base specifier.
515 // FIXME: Allocate via ASTContext?
Mike Stump1eb44332009-09-09 15:08:12 +0000516 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
517 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000518 Access, BaseType);
519}
520
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000521/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
522/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000523/// example:
524/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000525/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000526Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000527Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000528 bool Virtual, AccessSpecifier Access,
529 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000530 if (!classdecl)
531 return true;
532
Douglas Gregor40808ce2009-03-09 23:48:35 +0000533 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000534 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000535 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000536 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
537 Virtual, Access,
538 BaseType, BaseLoc))
539 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Douglas Gregor2943aed2009-03-03 04:44:36 +0000541 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000542}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000543
Douglas Gregor2943aed2009-03-03 04:44:36 +0000544/// \brief Performs the actual work of attaching the given base class
545/// specifiers to a C++ class.
546bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
547 unsigned NumBases) {
548 if (NumBases == 0)
549 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000550
551 // Used to keep track of which base types we have already seen, so
552 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000553 // that the key is always the unqualified canonical type of the base
554 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000555 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
556
557 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000558 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000559 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000560 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000561 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000562 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor57c856b2008-10-23 18:13:27 +0000563 NewBaseType = NewBaseType.getUnqualifiedType();
564
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000565 if (KnownBaseTypes[NewBaseType]) {
566 // C++ [class.mi]p3:
567 // A class shall not be specified as a direct base class of a
568 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000569 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000570 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000571 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000572 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000573
574 // Delete the duplicate base class specifier; we're going to
575 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000576 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000577
578 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000579 } else {
580 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000581 KnownBaseTypes[NewBaseType] = Bases[idx];
582 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000583 }
584 }
585
586 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000587 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000588
589 // Delete the remaining (good) base class specifiers, since their
590 // data has been copied into the CXXRecordDecl.
591 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000592 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000593
594 return Invalid;
595}
596
597/// ActOnBaseSpecifiers - Attach the given base specifiers to the
598/// class, after checking whether there are any duplicate base
599/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000600void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000601 unsigned NumBases) {
602 if (!ClassDecl || !Bases || !NumBases)
603 return;
604
605 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000606 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000607 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000608}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000609
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000610//===----------------------------------------------------------------------===//
611// C++ class member Handling
612//===----------------------------------------------------------------------===//
613
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000614/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
615/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
616/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000617/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000618Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000619Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000620 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redle2b68332009-04-12 17:16:29 +0000621 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000622 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000623 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000624 Expr *BitWidth = static_cast<Expr*>(BW);
625 Expr *Init = static_cast<Expr*>(InitExpr);
626 SourceLocation Loc = D.getIdentifierLoc();
627
Sebastian Redl669d5d72008-11-14 23:42:31 +0000628 bool isFunc = D.isFunctionDeclarator();
629
John McCall67d1a672009-08-06 02:15:43 +0000630 assert(!DS.isFriendSpecified());
631
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000632 // C++ 9.2p6: A member shall not be declared to have automatic storage
633 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000634 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
635 // data members and cannot be applied to names declared const or static,
636 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000637 switch (DS.getStorageClassSpec()) {
638 case DeclSpec::SCS_unspecified:
639 case DeclSpec::SCS_typedef:
640 case DeclSpec::SCS_static:
641 // FALL THROUGH.
642 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000643 case DeclSpec::SCS_mutable:
644 if (isFunc) {
645 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000646 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000647 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000648 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000649
Sebastian Redla11f42f2008-11-17 23:24:37 +0000650 // FIXME: It would be nicer if the keyword was ignored only for this
651 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000652 D.getMutableDeclSpec().ClearStorageClassSpecs();
653 } else {
654 QualType T = GetTypeForDeclarator(D, S);
655 diag::kind err = static_cast<diag::kind>(0);
656 if (T->isReferenceType())
657 err = diag::err_mutable_reference;
658 else if (T.isConstQualified())
659 err = diag::err_mutable_const;
660 if (err != 0) {
661 if (DS.getStorageClassSpecLoc().isValid())
662 Diag(DS.getStorageClassSpecLoc(), err);
663 else
664 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000665 // FIXME: It would be nicer if the keyword was ignored only for this
666 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000667 D.getMutableDeclSpec().ClearStorageClassSpecs();
668 }
669 }
670 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000671 default:
672 if (DS.getStorageClassSpecLoc().isValid())
673 Diag(DS.getStorageClassSpecLoc(),
674 diag::err_storageclass_invalid_for_member);
675 else
676 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
677 D.getMutableDeclSpec().ClearStorageClassSpecs();
678 }
679
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000680 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000681 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000682 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000683 // Check also for this case:
684 //
685 // typedef int f();
686 // f a;
687 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000688 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000689 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000690 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000691
Sebastian Redl669d5d72008-11-14 23:42:31 +0000692 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
693 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000694 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000695
696 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000697 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000698 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000699 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
700 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000701 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000702 } else {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000703 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
704 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000705 if (!Member) {
706 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000707 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000708 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000709
710 // Non-instance-fields can't have a bitfield.
711 if (BitWidth) {
712 if (Member->isInvalidDecl()) {
713 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000714 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000715 // C++ 9.6p3: A bit-field shall not be a static member.
716 // "static member 'A' cannot be a bit-field"
717 Diag(Loc, diag::err_static_not_bitfield)
718 << Name << BitWidth->getSourceRange();
719 } else if (isa<TypedefDecl>(Member)) {
720 // "typedef member 'x' cannot be a bit-field"
721 Diag(Loc, diag::err_typedef_not_bitfield)
722 << Name << BitWidth->getSourceRange();
723 } else {
724 // A function typedef ("typedef int f(); f a;").
725 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
726 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000727 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000728 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000729 }
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Chris Lattner8b963ef2009-03-05 23:01:03 +0000731 DeleteExpr(BitWidth);
732 BitWidth = 0;
733 Member->setInvalidDecl();
734 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000735
736 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Douglas Gregor37b372b2009-08-20 22:52:58 +0000738 // If we have declared a member function template, set the access of the
739 // templated declaration as well.
740 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
741 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000742 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000743
Douglas Gregor10bd3682008-11-17 22:58:34 +0000744 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000745
Douglas Gregor021c3b32009-03-11 23:00:04 +0000746 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000747 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000748 if (Deleted) // FIXME: Source location is not very good.
749 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000750
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000751 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000752 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000753 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000754 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000755 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000756}
757
Douglas Gregor7ad83902008-11-05 04:29:56 +0000758/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000759Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000760Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000761 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000762 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000763 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000764 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000765 SourceLocation IdLoc,
766 SourceLocation LParenLoc,
767 ExprTy **Args, unsigned NumArgs,
768 SourceLocation *CommaLocs,
769 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000770 if (!ConstructorD)
771 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000773 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +0000774
775 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000776 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000777 if (!Constructor) {
778 // The user wrote a constructor initializer on a function that is
779 // not a C++ constructor. Ignore the error for now, because we may
780 // have more member initializers coming; we'll diagnose it just
781 // once in ActOnMemInitializers.
782 return true;
783 }
784
785 CXXRecordDecl *ClassDecl = Constructor->getParent();
786
787 // C++ [class.base.init]p2:
788 // Names in a mem-initializer-id are looked up in the scope of the
789 // constructor’s class and, if not found in that scope, are looked
790 // up in the scope containing the constructor’s
791 // definition. [Note: if the constructor’s class contains a member
792 // with the same name as a direct or virtual base class of the
793 // class, a mem-initializer-id naming the member or base class and
794 // composed of a single identifier refers to the class member. A
795 // mem-initializer-id for the hidden base class may be specified
796 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000797 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000798 // Look for a member, first.
799 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000800 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000801 = ClassDecl->lookup(MemberOrBase);
802 if (Result.first != Result.second)
803 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000804
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000805 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000806
Eli Friedman59c04372009-07-29 19:44:27 +0000807 if (Member)
808 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
809 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000810 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000811 // It didn't name a member, so see if it names a class.
Mike Stump1eb44332009-09-09 15:08:12 +0000812 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanian96174332009-07-01 19:21:19 +0000813 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000814 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000815 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
816 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000818 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000819
Eli Friedman59c04372009-07-29 19:44:27 +0000820 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
821 RParenLoc, ClassDecl);
822}
823
824Sema::MemInitResult
825Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
826 unsigned NumArgs, SourceLocation IdLoc,
827 SourceLocation RParenLoc) {
828 bool HasDependentArg = false;
829 for (unsigned i = 0; i < NumArgs; i++)
830 HasDependentArg |= Args[i]->isTypeDependent();
831
832 CXXConstructorDecl *C = 0;
833 QualType FieldType = Member->getType();
834 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
835 FieldType = Array->getElementType();
836 if (FieldType->isDependentType()) {
837 // Can't check init for dependent type.
Ted Kremenek6217b802009-07-29 21:53:49 +0000838 } else if (FieldType->getAs<RecordType>()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000839 if (!HasDependentArg) {
840 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
841
842 C = PerformInitializationByConstructor(FieldType,
843 MultiExprArg(*this,
844 (void**)Args,
845 NumArgs),
846 IdLoc,
847 SourceRange(IdLoc, RParenLoc),
848 Member->getDeclName(), IK_Direct,
849 ConstructorArgs);
850
851 if (C) {
852 // Take over the constructor arguments as our own.
853 NumArgs = ConstructorArgs.size();
854 Args = (Expr **)ConstructorArgs.take();
855 }
856 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +0000857 } else if (NumArgs != 1 && NumArgs != 0) {
Mike Stump1eb44332009-09-09 15:08:12 +0000858 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +0000859 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
860 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +0000861 Expr *NewExp;
862 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000863 if (FieldType->isReferenceType()) {
864 Diag(IdLoc, diag::err_null_intialized_reference_member)
865 << Member->getDeclName();
866 return Diag(Member->getLocation(), diag::note_declared_at);
867 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +0000868 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
869 NumArgs = 1;
870 }
871 else
872 NewExp = (Expr*)Args[0];
Eli Friedman59c04372009-07-29 19:44:27 +0000873 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
874 return true;
875 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +0000876 }
Eli Friedman59c04372009-07-29 19:44:27 +0000877 // FIXME: Perform direct initialization of the member.
Mike Stump1eb44332009-09-09 15:08:12 +0000878 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +0000879 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +0000880}
881
882Sema::MemInitResult
883Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
884 unsigned NumArgs, SourceLocation IdLoc,
885 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
886 bool HasDependentArg = false;
887 for (unsigned i = 0; i < NumArgs; i++)
888 HasDependentArg |= Args[i]->isTypeDependent();
889
890 if (!BaseType->isDependentType()) {
891 if (!BaseType->isRecordType())
892 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
893 << BaseType << SourceRange(IdLoc, RParenLoc);
894
895 // C++ [class.base.init]p2:
896 // [...] Unless the mem-initializer-id names a nonstatic data
897 // member of the constructor’s class or a direct or virtual base
898 // of that class, the mem-initializer is ill-formed. A
899 // mem-initializer-list can initialize a base class using any
900 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Eli Friedman59c04372009-07-29 19:44:27 +0000902 // First, check for a direct base class.
903 const CXXBaseSpecifier *DirectBaseSpec = 0;
904 for (CXXRecordDecl::base_class_const_iterator Base =
905 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +0000906 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
Eli Friedman59c04372009-07-29 19:44:27 +0000907 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
908 // We found a direct base of this type. That's what we're
909 // initializing.
910 DirectBaseSpec = &*Base;
911 break;
912 }
913 }
Mike Stump1eb44332009-09-09 15:08:12 +0000914
Eli Friedman59c04372009-07-29 19:44:27 +0000915 // Check for a virtual base class.
916 // FIXME: We might be able to short-circuit this if we know in advance that
917 // there are no virtual bases.
918 const CXXBaseSpecifier *VirtualBaseSpec = 0;
919 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
920 // We haven't found a base yet; search the class hierarchy for a
921 // virtual base class.
922 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
923 /*DetectVirtual=*/false);
924 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000925 for (BasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +0000926 Path != Paths.end(); ++Path) {
927 if (Path->back().Base->isVirtual()) {
928 VirtualBaseSpec = Path->back().Base;
929 break;
930 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000931 }
932 }
933 }
Eli Friedman59c04372009-07-29 19:44:27 +0000934
935 // C++ [base.class.init]p2:
936 // If a mem-initializer-id is ambiguous because it designates both
937 // a direct non-virtual base class and an inherited virtual base
938 // class, the mem-initializer is ill-formed.
939 if (DirectBaseSpec && VirtualBaseSpec)
940 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
941 << BaseType << SourceRange(IdLoc, RParenLoc);
942 // C++ [base.class.init]p2:
943 // Unless the mem-initializer-id names a nonstatic data membeer of the
944 // constructor's class ot a direst or virtual base of that class, the
945 // mem-initializer is ill-formed.
946 if (!DirectBaseSpec && !VirtualBaseSpec)
947 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
948 << BaseType << ClassDecl->getNameAsCString()
949 << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000950 }
951
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +0000952 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +0000953 if (!BaseType->isDependentType() && !HasDependentArg) {
954 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
955 Context.getCanonicalType(BaseType));
Douglas Gregor39da0b82009-09-09 23:08:42 +0000956 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
957
958 C = PerformInitializationByConstructor(BaseType,
959 MultiExprArg(*this,
960 (void**)Args, NumArgs),
Mike Stump1eb44332009-09-09 15:08:12 +0000961 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000962 Name, IK_Direct,
963 ConstructorArgs);
964 if (C) {
965 // Take over the constructor arguments as our own.
966 NumArgs = ConstructorArgs.size();
967 Args = (Expr **)ConstructorArgs.take();
968 }
Eli Friedman59c04372009-07-29 19:44:27 +0000969 }
970
Mike Stump1eb44332009-09-09 15:08:12 +0000971 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +0000972 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000973}
974
Fariborz Jahanian87595e42009-07-23 23:32:59 +0000975void
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000976Sema::setBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
977 CXXBaseOrMemberInitializer **Initializers,
978 unsigned NumInitializers,
Mike Stump1eb44332009-09-09 15:08:12 +0000979 llvm::SmallVectorImpl<CXXBaseSpecifier *>& Bases,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000980 llvm::SmallVectorImpl<FieldDecl *>&Fields) {
981 // We need to build the initializer AST according to order of construction
982 // and not what user specified in the Initializers list.
983 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
984 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
985 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
986 bool HasDependentBaseInit = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000988 for (unsigned i = 0; i < NumInitializers; i++) {
989 CXXBaseOrMemberInitializer *Member = Initializers[i];
990 if (Member->isBaseInitializer()) {
991 if (Member->getBaseClass()->isDependentType())
992 HasDependentBaseInit = true;
993 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
994 } else {
995 AllBaseFields[Member->getMember()] = Member;
996 }
997 }
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000999 if (HasDependentBaseInit) {
1000 // FIXME. This does not preserve the ordering of the initializers.
1001 // Try (with -Wreorder)
1002 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001003 // template<class X> struct B : A<X> {
1004 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001005 // int x1;
1006 // };
1007 // B<int> x;
1008 // On seeing one dependent type, we should essentially exit this routine
1009 // while preserving user-declared initializer list. When this routine is
1010 // called during instantiatiation process, this routine will rebuild the
1011 // oderdered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001013 // If we have a dependent base initialization, we can't determine the
1014 // association between initializers and bases; just dump the known
1015 // initializers into the list, and don't try to deal with other bases.
1016 for (unsigned i = 0; i < NumInitializers; i++) {
1017 CXXBaseOrMemberInitializer *Member = Initializers[i];
1018 if (Member->isBaseInitializer())
1019 AllToInit.push_back(Member);
1020 }
1021 } else {
1022 // Push virtual bases before others.
1023 for (CXXRecordDecl::base_class_iterator VBase =
1024 ClassDecl->vbases_begin(),
1025 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1026 if (VBase->getType()->isDependentType())
1027 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001028 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001029 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001030 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001031 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1032 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
1033 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1034 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001035 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001036 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001037 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001038 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001039 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1040 assert(VBaseDecl && "setBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001041 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
1042 if (!Ctor)
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001043 Bases.push_back(VBase);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001044 else
1045 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1046
Mike Stump1eb44332009-09-09 15:08:12 +00001047 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001048 new (Context) CXXBaseOrMemberInitializer(VBase->getType(), 0, 0,
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001049 Ctor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001050 SourceLocation(),
1051 SourceLocation());
1052 AllToInit.push_back(Member);
1053 }
1054 }
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001056 for (CXXRecordDecl::base_class_iterator Base =
1057 ClassDecl->bases_begin(),
1058 E = ClassDecl->bases_end(); Base != E; ++Base) {
1059 // Virtuals are in the virtual base list and already constructed.
1060 if (Base->isVirtual())
1061 continue;
1062 // Skip dependent types.
1063 if (Base->getType()->isDependentType())
1064 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001065 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001066 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001067 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001068 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1069 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
1070 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1071 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001072 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001073 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001074 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001075 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001076 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001077 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001078 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
1079 if (!Ctor)
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001080 Bases.push_back(Base);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001081 else
1082 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1083
Mike Stump1eb44332009-09-09 15:08:12 +00001084 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001085 new (Context) CXXBaseOrMemberInitializer(Base->getType(), 0, 0,
1086 BaseDecl->getDefaultConstructor(Context),
1087 SourceLocation(),
1088 SourceLocation());
1089 AllToInit.push_back(Member);
1090 }
1091 }
1092 }
Mike Stump1eb44332009-09-09 15:08:12 +00001093
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001094 // non-static data members.
1095 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1096 E = ClassDecl->field_end(); Field != E; ++Field) {
1097 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001098 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001099 Field->getType()->getAs<RecordType>()) {
1100 CXXRecordDecl *FieldClassDecl
1101 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001102 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001103 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1104 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1105 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1106 // set to the anonymous union data member used in the initializer
1107 // list.
1108 Value->setMember(*Field);
1109 Value->setAnonUnionMember(*FA);
1110 AllToInit.push_back(Value);
1111 break;
1112 }
1113 }
1114 }
1115 continue;
1116 }
1117 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001118 QualType FT = (*Field)->getType();
1119 if (const RecordType* RT = FT->getAs<RecordType>()) {
1120 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl());
1121 assert(FieldRecDecl && "setBaseOrMemberInitializers - BaseDecl null");
Mike Stump1eb44332009-09-09 15:08:12 +00001122 if (CXXConstructorDecl *Ctor =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001123 FieldRecDecl->getDefaultConstructor(Context))
1124 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
1125 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001126 AllToInit.push_back(Value);
1127 continue;
1128 }
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001130 QualType FT = Context.getBaseElementType((*Field)->getType());
1131 if (const RecordType* RT = FT->getAs<RecordType>()) {
1132 CXXConstructorDecl *Ctor =
1133 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
1134 if (!Ctor && !FT->isDependentType())
1135 Fields.push_back(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001136 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001137 new (Context) CXXBaseOrMemberInitializer((*Field), 0, 0,
1138 Ctor,
1139 SourceLocation(),
1140 SourceLocation());
1141 AllToInit.push_back(Member);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001142 if (Ctor)
1143 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001144 if (FT.isConstQualified() && (!Ctor || Ctor->isTrivial())) {
1145 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1146 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1147 Diag((*Field)->getLocation(), diag::note_declared_at);
1148 }
1149 }
1150 else if (FT->isReferenceType()) {
1151 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1152 << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getDeclName();
1153 Diag((*Field)->getLocation(), diag::note_declared_at);
1154 }
1155 else if (FT.isConstQualified()) {
1156 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1157 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1158 Diag((*Field)->getLocation(), diag::note_declared_at);
1159 }
1160 }
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001162 NumInitializers = AllToInit.size();
1163 if (NumInitializers > 0) {
1164 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1165 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1166 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001168 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1169 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1170 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1171 }
1172}
1173
1174void
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001175Sema::BuildBaseOrMemberInitializers(ASTContext &C,
1176 CXXConstructorDecl *Constructor,
1177 CXXBaseOrMemberInitializer **Initializers,
1178 unsigned NumInitializers
1179 ) {
1180 llvm::SmallVector<CXXBaseSpecifier *, 4>Bases;
1181 llvm::SmallVector<FieldDecl *, 4>Members;
Mike Stump1eb44332009-09-09 15:08:12 +00001182
1183 setBaseOrMemberInitializers(Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001184 Initializers, NumInitializers, Bases, Members);
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001185 for (unsigned int i = 0; i < Bases.size(); i++)
Mike Stump1eb44332009-09-09 15:08:12 +00001186 Diag(Bases[i]->getSourceRange().getBegin(),
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001187 diag::err_missing_default_constructor) << 0 << Bases[i]->getType();
1188 for (unsigned int i = 0; i < Members.size(); i++)
Mike Stump1eb44332009-09-09 15:08:12 +00001189 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor)
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001190 << 1 << Members[i]->getType();
1191}
1192
Eli Friedman6347f422009-07-21 19:28:10 +00001193static void *GetKeyForTopLevelField(FieldDecl *Field) {
1194 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001195 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001196 if (RT->getDecl()->isAnonymousStructOrUnion())
1197 return static_cast<void *>(RT->getDecl());
1198 }
1199 return static_cast<void *>(Field);
1200}
1201
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001202static void *GetKeyForBase(QualType BaseType) {
1203 if (const RecordType *RT = BaseType->getAs<RecordType>())
1204 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001206 assert(0 && "Unexpected base type!");
1207 return 0;
1208}
1209
Mike Stump1eb44332009-09-09 15:08:12 +00001210static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001211 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001212 // For fields injected into the class via declaration of an anonymous union,
1213 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001214 if (Member->isMemberInitializer()) {
1215 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001217 // After BuildBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001218 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001219 // in AnonUnionMember field.
1220 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1221 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001222 if (Field->getDeclContext()->isRecord()) {
1223 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1224 if (RD->isAnonymousStructOrUnion())
1225 return static_cast<void *>(RD);
1226 }
1227 return static_cast<void *>(Field);
1228 }
Mike Stump1eb44332009-09-09 15:08:12 +00001229
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001230 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001231}
1232
Mike Stump1eb44332009-09-09 15:08:12 +00001233void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001234 SourceLocation ColonLoc,
1235 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001236 if (!ConstructorDecl)
1237 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001238
1239 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001240
1241 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001242 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Anders Carlssona7b35212009-03-25 02:58:17 +00001244 if (!Constructor) {
1245 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1246 return;
1247 }
Mike Stump1eb44332009-09-09 15:08:12 +00001248
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001249 if (!Constructor->isDependentContext()) {
1250 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1251 bool err = false;
1252 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001253 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001254 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1255 void *KeyToMember = GetKeyForMember(Member);
1256 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1257 if (!PrevMember) {
1258 PrevMember = Member;
1259 continue;
1260 }
1261 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001262 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001263 diag::error_multiple_mem_initialization)
1264 << Field->getNameAsString();
1265 else {
1266 Type *BaseClass = Member->getBaseClass();
1267 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001268 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001269 diag::error_multiple_base_initialization)
1270 << BaseClass->getDesugaredType(true);
1271 }
1272 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1273 << 0;
1274 err = true;
1275 }
Mike Stump1eb44332009-09-09 15:08:12 +00001276
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001277 if (err)
1278 return;
1279 }
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001281 BuildBaseOrMemberInitializers(Context, Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001282 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001283 NumMemInits);
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001285 if (Constructor->isDependentContext())
1286 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001287
1288 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001289 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001290 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001291 Diagnostic::Ignored)
1292 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001294 // Also issue warning if order of ctor-initializer list does not match order
1295 // of 1) base class declarations and 2) order of non-static data members.
1296 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001298 CXXRecordDecl *ClassDecl
1299 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1300 // Push virtual bases before others.
1301 for (CXXRecordDecl::base_class_iterator VBase =
1302 ClassDecl->vbases_begin(),
1303 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001304 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001305
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001306 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1307 E = ClassDecl->bases_end(); Base != E; ++Base) {
1308 // Virtuals are alread in the virtual base list and are constructed
1309 // first.
1310 if (Base->isVirtual())
1311 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001312 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001313 }
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001315 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1316 E = ClassDecl->field_end(); Field != E; ++Field)
1317 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001319 int Last = AllBaseOrMembers.size();
1320 int curIndex = 0;
1321 CXXBaseOrMemberInitializer *PrevMember = 0;
1322 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001323 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001324 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1325 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001326
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001327 for (; curIndex < Last; curIndex++)
1328 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1329 break;
1330 if (curIndex == Last) {
1331 assert(PrevMember && "Member not in member list?!");
1332 // Initializer as specified in ctor-initializer list is out of order.
1333 // Issue a warning diagnostic.
1334 if (PrevMember->isBaseInitializer()) {
1335 // Diagnostics is for an initialized base class.
1336 Type *BaseClass = PrevMember->getBaseClass();
1337 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001338 diag::warn_base_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001339 << BaseClass->getDesugaredType(true);
1340 } else {
1341 FieldDecl *Field = PrevMember->getMember();
1342 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001343 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001344 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001345 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001346 // Also the note!
1347 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001348 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001349 diag::note_fieldorbase_initialized_here) << 0
1350 << Field->getNameAsString();
1351 else {
1352 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001353 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001354 diag::note_fieldorbase_initialized_here) << 1
1355 << BaseClass->getDesugaredType(true);
1356 }
1357 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001358 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001359 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001360 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001361 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001362 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001363}
1364
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001365void
1366Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) {
1367 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext());
1368 llvm::SmallVector<uintptr_t, 32> AllToDestruct;
Mike Stump1eb44332009-09-09 15:08:12 +00001369
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001370 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1371 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1372 if (VBase->getType()->isDependentType())
1373 continue;
1374 // Skip over virtual bases which have trivial destructors.
1375 CXXRecordDecl *BaseClassDecl
1376 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1377 if (BaseClassDecl->hasTrivialDestructor())
1378 continue;
1379 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001380 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001381 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001382
1383 uintptr_t Member =
1384 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001385 | CXXDestructorDecl::VBASE;
1386 AllToDestruct.push_back(Member);
1387 }
1388 for (CXXRecordDecl::base_class_iterator Base =
1389 ClassDecl->bases_begin(),
1390 E = ClassDecl->bases_end(); Base != E; ++Base) {
1391 if (Base->isVirtual())
1392 continue;
1393 if (Base->getType()->isDependentType())
1394 continue;
1395 // Skip over virtual bases which have trivial destructors.
1396 CXXRecordDecl *BaseClassDecl
1397 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1398 if (BaseClassDecl->hasTrivialDestructor())
1399 continue;
1400 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001401 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001402 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001403 uintptr_t Member =
1404 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001405 | CXXDestructorDecl::DRCTNONVBASE;
1406 AllToDestruct.push_back(Member);
1407 }
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001409 // non-static data members.
1410 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1411 E = ClassDecl->field_end(); Field != E; ++Field) {
1412 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001414 if (const RecordType* RT = FieldType->getAs<RecordType>()) {
1415 // Skip over virtual bases which have trivial destructors.
1416 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1417 if (FieldClassDecl->hasTrivialDestructor())
1418 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001419 if (const CXXDestructorDecl *Dtor =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001420 FieldClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001421 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001422 const_cast<CXXDestructorDecl*>(Dtor));
1423 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field);
1424 AllToDestruct.push_back(Member);
1425 }
1426 }
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001428 unsigned NumDestructions = AllToDestruct.size();
1429 if (NumDestructions > 0) {
1430 Destructor->setNumBaseOrMemberDestructions(NumDestructions);
Mike Stump1eb44332009-09-09 15:08:12 +00001431 uintptr_t *BaseOrMemberDestructions =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001432 new (Context) uintptr_t [NumDestructions];
1433 // Insert in reverse order.
1434 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx)
1435 BaseOrMemberDestructions[i++] = AllToDestruct[Idx];
1436 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions);
1437 }
1438}
1439
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001440void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001441 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001442 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001444 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001445
1446 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001447 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001448 BuildBaseOrMemberInitializers(Context,
1449 Constructor,
1450 (CXXBaseOrMemberInitializer **)0, 0);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001451}
1452
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001453namespace {
1454 /// PureVirtualMethodCollector - traverses a class and its superclasses
1455 /// and determines if it has any pure virtual methods.
1456 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1457 ASTContext &Context;
1458
Sebastian Redldfe292d2009-03-22 21:28:55 +00001459 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001460 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001461
1462 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001463 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001465 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001467 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001468 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001469 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001471 MethodList List;
1472 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001474 // Copy the temporary list to methods, and make sure to ignore any
1475 // null entries.
1476 for (size_t i = 0, e = List.size(); i != e; ++i) {
1477 if (List[i])
1478 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001479 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001480 }
Mike Stump1eb44332009-09-09 15:08:12 +00001481
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001482 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001484 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1485 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001486 };
Mike Stump1eb44332009-09-09 15:08:12 +00001487
1488 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001489 MethodList& Methods) {
1490 // First, collect the pure virtual methods for the base classes.
1491 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1492 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001493 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001494 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001495 if (BaseDecl && BaseDecl->isAbstract())
1496 Collect(BaseDecl, Methods);
1497 }
1498 }
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001500 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001501 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001503 MethodSetTy OverriddenMethods;
1504 size_t MethodsSize = Methods.size();
1505
Mike Stump1eb44332009-09-09 15:08:12 +00001506 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001507 i != e; ++i) {
1508 // Traverse the record, looking for methods.
1509 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001510 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001511 if (MD->isPure()) {
1512 Methods.push_back(MD);
1513 continue;
1514 }
Mike Stump1eb44332009-09-09 15:08:12 +00001515
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001516 // Otherwise, record all the overridden methods in our set.
1517 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1518 E = MD->end_overridden_methods(); I != E; ++I) {
1519 // Keep track of the overridden methods.
1520 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001521 }
1522 }
1523 }
Mike Stump1eb44332009-09-09 15:08:12 +00001524
1525 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001526 // overridden.
1527 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1528 if (OverriddenMethods.count(Methods[i]))
1529 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001530 }
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001532 }
1533}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001534
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001535
Mike Stump1eb44332009-09-09 15:08:12 +00001536bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001537 unsigned DiagID, AbstractDiagSelID SelID,
1538 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001539 if (SelID == -1)
1540 return RequireNonAbstractType(Loc, T,
1541 PDiag(DiagID), CurrentRD);
1542 else
1543 return RequireNonAbstractType(Loc, T,
1544 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001545}
1546
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001547bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1548 const PartialDiagnostic &PD,
1549 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001550 if (!getLangOptions().CPlusPlus)
1551 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Anders Carlsson11f21a02009-03-23 19:10:31 +00001553 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001554 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001555 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Ted Kremenek6217b802009-07-29 21:53:49 +00001557 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001558 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001559 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001560 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001562 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001563 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001564 }
Mike Stump1eb44332009-09-09 15:08:12 +00001565
Ted Kremenek6217b802009-07-29 21:53:49 +00001566 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001567 if (!RT)
1568 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001570 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1571 if (!RD)
1572 return false;
1573
Anders Carlssone65a3c82009-03-24 17:23:42 +00001574 if (CurrentRD && CurrentRD != RD)
1575 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001577 if (!RD->isAbstract())
1578 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001579
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001580 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001582 // Check if we've already emitted the list of pure virtual functions for this
1583 // class.
1584 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1585 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001587 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001588
1589 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001590 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1591 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001592
1593 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001594 MD->getDeclName();
1595 }
1596
1597 if (!PureVirtualClassDiagSet)
1598 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1599 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001601 return true;
1602}
1603
Anders Carlsson8211eff2009-03-24 01:19:16 +00001604namespace {
Mike Stump1eb44332009-09-09 15:08:12 +00001605 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001606 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1607 Sema &SemaRef;
1608 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Anders Carlssone65a3c82009-03-24 17:23:42 +00001610 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001611 bool Invalid = false;
1612
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001613 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1614 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001615 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001616
Anders Carlsson8211eff2009-03-24 01:19:16 +00001617 return Invalid;
1618 }
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Anders Carlssone65a3c82009-03-24 17:23:42 +00001620 public:
1621 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1622 : SemaRef(SemaRef), AbstractClass(ac) {
1623 Visit(SemaRef.Context.getTranslationUnitDecl());
1624 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001625
Anders Carlssone65a3c82009-03-24 17:23:42 +00001626 bool VisitFunctionDecl(const FunctionDecl *FD) {
1627 if (FD->isThisDeclarationADefinition()) {
1628 // No need to do the check if we're in a definition, because it requires
1629 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00001630 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001631 return VisitDeclContext(FD);
1632 }
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Anders Carlssone65a3c82009-03-24 17:23:42 +00001634 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00001635 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001636 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00001637 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1638 diag::err_abstract_type_in_decl,
1639 Sema::AbstractReturnType,
1640 AbstractClass);
1641
Mike Stump1eb44332009-09-09 15:08:12 +00001642 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001643 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001644 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001645 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001646 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001647 VD->getOriginalType(),
1648 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001649 Sema::AbstractParamType,
1650 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001651 }
1652
1653 return Invalid;
1654 }
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Anders Carlssone65a3c82009-03-24 17:23:42 +00001656 bool VisitDecl(const Decl* D) {
1657 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1658 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00001659
Anders Carlssone65a3c82009-03-24 17:23:42 +00001660 return false;
1661 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001662 };
1663}
1664
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001665void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001666 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001667 SourceLocation LBrac,
1668 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001669 if (!TagDecl)
1670 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Douglas Gregor42af25f2009-05-11 19:58:34 +00001672 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001673 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001674 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00001675 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001676
Chris Lattnerb28317a2009-03-28 19:18:32 +00001677 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001678 if (!RD->isAbstract()) {
1679 // Collect all the pure virtual methods and see if this is an abstract
1680 // class after all.
1681 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001682 if (!Collector.empty())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001683 RD->setAbstract(true);
1684 }
Mike Stump1eb44332009-09-09 15:08:12 +00001685
1686 if (RD->isAbstract())
Anders Carlssone65a3c82009-03-24 17:23:42 +00001687 AbstractClassUsageDiagnoser(*this, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Douglas Gregor42af25f2009-05-11 19:58:34 +00001689 if (!RD->isDependentType())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001690 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001691}
1692
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001693/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1694/// special functions, such as the default constructor, copy
1695/// constructor, or destructor, to the given C++ class (C++
1696/// [special]p1). This routine can only be executed just before the
1697/// definition of the class is complete.
1698void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00001699 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00001700 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001701
Sebastian Redl465226e2009-05-27 22:11:52 +00001702 // FIXME: Implicit declarations have exception specifications, which are
1703 // the union of the specifications of the implicitly called functions.
1704
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001705 if (!ClassDecl->hasUserDeclaredConstructor()) {
1706 // C++ [class.ctor]p5:
1707 // A default constructor for a class X is a constructor of class X
1708 // that can be called without an argument. If there is no
1709 // user-declared constructor for class X, a default constructor is
1710 // implicitly declared. An implicitly-declared default constructor
1711 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001712 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001713 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00001714 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001715 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001716 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001717 Context.getFunctionType(Context.VoidTy,
1718 0, 0, false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001719 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001720 /*isExplicit=*/false,
1721 /*isInline=*/true,
1722 /*isImplicitlyDeclared=*/true);
1723 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001724 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001725 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001726 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001727 }
1728
1729 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1730 // C++ [class.copy]p4:
1731 // If the class definition does not explicitly declare a copy
1732 // constructor, one is declared implicitly.
1733
1734 // C++ [class.copy]p5:
1735 // The implicitly-declared copy constructor for a class X will
1736 // have the form
1737 //
1738 // X::X(const X&)
1739 //
1740 // if
1741 bool HasConstCopyConstructor = true;
1742
1743 // -- each direct or virtual base class B of X has a copy
1744 // constructor whose first parameter is of type const B& or
1745 // const volatile B&, and
1746 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1747 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1748 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00001749 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001750 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001751 = BaseClassDecl->hasConstCopyConstructor(Context);
1752 }
1753
1754 // -- for all the nonstatic data members of X that are of a
1755 // class type M (or array thereof), each such class type
1756 // has a copy constructor whose first parameter is of type
1757 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001758 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1759 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001760 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001761 QualType FieldType = (*Field)->getType();
1762 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1763 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001764 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001765 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001766 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001767 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001768 = FieldClassDecl->hasConstCopyConstructor(Context);
1769 }
1770 }
1771
Sebastian Redl64b45f72009-01-05 20:52:13 +00001772 // Otherwise, the implicitly declared copy constructor will have
1773 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001774 //
1775 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00001776 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001777 if (HasConstCopyConstructor)
1778 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001779 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001780
Sebastian Redl64b45f72009-01-05 20:52:13 +00001781 // An implicitly-declared copy constructor is an inline public
1782 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001783 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001784 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001785 CXXConstructorDecl *CopyConstructor
1786 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001787 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001788 Context.getFunctionType(Context.VoidTy,
1789 &ArgType, 1,
1790 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001791 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001792 /*isExplicit=*/false,
1793 /*isInline=*/true,
1794 /*isImplicitlyDeclared=*/true);
1795 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001796 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001797 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001798
1799 // Add the parameter to the constructor.
1800 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1801 ClassDecl->getLocation(),
1802 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001803 ArgType, /*DInfo=*/0,
1804 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00001805 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001806 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001807 }
1808
Sebastian Redl64b45f72009-01-05 20:52:13 +00001809 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1810 // Note: The following rules are largely analoguous to the copy
1811 // constructor rules. Note that virtual bases are not taken into account
1812 // for determining the argument type of the operator. Note also that
1813 // operators taking an object instead of a reference are allowed.
1814 //
1815 // C++ [class.copy]p10:
1816 // If the class definition does not explicitly declare a copy
1817 // assignment operator, one is declared implicitly.
1818 // The implicitly-defined copy assignment operator for a class X
1819 // will have the form
1820 //
1821 // X& X::operator=(const X&)
1822 //
1823 // if
1824 bool HasConstCopyAssignment = true;
1825
1826 // -- each direct base class B of X has a copy assignment operator
1827 // whose parameter is of type const B&, const volatile B& or B,
1828 // and
1829 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1830 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1831 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00001832 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001833 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001834 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001835 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001836 }
1837
1838 // -- for all the nonstatic data members of X that are of a class
1839 // type M (or array thereof), each such class type has a copy
1840 // assignment operator whose parameter is of type const M&,
1841 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001842 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1843 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001844 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00001845 QualType FieldType = (*Field)->getType();
1846 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1847 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001848 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00001849 const CXXRecordDecl *FieldClassDecl
1850 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001851 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00001852 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001853 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001854 }
1855 }
1856
1857 // Otherwise, the implicitly declared copy assignment operator will
1858 // have the form
1859 //
1860 // X& X::operator=(X&)
1861 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001862 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001863 if (HasConstCopyAssignment)
1864 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001865 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001866
1867 // An implicitly-declared copy assignment operator is an inline public
1868 // member of its class.
1869 DeclarationName Name =
1870 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1871 CXXMethodDecl *CopyAssignment =
1872 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1873 Context.getFunctionType(RetType, &ArgType, 1,
1874 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001875 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001876 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001877 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001878 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001879 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001880
1881 // Add the parameter to the operator.
1882 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1883 ClassDecl->getLocation(),
1884 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001885 ArgType, /*DInfo=*/0,
1886 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00001887 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001888
1889 // Don't call addedAssignmentOperator. There is no way to distinguish an
1890 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001891 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001892 }
1893
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001894 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001895 // C++ [class.dtor]p2:
1896 // If a class has no user-declared destructor, a destructor is
1897 // declared implicitly. An implicitly-declared destructor is an
1898 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001899 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001900 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00001901 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00001902 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001903 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00001904 Context.getFunctionType(Context.VoidTy,
1905 0, 0, false, 0),
1906 /*isInline=*/true,
1907 /*isImplicitlyDeclared=*/true);
1908 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001909 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001910 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001911 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001912 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001913}
1914
Douglas Gregor6569d682009-05-27 23:11:45 +00001915void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00001916 Decl *D = TemplateD.getAs<Decl>();
1917 if (!D)
1918 return;
1919
1920 TemplateParameterList *Params = 0;
1921 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
1922 Params = Template->getTemplateParameters();
1923 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1924 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
1925 Params = PartialSpec->getTemplateParameters();
1926 else
Douglas Gregor6569d682009-05-27 23:11:45 +00001927 return;
1928
Douglas Gregor6569d682009-05-27 23:11:45 +00001929 for (TemplateParameterList::iterator Param = Params->begin(),
1930 ParamEnd = Params->end();
1931 Param != ParamEnd; ++Param) {
1932 NamedDecl *Named = cast<NamedDecl>(*Param);
1933 if (Named->getDeclName()) {
1934 S->AddDecl(DeclPtrTy::make(Named));
1935 IdResolver.AddDecl(Named);
1936 }
1937 }
1938}
1939
Douglas Gregor72b505b2008-12-16 21:30:33 +00001940/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1941/// parsing a top-level (non-nested) C++ class, and we are now
1942/// parsing those parts of the given Method declaration that could
1943/// not be parsed earlier (C++ [class.mem]p2), such as default
1944/// arguments. This action should enter the scope of the given
1945/// Method declaration as if we had just parsed the qualified method
1946/// name. However, it should not bring the parameters into scope;
1947/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001948void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001949 if (!MethodD)
1950 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001952 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Douglas Gregor72b505b2008-12-16 21:30:33 +00001954 CXXScopeSpec SS;
Chris Lattnerb28317a2009-03-28 19:18:32 +00001955 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001956 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00001957 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1958 SS.setScopeRep(
1959 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001960 ActOnCXXEnterDeclaratorScope(S, SS);
1961}
1962
1963/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1964/// C++ method declaration. We're (re-)introducing the given
1965/// function parameter into scope for use in parsing later parts of
1966/// the method declaration. For example, we could see an
1967/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001968void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001969 if (!ParamD)
1970 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Chris Lattnerb28317a2009-03-28 19:18:32 +00001972 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00001973
1974 // If this parameter has an unparsed default argument, clear it out
1975 // to make way for the parsed default argument.
1976 if (Param->hasUnparsedDefaultArg())
1977 Param->setDefaultArg(0);
1978
Chris Lattnerb28317a2009-03-28 19:18:32 +00001979 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001980 if (Param->getDeclName())
1981 IdResolver.AddDecl(Param);
1982}
1983
1984/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1985/// processing the delayed method declaration for Method. The method
1986/// declaration is now considered finished. There may be a separate
1987/// ActOnStartOfFunctionDef action later (not necessarily
1988/// immediately!) for this method, if it was also defined inside the
1989/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001990void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001991 if (!MethodD)
1992 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001994 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Chris Lattnerb28317a2009-03-28 19:18:32 +00001996 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00001997 CXXScopeSpec SS;
Mike Stump1eb44332009-09-09 15:08:12 +00001998 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00001999 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2000 SS.setScopeRep(
2001 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002002 ActOnCXXExitDeclaratorScope(S, SS);
2003
2004 // Now that we have our default arguments, check the constructor
2005 // again. It could produce additional diagnostics or affect whether
2006 // the class has implicitly-declared destructors, among other
2007 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002008 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2009 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002010
2011 // Check the default arguments, which we may have added.
2012 if (!Method->isInvalidDecl())
2013 CheckCXXDefaultArguments(Method);
2014}
2015
Douglas Gregor42a552f2008-11-05 20:51:48 +00002016/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002017/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002018/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002019/// emit diagnostics and set the invalid bit to true. In any case, the type
2020/// will be updated to reflect a well-formed type for the constructor and
2021/// returned.
2022QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2023 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002024 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002025
2026 // C++ [class.ctor]p3:
2027 // A constructor shall not be virtual (10.3) or static (9.4). A
2028 // constructor can be invoked for a const, volatile or const
2029 // volatile object. A constructor shall not be declared const,
2030 // volatile, or const volatile (9.3.2).
2031 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002032 if (!D.isInvalidType())
2033 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2034 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2035 << SourceRange(D.getIdentifierLoc());
2036 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002037 }
2038 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002039 if (!D.isInvalidType())
2040 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2041 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2042 << SourceRange(D.getIdentifierLoc());
2043 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002044 SC = FunctionDecl::None;
2045 }
Mike Stump1eb44332009-09-09 15:08:12 +00002046
Chris Lattner65401802009-04-25 08:28:21 +00002047 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2048 if (FTI.TypeQuals != 0) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002049 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002050 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2051 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002052 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002053 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2054 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002055 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002056 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2057 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002058 }
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Douglas Gregor42a552f2008-11-05 20:51:48 +00002060 // Rebuild the function type "R" without any type qualifiers (in
2061 // case any of the errors above fired) and with "void" as the
2062 // return type, since constructors don't have return types. We
2063 // *always* have to do this, because GetTypeForDeclarator will
2064 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002065 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002066 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2067 Proto->getNumArgs(),
2068 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002069}
2070
Douglas Gregor72b505b2008-12-16 21:30:33 +00002071/// CheckConstructor - Checks a fully-formed constructor for
2072/// well-formedness, issuing any diagnostics required. Returns true if
2073/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002074void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002075 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002076 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2077 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002078 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002079
2080 // C++ [class.copy]p3:
2081 // A declaration of a constructor for a class X is ill-formed if
2082 // its first parameter is of type (optionally cv-qualified) X and
2083 // either there are no other parameters or else all other
2084 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002085 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002086 ((Constructor->getNumParams() == 1) ||
2087 (Constructor->getNumParams() > 1 &&
Anders Carlssonae0b4e72009-06-06 04:14:07 +00002088 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002089 QualType ParamType = Constructor->getParamDecl(0)->getType();
2090 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2091 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002092 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2093 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002094 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattner6e475012009-04-25 08:35:12 +00002095 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002096 }
2097 }
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Douglas Gregor72b505b2008-12-16 21:30:33 +00002099 // Notify the class that we've added a constructor.
2100 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002101}
2102
Mike Stump1eb44332009-09-09 15:08:12 +00002103static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002104FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2105 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2106 FTI.ArgInfo[0].Param &&
2107 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2108}
2109
Douglas Gregor42a552f2008-11-05 20:51:48 +00002110/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2111/// the well-formednes of the destructor declarator @p D with type @p
2112/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002113/// emit diagnostics and set the declarator to invalid. Even if this happens,
2114/// will be updated to reflect a well-formed type for the destructor and
2115/// returned.
2116QualType Sema::CheckDestructorDeclarator(Declarator &D,
2117 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002118 // C++ [class.dtor]p1:
2119 // [...] A typedef-name that names a class is a class-name
2120 // (7.1.3); however, a typedef-name that names a class shall not
2121 // be used as the identifier in the declarator for a destructor
2122 // declaration.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002123 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType());
Chris Lattner65401802009-04-25 08:28:21 +00002124 if (isa<TypedefType>(DeclaratorType)) {
2125 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002126 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002127 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002128 }
2129
2130 // C++ [class.dtor]p2:
2131 // A destructor is used to destroy objects of its class type. A
2132 // destructor takes no parameters, and no return type can be
2133 // specified for it (not even void). The address of a destructor
2134 // shall not be taken. A destructor shall not be static. A
2135 // destructor can be invoked for a const, volatile or const
2136 // volatile object. A destructor shall not be declared const,
2137 // volatile or const volatile (9.3.2).
2138 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002139 if (!D.isInvalidType())
2140 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2141 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2142 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002143 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002144 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002145 }
Chris Lattner65401802009-04-25 08:28:21 +00002146 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002147 // Destructors don't have return types, but the parser will
2148 // happily parse something like:
2149 //
2150 // class X {
2151 // float ~X();
2152 // };
2153 //
2154 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002155 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2156 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2157 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002158 }
Mike Stump1eb44332009-09-09 15:08:12 +00002159
Chris Lattner65401802009-04-25 08:28:21 +00002160 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2161 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002162 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002163 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2164 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002165 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002166 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2167 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002168 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002169 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2170 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002171 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002172 }
2173
2174 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002175 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002176 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2177
2178 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002179 FTI.freeArgs();
2180 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002181 }
2182
Mike Stump1eb44332009-09-09 15:08:12 +00002183 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002184 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002185 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002186 D.setInvalidType();
2187 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002188
2189 // Rebuild the function type "R" without any type qualifiers or
2190 // parameters (in case any of the errors above fired) and with
2191 // "void" as the return type, since destructors don't have return
2192 // types. We *always* have to do this, because GetTypeForDeclarator
2193 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002194 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002195}
2196
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002197/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2198/// well-formednes of the conversion function declarator @p D with
2199/// type @p R. If there are any errors in the declarator, this routine
2200/// will emit diagnostics and return true. Otherwise, it will return
2201/// false. Either way, the type @p R will be updated to reflect a
2202/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002203void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002204 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002205 // C++ [class.conv.fct]p1:
2206 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002207 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002208 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002209 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002210 if (!D.isInvalidType())
2211 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2212 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2213 << SourceRange(D.getIdentifierLoc());
2214 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002215 SC = FunctionDecl::None;
2216 }
Chris Lattner6e475012009-04-25 08:35:12 +00002217 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002218 // Conversion functions don't have return types, but the parser will
2219 // happily parse something like:
2220 //
2221 // class X {
2222 // float operator bool();
2223 // };
2224 //
2225 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002226 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2227 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2228 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002229 }
2230
2231 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002232 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002233 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2234
2235 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002236 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002237 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002238 }
2239
Mike Stump1eb44332009-09-09 15:08:12 +00002240 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002241 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002242 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002243 D.setInvalidType();
2244 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002245
2246 // C++ [class.conv.fct]p4:
2247 // The conversion-type-id shall not represent a function type nor
2248 // an array type.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002249 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002250 if (ConvType->isArrayType()) {
2251 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2252 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002253 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002254 } else if (ConvType->isFunctionType()) {
2255 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2256 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002257 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002258 }
2259
2260 // Rebuild the function type "R" without any parameters (in case any
2261 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002262 // return type.
2263 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002264 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002265
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002266 // C++0x explicit conversion operators.
2267 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002268 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002269 diag::warn_explicit_conversion_functions)
2270 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002271}
2272
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002273/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2274/// the declaration of the given C++ conversion function. This routine
2275/// is responsible for recording the conversion function in the C++
2276/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002277Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002278 assert(Conversion && "Expected to receive a conversion function declaration");
2279
Douglas Gregor9d350972008-12-12 08:25:50 +00002280 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002281
2282 // Make sure we aren't redeclaring the conversion function.
2283 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002284
2285 // C++ [class.conv.fct]p1:
2286 // [...] A conversion function is never used to convert a
2287 // (possibly cv-qualified) object to the (possibly cv-qualified)
2288 // same object type (or a reference to it), to a (possibly
2289 // cv-qualified) base class of that type (or a reference to it),
2290 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002291 // FIXME: Suppress this warning if the conversion function ends up being a
2292 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002293 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002294 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002295 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002296 ConvType = ConvTypeRef->getPointeeType();
2297 if (ConvType->isRecordType()) {
2298 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2299 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002300 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002301 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002302 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002303 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002304 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002305 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002306 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002307 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002308 }
2309
Douglas Gregor70316a02008-12-26 15:00:45 +00002310 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002311 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002312 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002313 = Conversion->getDescribedFunctionTemplate())
2314 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor70316a02008-12-26 15:00:45 +00002315 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00002316 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor70316a02008-12-26 15:00:45 +00002317 Conv = Conversions->function_begin(),
2318 ConvEnd = Conversions->function_end();
2319 Conv != ConvEnd; ++Conv) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002320 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor70316a02008-12-26 15:00:45 +00002321 *Conv = Conversion;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002322 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002323 }
2324 }
2325 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002326 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002327 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002328 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002329 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002330 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002331
Chris Lattnerb28317a2009-03-28 19:18:32 +00002332 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002333}
2334
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002335//===----------------------------------------------------------------------===//
2336// Namespace Handling
2337//===----------------------------------------------------------------------===//
2338
2339/// ActOnStartNamespaceDef - This is called at the start of a namespace
2340/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002341Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2342 SourceLocation IdentLoc,
2343 IdentifierInfo *II,
2344 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002345 NamespaceDecl *Namespc =
2346 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2347 Namespc->setLBracLoc(LBrace);
2348
2349 Scope *DeclRegionScope = NamespcScope->getParent();
2350
2351 if (II) {
2352 // C++ [namespace.def]p2:
2353 // The identifier in an original-namespace-definition shall not have been
2354 // previously defined in the declarative region in which the
2355 // original-namespace-definition appears. The identifier in an
2356 // original-namespace-definition is the name of the namespace. Subsequently
2357 // in that declarative region, it is treated as an original-namespace-name.
2358
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002359 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
2360 true);
Mike Stump1eb44332009-09-09 15:08:12 +00002361
Douglas Gregor44b43212008-12-11 16:49:14 +00002362 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2363 // This is an extended namespace definition.
2364 // Attach this namespace decl to the chain of extended namespace
2365 // definitions.
2366 OrigNS->setNextNamespace(Namespc);
2367 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002368
Mike Stump1eb44332009-09-09 15:08:12 +00002369 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002370 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002371 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002372 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002373 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002374 } else if (PrevDecl) {
2375 // This is an invalid name redefinition.
2376 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2377 << Namespc->getDeclName();
2378 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2379 Namespc->setInvalidDecl();
2380 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002381 } else if (II->isStr("std") &&
2382 CurContext->getLookupContext()->isTranslationUnit()) {
2383 // This is the first "real" definition of the namespace "std", so update
2384 // our cache of the "std" namespace to point at this definition.
2385 if (StdNamespace) {
2386 // We had already defined a dummy namespace "std". Link this new
2387 // namespace definition to the dummy namespace "std".
2388 StdNamespace->setNextNamespace(Namespc);
2389 StdNamespace->setLocation(IdentLoc);
2390 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2391 }
2392
2393 // Make our StdNamespace cache point at the first real definition of the
2394 // "std" namespace.
2395 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002396 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002397
2398 PushOnScopeChains(Namespc, DeclRegionScope);
2399 } else {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002400 // FIXME: Handle anonymous namespaces
2401 }
2402
2403 // Although we could have an invalid decl (i.e. the namespace name is a
2404 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002405 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2406 // for the namespace has the declarations that showed up in that particular
2407 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002408 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002409 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002410}
2411
2412/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2413/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002414void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2415 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002416 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2417 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2418 Namespc->setRBracLoc(RBrace);
2419 PopDeclContext();
2420}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002421
Chris Lattnerb28317a2009-03-28 19:18:32 +00002422Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2423 SourceLocation UsingLoc,
2424 SourceLocation NamespcLoc,
2425 const CXXScopeSpec &SS,
2426 SourceLocation IdentLoc,
2427 IdentifierInfo *NamespcName,
2428 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002429 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2430 assert(NamespcName && "Invalid NamespcName.");
2431 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002432 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002433
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002434 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002435
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002436 // Lookup namespace name.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002437 LookupResult R = LookupParsedName(S, &SS, NamespcName,
2438 LookupNamespaceName, false);
2439 if (R.isAmbiguous()) {
2440 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002441 return DeclPtrTy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002442 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002443 if (NamedDecl *NS = R) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002444 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002445 // C++ [namespace.udir]p1:
2446 // A using-directive specifies that the names in the nominated
2447 // namespace can be used in the scope in which the
2448 // using-directive appears after the using-directive. During
2449 // unqualified name lookup (3.4.1), the names appear as if they
2450 // were declared in the nearest enclosing namespace which
2451 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002452 // namespace. [Note: in this context, "contains" means "contains
2453 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002454
2455 // Find enclosing context containing both using-directive and
2456 // nominated namespace.
2457 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2458 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2459 CommonAncestor = CommonAncestor->getParent();
2460
Mike Stump1eb44332009-09-09 15:08:12 +00002461 UDir = UsingDirectiveDecl::Create(Context,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002462 CurContext, UsingLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002463 NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002464 SS.getRange(),
2465 (NestedNameSpecifier *)SS.getScopeRep(),
2466 IdentLoc,
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002467 cast<NamespaceDecl>(NS),
2468 CommonAncestor);
2469 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002470 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002471 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002472 }
2473
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002474 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002475 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002476 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002477}
2478
2479void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2480 // If scope has associated entity, then using directive is at namespace
2481 // or translation unit scope. We add UsingDirectiveDecls, into
2482 // it's lookup structure.
2483 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002484 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002485 else
2486 // Otherwise it is block-sope. using-directives will affect lookup
2487 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002488 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002489}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002490
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002491
2492Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002493 AccessSpecifier AS,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002494 SourceLocation UsingLoc,
2495 const CXXScopeSpec &SS,
2496 SourceLocation IdentLoc,
2497 IdentifierInfo *TargetName,
2498 OverloadedOperatorKind Op,
2499 AttributeList *AttrList,
2500 bool IsTypeName) {
Eli Friedman5d39dee2009-06-27 05:59:59 +00002501 assert((TargetName || Op) && "Invalid TargetName.");
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002502 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002503
Anders Carlsson0c6139d2009-06-27 00:27:47 +00002504 DeclarationName Name;
2505 if (TargetName)
2506 Name = TargetName;
2507 else
2508 Name = Context.DeclarationNames.getCXXOperatorName(Op);
Mike Stump1eb44332009-09-09 15:08:12 +00002509
2510 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS, IdentLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00002511 Name, AttrList, IsTypeName);
Anders Carlsson595adc12009-08-29 19:54:19 +00002512 if (UD) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00002513 PushOnScopeChains(UD, S);
Anders Carlsson595adc12009-08-29 19:54:19 +00002514 UD->setAccess(AS);
2515 }
Mike Stump1eb44332009-09-09 15:08:12 +00002516
Anders Carlssonc72160b2009-08-28 05:40:36 +00002517 return DeclPtrTy::make(UD);
2518}
2519
2520NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2521 const CXXScopeSpec &SS,
2522 SourceLocation IdentLoc,
2523 DeclarationName Name,
2524 AttributeList *AttrList,
2525 bool IsTypeName) {
2526 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2527 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00002528
Anders Carlsson550b14b2009-08-28 05:49:21 +00002529 // FIXME: We ignore attributes for now.
2530 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00002531
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002532 if (SS.isEmpty()) {
2533 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002534 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002535 }
Mike Stump1eb44332009-09-09 15:08:12 +00002536
2537 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002538 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2539
Anders Carlsson550b14b2009-08-28 05:49:21 +00002540 if (isUnknownSpecialization(SS)) {
2541 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2542 SS.getRange(), NNS,
2543 IdentLoc, Name, IsTypeName);
2544 }
Mike Stump1eb44332009-09-09 15:08:12 +00002545
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002546 DeclContext *LookupContext = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002547
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002548 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2549 // C++0x N2914 [namespace.udecl]p3:
2550 // A using-declaration used as a member-declaration shall refer to a member
2551 // of a base class of the class being defined, shall refer to a member of an
2552 // anonymous union that is a member of a base class of the class being
Mike Stump1eb44332009-09-09 15:08:12 +00002553 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002554 // a member of a base class of the class being defined.
2555 const Type *Ty = NNS->getAsType();
2556 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) {
2557 Diag(SS.getRange().getBegin(),
2558 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2559 << NNS << RD->getDeclName();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002560 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002561 }
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002562
2563 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0));
2564 LookupContext = BaseTy->getAs<RecordType>()->getDecl();
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002565 } else {
2566 // C++0x N2914 [namespace.udecl]p8:
2567 // A using-declaration for a class member shall be a member-declaration.
2568 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002569 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002570 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002571 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002572 }
Mike Stump1eb44332009-09-09 15:08:12 +00002573
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002574 // C++0x N2914 [namespace.udecl]p9:
2575 // In a using-declaration, a prefix :: refers to the global namespace.
2576 if (NNS->getKind() == NestedNameSpecifier::Global)
2577 LookupContext = Context.getTranslationUnitDecl();
2578 else
2579 LookupContext = NNS->getAsNamespace();
2580 }
2581
2582
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002583 // Lookup target name.
Mike Stump1eb44332009-09-09 15:08:12 +00002584 LookupResult R = LookupQualifiedName(LookupContext,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002585 Name, LookupOrdinaryName);
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002587 if (!R) {
Anders Carlsson05180af2009-08-30 00:58:45 +00002588 DiagnoseMissingMember(IdentLoc, Name, NNS, SS.getRange());
Anders Carlssonc72160b2009-08-28 05:40:36 +00002589 return 0;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002590 }
2591
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002592 NamedDecl *ND = R.getAsDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002593
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002594 if (IsTypeName && !isa<TypeDecl>(ND)) {
2595 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002596 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002597 }
2598
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002599 // C++0x N2914 [namespace.udecl]p6:
2600 // A using-declaration shall not name a namespace.
2601 if (isa<NamespaceDecl>(ND)) {
2602 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2603 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002604 return 0;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002605 }
Mike Stump1eb44332009-09-09 15:08:12 +00002606
Anders Carlssonc72160b2009-08-28 05:40:36 +00002607 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2608 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002609}
2610
Anders Carlsson81c85c42009-03-28 23:53:49 +00002611/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2612/// is a namespace alias, returns the namespace it points to.
2613static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2614 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2615 return AD->getNamespace();
2616 return dyn_cast_or_null<NamespaceDecl>(D);
2617}
2618
Mike Stump1eb44332009-09-09 15:08:12 +00002619Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002620 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002621 SourceLocation AliasLoc,
2622 IdentifierInfo *Alias,
2623 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002624 SourceLocation IdentLoc,
2625 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00002626
Anders Carlsson81c85c42009-03-28 23:53:49 +00002627 // Lookup the namespace name.
2628 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
2629
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002630 // Check if we have a previous declaration with the same name.
Anders Carlssondd729fc2009-03-28 23:49:35 +00002631 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00002632 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002633 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00002634 // namespace, so don't create a new one.
2635 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
2636 return DeclPtrTy();
2637 }
Mike Stump1eb44332009-09-09 15:08:12 +00002638
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002639 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2640 diag::err_redefinition_different_kind;
2641 Diag(AliasLoc, DiagID) << Alias;
2642 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002643 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002644 }
2645
Anders Carlsson5721c682009-03-28 06:42:02 +00002646 if (R.isAmbiguous()) {
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002647 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002648 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002649 }
Mike Stump1eb44332009-09-09 15:08:12 +00002650
Anders Carlsson5721c682009-03-28 06:42:02 +00002651 if (!R) {
2652 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00002653 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002654 }
Mike Stump1eb44332009-09-09 15:08:12 +00002655
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002656 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00002657 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2658 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00002659 (NestedNameSpecifier *)SS.getScopeRep(),
Anders Carlsson68771c72009-03-28 22:58:02 +00002660 IdentLoc, R);
Mike Stump1eb44332009-09-09 15:08:12 +00002661
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002662 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00002663 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00002664}
2665
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002666void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2667 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00002668 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2669 !Constructor->isUsed()) &&
2670 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00002671
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002672 CXXRecordDecl *ClassDecl
2673 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002674 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Mike Stump1eb44332009-09-09 15:08:12 +00002675 // Before the implicitly-declared default constructor for a class is
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002676 // implicitly defined, all the implicitly-declared default constructors
2677 // for its base class and its non-static data members shall have been
2678 // implicitly defined.
2679 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002680 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2681 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002682 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002683 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002684 if (!BaseClassDecl->hasTrivialConstructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002685 if (CXXConstructorDecl *BaseCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002686 BaseClassDecl->getDefaultConstructor(Context))
2687 MarkDeclarationReferenced(CurrentLocation, BaseCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002688 else {
Mike Stump1eb44332009-09-09 15:08:12 +00002689 Diag(CurrentLocation, diag::err_defining_default_ctor)
2690 << Context.getTagDeclType(ClassDecl) << 1
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002691 << Context.getTagDeclType(BaseClassDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002692 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002693 << Context.getTagDeclType(BaseClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002694 err = true;
2695 }
2696 }
2697 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002698 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2699 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002700 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2701 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2702 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002703 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002704 CXXRecordDecl *FieldClassDecl
2705 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Duncan Sands6887e632009-06-25 09:03:06 +00002706 if (!FieldClassDecl->hasTrivialConstructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002707 if (CXXConstructorDecl *FieldCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002708 FieldClassDecl->getDefaultConstructor(Context))
2709 MarkDeclarationReferenced(CurrentLocation, FieldCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002710 else {
Mike Stump1eb44332009-09-09 15:08:12 +00002711 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002712 << Context.getTagDeclType(ClassDecl) << 0 <<
2713 Context.getTagDeclType(FieldClassDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002714 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002715 << Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002716 err = true;
2717 }
2718 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002719 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002720 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00002721 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002722 Diag((*Field)->getLocation(), diag::note_declared_at);
2723 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002724 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002725 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00002726 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002727 Diag((*Field)->getLocation(), diag::note_declared_at);
2728 err = true;
2729 }
2730 }
2731 if (!err)
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00002732 Constructor->setUsed();
2733 else
2734 Constructor->setInvalidDecl();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002735}
2736
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002737void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00002738 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002739 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2740 "DefineImplicitDestructor - call it for implicit default dtor");
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002742 CXXRecordDecl *ClassDecl
2743 = cast<CXXRecordDecl>(Destructor->getDeclContext());
2744 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2745 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00002746 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002747 // implicitly defined, all the implicitly-declared default destructors
2748 // for its base class and its non-static data members shall have been
2749 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002750 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2751 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002752 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002753 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002754 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002755 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002756 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2757 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2758 else
Mike Stump1eb44332009-09-09 15:08:12 +00002759 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002760 "DefineImplicitDestructor - missing dtor in a base class");
2761 }
2762 }
Mike Stump1eb44332009-09-09 15:08:12 +00002763
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002764 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2765 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002766 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2767 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2768 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002769 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002770 CXXRecordDecl *FieldClassDecl
2771 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2772 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002773 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002774 const_cast<CXXDestructorDecl*>(
2775 FieldClassDecl->getDestructor(Context)))
2776 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
2777 else
Mike Stump1eb44332009-09-09 15:08:12 +00002778 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002779 "DefineImplicitDestructor - missing dtor in class of a data member");
2780 }
2781 }
2782 }
2783 Destructor->setUsed();
2784}
2785
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002786void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
2787 CXXMethodDecl *MethodDecl) {
2788 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
2789 MethodDecl->getOverloadedOperator() == OO_Equal &&
2790 !MethodDecl->isUsed()) &&
2791 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00002792
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002793 CXXRecordDecl *ClassDecl
2794 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00002796 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002797 // Before the implicitly-declared copy assignment operator for a class is
2798 // implicitly defined, all implicitly-declared copy assignment operators
2799 // for its direct base classes and its nonstatic data members shall have
2800 // been implicitly defined.
2801 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002802 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2803 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002804 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002805 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002806 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002807 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
2808 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
2809 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002810 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2811 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002812 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2813 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2814 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002815 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002816 CXXRecordDecl *FieldClassDecl
2817 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002818 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002819 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
2820 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002821 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002822 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00002823 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
2824 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002825 Diag(CurrentLocation, diag::note_first_required_here);
2826 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002827 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002828 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00002829 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
2830 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002831 Diag(CurrentLocation, diag::note_first_required_here);
2832 err = true;
2833 }
2834 }
2835 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00002836 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002837}
2838
2839CXXMethodDecl *
2840Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
2841 CXXRecordDecl *ClassDecl) {
2842 QualType LHSType = Context.getTypeDeclType(ClassDecl);
2843 QualType RHSType(LHSType);
2844 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00002845 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002846 // operator = (B&).
2847 if (ParmDecl->getType().isConstQualified())
2848 RHSType.addConst();
2849 if (ParmDecl->getType().isVolatileQualified())
2850 RHSType.addVolatile();
Mike Stump1eb44332009-09-09 15:08:12 +00002851 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
2852 LHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002853 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00002854 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
2855 RHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002856 SourceLocation()));
2857 Expr *Args[2] = { &*LHS, &*RHS };
2858 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00002859 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002860 CandidateSet);
2861 OverloadCandidateSet::iterator Best;
Mike Stump1eb44332009-09-09 15:08:12 +00002862 if (BestViableFunction(CandidateSet,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002863 ClassDecl->getLocation(), Best) == OR_Success)
2864 return cast<CXXMethodDecl>(Best->Function);
2865 assert(false &&
2866 "getAssignOperatorMethod - copy assignment operator method not found");
2867 return 0;
2868}
2869
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002870void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2871 CXXConstructorDecl *CopyConstructor,
2872 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00002873 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002874 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
2875 !CopyConstructor->isUsed()) &&
2876 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00002877
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002878 CXXRecordDecl *ClassDecl
2879 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
2880 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002881 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00002882 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002883 // implicitly defined, all the implicitly-declared copy constructors
2884 // for its base class and its non-static data members shall have been
2885 // implicitly defined.
2886 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2887 Base != ClassDecl->bases_end(); ++Base) {
2888 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002889 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002890 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002891 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002892 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002893 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002894 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2895 FieldEnd = ClassDecl->field_end();
2896 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002897 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2898 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2899 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002900 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002901 CXXRecordDecl *FieldClassDecl
2902 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002903 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002904 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002905 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002906 }
2907 }
2908 CopyConstructor->setUsed();
2909}
2910
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002911Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00002912Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00002913 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002914 MultiExprArg ExprArgs) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002915 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002916
Douglas Gregor39da0b82009-09-09 23:08:42 +00002917 // C++ [class.copy]p15:
2918 // Whenever a temporary class object is copied using a copy constructor, and
2919 // this object and the copy have the same cv-unqualified type, an
2920 // implementation is permitted to treat the original and the copy as two
2921 // different ways of referring to the same object and not perform a copy at
2922 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00002923
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002924 // FIXME: Is this enough?
Douglas Gregor39da0b82009-09-09 23:08:42 +00002925 if (Constructor->isCopyConstructor(Context)) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00002926 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002927 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2928 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00002929 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2930 if (ICE->getCastKind() == CastExpr::CK_NoOp)
2931 E = ICE->getSubExpr();
2932
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002933 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
2934 Elidable = true;
2935 }
Mike Stump1eb44332009-09-09 15:08:12 +00002936
2937 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002938 Elidable, move(ExprArgs));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002939}
2940
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002941/// BuildCXXConstructExpr - Creates a complete call to a constructor,
2942/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002943Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00002944Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2945 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002946 MultiExprArg ExprArgs) {
2947 unsigned NumExprs = ExprArgs.size();
2948 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00002949
Douglas Gregor39da0b82009-09-09 23:08:42 +00002950 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
2951 Elidable, Exprs, NumExprs));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002952}
2953
Anders Carlssone7624a72009-08-27 05:08:22 +00002954Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00002955Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
2956 QualType Ty,
2957 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00002958 MultiExprArg Args,
2959 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002960 unsigned NumExprs = Args.size();
2961 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00002962
Douglas Gregor39da0b82009-09-09 23:08:42 +00002963 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
2964 TyBeginLoc, Exprs,
2965 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00002966}
2967
2968
Mike Stump1eb44332009-09-09 15:08:12 +00002969bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002970 CXXConstructorDecl *Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00002971 QualType DeclInitType,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002972 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002973 OwningExprResult TempResult =
2974 BuildCXXConstructExpr(VD->getLocation(), DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002975 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00002976 if (TempResult.isInvalid())
2977 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002978
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002979 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002980 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +00002981 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor78d15832009-05-26 18:54:04 +00002982 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00002983
Anders Carlssonfe2de492009-08-25 05:18:00 +00002984 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00002985}
2986
Mike Stump1eb44332009-09-09 15:08:12 +00002987void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002988 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00002989 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002990 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00002991 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002992 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002993 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002994}
2995
Mike Stump1eb44332009-09-09 15:08:12 +00002996/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002997/// ActOnDeclarator, when a C++ direct initializer is present.
2998/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00002999void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3000 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00003001 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003002 SourceLocation *CommaLocs,
3003 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00003004 unsigned NumExprs = Exprs.size();
3005 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00003006 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003007
3008 // If there is no declaration, there was an error parsing it. Just ignore
3009 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003010 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003011 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003012
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003013 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3014 if (!VDecl) {
3015 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3016 RealDecl->setInvalidDecl();
3017 return;
3018 }
3019
Douglas Gregor83ddad32009-08-26 21:14:46 +00003020 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003021 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003022 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3023 //
3024 // Clients that want to distinguish between the two forms, can check for
3025 // direct initializer using VarDecl::hasCXXDirectInitializer().
3026 // A major benefit is that clients that don't particularly care about which
3027 // exactly form was it (like the CodeGen) can handle both cases without
3028 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003029
Douglas Gregor83ddad32009-08-26 21:14:46 +00003030 // If either the declaration has a dependent type or if any of the expressions
3031 // is type-dependent, we represent the initialization via a ParenListExpr for
3032 // later use during template instantiation.
3033 if (VDecl->getType()->isDependentType() ||
3034 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3035 // Let clients know that initialization was done with a direct initializer.
3036 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003037
Douglas Gregor83ddad32009-08-26 21:14:46 +00003038 // Store the initialization expressions as a ParenListExpr.
3039 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003040 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003041 new (Context) ParenListExpr(Context, LParenLoc,
3042 (Expr **)Exprs.release(),
3043 NumExprs, RParenLoc));
3044 return;
3045 }
Mike Stump1eb44332009-09-09 15:08:12 +00003046
Douglas Gregor83ddad32009-08-26 21:14:46 +00003047
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003048 // C++ 8.5p11:
3049 // The form of initialization (using parentheses or '=') is generally
3050 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003051 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003052 QualType DeclInitType = VDecl->getType();
3053 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
3054 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003055
Douglas Gregor615c5d42009-03-24 16:43:20 +00003056 // FIXME: This isn't the right place to complete the type.
3057 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3058 diag::err_typecheck_decl_incomplete_type)) {
3059 VDecl->setInvalidDecl();
3060 return;
3061 }
3062
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003063 if (VDecl->getType()->isRecordType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003064 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3065
Douglas Gregor18fe5682008-11-03 20:45:27 +00003066 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00003067 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003068 move(Exprs),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003069 VDecl->getLocation(),
3070 SourceRange(VDecl->getLocation(),
3071 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003072 VDecl->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +00003073 IK_Direct,
3074 ConstructorArgs);
Sebastian Redlf53597f2009-03-15 17:47:39 +00003075 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00003076 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00003077 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00003078 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003079 if (InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003080 move_arg(ConstructorArgs)))
Anders Carlssonfe2de492009-08-25 05:18:00 +00003081 RealDecl->setInvalidDecl();
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003082 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00003083 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003084 return;
3085 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003086
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003087 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003088 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3089 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003090 RealDecl->setInvalidDecl();
3091 return;
3092 }
3093
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003094 // Let clients know that initialization was done with a direct initializer.
3095 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003096
3097 assert(NumExprs == 1 && "Expected 1 expression");
3098 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00003099 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3100 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003101}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003102
Douglas Gregor39da0b82009-09-09 23:08:42 +00003103/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3104/// may occur as part of direct-initialization or copy-initialization.
3105///
3106/// \param ClassType the type of the object being initialized, which must have
3107/// class type.
3108///
3109/// \param ArgsPtr the arguments provided to initialize the object
3110///
3111/// \param Loc the source location where the initialization occurs
3112///
3113/// \param Range the source range that covers the entire initialization
3114///
3115/// \param InitEntity the name of the entity being initialized, if known
3116///
3117/// \param Kind the type of initialization being performed
3118///
3119/// \param ConvertedArgs a vector that will be filled in with the
3120/// appropriately-converted arguments to the constructor (if initialization
3121/// succeeded).
3122///
3123/// \returns the constructor used to initialize the object, if successful.
3124/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003125CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003126Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003127 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003128 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003129 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003130 InitializationKind Kind,
3131 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003132 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregor18fe5682008-11-03 20:45:27 +00003133 assert(ClassRec && "Can only initialize a class type here");
Douglas Gregor39da0b82009-09-09 23:08:42 +00003134 Expr **Args = (Expr **)ArgsPtr.get();
3135 unsigned NumArgs = ArgsPtr.size();
3136
Mike Stump1eb44332009-09-09 15:08:12 +00003137 // C++ [dcl.init]p14:
Douglas Gregor18fe5682008-11-03 20:45:27 +00003138 // If the initialization is direct-initialization, or if it is
3139 // copy-initialization where the cv-unqualified version of the
3140 // source type is the same class as, or a derived class of, the
3141 // class of the destination, constructors are considered. The
3142 // applicable constructors are enumerated (13.3.1.3), and the
3143 // best one is chosen through overload resolution (13.3). The
3144 // constructor so selected is called to initialize the object,
3145 // with the initializer expression(s) as its argument(s). If no
3146 // constructor applies, or the overload resolution is ambiguous,
3147 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003148 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3149 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003150
3151 // Add constructors to the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00003152 DeclarationName ConstructorName
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003153 = Context.DeclarationNames.getCXXConstructorName(
3154 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003155 DeclContext::lookup_const_iterator Con, ConEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003156 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003157 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00003158 // Find the constructor (which may be a template).
3159 CXXConstructorDecl *Constructor = 0;
3160 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3161 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003162 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003163 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3164 else
3165 Constructor = cast<CXXConstructorDecl>(*Con);
3166
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003167 if ((Kind == IK_Direct) ||
Mike Stump1eb44332009-09-09 15:08:12 +00003168 (Kind == IK_Copy &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00003169 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregordec06662009-08-21 18:42:58 +00003170 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
3171 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003172 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
Douglas Gregordec06662009-08-21 18:42:58 +00003173 Args, NumArgs, CandidateSet);
3174 else
3175 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3176 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003177 }
3178
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003179 // FIXME: When we decide not to synthesize the implicitly-declared
3180 // constructors, we'll need to make them appear here.
3181
Douglas Gregor18fe5682008-11-03 20:45:27 +00003182 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003183 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00003184 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00003185 // We found a constructor. Break out so that we can convert the arguments
3186 // appropriately.
3187 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003188
Douglas Gregor18fe5682008-11-03 20:45:27 +00003189 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003190 if (InitEntity)
3191 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003192 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00003193 else
3194 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003195 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00003196 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00003197 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003198
Douglas Gregor18fe5682008-11-03 20:45:27 +00003199 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003200 if (InitEntity)
3201 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3202 else
3203 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003204 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3205 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003206
3207 case OR_Deleted:
3208 if (InitEntity)
3209 Diag(Loc, diag::err_ovl_deleted_init)
3210 << Best->Function->isDeleted()
3211 << InitEntity << Range;
3212 else
3213 Diag(Loc, diag::err_ovl_deleted_init)
3214 << Best->Function->isDeleted()
3215 << InitEntity << Range;
3216 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3217 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003218 }
Mike Stump1eb44332009-09-09 15:08:12 +00003219
Douglas Gregor39da0b82009-09-09 23:08:42 +00003220 // Convert the arguments, fill in default arguments, etc.
3221 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3222 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3223 return 0;
3224
3225 return Constructor;
3226}
3227
3228/// \brief Given a constructor and the set of arguments provided for the
3229/// constructor, convert the arguments and add any required default arguments
3230/// to form a proper call to this constructor.
3231///
3232/// \returns true if an error occurred, false otherwise.
3233bool
3234Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3235 MultiExprArg ArgsPtr,
3236 SourceLocation Loc,
3237 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3238 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3239 unsigned NumArgs = ArgsPtr.size();
3240 Expr **Args = (Expr **)ArgsPtr.get();
3241
3242 const FunctionProtoType *Proto
3243 = Constructor->getType()->getAs<FunctionProtoType>();
3244 assert(Proto && "Constructor without a prototype?");
3245 unsigned NumArgsInProto = Proto->getNumArgs();
3246 unsigned NumArgsToCheck = NumArgs;
3247
3248 // If too few arguments are available, we'll fill in the rest with defaults.
3249 if (NumArgs < NumArgsInProto) {
3250 NumArgsToCheck = NumArgsInProto;
3251 ConvertedArgs.reserve(NumArgsInProto);
3252 } else {
3253 ConvertedArgs.reserve(NumArgs);
3254 if (NumArgs > NumArgsInProto)
3255 NumArgsToCheck = NumArgsInProto;
3256 }
3257
3258 // Convert arguments
3259 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3260 QualType ProtoArgType = Proto->getArgType(i);
3261
3262 Expr *Arg;
3263 if (i < NumArgs) {
3264 Arg = Args[i];
Anders Carlsson71710112009-09-15 21:14:33 +00003265
3266 // Pass the argument.
3267 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3268 return true;
3269
3270 Args[i] = 0;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003271 } else {
3272 ParmVarDecl *Param = Constructor->getParamDecl(i);
3273
3274 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3275 if (DefArg.isInvalid())
3276 return true;
3277
3278 Arg = DefArg.takeAs<Expr>();
3279 }
3280
3281 ConvertedArgs.push_back(Arg);
3282 }
3283
3284 // If this is a variadic call, handle args passed through "...".
3285 if (Proto->isVariadic()) {
3286 // Promote the arguments (C99 6.5.2.2p7).
3287 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3288 Expr *Arg = Args[i];
3289 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3290 return true;
3291
3292 ConvertedArgs.push_back(Arg);
3293 Args[i] = 0;
3294 }
3295 }
3296
3297 return false;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003298}
3299
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003300/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3301/// determine whether they are reference-related,
3302/// reference-compatible, reference-compatible with added
3303/// qualification, or incompatible, for use in C++ initialization by
3304/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3305/// type, and the first type (T1) is the pointee type of the reference
3306/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00003307Sema::ReferenceCompareResult
3308Sema::CompareReferenceRelationship(QualType T1, QualType T2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003309 bool& DerivedToBase) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003310 assert(!T1->isReferenceType() &&
3311 "T1 must be the pointee type of the reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003312 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
3313
3314 T1 = Context.getCanonicalType(T1);
3315 T2 = Context.getCanonicalType(T2);
3316 QualType UnqualT1 = T1.getUnqualifiedType();
3317 QualType UnqualT2 = T2.getUnqualifiedType();
3318
3319 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003320 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00003321 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003322 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003323 if (UnqualT1 == UnqualT2)
3324 DerivedToBase = false;
3325 else if (IsDerivedFrom(UnqualT2, UnqualT1))
3326 DerivedToBase = true;
3327 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003328 return Ref_Incompatible;
3329
3330 // At this point, we know that T1 and T2 are reference-related (at
3331 // least).
3332
3333 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003334 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003335 // reference-related to T2 and cv1 is the same cv-qualification
3336 // as, or greater cv-qualification than, cv2. For purposes of
3337 // overload resolution, cases for which cv1 is greater
3338 // cv-qualification than cv2 are identified as
3339 // reference-compatible with added qualification (see 13.3.3.2).
3340 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3341 return Ref_Compatible;
3342 else if (T1.isMoreQualifiedThan(T2))
3343 return Ref_Compatible_With_Added_Qualification;
3344 else
3345 return Ref_Related;
3346}
3347
3348/// CheckReferenceInit - Check the initialization of a reference
3349/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3350/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00003351/// list), and DeclType is the type of the declaration. When ICS is
3352/// non-null, this routine will compute the implicit conversion
3353/// sequence according to C++ [over.ics.ref] and will not produce any
3354/// diagnostics; when ICS is null, it will emit diagnostics when any
3355/// errors are found. Either way, a return value of true indicates
3356/// that there was a failure, a return value of false indicates that
3357/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00003358///
3359/// When @p SuppressUserConversions, user-defined conversions are
3360/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003361/// When @p AllowExplicit, we also permit explicit user-defined
3362/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00003363/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00003364bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003365Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003366 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00003367 bool AllowExplicit, bool ForceRValue,
3368 ImplicitConversionSequence *ICS) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003369 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3370
Ted Kremenek6217b802009-07-29 21:53:49 +00003371 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003372 QualType T2 = Init->getType();
3373
Douglas Gregor904eed32008-11-10 20:40:00 +00003374 // If the initializer is the address of an overloaded function, try
3375 // to resolve the overloaded function. If all goes well, T2 is the
3376 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00003377 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00003378 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003379 ICS != 0);
3380 if (Fn) {
3381 // Since we're performing this reference-initialization for
3382 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003383 if (!ICS) {
3384 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
3385 return true;
3386
Douglas Gregor904eed32008-11-10 20:40:00 +00003387 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003388 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003389
3390 T2 = Fn->getType();
3391 }
3392 }
3393
Douglas Gregor15da57e2008-10-29 02:00:59 +00003394 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003395 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00003396 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00003397 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3398 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003399 ReferenceCompareResult RefRelationship
Douglas Gregor15da57e2008-10-29 02:00:59 +00003400 = CompareReferenceRelationship(T1, T2, DerivedToBase);
3401
3402 // Most paths end in a failed conversion.
3403 if (ICS)
3404 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003405
3406 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00003407 // A reference to type "cv1 T1" is initialized by an expression
3408 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003409
3410 // -- If the initializer expression
3411
Sebastian Redla9845802009-03-29 15:27:50 +00003412 // Rvalue references cannot bind to lvalues (N2812).
3413 // There is absolutely no situation where they can. In particular, note that
3414 // this is ill-formed, even if B has a user-defined conversion to A&&:
3415 // B b;
3416 // A&& r = b;
3417 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3418 if (!ICS)
3419 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
3420 << Init->getSourceRange();
3421 return true;
3422 }
3423
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003424 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00003425 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3426 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00003427 //
3428 // Note that the bit-field check is skipped if we are just computing
3429 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003430 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003431 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003432 BindsDirectly = true;
3433
Douglas Gregor15da57e2008-10-29 02:00:59 +00003434 if (ICS) {
3435 // C++ [over.ics.ref]p1:
3436 // When a parameter of reference type binds directly (8.5.3)
3437 // to an argument expression, the implicit conversion sequence
3438 // is the identity conversion, unless the argument expression
3439 // has a type that is a derived class of the parameter type,
3440 // in which case the implicit conversion sequence is a
3441 // derived-to-base Conversion (13.3.3.1).
3442 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3443 ICS->Standard.First = ICK_Identity;
3444 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3445 ICS->Standard.Third = ICK_Identity;
3446 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3447 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003448 ICS->Standard.ReferenceBinding = true;
3449 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003450 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00003451 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003452
3453 // Nothing more to do: the inaccessibility/ambiguity check for
3454 // derived-to-base conversions is suppressed when we're
3455 // computing the implicit conversion sequence (C++
3456 // [over.best.ics]p2).
3457 return false;
3458 } else {
3459 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00003460 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3461 if (DerivedToBase)
3462 CK = CastExpr::CK_DerivedToBase;
3463 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003464 }
3465 }
3466
3467 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00003468 // implicitly converted to an lvalue of type "cv3 T3,"
3469 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003470 // 92) (this conversion is selected by enumerating the
3471 // applicable conversion functions (13.3.1.6) and choosing
3472 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00003473 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
3474 !RequireCompleteType(SourceLocation(), T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003475 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003476 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003477
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003478 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003479 OverloadedFunctionDecl *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003480 = T2RecordDecl->getVisibleConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00003481 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003482 = Conversions->function_begin();
3483 Func != Conversions->function_end(); ++Func) {
Mike Stump1eb44332009-09-09 15:08:12 +00003484 FunctionTemplateDecl *ConvTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003485 = dyn_cast<FunctionTemplateDecl>(*Func);
3486 CXXConversionDecl *Conv;
3487 if (ConvTemplate)
3488 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3489 else
3490 Conv = cast<CXXConversionDecl>(*Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003491
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003492 // If the conversion function doesn't return a reference type,
3493 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003494 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003495 (AllowExplicit || !Conv->isExplicit())) {
3496 if (ConvTemplate)
Mike Stump1eb44332009-09-09 15:08:12 +00003497 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003498 CandidateSet);
3499 else
3500 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3501 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003502 }
3503
3504 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003505 switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003506 case OR_Success:
3507 // This is a direct binding.
3508 BindsDirectly = true;
3509
3510 if (ICS) {
3511 // C++ [over.ics.ref]p1:
3512 //
3513 // [...] If the parameter binds directly to the result of
3514 // applying a conversion function to the argument
3515 // expression, the implicit conversion sequence is a
3516 // user-defined conversion sequence (13.3.3.1.2), with the
3517 // second standard conversion sequence either an identity
3518 // conversion or, if the conversion function returns an
3519 // entity of a type that is a derived class of the parameter
3520 // type, a derived-to-base Conversion.
3521 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3522 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3523 ICS->UserDefined.After = Best->FinalConversion;
3524 ICS->UserDefined.ConversionFunction = Best->Function;
3525 assert(ICS->UserDefined.After.ReferenceBinding &&
3526 ICS->UserDefined.After.DirectBinding &&
3527 "Expected a direct reference binding!");
3528 return false;
3529 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003530 OwningExprResult InitConversion =
3531 BuildCXXCastArgument(Init->getLocStart(), QualType(),
3532 CastExpr::CK_UserDefinedConversion,
3533 cast<CXXMethodDecl>(Best->Function),
3534 Owned(Init));
3535 Init = InitConversion.takeAs<Expr>();
3536
3537 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3538 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003539 }
3540 break;
3541
3542 case OR_Ambiguous:
3543 assert(false && "Ambiguous reference binding conversions not implemented.");
3544 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003545
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003546 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003547 case OR_Deleted:
3548 // There was no suitable conversion, or we found a deleted
3549 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003550 break;
3551 }
3552 }
Mike Stump1eb44332009-09-09 15:08:12 +00003553
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003554 if (BindsDirectly) {
3555 // C++ [dcl.init.ref]p4:
3556 // [...] In all cases where the reference-related or
3557 // reference-compatible relationship of two types is used to
3558 // establish the validity of a reference binding, and T1 is a
3559 // base class of T2, a program that necessitates such a binding
3560 // is ill-formed if T1 is an inaccessible (clause 11) or
3561 // ambiguous (10.2) base class of T2.
3562 //
3563 // Note that we only check this condition when we're allowed to
3564 // complain about errors, because we should not be checking for
3565 // ambiguity (or inaccessibility) unless the reference binding
3566 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00003567 if (DerivedToBase)
3568 return CheckDerivedToBaseConversion(T2, T1,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003569 Init->getSourceRange().getBegin(),
3570 Init->getSourceRange());
3571 else
3572 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003573 }
3574
3575 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00003576 // type (i.e., cv1 shall be const), or the reference shall be an
3577 // rvalue reference and the initializer expression shall be an rvalue.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003578 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00003579 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003580 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003581 diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00003582 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3583 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003584 return true;
3585 }
3586
3587 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00003588 // class type, and "cv1 T1" is reference-compatible with
3589 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003590 // following ways (the choice is implementation-defined):
3591 //
3592 // -- The reference is bound to the object represented by
3593 // the rvalue (see 3.10) or to a sub-object within that
3594 // object.
3595 //
Eli Friedman33a31382009-08-05 19:21:58 +00003596 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003597 // a constructor is called to copy the entire rvalue
3598 // object into the temporary. The reference is bound to
3599 // the temporary or to a sub-object within the
3600 // temporary.
3601 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003602 // The constructor that would be used to make the copy
3603 // shall be callable whether or not the copy is actually
3604 // done.
3605 //
Sebastian Redla9845802009-03-29 15:27:50 +00003606 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003607 // freedom, so we will always take the first option and never build
3608 // a temporary in this case. FIXME: We will, however, have to check
3609 // for the presence of a copy constructor in C++98/03 mode.
3610 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003611 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3612 if (ICS) {
3613 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3614 ICS->Standard.First = ICK_Identity;
3615 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3616 ICS->Standard.Third = ICK_Identity;
3617 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3618 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003619 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003620 ICS->Standard.DirectBinding = false;
3621 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00003622 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003623 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003624 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3625 if (DerivedToBase)
3626 CK = CastExpr::CK_DerivedToBase;
3627 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003628 }
3629 return false;
3630 }
3631
Eli Friedman33a31382009-08-05 19:21:58 +00003632 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003633 // initialized from the initializer expression using the
3634 // rules for a non-reference copy initialization (8.5). The
3635 // reference is then bound to the temporary. If T1 is
3636 // reference-related to T2, cv1 must be the same
3637 // cv-qualification as, or greater cv-qualification than,
3638 // cv2; otherwise, the program is ill-formed.
3639 if (RefRelationship == Ref_Related) {
3640 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3641 // we would be reference-compatible or reference-compatible with
3642 // added qualification. But that wasn't the case, so the reference
3643 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003644 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003645 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003646 diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00003647 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3648 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003649 return true;
3650 }
3651
Douglas Gregor734d9862009-01-30 23:27:23 +00003652 // If at least one of the types is a class type, the types are not
3653 // related, and we aren't allowed any user conversions, the
3654 // reference binding fails. This case is important for breaking
3655 // recursion, since TryImplicitConversion below will attempt to
3656 // create a temporary through the use of a copy constructor.
3657 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3658 (T1->isRecordType() || T2->isRecordType())) {
3659 if (!ICS)
3660 Diag(Init->getSourceRange().getBegin(),
3661 diag::err_typecheck_convert_incompatible)
3662 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3663 return true;
3664 }
3665
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003666 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003667 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00003668 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003669 //
Sebastian Redla9845802009-03-29 15:27:50 +00003670 // When a parameter of reference type is not bound directly to
3671 // an argument expression, the conversion sequence is the one
3672 // required to convert the argument expression to the
3673 // underlying type of the reference according to
3674 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3675 // to copy-initializing a temporary of the underlying type with
3676 // the argument expression. Any difference in top-level
3677 // cv-qualification is subsumed by the initialization itself
3678 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003679 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
3680 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00003681 /*ForceRValue=*/false,
3682 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003683
Sebastian Redla9845802009-03-29 15:27:50 +00003684 // Of course, that's still a reference binding.
3685 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3686 ICS->Standard.ReferenceBinding = true;
3687 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003688 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00003689 ImplicitConversionSequence::UserDefinedConversion) {
3690 ICS->UserDefined.After.ReferenceBinding = true;
3691 ICS->UserDefined.After.RRefBinding = isRValRef;
3692 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00003693 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3694 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003695 ImplicitConversionSequence Conversions;
3696 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
3697 false, false,
3698 Conversions);
3699 if (badConversion) {
3700 if ((Conversions.ConversionKind ==
3701 ImplicitConversionSequence::BadConversion)
3702 && Conversions.ConversionFunctionSet.size() > 0) {
3703 Diag(Init->getSourceRange().getBegin(),
3704 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
3705 for (int j = Conversions.ConversionFunctionSet.size()-1;
3706 j >= 0; j--) {
3707 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
3708 Diag(Func->getLocation(), diag::err_ovl_candidate);
3709 }
3710 }
3711 else
3712 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
3713 << Init->getSourceRange();
3714 }
3715 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003716 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003717}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003718
3719/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3720/// of this overloaded operator is well-formed. If so, returns false;
3721/// otherwise, emits appropriate diagnostics and returns true.
3722bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003723 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003724 "Expected an overloaded operator declaration");
3725
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003726 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
3727
Mike Stump1eb44332009-09-09 15:08:12 +00003728 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003729 // The allocation and deallocation functions, operator new,
3730 // operator new[], operator delete and operator delete[], are
3731 // described completely in 3.7.3. The attributes and restrictions
3732 // found in the rest of this subclause do not apply to them unless
3733 // explicitly stated in 3.7.3.
Mike Stump390b4cc2009-05-16 07:39:55 +00003734 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003735 if (Op == OO_New || Op == OO_Array_New ||
3736 Op == OO_Delete || Op == OO_Array_Delete)
3737 return false;
3738
3739 // C++ [over.oper]p6:
3740 // An operator function shall either be a non-static member
3741 // function or be a non-member function and have at least one
3742 // parameter whose type is a class, a reference to a class, an
3743 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003744 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
3745 if (MethodDecl->isStatic())
3746 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003747 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003748 } else {
3749 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003750 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
3751 ParamEnd = FnDecl->param_end();
3752 Param != ParamEnd; ++Param) {
3753 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00003754 if (ParamType->isDependentType() || ParamType->isRecordType() ||
3755 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003756 ClassOrEnumParam = true;
3757 break;
3758 }
3759 }
3760
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003761 if (!ClassOrEnumParam)
3762 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003763 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003764 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003765 }
3766
3767 // C++ [over.oper]p8:
3768 // An operator function cannot have default arguments (8.3.6),
3769 // except where explicitly stated below.
3770 //
Mike Stump1eb44332009-09-09 15:08:12 +00003771 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003772 // (C++ [over.call]p1).
3773 if (Op != OO_Call) {
3774 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
3775 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00003776 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00003777 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00003778 diag::err_operator_overload_default_arg)
3779 << FnDecl->getDeclName();
3780 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003781 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003782 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003783 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003784 }
3785 }
3786
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003787 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
3788 { false, false, false }
3789#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3790 , { Unary, Binary, MemberOnly }
3791#include "clang/Basic/OperatorKinds.def"
3792 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003793
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003794 bool CanBeUnaryOperator = OperatorUses[Op][0];
3795 bool CanBeBinaryOperator = OperatorUses[Op][1];
3796 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003797
3798 // C++ [over.oper]p8:
3799 // [...] Operator functions cannot have more or fewer parameters
3800 // than the number required for the corresponding operator, as
3801 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00003802 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003803 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003804 if (Op != OO_Call &&
3805 ((NumParams == 1 && !CanBeUnaryOperator) ||
3806 (NumParams == 2 && !CanBeBinaryOperator) ||
3807 (NumParams < 1) || (NumParams > 2))) {
3808 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00003809 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003810 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00003811 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003812 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00003813 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003814 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00003815 assert(CanBeBinaryOperator &&
3816 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00003817 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003818 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003819
Chris Lattner416e46f2008-11-21 07:57:12 +00003820 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003821 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003822 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003823
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003824 // Overloaded operators other than operator() cannot be variadic.
3825 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00003826 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003827 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003828 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003829 }
3830
3831 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003832 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
3833 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003834 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003835 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003836 }
3837
3838 // C++ [over.inc]p1:
3839 // The user-defined function called operator++ implements the
3840 // prefix and postfix ++ operator. If this function is a member
3841 // function with no parameters, or a non-member function with one
3842 // parameter of class or enumeration type, it defines the prefix
3843 // increment operator ++ for objects of that type. If the function
3844 // is a member function with one parameter (which shall be of type
3845 // int) or a non-member function with two parameters (the second
3846 // of which shall be of type int), it defines the postfix
3847 // increment operator ++ for objects of that type.
3848 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
3849 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
3850 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00003851 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003852 ParamIsInt = BT->getKind() == BuiltinType::Int;
3853
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00003854 if (!ParamIsInt)
3855 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003856 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00003857 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003858 }
3859
Sebastian Redl64b45f72009-01-05 20:52:13 +00003860 // Notify the class if it got an assignment operator.
3861 if (Op == OO_Equal) {
3862 // Would have returned earlier otherwise.
3863 assert(isa<CXXMethodDecl>(FnDecl) &&
3864 "Overloaded = not member, but not filtered.");
3865 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Fariborz Jahanianad258832009-08-13 21:09:41 +00003866 Method->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003867 Method->getParent()->addedAssignmentOperator(Context, Method);
3868 }
3869
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003870 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003871}
Chris Lattner5a003a42008-12-17 07:09:26 +00003872
Douglas Gregor074149e2009-01-05 19:45:36 +00003873/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
3874/// linkage specification, including the language and (if present)
3875/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
3876/// the location of the language string literal, which is provided
3877/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
3878/// the '{' brace. Otherwise, this linkage specification does not
3879/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003880Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
3881 SourceLocation ExternLoc,
3882 SourceLocation LangLoc,
3883 const char *Lang,
3884 unsigned StrSize,
3885 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00003886 LinkageSpecDecl::LanguageIDs Language;
3887 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3888 Language = LinkageSpecDecl::lang_c;
3889 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3890 Language = LinkageSpecDecl::lang_cxx;
3891 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00003892 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003893 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00003894 }
Mike Stump1eb44332009-09-09 15:08:12 +00003895
Chris Lattnercc98eac2008-12-17 07:13:27 +00003896 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00003897
Douglas Gregor074149e2009-01-05 19:45:36 +00003898 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00003899 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00003900 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003901 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00003902 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003903 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00003904}
3905
Douglas Gregor074149e2009-01-05 19:45:36 +00003906/// ActOnFinishLinkageSpecification - Completely the definition of
3907/// the C++ linkage specification LinkageSpec. If RBraceLoc is
3908/// valid, it's the position of the closing '}' brace in a linkage
3909/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003910Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
3911 DeclPtrTy LinkageSpec,
3912 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00003913 if (LinkageSpec)
3914 PopDeclContext();
3915 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00003916}
3917
Douglas Gregord308e622009-05-18 20:51:54 +00003918/// \brief Perform semantic analysis for the variable declaration that
3919/// occurs within a C++ catch clause, returning the newly-created
3920/// variable.
3921VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003922 DeclaratorInfo *DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00003923 IdentifierInfo *Name,
3924 SourceLocation Loc,
3925 SourceRange Range) {
3926 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003927
3928 // Arrays and functions decay.
3929 if (ExDeclType->isArrayType())
3930 ExDeclType = Context.getArrayDecayedType(ExDeclType);
3931 else if (ExDeclType->isFunctionType())
3932 ExDeclType = Context.getPointerType(ExDeclType);
3933
3934 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
3935 // The exception-declaration shall not denote a pointer or reference to an
3936 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003937 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00003938 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00003939 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003940 Invalid = true;
3941 }
Douglas Gregord308e622009-05-18 20:51:54 +00003942
Sebastian Redl4b07b292008-12-22 19:15:10 +00003943 QualType BaseType = ExDeclType;
3944 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003945 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00003946 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003947 BaseType = Ptr->getPointeeType();
3948 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003949 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00003950 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003951 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00003952 BaseType = Ref->getPointeeType();
3953 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003954 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003955 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003956 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00003957 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00003958 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003959
Mike Stump1eb44332009-09-09 15:08:12 +00003960 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00003961 RequireNonAbstractType(Loc, ExDeclType,
3962 diag::err_abstract_type_in_decl,
3963 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00003964 Invalid = true;
3965
Douglas Gregord308e622009-05-18 20:51:54 +00003966 // FIXME: Need to test for ability to copy-construct and destroy the
3967 // exception variable.
3968
Sebastian Redl8351da02008-12-22 21:35:02 +00003969 // FIXME: Need to check for abstract classes.
3970
Mike Stump1eb44332009-09-09 15:08:12 +00003971 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003972 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00003973
3974 if (Invalid)
3975 ExDecl->setInvalidDecl();
3976
3977 return ExDecl;
3978}
3979
3980/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
3981/// handler.
3982Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003983 DeclaratorInfo *DInfo = 0;
3984 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00003985
3986 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00003987 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003988 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003989 // The scope should be freshly made just for us. There is just no way
3990 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003991 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00003992 if (PrevDecl->isTemplateParameter()) {
3993 // Maybe we will complain about the shadowed template parameter.
3994 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003995 }
3996 }
3997
Chris Lattnereaaebc72009-04-25 08:06:05 +00003998 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003999 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4000 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004001 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004002 }
4003
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004004 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004005 D.getIdentifier(),
4006 D.getIdentifierLoc(),
4007 D.getDeclSpec().getSourceRange());
4008
Chris Lattnereaaebc72009-04-25 08:06:05 +00004009 if (Invalid)
4010 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004011
Sebastian Redl4b07b292008-12-22 19:15:10 +00004012 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004013 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00004014 PushOnScopeChains(ExDecl, S);
4015 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004016 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004017
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004018 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004019 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004020}
Anders Carlssonfb311762009-03-14 00:25:26 +00004021
Mike Stump1eb44332009-09-09 15:08:12 +00004022Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004023 ExprArg assertexpr,
4024 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00004025 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004026 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00004027 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4028
Anders Carlssonc3082412009-03-14 00:33:21 +00004029 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4030 llvm::APSInt Value(32);
4031 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4032 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4033 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00004034 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00004035 }
Anders Carlssonfb311762009-03-14 00:25:26 +00004036
Anders Carlssonc3082412009-03-14 00:33:21 +00004037 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00004038 std::string str(AssertMessage->getStrData(),
Anders Carlssonc3082412009-03-14 00:33:21 +00004039 AssertMessage->getByteLength());
Mike Stump1eb44332009-09-09 15:08:12 +00004040 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson94b15fb2009-03-15 18:44:04 +00004041 << str << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00004042 }
4043 }
Mike Stump1eb44332009-09-09 15:08:12 +00004044
Anders Carlsson77d81422009-03-15 17:35:16 +00004045 assertexpr.release();
4046 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004047 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00004048 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00004049
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004050 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004051 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00004052}
Sebastian Redl50de12f2009-03-24 22:27:57 +00004053
John McCalldd4a3b02009-09-16 22:47:08 +00004054/// Handle a friend type declaration. This works in tandem with
4055/// ActOnTag.
4056///
4057/// Notes on friend class templates:
4058///
4059/// We generally treat friend class declarations as if they were
4060/// declaring a class. So, for example, the elaborated type specifier
4061/// in a friend declaration is required to obey the restrictions of a
4062/// class-head (i.e. no typedefs in the scope chain), template
4063/// parameters are required to match up with simple template-ids, &c.
4064/// However, unlike when declaring a template specialization, it's
4065/// okay to refer to a template specialization without an empty
4066/// template parameter declaration, e.g.
4067/// friend class A<T>::B<unsigned>;
4068/// We permit this as a special case; if there are any template
4069/// parameters present at all, require proper matching, i.e.
4070/// template <> template <class T> friend class A<int>::B;
John McCall02cace72009-08-28 07:59:38 +00004071Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S,
John McCall05b23ea2009-09-14 21:59:20 +00004072 const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00004073 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00004074 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00004075
4076 assert(DS.isFriendSpecified());
4077 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4078
John McCalldd4a3b02009-09-16 22:47:08 +00004079 // Try to convert the decl specifier to a type. This works for
4080 // friend templates because ActOnTag never produces a ClassTemplateDecl
4081 // for a TUK_Friend.
John McCall6b2becf2009-09-08 17:47:29 +00004082 bool invalid = false;
4083 QualType T = ConvertDeclSpecToType(DS, Loc, invalid);
4084 if (invalid) return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00004085
John McCalldd4a3b02009-09-16 22:47:08 +00004086 // This is definitely an error in C++98. It's probably meant to
4087 // be forbidden in C++0x, too, but the specification is just
4088 // poorly written.
4089 //
4090 // The problem is with declarations like the following:
4091 // template <T> friend A<T>::foo;
4092 // where deciding whether a class C is a friend or not now hinges
4093 // on whether there exists an instantiation of A that causes
4094 // 'foo' to equal C. There are restrictions on class-heads
4095 // (which we declare (by fiat) elaborated friend declarations to
4096 // be) that makes this tractable.
4097 //
4098 // FIXME: handle "template <> friend class A<T>;", which
4099 // is possibly well-formed? Who even knows?
4100 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4101 Diag(Loc, diag::err_tagless_friend_type_template)
4102 << DS.getSourceRange();
4103 return DeclPtrTy();
4104 }
4105
John McCall02cace72009-08-28 07:59:38 +00004106 // C++ [class.friend]p2:
4107 // An elaborated-type-specifier shall be used in a friend declaration
4108 // for a class.*
4109 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00004110 // This is one of the rare places in Clang where it's legitimate to
4111 // ask about the "spelling" of the type.
4112 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4113 // If we evaluated the type to a record type, suggest putting
4114 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00004115 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00004116 RecordDecl *RD = RT->getDecl();
4117
4118 std::string InsertionText = std::string(" ") + RD->getKindName();
4119
4120 Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type)
4121 << (RD->isUnion())
4122 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4123 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00004124 return DeclPtrTy();
4125 }else {
John McCall6b2becf2009-09-08 17:47:29 +00004126 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4127 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004128 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00004129 }
4130 }
4131
John McCallbbbcdd92009-09-11 21:02:39 +00004132 bool IsDefinition = false;
John McCall6b2becf2009-09-08 17:47:29 +00004133
John McCallbbbcdd92009-09-11 21:02:39 +00004134 // We want to do a few things differently if the type was declared with
4135 // a tag: specifically, we want to use the associated RecordDecl as
4136 // the object of our friend declaration, and we want to disallow
4137 // class definitions.
John McCall6b2becf2009-09-08 17:47:29 +00004138 switch (DS.getTypeSpecType()) {
4139 default: break;
4140 case DeclSpec::TST_class:
4141 case DeclSpec::TST_struct:
4142 case DeclSpec::TST_union:
4143 CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep());
John McCalldd4a3b02009-09-16 22:47:08 +00004144 if (RD)
John McCall6b2becf2009-09-08 17:47:29 +00004145 IsDefinition |= RD->isDefinition();
John McCall6b2becf2009-09-08 17:47:29 +00004146 break;
4147 }
John McCall02cace72009-08-28 07:59:38 +00004148
4149 // C++ [class.friend]p2: A class shall not be defined inside
4150 // a friend declaration.
4151 if (IsDefinition) {
4152 Diag(DS.getFriendSpecLoc(), diag::err_friend_decl_defines_class)
4153 << DS.getSourceRange();
4154 return DeclPtrTy();
4155 }
4156
4157 // C++98 [class.friend]p1: A friend of a class is a function
4158 // or class that is not a member of the class . . .
4159 // But that's a silly restriction which nobody implements for
4160 // inner classes, and C++0x removes it anyway, so we only report
4161 // this (as a warning) if we're being pedantic.
John McCall6b2becf2009-09-08 17:47:29 +00004162 if (!getLangOptions().CPlusPlus0x)
4163 if (const RecordType *RT = T->getAs<RecordType>())
4164 if (RT->getDecl()->getDeclContext() == CurContext)
4165 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCall02cace72009-08-28 07:59:38 +00004166
John McCalldd4a3b02009-09-16 22:47:08 +00004167 Decl *D;
4168 if (TempParams.size())
4169 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4170 TempParams.size(),
4171 (TemplateParameterList**) TempParams.release(),
4172 T.getTypePtr(),
4173 DS.getFriendSpecLoc());
4174 else
4175 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4176 DS.getFriendSpecLoc());
4177 D->setAccess(AS_public);
4178 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00004179
John McCalldd4a3b02009-09-16 22:47:08 +00004180 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00004181}
4182
John McCallbbbcdd92009-09-11 21:02:39 +00004183Sema::DeclPtrTy
4184Sema::ActOnFriendFunctionDecl(Scope *S,
4185 Declarator &D,
4186 bool IsDefinition,
4187 MultiTemplateParamsArg TemplateParams) {
4188 // FIXME: do something with template parameters
4189
John McCall02cace72009-08-28 07:59:38 +00004190 const DeclSpec &DS = D.getDeclSpec();
4191
4192 assert(DS.isFriendSpecified());
4193 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4194
4195 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004196 DeclaratorInfo *DInfo = 0;
John McCall02cace72009-08-28 07:59:38 +00004197 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall67d1a672009-08-06 02:15:43 +00004198
4199 // C++ [class.friend]p1
4200 // A friend of a class is a function or class....
4201 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00004202 // It *doesn't* see through dependent types, which is correct
4203 // according to [temp.arg.type]p3:
4204 // If a declaration acquires a function type through a
4205 // type dependent on a template-parameter and this causes
4206 // a declaration that does not use the syntactic form of a
4207 // function declarator to have a function type, the program
4208 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00004209 if (!T->isFunctionType()) {
4210 Diag(Loc, diag::err_unexpected_friend);
4211
4212 // It might be worthwhile to try to recover by creating an
4213 // appropriate declaration.
4214 return DeclPtrTy();
4215 }
4216
4217 // C++ [namespace.memdef]p3
4218 // - If a friend declaration in a non-local class first declares a
4219 // class or function, the friend class or function is a member
4220 // of the innermost enclosing namespace.
4221 // - The name of the friend is not found by simple name lookup
4222 // until a matching declaration is provided in that namespace
4223 // scope (either before or after the class declaration granting
4224 // friendship).
4225 // - If a friend function is called, its name may be found by the
4226 // name lookup that considers functions from namespaces and
4227 // classes associated with the types of the function arguments.
4228 // - When looking for a prior declaration of a class or a function
4229 // declared as a friend, scopes outside the innermost enclosing
4230 // namespace scope are not considered.
4231
John McCall02cace72009-08-28 07:59:38 +00004232 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4233 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00004234 assert(Name);
4235
4236 // The existing declaration we found.
4237 FunctionDecl *FD = NULL;
4238
4239 // The context we found the declaration in, or in which we should
4240 // create the declaration.
4241 DeclContext *DC;
4242
4243 // FIXME: handle local classes
4244
4245 // Recover from invalid scope qualifiers as if they just weren't there.
4246 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
4247 DC = computeDeclContext(ScopeQual);
4248
4249 // FIXME: handle dependent contexts
4250 if (!DC) return DeclPtrTy();
4251
4252 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
4253
4254 // If searching in that context implicitly found a declaration in
4255 // a different context, treat it like it wasn't found at all.
4256 // TODO: better diagnostics for this case. Suggesting the right
4257 // qualified scope would be nice...
4258 if (!Dec || Dec->getDeclContext() != DC) {
John McCall02cace72009-08-28 07:59:38 +00004259 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00004260 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4261 return DeclPtrTy();
4262 }
4263
4264 // C++ [class.friend]p1: A friend of a class is a function or
4265 // class that is not a member of the class . . .
4266 if (DC == CurContext)
4267 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4268
4269 FD = cast<FunctionDecl>(Dec);
4270
4271 // Otherwise walk out to the nearest namespace scope looking for matches.
4272 } else {
4273 // TODO: handle local class contexts.
4274
4275 DC = CurContext;
4276 while (true) {
4277 // Skip class contexts. If someone can cite chapter and verse
4278 // for this behavior, that would be nice --- it's what GCC and
4279 // EDG do, and it seems like a reasonable intent, but the spec
4280 // really only says that checks for unqualified existing
4281 // declarations should stop at the nearest enclosing namespace,
4282 // not that they should only consider the nearest enclosing
4283 // namespace.
4284 while (DC->isRecord()) DC = DC->getParent();
4285
4286 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
4287
4288 // TODO: decide what we think about using declarations.
4289 if (Dec) {
4290 FD = cast<FunctionDecl>(Dec);
4291 break;
4292 }
4293 if (DC->isFileContext()) break;
4294 DC = DC->getParent();
4295 }
4296
4297 // C++ [class.friend]p1: A friend of a class is a function or
4298 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00004299 // C++0x changes this for both friend types and functions.
4300 // Most C++ 98 compilers do seem to give an error here, so
4301 // we do, too.
4302 if (FD && DC == CurContext && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00004303 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4304 }
4305
John McCall3f9a8a62009-08-11 06:59:38 +00004306 bool Redeclaration = (FD != 0);
4307
4308 // If we found a match, create a friend function declaration with
4309 // that function as the previous declaration.
4310 if (Redeclaration) {
4311 // Create it in the semantic context of the original declaration.
4312 DC = FD->getDeclContext();
4313
John McCall67d1a672009-08-06 02:15:43 +00004314 // If we didn't find something matching the type exactly, create
4315 // a declaration. This declaration should only be findable via
4316 // argument-dependent lookup.
John McCall3f9a8a62009-08-11 06:59:38 +00004317 } else {
John McCall67d1a672009-08-06 02:15:43 +00004318 assert(DC->isFileContext());
4319
4320 // This implies that it has to be an operator or function.
John McCall02cace72009-08-28 07:59:38 +00004321 if (D.getKind() == Declarator::DK_Constructor ||
4322 D.getKind() == Declarator::DK_Destructor ||
4323 D.getKind() == Declarator::DK_Conversion) {
John McCall67d1a672009-08-06 02:15:43 +00004324 Diag(Loc, diag::err_introducing_special_friend) <<
John McCall02cace72009-08-28 07:59:38 +00004325 (D.getKind() == Declarator::DK_Constructor ? 0 :
4326 D.getKind() == Declarator::DK_Destructor ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00004327 return DeclPtrTy();
4328 }
John McCall67d1a672009-08-06 02:15:43 +00004329 }
4330
John McCall02cace72009-08-28 07:59:38 +00004331 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo,
John McCall3f9a8a62009-08-11 06:59:38 +00004332 /* PrevDecl = */ FD,
4333 MultiTemplateParamsArg(*this),
4334 IsDefinition,
4335 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00004336 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00004337
4338 assert(cast<FunctionDecl>(ND)->getPreviousDeclaration() == FD &&
4339 "lost reference to previous declaration");
4340
John McCall02cace72009-08-28 07:59:38 +00004341 FD = cast<FunctionDecl>(ND);
John McCall3f9a8a62009-08-11 06:59:38 +00004342
John McCall88232aa2009-08-18 00:00:49 +00004343 assert(FD->getDeclContext() == DC);
4344 assert(FD->getLexicalDeclContext() == CurContext);
4345
John McCallab88d972009-08-31 22:39:49 +00004346 // Add the function declaration to the appropriate lookup tables,
4347 // adjusting the redeclarations list as necessary. We don't
4348 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00004349 //
John McCallab88d972009-08-31 22:39:49 +00004350 // Also update the scope-based lookup if the target context's
4351 // lookup context is in lexical scope.
4352 if (!CurContext->isDependentContext()) {
4353 DC = DC->getLookupContext();
4354 DC->makeDeclVisibleInContext(FD, /* Recoverable=*/ false);
4355 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4356 PushOnScopeChains(FD, EnclosingScope, /*AddToContext=*/ false);
4357 }
John McCall02cace72009-08-28 07:59:38 +00004358
4359 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
4360 D.getIdentifierLoc(), FD,
4361 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00004362 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00004363 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00004364
4365 return DeclPtrTy::make(FD);
Anders Carlsson00338362009-05-11 22:55:49 +00004366}
4367
Chris Lattnerb28317a2009-03-28 19:18:32 +00004368void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004369 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004370
Chris Lattnerb28317a2009-03-28 19:18:32 +00004371 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00004372 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4373 if (!Fn) {
4374 Diag(DelLoc, diag::err_deleted_non_function);
4375 return;
4376 }
4377 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4378 Diag(DelLoc, diag::err_deleted_decl_not_first);
4379 Diag(Prev->getLocation(), diag::note_previous_declaration);
4380 // If the declaration wasn't the first, we delete the function anyway for
4381 // recovery.
4382 }
4383 Fn->setDeleted();
4384}
Sebastian Redl13e88542009-04-27 21:33:24 +00004385
4386static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4387 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4388 ++CI) {
4389 Stmt *SubStmt = *CI;
4390 if (!SubStmt)
4391 continue;
4392 if (isa<ReturnStmt>(SubStmt))
4393 Self.Diag(SubStmt->getSourceRange().getBegin(),
4394 diag::err_return_in_constructor_handler);
4395 if (!isa<Expr>(SubStmt))
4396 SearchForReturnInStmt(Self, SubStmt);
4397 }
4398}
4399
4400void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4401 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4402 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4403 SearchForReturnInStmt(*this, Handler);
4404 }
4405}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004406
Mike Stump1eb44332009-09-09 15:08:12 +00004407bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004408 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00004409 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4410 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004411
4412 QualType CNewTy = Context.getCanonicalType(NewTy);
4413 QualType COldTy = Context.getCanonicalType(OldTy);
4414
Mike Stump1eb44332009-09-09 15:08:12 +00004415 if (CNewTy == COldTy &&
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004416 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
4417 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004418
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004419 // Check if the return types are covariant
4420 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004421
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004422 /// Both types must be pointers or references to classes.
4423 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4424 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4425 NewClassTy = NewPT->getPointeeType();
4426 OldClassTy = OldPT->getPointeeType();
4427 }
4428 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4429 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4430 NewClassTy = NewRT->getPointeeType();
4431 OldClassTy = OldRT->getPointeeType();
4432 }
4433 }
Mike Stump1eb44332009-09-09 15:08:12 +00004434
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004435 // The return types aren't either both pointers or references to a class type.
4436 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004437 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004438 diag::err_different_return_type_for_overriding_virtual_function)
4439 << New->getDeclName() << NewTy << OldTy;
4440 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00004441
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004442 return true;
4443 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004444
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004445 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
4446 // Check if the new class derives from the old class.
4447 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4448 Diag(New->getLocation(),
4449 diag::err_covariant_return_not_derived)
4450 << New->getDeclName() << NewTy << OldTy;
4451 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4452 return true;
4453 }
Mike Stump1eb44332009-09-09 15:08:12 +00004454
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004455 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00004456 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004457 diag::err_covariant_return_inaccessible_base,
4458 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4459 // FIXME: Should this point to the return type?
4460 New->getLocation(), SourceRange(), New->getDeclName())) {
4461 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4462 return true;
4463 }
4464 }
Mike Stump1eb44332009-09-09 15:08:12 +00004465
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004466 // The qualifiers of the return types must be the same.
4467 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
4468 Diag(New->getLocation(),
4469 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004470 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004471 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4472 return true;
4473 };
Mike Stump1eb44332009-09-09 15:08:12 +00004474
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004475
4476 // The new class type must have the same or less qualifiers as the old type.
4477 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4478 Diag(New->getLocation(),
4479 diag::err_covariant_return_type_class_type_more_qualified)
4480 << New->getDeclName() << NewTy << OldTy;
4481 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4482 return true;
4483 };
Mike Stump1eb44332009-09-09 15:08:12 +00004484
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004485 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004486}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004487
Sebastian Redl23c7d062009-07-07 20:29:57 +00004488bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
Mike Stump1eb44332009-09-09 15:08:12 +00004489 const CXXMethodDecl *Old) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00004490 return CheckExceptionSpecSubset(diag::err_override_exception_spec,
4491 diag::note_overridden_virtual_function,
John McCall183700f2009-09-21 23:43:11 +00004492 Old->getType()->getAs<FunctionProtoType>(),
Sebastian Redl23c7d062009-07-07 20:29:57 +00004493 Old->getLocation(),
John McCall183700f2009-09-21 23:43:11 +00004494 New->getType()->getAs<FunctionProtoType>(),
Sebastian Redl23c7d062009-07-07 20:29:57 +00004495 New->getLocation());
4496}
4497
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004498/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4499/// initializer for the declaration 'Dcl'.
4500/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4501/// static data member of class X, names should be looked up in the scope of
4502/// class X.
4503void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004504 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004505
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004506 Decl *D = Dcl.getAs<Decl>();
4507 // If there is no declaration, there was an error parsing it.
4508 if (D == 0)
4509 return;
4510
4511 // Check whether it is a declaration with a nested name specifier like
4512 // int foo::bar;
4513 if (!D->isOutOfLine())
4514 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004515
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004516 // C++ [basic.lookup.unqual]p13
4517 //
4518 // A name used in the definition of a static data member of class X
4519 // (after the qualified-id of the static member) is looked up as if the name
4520 // was used in a member function of X.
Mike Stump1eb44332009-09-09 15:08:12 +00004521
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004522 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004523 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004524}
4525
4526/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4527/// initializer for the declaration 'Dcl'.
4528void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004529 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004530
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004531 Decl *D = Dcl.getAs<Decl>();
4532 // If there is no declaration, there was an error parsing it.
4533 if (D == 0)
4534 return;
4535
4536 // Check whether it is a declaration with a nested name specifier like
4537 // int foo::bar;
4538 if (!D->isOutOfLine())
4539 return;
4540
4541 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004542 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004543}