blob: 6135368039949f4ee9033e9a76fb66303cb40f5d [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregore8381c02008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000019#include "clang/AST/TypeOrdering.h"
Chris Lattner58258242008-04-10 02:22:51 +000020#include "clang/AST/StmtVisitor.h"
Anders Carlssond624e162009-08-26 23:45:07 +000021#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000022#include "clang/Lex/Preprocessor.h"
Daniel Dunbar34fb6722008-08-11 03:27:53 +000023#include "clang/Parse/DeclSpec.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Chris Lattner58258242008-04-10 02:22:51 +000025#include "llvm/Support/Compiler.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000026#include <algorithm> // for std::equal
Douglas Gregor29a92472008-10-22 17:49:05 +000027#include <map>
Chris Lattner199abbc2008-04-08 05:04:30 +000028
29using namespace clang;
30
Chris Lattner58258242008-04-10 02:22:51 +000031//===----------------------------------------------------------------------===//
32// CheckDefaultArgumentVisitor
33//===----------------------------------------------------------------------===//
34
Chris Lattnerb0d38442008-04-12 23:52:44 +000035namespace {
36 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
37 /// the default argument of a parameter to determine whether it
38 /// contains any ill-formed subexpressions. For example, this will
39 /// diagnose the use of local variables or parameters within the
40 /// default argument expression.
Mike Stump11289f42009-09-09 15:08:12 +000041 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000042 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000043 Expr *DefaultArg;
44 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000045
Chris Lattnerb0d38442008-04-12 23:52:44 +000046 public:
Mike Stump11289f42009-09-09 15:08:12 +000047 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000048 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000049
Chris Lattnerb0d38442008-04-12 23:52:44 +000050 bool VisitExpr(Expr *Node);
51 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000052 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000053 };
Chris Lattner58258242008-04-10 02:22:51 +000054
Chris Lattnerb0d38442008-04-12 23:52:44 +000055 /// VisitExpr - Visit all of the children of this expression.
56 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
57 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000058 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000059 E = Node->child_end(); I != E; ++I)
60 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000062 }
63
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 /// VisitDeclRefExpr - Visit a reference to a declaration, to
65 /// determine whether this declaration can be used in the default
66 /// argument expression.
67 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000068 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000069 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
70 // C++ [dcl.fct.default]p9
71 // Default arguments are evaluated each time the function is
72 // called. The order of evaluation of function arguments is
73 // unspecified. Consequently, parameters of a function shall not
74 // be used in default argument expressions, even if they are not
75 // evaluated. Parameters of a function declared before a default
76 // argument expression are in scope and can hide namespace and
77 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000078 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000079 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000080 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000081 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000082 // C++ [dcl.fct.default]p7
83 // Local variables shall not be used in default argument
84 // expressions.
Steve Naroff08899ff2008-04-15 22:42:06 +000085 if (VDecl->isBlockVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000088 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000089 }
Chris Lattner58258242008-04-10 02:22:51 +000090
Douglas Gregor8e12c382008-11-04 13:41:56 +000091 return false;
92 }
Chris Lattnerb0d38442008-04-12 23:52:44 +000093
Douglas Gregor97a9c812008-11-04 14:32:21 +000094 /// VisitCXXThisExpr - Visit a C++ "this" expression.
95 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
96 // C++ [dcl.fct.default]p8:
97 // The keyword this shall not be used in a default argument of a
98 // member function.
99 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000100 diag::err_param_default_argument_references_this)
101 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000102 }
Chris Lattner58258242008-04-10 02:22:51 +0000103}
104
Anders Carlssonc80a1272009-08-25 02:29:20 +0000105bool
106Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump11289f42009-09-09 15:08:12 +0000107 SourceLocation EqualLoc) {
Anders Carlssonc80a1272009-08-25 02:29:20 +0000108 QualType ParamType = Param->getType();
109
Anders Carlsson114056f2009-08-25 13:46:13 +0000110 if (RequireCompleteType(Param->getLocation(), Param->getType(),
111 diag::err_typecheck_decl_incomplete_type)) {
112 Param->setInvalidDecl();
113 return true;
114 }
115
Anders Carlssonc80a1272009-08-25 02:29:20 +0000116 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump11289f42009-09-09 15:08:12 +0000117
Anders Carlssonc80a1272009-08-25 02:29:20 +0000118 // C++ [dcl.fct.default]p5
119 // A default argument expression is implicitly converted (clause
120 // 4) to the parameter type. The default argument expression has
121 // the same semantic constraints as the initializer expression in
122 // a declaration of a variable of the parameter type, using the
123 // copy-initialization semantics (8.5).
Mike Stump11289f42009-09-09 15:08:12 +0000124 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssonc80a1272009-08-25 02:29:20 +0000125 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000126 return true;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000127
128 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump11289f42009-09-09 15:08:12 +0000129
Anders Carlssonc80a1272009-08-25 02:29:20 +0000130 // Okay: add the default argument to the parameter
131 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000132
Anders Carlssonc80a1272009-08-25 02:29:20 +0000133 DefaultArg.release();
Mike Stump11289f42009-09-09 15:08:12 +0000134
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000135 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000136}
137
Chris Lattner58258242008-04-10 02:22:51 +0000138/// ActOnParamDefaultArgument - Check whether the default argument
139/// provided for a function parameter is well-formed. If so, attach it
140/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000141void
Mike Stump11289f42009-09-09 15:08:12 +0000142Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000143 ExprArg defarg) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000144 if (!param || !defarg.get())
145 return;
Mike Stump11289f42009-09-09 15:08:12 +0000146
Chris Lattner83f095c2009-03-28 19:18:32 +0000147 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson84613c42009-06-12 16:51:40 +0000148 UnparsedDefaultArgLocs.erase(Param);
149
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000150 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner199abbc2008-04-08 05:04:30 +0000151 QualType ParamType = Param->getType();
152
153 // Default arguments are only permitted in C++
154 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000155 Diag(EqualLoc, diag::err_param_default_argument)
156 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000157 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000158 return;
159 }
160
Anders Carlssonf1c26952009-08-25 01:02:06 +0000161 // Check that the default argument is well-formed
162 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
163 if (DefaultArgChecker.Visit(DefaultArg.get())) {
164 Param->setInvalidDecl();
165 return;
166 }
Mike Stump11289f42009-09-09 15:08:12 +0000167
Anders Carlssonc80a1272009-08-25 02:29:20 +0000168 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000169}
170
Douglas Gregor58354032008-12-24 00:01:03 +0000171/// ActOnParamUnparsedDefaultArgument - We've seen a default
172/// argument for a function parameter, but we can't parse it yet
173/// because we're inside a class definition. Note that this default
174/// argument will be parsed later.
Mike Stump11289f42009-09-09 15:08:12 +0000175void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000176 SourceLocation EqualLoc,
177 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000178 if (!param)
179 return;
Mike Stump11289f42009-09-09 15:08:12 +0000180
Chris Lattner83f095c2009-03-28 19:18:32 +0000181 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000182 if (Param)
183 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000184
Anders Carlsson84613c42009-06-12 16:51:40 +0000185 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000186}
187
Douglas Gregor4d87df52008-12-16 21:30:33 +0000188/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
189/// the default argument for the parameter param failed.
Chris Lattner83f095c2009-03-28 19:18:32 +0000190void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000191 if (!param)
192 return;
Mike Stump11289f42009-09-09 15:08:12 +0000193
Anders Carlsson84613c42009-06-12 16:51:40 +0000194 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +0000195
Anders Carlsson84613c42009-06-12 16:51:40 +0000196 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000197
Anders Carlsson84613c42009-06-12 16:51:40 +0000198 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000199}
200
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000201/// CheckExtraCXXDefaultArguments - Check for any extra default
202/// arguments in the declarator, which is not a function declaration
203/// or definition and therefore is not permitted to have default
204/// arguments. This routine should be invoked for every declarator
205/// that is not a function declaration or definition.
206void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
207 // C++ [dcl.fct.default]p3
208 // A default argument expression shall be specified only in the
209 // parameter-declaration-clause of a function declaration or in a
210 // template-parameter (14.1). It shall not be specified for a
211 // parameter pack. If it is specified in a
212 // parameter-declaration-clause, it shall not occur within a
213 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000214 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000215 DeclaratorChunk &chunk = D.getTypeObject(i);
216 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000217 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
218 ParmVarDecl *Param =
219 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000220 if (Param->hasUnparsedDefaultArg()) {
221 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000222 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
223 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
224 delete Toks;
225 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000226 } else if (Param->getDefaultArg()) {
227 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
228 << Param->getDefaultArg()->getSourceRange();
229 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000230 }
231 }
232 }
233 }
234}
235
Chris Lattner199abbc2008-04-08 05:04:30 +0000236// MergeCXXFunctionDecl - Merge two declarations of the same C++
237// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000238// type. Subroutine of MergeFunctionDecl. Returns true if there was an
239// error, false otherwise.
240bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
241 bool Invalid = false;
242
Chris Lattner199abbc2008-04-08 05:04:30 +0000243 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-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 Gregorc732aba2009-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 Lattner199abbc2008-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 Gregorc732aba2009-09-11 18:44:32 +0000265 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Mike Stump11289f42009-09-09 15:08:12 +0000266 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000267 diag::err_param_default_argument_redefinition)
Douglas Gregorc732aba2009-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 Gregor75a45ba2009-02-16 17:45:42 +0000282 Invalid = true;
Chris Lattner199abbc2008-04-08 05:04:30 +0000283 } else if (OldParam->getDefaultArg()) {
284 // Merge the old default argument into the new parameter
285 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000286 } else if (NewParam->hasDefaultArg()) {
287 if (New->getDescribedFunctionTemplate()) {
288 // Paragraph 4, quoted above, only applies to non-template functions.
289 Diag(NewParam->getLocation(),
290 diag::err_param_default_argument_template_redecl)
291 << NewParam->getDefaultArgRange();
292 Diag(Old->getLocation(), diag::note_template_prev_declaration)
293 << false;
294 } else if (New->getDeclContext()->isDependentContext()) {
295 // C++ [dcl.fct.default]p6 (DR217):
296 // Default arguments for a member function of a class template shall
297 // be specified on the initial declaration of the member function
298 // within the class template.
299 //
300 // Reading the tea leaves a bit in DR217 and its reference to DR205
301 // leads me to the conclusion that one cannot add default function
302 // arguments for an out-of-line definition of a member function of a
303 // dependent type.
304 int WhichKind = 2;
305 if (CXXRecordDecl *Record
306 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
307 if (Record->getDescribedClassTemplate())
308 WhichKind = 0;
309 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
310 WhichKind = 1;
311 else
312 WhichKind = 2;
313 }
314
315 Diag(NewParam->getLocation(),
316 diag::err_param_default_argument_member_template_redecl)
317 << WhichKind
318 << NewParam->getDefaultArgRange();
319 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000320 }
321 }
322
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000323 if (CheckEquivalentExceptionSpec(
324 Old->getType()->getAsFunctionProtoType(), Old->getLocation(),
325 New->getType()->getAsFunctionProtoType(), New->getLocation())) {
326 Invalid = true;
327 }
328
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000329 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000330}
331
332/// CheckCXXDefaultArguments - Verify that the default arguments for a
333/// function declaration are well-formed according to C++
334/// [dcl.fct.default].
335void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
336 unsigned NumParams = FD->getNumParams();
337 unsigned p;
338
339 // Find first parameter with a default argument
340 for (p = 0; p < NumParams; ++p) {
341 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000342 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000343 break;
344 }
345
346 // C++ [dcl.fct.default]p4:
347 // In a given function declaration, all parameters
348 // subsequent to a parameter with a default argument shall
349 // have default arguments supplied in this or previous
350 // declarations. A default argument shall not be redefined
351 // by a later declaration (not even to the same value).
352 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000353 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000354 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000355 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000356 if (Param->isInvalidDecl())
357 /* We already complained about this parameter. */;
358 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000359 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000360 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000361 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000362 else
Mike Stump11289f42009-09-09 15:08:12 +0000363 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000364 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000365
Chris Lattner199abbc2008-04-08 05:04:30 +0000366 LastMissingDefaultArg = p;
367 }
368 }
369
370 if (LastMissingDefaultArg > 0) {
371 // Some default arguments were missing. Clear out all of the
372 // default arguments up to (and including) the last missing
373 // default argument, so that we leave the function parameters
374 // in a semantically valid state.
375 for (p = 0; p <= LastMissingDefaultArg; ++p) {
376 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000377 if (Param->hasDefaultArg()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000378 if (!Param->hasUnparsedDefaultArg())
379 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000380 Param->setDefaultArg(0);
381 }
382 }
383 }
384}
Douglas Gregor556877c2008-04-13 21:30:24 +0000385
Douglas Gregor61956c42008-10-31 09:07:45 +0000386/// isCurrentClassName - Determine whether the identifier II is the
387/// name of the class type currently being defined. In the case of
388/// nested classes, this will only return true if II is the name of
389/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000390bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
391 const CXXScopeSpec *SS) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000392 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000393 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000394 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000395 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
396 } else
397 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
398
399 if (CurDecl)
Douglas Gregor61956c42008-10-31 09:07:45 +0000400 return &II == CurDecl->getIdentifier();
401 else
402 return false;
403}
404
Mike Stump11289f42009-09-09 15:08:12 +0000405/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000406///
407/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
408/// and returns NULL otherwise.
409CXXBaseSpecifier *
410Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
411 SourceRange SpecifierRange,
412 bool Virtual, AccessSpecifier Access,
Mike Stump11289f42009-09-09 15:08:12 +0000413 QualType BaseType,
Douglas Gregor463421d2009-03-03 04:44:36 +0000414 SourceLocation BaseLoc) {
415 // C++ [class.union]p1:
416 // A union shall not have base classes.
417 if (Class->isUnion()) {
418 Diag(Class->getLocation(), diag::err_base_clause_on_union)
419 << SpecifierRange;
420 return 0;
421 }
422
423 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000424 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor463421d2009-03-03 04:44:36 +0000425 Class->getTagKind() == RecordDecl::TK_class,
426 Access, BaseType);
427
428 // Base specifiers must be record types.
429 if (!BaseType->isRecordType()) {
430 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
431 return 0;
432 }
433
434 // C++ [class.union]p1:
435 // A union shall not be used as a base class.
436 if (BaseType->isUnionType()) {
437 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
438 return 0;
439 }
440
441 // C++ [class.derived]p2:
442 // The class-name in a base-specifier shall not be an incompletely
443 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000444 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000445 PDiag(diag::err_incomplete_base_class)
446 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000447 return 0;
448
Eli Friedmanc96d4962009-08-15 21:55:26 +0000449 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000450 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000451 assert(BaseDecl && "Record type has no declaration");
452 BaseDecl = BaseDecl->getDefinition(Context);
453 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000454 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
455 assert(CXXBaseDecl && "Base type is not a C++ type");
456 if (!CXXBaseDecl->isEmpty())
457 Class->setEmpty(false);
458 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor463421d2009-03-03 04:44:36 +0000459 Class->setPolymorphic(true);
460
461 // C++ [dcl.init.aggr]p1:
462 // An aggregate is [...] a class with [...] no base classes [...].
463 Class->setAggregate(false);
464 Class->setPOD(false);
465
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000466 if (Virtual) {
467 // C++ [class.ctor]p5:
468 // A constructor is trivial if its class has no virtual base classes.
469 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000470
471 // C++ [class.copy]p6:
472 // A copy constructor is trivial if its class has no virtual base classes.
473 Class->setHasTrivialCopyConstructor(false);
474
475 // C++ [class.copy]p11:
476 // A copy assignment operator is trivial if its class has no virtual
477 // base classes.
478 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000479
480 // C++0x [meta.unary.prop] is_empty:
481 // T is a class type, but not a union type, with ... no virtual base
482 // classes
483 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000484 } else {
485 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000486 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000487 // class have trivial constructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000488 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
489 Class->setHasTrivialConstructor(false);
490
491 // C++ [class.copy]p6:
492 // A copy constructor is trivial if all the direct base classes of its
493 // class have trivial copy constructors.
494 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
495 Class->setHasTrivialCopyConstructor(false);
496
497 // C++ [class.copy]p11:
498 // A copy assignment operator is trivial if all the direct base classes
499 // of its class have trivial copy assignment operators.
500 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
501 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000502 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000503
504 // C++ [class.ctor]p3:
505 // A destructor is trivial if all the direct base classes of its class
506 // have trivial destructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000507 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
508 Class->setHasTrivialDestructor(false);
Mike Stump11289f42009-09-09 15:08:12 +0000509
Douglas Gregor463421d2009-03-03 04:44:36 +0000510 // Create the base specifier.
511 // FIXME: Allocate via ASTContext?
Mike Stump11289f42009-09-09 15:08:12 +0000512 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
513 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor463421d2009-03-03 04:44:36 +0000514 Access, BaseType);
515}
516
Douglas Gregor556877c2008-04-13 21:30:24 +0000517/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
518/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000519/// example:
520/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000521/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000522Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000523Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000524 bool Virtual, AccessSpecifier Access,
525 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000526 if (!classdecl)
527 return true;
528
Douglas Gregorc40290e2009-03-09 23:48:35 +0000529 AdjustDeclIfTemplate(classdecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000530 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000531 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000532 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
533 Virtual, Access,
534 BaseType, BaseLoc))
535 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000536
Douglas Gregor463421d2009-03-03 04:44:36 +0000537 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000538}
Douglas Gregor556877c2008-04-13 21:30:24 +0000539
Douglas Gregor463421d2009-03-03 04:44:36 +0000540/// \brief Performs the actual work of attaching the given base class
541/// specifiers to a C++ class.
542bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
543 unsigned NumBases) {
544 if (NumBases == 0)
545 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000546
547 // Used to keep track of which base types we have already seen, so
548 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000549 // that the key is always the unqualified canonical type of the base
550 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000551 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
552
553 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000554 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000555 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000556 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000557 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000558 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000559 NewBaseType = NewBaseType.getUnqualifiedType();
560
Douglas Gregor29a92472008-10-22 17:49:05 +0000561 if (KnownBaseTypes[NewBaseType]) {
562 // C++ [class.mi]p3:
563 // A class shall not be specified as a direct base class of a
564 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000565 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000566 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000567 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000568 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000569
570 // Delete the duplicate base class specifier; we're going to
571 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000572 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000573
574 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000575 } else {
576 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000577 KnownBaseTypes[NewBaseType] = Bases[idx];
578 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000579 }
580 }
581
582 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian9fa077c2009-07-02 18:26:15 +0000583 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000584
585 // Delete the remaining (good) base class specifiers, since their
586 // data has been copied into the CXXRecordDecl.
587 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000588 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000589
590 return Invalid;
591}
592
593/// ActOnBaseSpecifiers - Attach the given base specifiers to the
594/// class, after checking whether there are any duplicate base
595/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000596void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000597 unsigned NumBases) {
598 if (!ClassDecl || !Bases || !NumBases)
599 return;
600
601 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000602 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000603 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000604}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000605
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000606//===----------------------------------------------------------------------===//
607// C++ class member Handling
608//===----------------------------------------------------------------------===//
609
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000610/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
611/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
612/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000613/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000614Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000615Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000616 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000617 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000618 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000619 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000620 Expr *BitWidth = static_cast<Expr*>(BW);
621 Expr *Init = static_cast<Expr*>(InitExpr);
622 SourceLocation Loc = D.getIdentifierLoc();
623
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000624 bool isFunc = D.isFunctionDeclarator();
625
John McCall07e91c02009-08-06 02:15:43 +0000626 assert(!DS.isFriendSpecified());
627
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000628 // C++ 9.2p6: A member shall not be declared to have automatic storage
629 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000630 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
631 // data members and cannot be applied to names declared const or static,
632 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000633 switch (DS.getStorageClassSpec()) {
634 case DeclSpec::SCS_unspecified:
635 case DeclSpec::SCS_typedef:
636 case DeclSpec::SCS_static:
637 // FALL THROUGH.
638 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000639 case DeclSpec::SCS_mutable:
640 if (isFunc) {
641 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000642 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000643 else
Chris Lattner3b054132008-11-19 05:08:23 +0000644 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000645
Sebastian Redl8071edb2008-11-17 23:24:37 +0000646 // FIXME: It would be nicer if the keyword was ignored only for this
647 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000648 D.getMutableDeclSpec().ClearStorageClassSpecs();
649 } else {
650 QualType T = GetTypeForDeclarator(D, S);
651 diag::kind err = static_cast<diag::kind>(0);
652 if (T->isReferenceType())
653 err = diag::err_mutable_reference;
654 else if (T.isConstQualified())
655 err = diag::err_mutable_const;
656 if (err != 0) {
657 if (DS.getStorageClassSpecLoc().isValid())
658 Diag(DS.getStorageClassSpecLoc(), err);
659 else
660 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000661 // FIXME: It would be nicer if the keyword was ignored only for this
662 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000663 D.getMutableDeclSpec().ClearStorageClassSpecs();
664 }
665 }
666 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000667 default:
668 if (DS.getStorageClassSpecLoc().isValid())
669 Diag(DS.getStorageClassSpecLoc(),
670 diag::err_storageclass_invalid_for_member);
671 else
672 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
673 D.getMutableDeclSpec().ClearStorageClassSpecs();
674 }
675
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000676 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000677 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000678 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000679 // Check also for this case:
680 //
681 // typedef int f();
682 // f a;
683 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000684 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000685 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000686 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000687
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000688 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
689 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000690 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000691
692 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000693 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000694 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000695 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
696 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000697 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000698 } else {
Douglas Gregor3447e762009-08-20 22:52:58 +0000699 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
700 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000701 if (!Member) {
702 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000703 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000704 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000705
706 // Non-instance-fields can't have a bitfield.
707 if (BitWidth) {
708 if (Member->isInvalidDecl()) {
709 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000710 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000711 // C++ 9.6p3: A bit-field shall not be a static member.
712 // "static member 'A' cannot be a bit-field"
713 Diag(Loc, diag::err_static_not_bitfield)
714 << Name << BitWidth->getSourceRange();
715 } else if (isa<TypedefDecl>(Member)) {
716 // "typedef member 'x' cannot be a bit-field"
717 Diag(Loc, diag::err_typedef_not_bitfield)
718 << Name << BitWidth->getSourceRange();
719 } else {
720 // A function typedef ("typedef int f(); f a;").
721 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
722 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000723 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000724 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000725 }
Mike Stump11289f42009-09-09 15:08:12 +0000726
Chris Lattnerd26760a2009-03-05 23:01:03 +0000727 DeleteExpr(BitWidth);
728 BitWidth = 0;
729 Member->setInvalidDecl();
730 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000731
732 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000733
Douglas Gregor3447e762009-08-20 22:52:58 +0000734 // If we have declared a member function template, set the access of the
735 // templated declaration as well.
736 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
737 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000738 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000739
Douglas Gregor92751d42008-11-17 22:58:34 +0000740 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000741
Douglas Gregor0c880302009-03-11 23:00:04 +0000742 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000743 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000744 if (Deleted) // FIXME: Source location is not very good.
745 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000746
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000747 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000748 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000749 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000750 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000751 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000752}
753
Douglas Gregore8381c02008-11-05 04:29:56 +0000754/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +0000755Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000756Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +0000757 Scope *S,
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000758 const CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +0000759 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000760 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +0000761 SourceLocation IdLoc,
762 SourceLocation LParenLoc,
763 ExprTy **Args, unsigned NumArgs,
764 SourceLocation *CommaLocs,
765 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000766 if (!ConstructorD)
767 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000768
Douglas Gregorc8c277a2009-08-24 11:57:43 +0000769 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +0000770
771 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +0000772 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +0000773 if (!Constructor) {
774 // The user wrote a constructor initializer on a function that is
775 // not a C++ constructor. Ignore the error for now, because we may
776 // have more member initializers coming; we'll diagnose it just
777 // once in ActOnMemInitializers.
778 return true;
779 }
780
781 CXXRecordDecl *ClassDecl = Constructor->getParent();
782
783 // C++ [class.base.init]p2:
784 // Names in a mem-initializer-id are looked up in the scope of the
785 // constructor’s class and, if not found in that scope, are looked
786 // up in the scope containing the constructor’s
787 // definition. [Note: if the constructor’s class contains a member
788 // with the same name as a direct or virtual base class of the
789 // class, a mem-initializer-id naming the member or base class and
790 // composed of a single identifier refers to the class member. A
791 // mem-initializer-id for the hidden base class may be specified
792 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000793 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000794 // Look for a member, first.
795 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000796 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000797 = ClassDecl->lookup(MemberOrBase);
798 if (Result.first != Result.second)
799 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +0000800
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000801 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +0000802
Eli Friedman8e1433b2009-07-29 19:44:27 +0000803 if (Member)
804 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
805 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +0000806 }
Douglas Gregore8381c02008-11-05 04:29:56 +0000807 // It didn't name a member, so see if it names a class.
Mike Stump11289f42009-09-09 15:08:12 +0000808 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000809 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregore8381c02008-11-05 04:29:56 +0000810 if (!BaseTy)
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000811 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
812 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000813
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000814 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregore8381c02008-11-05 04:29:56 +0000815
Eli Friedman8e1433b2009-07-29 19:44:27 +0000816 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
817 RParenLoc, ClassDecl);
818}
819
820Sema::MemInitResult
821Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
822 unsigned NumArgs, SourceLocation IdLoc,
823 SourceLocation RParenLoc) {
824 bool HasDependentArg = false;
825 for (unsigned i = 0; i < NumArgs; i++)
826 HasDependentArg |= Args[i]->isTypeDependent();
827
828 CXXConstructorDecl *C = 0;
829 QualType FieldType = Member->getType();
830 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
831 FieldType = Array->getElementType();
832 if (FieldType->isDependentType()) {
833 // Can't check init for dependent type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000834 } else if (FieldType->getAs<RecordType>()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000835 if (!HasDependentArg) {
836 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
837
838 C = PerformInitializationByConstructor(FieldType,
839 MultiExprArg(*this,
840 (void**)Args,
841 NumArgs),
842 IdLoc,
843 SourceRange(IdLoc, RParenLoc),
844 Member->getDeclName(), IK_Direct,
845 ConstructorArgs);
846
847 if (C) {
848 // Take over the constructor arguments as our own.
849 NumArgs = ConstructorArgs.size();
850 Args = (Expr **)ConstructorArgs.take();
851 }
852 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +0000853 } else if (NumArgs != 1 && NumArgs != 0) {
Mike Stump11289f42009-09-09 15:08:12 +0000854 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman8e1433b2009-07-29 19:44:27 +0000855 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
856 } else if (!HasDependentArg) {
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +0000857 Expr *NewExp;
858 if (NumArgs == 0) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000859 if (FieldType->isReferenceType()) {
860 Diag(IdLoc, diag::err_null_intialized_reference_member)
861 << Member->getDeclName();
862 return Diag(Member->getLocation(), diag::note_declared_at);
863 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +0000864 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
865 NumArgs = 1;
866 }
867 else
868 NewExp = (Expr*)Args[0];
Eli Friedman8e1433b2009-07-29 19:44:27 +0000869 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
870 return true;
871 Args[0] = NewExp;
Douglas Gregore8381c02008-11-05 04:29:56 +0000872 }
Eli Friedman8e1433b2009-07-29 19:44:27 +0000873 // FIXME: Perform direct initialization of the member.
Mike Stump11289f42009-09-09 15:08:12 +0000874 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson1e172e02009-08-29 01:31:33 +0000875 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +0000876}
877
878Sema::MemInitResult
879Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
880 unsigned NumArgs, SourceLocation IdLoc,
881 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
882 bool HasDependentArg = false;
883 for (unsigned i = 0; i < NumArgs; i++)
884 HasDependentArg |= Args[i]->isTypeDependent();
885
886 if (!BaseType->isDependentType()) {
887 if (!BaseType->isRecordType())
888 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
889 << BaseType << SourceRange(IdLoc, RParenLoc);
890
891 // C++ [class.base.init]p2:
892 // [...] Unless the mem-initializer-id names a nonstatic data
893 // member of the constructor’s class or a direct or virtual base
894 // of that class, the mem-initializer is ill-formed. A
895 // mem-initializer-list can initialize a base class using any
896 // name that denotes that base class type.
Mike Stump11289f42009-09-09 15:08:12 +0000897
Eli Friedman8e1433b2009-07-29 19:44:27 +0000898 // First, check for a direct base class.
899 const CXXBaseSpecifier *DirectBaseSpec = 0;
900 for (CXXRecordDecl::base_class_const_iterator Base =
901 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Mike Stump11289f42009-09-09 15:08:12 +0000902 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
Eli Friedman8e1433b2009-07-29 19:44:27 +0000903 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
904 // We found a direct base of this type. That's what we're
905 // initializing.
906 DirectBaseSpec = &*Base;
907 break;
908 }
909 }
Mike Stump11289f42009-09-09 15:08:12 +0000910
Eli Friedman8e1433b2009-07-29 19:44:27 +0000911 // Check for a virtual base class.
912 // FIXME: We might be able to short-circuit this if we know in advance that
913 // there are no virtual bases.
914 const CXXBaseSpecifier *VirtualBaseSpec = 0;
915 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
916 // We haven't found a base yet; search the class hierarchy for a
917 // virtual base class.
918 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
919 /*DetectVirtual=*/false);
920 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Mike Stump11289f42009-09-09 15:08:12 +0000921 for (BasePaths::paths_iterator Path = Paths.begin();
Eli Friedman8e1433b2009-07-29 19:44:27 +0000922 Path != Paths.end(); ++Path) {
923 if (Path->back().Base->isVirtual()) {
924 VirtualBaseSpec = Path->back().Base;
925 break;
926 }
Douglas Gregore8381c02008-11-05 04:29:56 +0000927 }
928 }
929 }
Eli Friedman8e1433b2009-07-29 19:44:27 +0000930
931 // C++ [base.class.init]p2:
932 // If a mem-initializer-id is ambiguous because it designates both
933 // a direct non-virtual base class and an inherited virtual base
934 // class, the mem-initializer is ill-formed.
935 if (DirectBaseSpec && VirtualBaseSpec)
936 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
937 << BaseType << SourceRange(IdLoc, RParenLoc);
938 // C++ [base.class.init]p2:
939 // Unless the mem-initializer-id names a nonstatic data membeer of the
940 // constructor's class ot a direst or virtual base of that class, the
941 // mem-initializer is ill-formed.
942 if (!DirectBaseSpec && !VirtualBaseSpec)
943 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
944 << BaseType << ClassDecl->getNameAsCString()
945 << SourceRange(IdLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +0000946 }
947
Fariborz Jahanian0228bc12009-07-23 00:42:24 +0000948 CXXConstructorDecl *C = 0;
Eli Friedman8e1433b2009-07-29 19:44:27 +0000949 if (!BaseType->isDependentType() && !HasDependentArg) {
950 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
951 Context.getCanonicalType(BaseType));
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000952 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
953
954 C = PerformInitializationByConstructor(BaseType,
955 MultiExprArg(*this,
956 (void**)Args, NumArgs),
Mike Stump11289f42009-09-09 15:08:12 +0000957 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000958 Name, IK_Direct,
959 ConstructorArgs);
960 if (C) {
961 // Take over the constructor arguments as our own.
962 NumArgs = ConstructorArgs.size();
963 Args = (Expr **)ConstructorArgs.take();
964 }
Eli Friedman8e1433b2009-07-29 19:44:27 +0000965 }
966
Mike Stump11289f42009-09-09 15:08:12 +0000967 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson1e172e02009-08-29 01:31:33 +0000968 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +0000969}
970
Fariborz Jahanianca2f0852009-07-23 23:32:59 +0000971void
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000972Sema::setBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
973 CXXBaseOrMemberInitializer **Initializers,
974 unsigned NumInitializers,
Mike Stump11289f42009-09-09 15:08:12 +0000975 llvm::SmallVectorImpl<CXXBaseSpecifier *>& Bases,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000976 llvm::SmallVectorImpl<FieldDecl *>&Fields) {
977 // We need to build the initializer AST according to order of construction
978 // and not what user specified in the Initializers list.
979 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
980 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
981 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
982 bool HasDependentBaseInit = false;
Mike Stump11289f42009-09-09 15:08:12 +0000983
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000984 for (unsigned i = 0; i < NumInitializers; i++) {
985 CXXBaseOrMemberInitializer *Member = Initializers[i];
986 if (Member->isBaseInitializer()) {
987 if (Member->getBaseClass()->isDependentType())
988 HasDependentBaseInit = true;
989 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
990 } else {
991 AllBaseFields[Member->getMember()] = Member;
992 }
993 }
Mike Stump11289f42009-09-09 15:08:12 +0000994
Fariborz Jahanian3501bce2009-09-03 19:36:46 +0000995 if (HasDependentBaseInit) {
996 // FIXME. This does not preserve the ordering of the initializers.
997 // Try (with -Wreorder)
998 // template<class X> struct A {};
Mike Stump11289f42009-09-09 15:08:12 +0000999 // template<class X> struct B : A<X> {
1000 // B() : x1(10), A<X>() {}
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001001 // int x1;
1002 // };
1003 // B<int> x;
1004 // On seeing one dependent type, we should essentially exit this routine
1005 // while preserving user-declared initializer list. When this routine is
1006 // called during instantiatiation process, this routine will rebuild the
1007 // oderdered initializer list correctly.
Mike Stump11289f42009-09-09 15:08:12 +00001008
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001009 // If we have a dependent base initialization, we can't determine the
1010 // association between initializers and bases; just dump the known
1011 // initializers into the list, and don't try to deal with other bases.
1012 for (unsigned i = 0; i < NumInitializers; i++) {
1013 CXXBaseOrMemberInitializer *Member = Initializers[i];
1014 if (Member->isBaseInitializer())
1015 AllToInit.push_back(Member);
1016 }
1017 } else {
1018 // Push virtual bases before others.
1019 for (CXXRecordDecl::base_class_iterator VBase =
1020 ClassDecl->vbases_begin(),
1021 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1022 if (VBase->getType()->isDependentType())
1023 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001024 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001025 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Mike Stump11289f42009-09-09 15:08:12 +00001026 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001027 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1028 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
1029 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1030 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001031 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001032 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001033 else {
Mike Stump11289f42009-09-09 15:08:12 +00001034 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001035 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1036 assert(VBaseDecl && "setBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001037 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
1038 if (!Ctor)
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001039 Bases.push_back(VBase);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001040 else
1041 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1042
Mike Stump11289f42009-09-09 15:08:12 +00001043 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001044 new (Context) CXXBaseOrMemberInitializer(VBase->getType(), 0, 0,
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001045 Ctor,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001046 SourceLocation(),
1047 SourceLocation());
1048 AllToInit.push_back(Member);
1049 }
1050 }
Mike Stump11289f42009-09-09 15:08:12 +00001051
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001052 for (CXXRecordDecl::base_class_iterator Base =
1053 ClassDecl->bases_begin(),
1054 E = ClassDecl->bases_end(); Base != E; ++Base) {
1055 // Virtuals are in the virtual base list and already constructed.
1056 if (Base->isVirtual())
1057 continue;
1058 // Skip dependent types.
1059 if (Base->getType()->isDependentType())
1060 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001061 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001062 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Mike Stump11289f42009-09-09 15:08:12 +00001063 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001064 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1065 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
1066 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1067 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001068 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001069 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001070 else {
Mike Stump11289f42009-09-09 15:08:12 +00001071 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001072 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001073 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001074 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
1075 if (!Ctor)
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001076 Bases.push_back(Base);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001077 else
1078 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1079
Mike Stump11289f42009-09-09 15:08:12 +00001080 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001081 new (Context) CXXBaseOrMemberInitializer(Base->getType(), 0, 0,
1082 BaseDecl->getDefaultConstructor(Context),
1083 SourceLocation(),
1084 SourceLocation());
1085 AllToInit.push_back(Member);
1086 }
1087 }
1088 }
Mike Stump11289f42009-09-09 15:08:12 +00001089
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001090 // non-static data members.
1091 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1092 E = ClassDecl->field_end(); Field != E; ++Field) {
1093 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001094 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001095 Field->getType()->getAs<RecordType>()) {
1096 CXXRecordDecl *FieldClassDecl
1097 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001098 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001099 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1100 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1101 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1102 // set to the anonymous union data member used in the initializer
1103 // list.
1104 Value->setMember(*Field);
1105 Value->setAnonUnionMember(*FA);
1106 AllToInit.push_back(Value);
1107 break;
1108 }
1109 }
1110 }
1111 continue;
1112 }
1113 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001114 QualType FT = (*Field)->getType();
1115 if (const RecordType* RT = FT->getAs<RecordType>()) {
1116 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl());
1117 assert(FieldRecDecl && "setBaseOrMemberInitializers - BaseDecl null");
Mike Stump11289f42009-09-09 15:08:12 +00001118 if (CXXConstructorDecl *Ctor =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001119 FieldRecDecl->getDefaultConstructor(Context))
1120 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
1121 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001122 AllToInit.push_back(Value);
1123 continue;
1124 }
Mike Stump11289f42009-09-09 15:08:12 +00001125
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001126 QualType FT = Context.getBaseElementType((*Field)->getType());
1127 if (const RecordType* RT = FT->getAs<RecordType>()) {
1128 CXXConstructorDecl *Ctor =
1129 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
1130 if (!Ctor && !FT->isDependentType())
1131 Fields.push_back(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001132 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001133 new (Context) CXXBaseOrMemberInitializer((*Field), 0, 0,
1134 Ctor,
1135 SourceLocation(),
1136 SourceLocation());
1137 AllToInit.push_back(Member);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001138 if (Ctor)
1139 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001140 if (FT.isConstQualified() && (!Ctor || Ctor->isTrivial())) {
1141 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1142 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1143 Diag((*Field)->getLocation(), diag::note_declared_at);
1144 }
1145 }
1146 else if (FT->isReferenceType()) {
1147 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1148 << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getDeclName();
1149 Diag((*Field)->getLocation(), diag::note_declared_at);
1150 }
1151 else if (FT.isConstQualified()) {
1152 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1153 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1154 Diag((*Field)->getLocation(), diag::note_declared_at);
1155 }
1156 }
Mike Stump11289f42009-09-09 15:08:12 +00001157
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001158 NumInitializers = AllToInit.size();
1159 if (NumInitializers > 0) {
1160 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1161 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1162 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump11289f42009-09-09 15:08:12 +00001163
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001164 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1165 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1166 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1167 }
1168}
1169
1170void
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001171Sema::BuildBaseOrMemberInitializers(ASTContext &C,
1172 CXXConstructorDecl *Constructor,
1173 CXXBaseOrMemberInitializer **Initializers,
1174 unsigned NumInitializers
1175 ) {
1176 llvm::SmallVector<CXXBaseSpecifier *, 4>Bases;
1177 llvm::SmallVector<FieldDecl *, 4>Members;
Mike Stump11289f42009-09-09 15:08:12 +00001178
1179 setBaseOrMemberInitializers(Constructor,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001180 Initializers, NumInitializers, Bases, Members);
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001181 for (unsigned int i = 0; i < Bases.size(); i++)
Mike Stump11289f42009-09-09 15:08:12 +00001182 Diag(Bases[i]->getSourceRange().getBegin(),
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001183 diag::err_missing_default_constructor) << 0 << Bases[i]->getType();
1184 for (unsigned int i = 0; i < Members.size(); i++)
Mike Stump11289f42009-09-09 15:08:12 +00001185 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor)
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001186 << 1 << Members[i]->getType();
1187}
1188
Eli Friedman952c15d2009-07-21 19:28:10 +00001189static void *GetKeyForTopLevelField(FieldDecl *Field) {
1190 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001191 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001192 if (RT->getDecl()->isAnonymousStructOrUnion())
1193 return static_cast<void *>(RT->getDecl());
1194 }
1195 return static_cast<void *>(Field);
1196}
1197
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001198static void *GetKeyForBase(QualType BaseType) {
1199 if (const RecordType *RT = BaseType->getAs<RecordType>())
1200 return (void *)RT;
Mike Stump11289f42009-09-09 15:08:12 +00001201
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001202 assert(0 && "Unexpected base type!");
1203 return 0;
1204}
1205
Mike Stump11289f42009-09-09 15:08:12 +00001206static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001207 bool MemberMaybeAnon = false) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001208 // For fields injected into the class via declaration of an anonymous union,
1209 // use its anonymous union class declaration as the unique key.
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001210 if (Member->isMemberInitializer()) {
1211 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001212
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001213 // After BuildBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump11289f42009-09-09 15:08:12 +00001214 // data member of the class. Data member used in the initializer list is
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001215 // in AnonUnionMember field.
1216 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1217 Field = Member->getAnonUnionMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00001218 if (Field->getDeclContext()->isRecord()) {
1219 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1220 if (RD->isAnonymousStructOrUnion())
1221 return static_cast<void *>(RD);
1222 }
1223 return static_cast<void *>(Field);
1224 }
Mike Stump11289f42009-09-09 15:08:12 +00001225
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001226 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman952c15d2009-07-21 19:28:10 +00001227}
1228
Mike Stump11289f42009-09-09 15:08:12 +00001229void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001230 SourceLocation ColonLoc,
1231 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001232 if (!ConstructorDecl)
1233 return;
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001234
1235 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001236
1237 CXXConstructorDecl *Constructor
Douglas Gregor71a57182009-06-22 23:20:33 +00001238 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001239
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001240 if (!Constructor) {
1241 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1242 return;
1243 }
Mike Stump11289f42009-09-09 15:08:12 +00001244
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001245 if (!Constructor->isDependentContext()) {
1246 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1247 bool err = false;
1248 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001249 CXXBaseOrMemberInitializer *Member =
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001250 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1251 void *KeyToMember = GetKeyForMember(Member);
1252 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1253 if (!PrevMember) {
1254 PrevMember = Member;
1255 continue;
1256 }
1257 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001258 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001259 diag::error_multiple_mem_initialization)
1260 << Field->getNameAsString();
1261 else {
1262 Type *BaseClass = Member->getBaseClass();
1263 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump11289f42009-09-09 15:08:12 +00001264 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001265 diag::error_multiple_base_initialization)
1266 << BaseClass->getDesugaredType(true);
1267 }
1268 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1269 << 0;
1270 err = true;
1271 }
Mike Stump11289f42009-09-09 15:08:12 +00001272
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001273 if (err)
1274 return;
1275 }
Mike Stump11289f42009-09-09 15:08:12 +00001276
Anders Carlssone0eebb32009-08-27 05:45:01 +00001277 BuildBaseOrMemberInitializers(Context, Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00001278 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001279 NumMemInits);
Mike Stump11289f42009-09-09 15:08:12 +00001280
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001281 if (Constructor->isDependentContext())
1282 return;
Mike Stump11289f42009-09-09 15:08:12 +00001283
1284 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001285 Diagnostic::Ignored &&
Mike Stump11289f42009-09-09 15:08:12 +00001286 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001287 Diagnostic::Ignored)
1288 return;
Mike Stump11289f42009-09-09 15:08:12 +00001289
Anders Carlssone0eebb32009-08-27 05:45:01 +00001290 // Also issue warning if order of ctor-initializer list does not match order
1291 // of 1) base class declarations and 2) order of non-static data members.
1292 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump11289f42009-09-09 15:08:12 +00001293
Anders Carlssone0eebb32009-08-27 05:45:01 +00001294 CXXRecordDecl *ClassDecl
1295 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1296 // Push virtual bases before others.
1297 for (CXXRecordDecl::base_class_iterator VBase =
1298 ClassDecl->vbases_begin(),
1299 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001300 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001301
Anders Carlssone0eebb32009-08-27 05:45:01 +00001302 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1303 E = ClassDecl->bases_end(); Base != E; ++Base) {
1304 // Virtuals are alread in the virtual base list and are constructed
1305 // first.
1306 if (Base->isVirtual())
1307 continue;
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001308 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001309 }
Mike Stump11289f42009-09-09 15:08:12 +00001310
Anders Carlssone0eebb32009-08-27 05:45:01 +00001311 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1312 E = ClassDecl->field_end(); Field != E; ++Field)
1313 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001314
Anders Carlssone0eebb32009-08-27 05:45:01 +00001315 int Last = AllBaseOrMembers.size();
1316 int curIndex = 0;
1317 CXXBaseOrMemberInitializer *PrevMember = 0;
1318 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001319 CXXBaseOrMemberInitializer *Member =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001320 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1321 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman952c15d2009-07-21 19:28:10 +00001322
Anders Carlssone0eebb32009-08-27 05:45:01 +00001323 for (; curIndex < Last; curIndex++)
1324 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1325 break;
1326 if (curIndex == Last) {
1327 assert(PrevMember && "Member not in member list?!");
1328 // Initializer as specified in ctor-initializer list is out of order.
1329 // Issue a warning diagnostic.
1330 if (PrevMember->isBaseInitializer()) {
1331 // Diagnostics is for an initialized base class.
1332 Type *BaseClass = PrevMember->getBaseClass();
1333 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001334 diag::warn_base_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001335 << BaseClass->getDesugaredType(true);
1336 } else {
1337 FieldDecl *Field = PrevMember->getMember();
1338 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001339 diag::warn_field_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001340 << Field->getNameAsString();
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001341 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001342 // Also the note!
1343 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001344 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001345 diag::note_fieldorbase_initialized_here) << 0
1346 << Field->getNameAsString();
1347 else {
1348 Type *BaseClass = Member->getBaseClass();
Mike Stump11289f42009-09-09 15:08:12 +00001349 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001350 diag::note_fieldorbase_initialized_here) << 1
1351 << BaseClass->getDesugaredType(true);
1352 }
1353 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump11289f42009-09-09 15:08:12 +00001354 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001355 break;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001356 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001357 PrevMember = Member;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001358 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001359}
1360
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001361void
1362Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) {
1363 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext());
1364 llvm::SmallVector<uintptr_t, 32> AllToDestruct;
Mike Stump11289f42009-09-09 15:08:12 +00001365
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001366 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1367 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1368 if (VBase->getType()->isDependentType())
1369 continue;
1370 // Skip over virtual bases which have trivial destructors.
1371 CXXRecordDecl *BaseClassDecl
1372 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1373 if (BaseClassDecl->hasTrivialDestructor())
1374 continue;
1375 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001376 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001377 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump11289f42009-09-09 15:08:12 +00001378
1379 uintptr_t Member =
1380 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001381 | CXXDestructorDecl::VBASE;
1382 AllToDestruct.push_back(Member);
1383 }
1384 for (CXXRecordDecl::base_class_iterator Base =
1385 ClassDecl->bases_begin(),
1386 E = ClassDecl->bases_end(); Base != E; ++Base) {
1387 if (Base->isVirtual())
1388 continue;
1389 if (Base->getType()->isDependentType())
1390 continue;
1391 // Skip over virtual bases which have trivial destructors.
1392 CXXRecordDecl *BaseClassDecl
1393 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1394 if (BaseClassDecl->hasTrivialDestructor())
1395 continue;
1396 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001397 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001398 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump11289f42009-09-09 15:08:12 +00001399 uintptr_t Member =
1400 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001401 | CXXDestructorDecl::DRCTNONVBASE;
1402 AllToDestruct.push_back(Member);
1403 }
Mike Stump11289f42009-09-09 15:08:12 +00001404
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001405 // non-static data members.
1406 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1407 E = ClassDecl->field_end(); Field != E; ++Field) {
1408 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001409
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001410 if (const RecordType* RT = FieldType->getAs<RecordType>()) {
1411 // Skip over virtual bases which have trivial destructors.
1412 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1413 if (FieldClassDecl->hasTrivialDestructor())
1414 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001415 if (const CXXDestructorDecl *Dtor =
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001416 FieldClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001417 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001418 const_cast<CXXDestructorDecl*>(Dtor));
1419 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field);
1420 AllToDestruct.push_back(Member);
1421 }
1422 }
Mike Stump11289f42009-09-09 15:08:12 +00001423
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001424 unsigned NumDestructions = AllToDestruct.size();
1425 if (NumDestructions > 0) {
1426 Destructor->setNumBaseOrMemberDestructions(NumDestructions);
Mike Stump11289f42009-09-09 15:08:12 +00001427 uintptr_t *BaseOrMemberDestructions =
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001428 new (Context) uintptr_t [NumDestructions];
1429 // Insert in reverse order.
1430 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx)
1431 BaseOrMemberDestructions[i++] = AllToDestruct[Idx];
1432 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions);
1433 }
1434}
1435
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001436void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001437 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001438 return;
Mike Stump11289f42009-09-09 15:08:12 +00001439
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001440 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001441
1442 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001443 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001444 BuildBaseOrMemberInitializers(Context,
1445 Constructor,
1446 (CXXBaseOrMemberInitializer **)0, 0);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001447}
1448
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001449namespace {
1450 /// PureVirtualMethodCollector - traverses a class and its superclasses
1451 /// and determines if it has any pure virtual methods.
1452 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1453 ASTContext &Context;
1454
Sebastian Redlb7d64912009-03-22 21:28:55 +00001455 public:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001456 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redlb7d64912009-03-22 21:28:55 +00001457
1458 private:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001459 MethodList Methods;
Mike Stump11289f42009-09-09 15:08:12 +00001460
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001461 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump11289f42009-09-09 15:08:12 +00001462
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001463 public:
Mike Stump11289f42009-09-09 15:08:12 +00001464 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001465 : Context(Ctx) {
Mike Stump11289f42009-09-09 15:08:12 +00001466
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001467 MethodList List;
1468 Collect(RD, List);
Mike Stump11289f42009-09-09 15:08:12 +00001469
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001470 // Copy the temporary list to methods, and make sure to ignore any
1471 // null entries.
1472 for (size_t i = 0, e = List.size(); i != e; ++i) {
1473 if (List[i])
1474 Methods.push_back(List[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001475 }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001476 }
Mike Stump11289f42009-09-09 15:08:12 +00001477
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001478 bool empty() const { return Methods.empty(); }
Mike Stump11289f42009-09-09 15:08:12 +00001479
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001480 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1481 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001482 };
Mike Stump11289f42009-09-09 15:08:12 +00001483
1484 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001485 MethodList& Methods) {
1486 // First, collect the pure virtual methods for the base classes.
1487 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1488 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001489 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner85e2e142009-03-29 05:01:10 +00001490 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001491 if (BaseDecl && BaseDecl->isAbstract())
1492 Collect(BaseDecl, Methods);
1493 }
1494 }
Mike Stump11289f42009-09-09 15:08:12 +00001495
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001496 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson3c012712009-05-17 00:00:05 +00001497 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump11289f42009-09-09 15:08:12 +00001498
Anders Carlsson3c012712009-05-17 00:00:05 +00001499 MethodSetTy OverriddenMethods;
1500 size_t MethodsSize = Methods.size();
1501
Mike Stump11289f42009-09-09 15:08:12 +00001502 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson3c012712009-05-17 00:00:05 +00001503 i != e; ++i) {
1504 // Traverse the record, looking for methods.
1505 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl86be8542009-07-07 20:29:57 +00001506 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson3c012712009-05-17 00:00:05 +00001507 if (MD->isPure()) {
1508 Methods.push_back(MD);
1509 continue;
1510 }
Mike Stump11289f42009-09-09 15:08:12 +00001511
Anders Carlsson3c012712009-05-17 00:00:05 +00001512 // Otherwise, record all the overridden methods in our set.
1513 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1514 E = MD->end_overridden_methods(); I != E; ++I) {
1515 // Keep track of the overridden methods.
1516 OverriddenMethods.insert(*I);
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001517 }
1518 }
1519 }
Mike Stump11289f42009-09-09 15:08:12 +00001520
1521 // Now go through the methods and zero out all the ones we know are
Anders Carlsson3c012712009-05-17 00:00:05 +00001522 // overridden.
1523 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1524 if (OverriddenMethods.count(Methods[i]))
1525 Methods[i] = 0;
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001526 }
Mike Stump11289f42009-09-09 15:08:12 +00001527
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001528 }
1529}
Douglas Gregore8381c02008-11-05 04:29:56 +00001530
Anders Carlssoneabf7702009-08-27 00:13:57 +00001531
Mike Stump11289f42009-09-09 15:08:12 +00001532bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001533 unsigned DiagID, AbstractDiagSelID SelID,
1534 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00001535 if (SelID == -1)
1536 return RequireNonAbstractType(Loc, T,
1537 PDiag(DiagID), CurrentRD);
1538 else
1539 return RequireNonAbstractType(Loc, T,
1540 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001541}
1542
Anders Carlssoneabf7702009-08-27 00:13:57 +00001543bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1544 const PartialDiagnostic &PD,
1545 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001546 if (!getLangOptions().CPlusPlus)
1547 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001548
Anders Carlssoneb0c5322009-03-23 19:10:31 +00001549 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001550 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001551 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001552
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001553 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001554 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001555 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001556 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00001557
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001558 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001559 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001560 }
Mike Stump11289f42009-09-09 15:08:12 +00001561
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001562 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001563 if (!RT)
1564 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001565
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001566 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1567 if (!RD)
1568 return false;
1569
Anders Carlssonb57738b2009-03-24 17:23:42 +00001570 if (CurrentRD && CurrentRD != RD)
1571 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001572
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001573 if (!RD->isAbstract())
1574 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001575
Anders Carlssoneabf7702009-08-27 00:13:57 +00001576 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00001577
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001578 // Check if we've already emitted the list of pure virtual functions for this
1579 // class.
1580 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1581 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001582
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001583 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001584
1585 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001586 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1587 const CXXMethodDecl *MD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001588
1589 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001590 MD->getDeclName();
1591 }
1592
1593 if (!PureVirtualClassDiagSet)
1594 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1595 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00001596
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001597 return true;
1598}
1599
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001600namespace {
Mike Stump11289f42009-09-09 15:08:12 +00001601 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001602 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1603 Sema &SemaRef;
1604 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00001605
Anders Carlssonb57738b2009-03-24 17:23:42 +00001606 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001607 bool Invalid = false;
1608
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001609 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1610 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001611 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00001612
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001613 return Invalid;
1614 }
Mike Stump11289f42009-09-09 15:08:12 +00001615
Anders Carlssonb57738b2009-03-24 17:23:42 +00001616 public:
1617 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1618 : SemaRef(SemaRef), AbstractClass(ac) {
1619 Visit(SemaRef.Context.getTranslationUnitDecl());
1620 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001621
Anders Carlssonb57738b2009-03-24 17:23:42 +00001622 bool VisitFunctionDecl(const FunctionDecl *FD) {
1623 if (FD->isThisDeclarationADefinition()) {
1624 // No need to do the check if we're in a definition, because it requires
1625 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00001626 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00001627 return VisitDeclContext(FD);
1628 }
Mike Stump11289f42009-09-09 15:08:12 +00001629
Anders Carlssonb57738b2009-03-24 17:23:42 +00001630 // Check the return type.
1631 QualType RTy = FD->getType()->getAsFunctionType()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001632 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00001633 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1634 diag::err_abstract_type_in_decl,
1635 Sema::AbstractReturnType,
1636 AbstractClass);
1637
Mike Stump11289f42009-09-09 15:08:12 +00001638 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00001639 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001640 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001641 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001642 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001643 VD->getOriginalType(),
1644 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001645 Sema::AbstractParamType,
1646 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001647 }
1648
1649 return Invalid;
1650 }
Mike Stump11289f42009-09-09 15:08:12 +00001651
Anders Carlssonb57738b2009-03-24 17:23:42 +00001652 bool VisitDecl(const Decl* D) {
1653 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1654 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001655
Anders Carlssonb57738b2009-03-24 17:23:42 +00001656 return false;
1657 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001658 };
1659}
1660
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001661void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00001662 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001663 SourceLocation LBrac,
1664 SourceLocation RBrac) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001665 if (!TagDecl)
1666 return;
Mike Stump11289f42009-09-09 15:08:12 +00001667
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001668 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001669 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00001670 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar15619c72008-10-03 02:03:53 +00001671 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor463421d2009-03-03 04:44:36 +00001672
Chris Lattner83f095c2009-03-28 19:18:32 +00001673 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001674 if (!RD->isAbstract()) {
1675 // Collect all the pure virtual methods and see if this is an abstract
1676 // class after all.
1677 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001678 if (!Collector.empty())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001679 RD->setAbstract(true);
1680 }
Mike Stump11289f42009-09-09 15:08:12 +00001681
1682 if (RD->isAbstract())
Anders Carlssonb57738b2009-03-24 17:23:42 +00001683 AbstractClassUsageDiagnoser(*this, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001684
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001685 if (!RD->isDependentType())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001686 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001687}
1688
Douglas Gregor05379422008-11-03 17:51:48 +00001689/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1690/// special functions, such as the default constructor, copy
1691/// constructor, or destructor, to the given C++ class (C++
1692/// [special]p1). This routine can only be executed just before the
1693/// definition of the class is complete.
1694void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00001695 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00001696 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00001697
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001698 // FIXME: Implicit declarations have exception specifications, which are
1699 // the union of the specifications of the implicitly called functions.
1700
Douglas Gregor05379422008-11-03 17:51:48 +00001701 if (!ClassDecl->hasUserDeclaredConstructor()) {
1702 // C++ [class.ctor]p5:
1703 // A default constructor for a class X is a constructor of class X
1704 // that can be called without an argument. If there is no
1705 // user-declared constructor for class X, a default constructor is
1706 // implicitly declared. An implicitly-declared default constructor
1707 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00001708 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00001709 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00001710 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00001711 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00001712 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00001713 Context.getFunctionType(Context.VoidTy,
1714 0, 0, false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001715 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00001716 /*isExplicit=*/false,
1717 /*isInline=*/true,
1718 /*isImplicitlyDeclared=*/true);
1719 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00001720 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00001721 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001722 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00001723 }
1724
1725 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1726 // C++ [class.copy]p4:
1727 // If the class definition does not explicitly declare a copy
1728 // constructor, one is declared implicitly.
1729
1730 // C++ [class.copy]p5:
1731 // The implicitly-declared copy constructor for a class X will
1732 // have the form
1733 //
1734 // X::X(const X&)
1735 //
1736 // if
1737 bool HasConstCopyConstructor = true;
1738
1739 // -- each direct or virtual base class B of X has a copy
1740 // constructor whose first parameter is of type const B& or
1741 // const volatile B&, and
1742 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1743 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1744 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001745 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001746 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00001747 = BaseClassDecl->hasConstCopyConstructor(Context);
1748 }
1749
1750 // -- for all the nonstatic data members of X that are of a
1751 // class type M (or array thereof), each such class type
1752 // has a copy constructor whose first parameter is of type
1753 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001754 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1755 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001756 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00001757 QualType FieldType = (*Field)->getType();
1758 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1759 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001760 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001761 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00001762 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001763 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00001764 = FieldClassDecl->hasConstCopyConstructor(Context);
1765 }
1766 }
1767
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001768 // Otherwise, the implicitly declared copy constructor will have
1769 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00001770 //
1771 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001772 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00001773 if (HasConstCopyConstructor)
1774 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001775 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00001776
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001777 // An implicitly-declared copy constructor is an inline public
1778 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00001779 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00001780 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00001781 CXXConstructorDecl *CopyConstructor
1782 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00001783 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00001784 Context.getFunctionType(Context.VoidTy,
1785 &ArgType, 1,
1786 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001787 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00001788 /*isExplicit=*/false,
1789 /*isInline=*/true,
1790 /*isImplicitlyDeclared=*/true);
1791 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00001792 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00001793 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00001794
1795 // Add the parameter to the constructor.
1796 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1797 ClassDecl->getLocation(),
1798 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001799 ArgType, /*DInfo=*/0,
1800 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00001801 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001802 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00001803 }
1804
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001805 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1806 // Note: The following rules are largely analoguous to the copy
1807 // constructor rules. Note that virtual bases are not taken into account
1808 // for determining the argument type of the operator. Note also that
1809 // operators taking an object instead of a reference are allowed.
1810 //
1811 // C++ [class.copy]p10:
1812 // If the class definition does not explicitly declare a copy
1813 // assignment operator, one is declared implicitly.
1814 // The implicitly-defined copy assignment operator for a class X
1815 // will have the form
1816 //
1817 // X& X::operator=(const X&)
1818 //
1819 // if
1820 bool HasConstCopyAssignment = true;
1821
1822 // -- each direct base class B of X has a copy assignment operator
1823 // whose parameter is of type const B&, const volatile B& or B,
1824 // and
1825 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1826 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1827 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001828 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001829 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001830 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001831 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001832 }
1833
1834 // -- for all the nonstatic data members of X that are of a class
1835 // type M (or array thereof), each such class type has a copy
1836 // assignment operator whose parameter is of type const M&,
1837 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001838 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1839 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001840 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001841 QualType FieldType = (*Field)->getType();
1842 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1843 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001844 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001845 const CXXRecordDecl *FieldClassDecl
1846 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001847 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001848 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001849 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001850 }
1851 }
1852
1853 // Otherwise, the implicitly declared copy assignment operator will
1854 // have the form
1855 //
1856 // X& X::operator=(X&)
1857 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001858 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001859 if (HasConstCopyAssignment)
1860 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001861 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001862
1863 // An implicitly-declared copy assignment operator is an inline public
1864 // member of its class.
1865 DeclarationName Name =
1866 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1867 CXXMethodDecl *CopyAssignment =
1868 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1869 Context.getFunctionType(RetType, &ArgType, 1,
1870 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001871 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001872 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00001873 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00001874 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001875 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001876
1877 // Add the parameter to the operator.
1878 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1879 ClassDecl->getLocation(),
1880 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001881 ArgType, /*DInfo=*/0,
1882 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00001883 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001884
1885 // Don't call addedAssignmentOperator. There is no way to distinguish an
1886 // implicit from an explicit assignment operator.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001887 ClassDecl->addDecl(CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001888 }
1889
Douglas Gregor1349b452008-12-15 21:24:18 +00001890 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00001891 // C++ [class.dtor]p2:
1892 // If a class has no user-declared destructor, a destructor is
1893 // declared implicitly. An implicitly-declared destructor is an
1894 // inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00001895 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00001896 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00001897 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00001898 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00001899 ClassDecl->getLocation(), Name,
Douglas Gregor831c93f2008-11-05 20:51:48 +00001900 Context.getFunctionType(Context.VoidTy,
1901 0, 0, false, 0),
1902 /*isInline=*/true,
1903 /*isImplicitlyDeclared=*/true);
1904 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00001905 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00001906 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001907 ClassDecl->addDecl(Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00001908 }
Douglas Gregor05379422008-11-03 17:51:48 +00001909}
1910
Douglas Gregore44a2ad2009-05-27 23:11:45 +00001911void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00001912 Decl *D = TemplateD.getAs<Decl>();
1913 if (!D)
1914 return;
1915
1916 TemplateParameterList *Params = 0;
1917 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
1918 Params = Template->getTemplateParameters();
1919 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1920 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
1921 Params = PartialSpec->getTemplateParameters();
1922 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00001923 return;
1924
Douglas Gregore44a2ad2009-05-27 23:11:45 +00001925 for (TemplateParameterList::iterator Param = Params->begin(),
1926 ParamEnd = Params->end();
1927 Param != ParamEnd; ++Param) {
1928 NamedDecl *Named = cast<NamedDecl>(*Param);
1929 if (Named->getDeclName()) {
1930 S->AddDecl(DeclPtrTy::make(Named));
1931 IdResolver.AddDecl(Named);
1932 }
1933 }
1934}
1935
Douglas Gregor4d87df52008-12-16 21:30:33 +00001936/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1937/// parsing a top-level (non-nested) C++ class, and we are now
1938/// parsing those parts of the given Method declaration that could
1939/// not be parsed earlier (C++ [class.mem]p2), such as default
1940/// arguments. This action should enter the scope of the given
1941/// Method declaration as if we had just parsed the qualified method
1942/// name. However, it should not bring the parameters into scope;
1943/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00001944void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001945 if (!MethodD)
1946 return;
Mike Stump11289f42009-09-09 15:08:12 +00001947
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001948 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00001949
Douglas Gregor4d87df52008-12-16 21:30:33 +00001950 CXXScopeSpec SS;
Chris Lattner83f095c2009-03-28 19:18:32 +00001951 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001952 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00001953 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1954 SS.setScopeRep(
1955 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00001956 ActOnCXXEnterDeclaratorScope(S, SS);
1957}
1958
1959/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1960/// C++ method declaration. We're (re-)introducing the given
1961/// function parameter into scope for use in parsing later parts of
1962/// the method declaration. For example, we could see an
1963/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00001964void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001965 if (!ParamD)
1966 return;
Mike Stump11289f42009-09-09 15:08:12 +00001967
Chris Lattner83f095c2009-03-28 19:18:32 +00001968 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00001969
1970 // If this parameter has an unparsed default argument, clear it out
1971 // to make way for the parsed default argument.
1972 if (Param->hasUnparsedDefaultArg())
1973 Param->setDefaultArg(0);
1974
Chris Lattner83f095c2009-03-28 19:18:32 +00001975 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00001976 if (Param->getDeclName())
1977 IdResolver.AddDecl(Param);
1978}
1979
1980/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1981/// processing the delayed method declaration for Method. The method
1982/// declaration is now considered finished. There may be a separate
1983/// ActOnStartOfFunctionDef action later (not necessarily
1984/// immediately!) for this method, if it was also defined inside the
1985/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00001986void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001987 if (!MethodD)
1988 return;
Mike Stump11289f42009-09-09 15:08:12 +00001989
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001990 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00001991
Chris Lattner83f095c2009-03-28 19:18:32 +00001992 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00001993 CXXScopeSpec SS;
Mike Stump11289f42009-09-09 15:08:12 +00001994 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00001995 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1996 SS.setScopeRep(
1997 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00001998 ActOnCXXExitDeclaratorScope(S, SS);
1999
2000 // Now that we have our default arguments, check the constructor
2001 // again. It could produce additional diagnostics or affect whether
2002 // the class has implicitly-declared destructors, among other
2003 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002004 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2005 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002006
2007 // Check the default arguments, which we may have added.
2008 if (!Method->isInvalidDecl())
2009 CheckCXXDefaultArguments(Method);
2010}
2011
Douglas Gregor831c93f2008-11-05 20:51:48 +00002012/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002013/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002014/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002015/// emit diagnostics and set the invalid bit to true. In any case, the type
2016/// will be updated to reflect a well-formed type for the constructor and
2017/// returned.
2018QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2019 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002020 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002021
2022 // C++ [class.ctor]p3:
2023 // A constructor shall not be virtual (10.3) or static (9.4). A
2024 // constructor can be invoked for a const, volatile or const
2025 // volatile object. A constructor shall not be declared const,
2026 // volatile, or const volatile (9.3.2).
2027 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002028 if (!D.isInvalidType())
2029 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2030 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2031 << SourceRange(D.getIdentifierLoc());
2032 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002033 }
2034 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002035 if (!D.isInvalidType())
2036 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2037 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2038 << SourceRange(D.getIdentifierLoc());
2039 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002040 SC = FunctionDecl::None;
2041 }
Mike Stump11289f42009-09-09 15:08:12 +00002042
Chris Lattner38378bf2009-04-25 08:28:21 +00002043 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2044 if (FTI.TypeQuals != 0) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002045 if (FTI.TypeQuals & QualType::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002046 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2047 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002048 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002049 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2050 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002051 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002052 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2053 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002054 }
Mike Stump11289f42009-09-09 15:08:12 +00002055
Douglas Gregor831c93f2008-11-05 20:51:48 +00002056 // Rebuild the function type "R" without any type qualifiers (in
2057 // case any of the errors above fired) and with "void" as the
2058 // return type, since constructors don't have return types. We
2059 // *always* have to do this, because GetTypeForDeclarator will
2060 // put in a result type of "int" when none was specified.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002061 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Chris Lattner38378bf2009-04-25 08:28:21 +00002062 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2063 Proto->getNumArgs(),
2064 Proto->isVariadic(), 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002065}
2066
Douglas Gregor4d87df52008-12-16 21:30:33 +00002067/// CheckConstructor - Checks a fully-formed constructor for
2068/// well-formedness, issuing any diagnostics required. Returns true if
2069/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002070void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002071 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002072 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2073 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002074 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002075
2076 // C++ [class.copy]p3:
2077 // A declaration of a constructor for a class X is ill-formed if
2078 // its first parameter is of type (optionally cv-qualified) X and
2079 // either there are no other parameters or else all other
2080 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002081 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002082 ((Constructor->getNumParams() == 1) ||
2083 (Constructor->getNumParams() > 1 &&
Anders Carlsson85446472009-06-06 04:14:07 +00002084 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002085 QualType ParamType = Constructor->getParamDecl(0)->getType();
2086 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2087 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002088 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2089 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor578dae52009-04-02 01:08:08 +00002090 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002091 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002092 }
2093 }
Mike Stump11289f42009-09-09 15:08:12 +00002094
Douglas Gregor4d87df52008-12-16 21:30:33 +00002095 // Notify the class that we've added a constructor.
2096 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002097}
2098
Mike Stump11289f42009-09-09 15:08:12 +00002099static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002100FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2101 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2102 FTI.ArgInfo[0].Param &&
2103 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2104}
2105
Douglas Gregor831c93f2008-11-05 20:51:48 +00002106/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2107/// the well-formednes of the destructor declarator @p D with type @p
2108/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002109/// emit diagnostics and set the declarator to invalid. Even if this happens,
2110/// will be updated to reflect a well-formed type for the destructor and
2111/// returned.
2112QualType Sema::CheckDestructorDeclarator(Declarator &D,
2113 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002114 // C++ [class.dtor]p1:
2115 // [...] A typedef-name that names a class is a class-name
2116 // (7.1.3); however, a typedef-name that names a class shall not
2117 // be used as the identifier in the declarator for a destructor
2118 // declaration.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00002119 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType());
Chris Lattner38378bf2009-04-25 08:28:21 +00002120 if (isa<TypedefType>(DeclaratorType)) {
2121 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002122 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002123 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002124 }
2125
2126 // C++ [class.dtor]p2:
2127 // A destructor is used to destroy objects of its class type. A
2128 // destructor takes no parameters, and no return type can be
2129 // specified for it (not even void). The address of a destructor
2130 // shall not be taken. A destructor shall not be static. A
2131 // destructor can be invoked for a const, volatile or const
2132 // volatile object. A destructor shall not be declared const,
2133 // volatile or const volatile (9.3.2).
2134 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002135 if (!D.isInvalidType())
2136 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2137 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2138 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002139 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002140 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002141 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002142 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002143 // Destructors don't have return types, but the parser will
2144 // happily parse something like:
2145 //
2146 // class X {
2147 // float ~X();
2148 // };
2149 //
2150 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002151 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2152 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2153 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002154 }
Mike Stump11289f42009-09-09 15:08:12 +00002155
Chris Lattner38378bf2009-04-25 08:28:21 +00002156 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2157 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002158 if (FTI.TypeQuals & QualType::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002159 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2160 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002161 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002162 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2163 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002164 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002165 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2166 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002167 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002168 }
2169
2170 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002171 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002172 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2173
2174 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002175 FTI.freeArgs();
2176 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002177 }
2178
Mike Stump11289f42009-09-09 15:08:12 +00002179 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002180 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002181 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002182 D.setInvalidType();
2183 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002184
2185 // Rebuild the function type "R" without any type qualifiers or
2186 // parameters (in case any of the errors above fired) and with
2187 // "void" as the return type, since destructors don't have return
2188 // types. We *always* have to do this, because GetTypeForDeclarator
2189 // will put in a result type of "int" when none was specified.
Chris Lattner38378bf2009-04-25 08:28:21 +00002190 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002191}
2192
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002193/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2194/// well-formednes of the conversion function declarator @p D with
2195/// type @p R. If there are any errors in the declarator, this routine
2196/// will emit diagnostics and return true. Otherwise, it will return
2197/// false. Either way, the type @p R will be updated to reflect a
2198/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002199void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002200 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002201 // C++ [class.conv.fct]p1:
2202 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00002203 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00002204 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002205 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002206 if (!D.isInvalidType())
2207 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2208 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2209 << SourceRange(D.getIdentifierLoc());
2210 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002211 SC = FunctionDecl::None;
2212 }
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002213 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002214 // Conversion functions don't have return types, but the parser will
2215 // happily parse something like:
2216 //
2217 // class X {
2218 // float operator bool();
2219 // };
2220 //
2221 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00002222 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2223 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2224 << SourceRange(D.getIdentifierLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002225 }
2226
2227 // Make sure we don't have any parameters.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002228 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002229 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2230
2231 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00002232 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002233 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002234 }
2235
Mike Stump11289f42009-09-09 15:08:12 +00002236 // Make sure the conversion function isn't variadic.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002237 if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002238 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002239 D.setInvalidType();
2240 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002241
2242 // C++ [class.conv.fct]p4:
2243 // The conversion-type-id shall not represent a function type nor
2244 // an array type.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00002245 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002246 if (ConvType->isArrayType()) {
2247 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2248 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002249 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002250 } else if (ConvType->isFunctionType()) {
2251 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2252 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002253 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002254 }
2255
2256 // Rebuild the function type "R" without any parameters (in case any
2257 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00002258 // return type.
2259 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002260 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002261
Douglas Gregor5fb53972009-01-14 15:45:31 +00002262 // C++0x explicit conversion operators.
2263 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00002264 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002265 diag::warn_explicit_conversion_functions)
2266 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002267}
2268
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002269/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2270/// the declaration of the given C++ conversion function. This routine
2271/// is responsible for recording the conversion function in the C++
2272/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00002273Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002274 assert(Conversion && "Expected to receive a conversion function declaration");
2275
Douglas Gregor4287b372008-12-12 08:25:50 +00002276 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002277
2278 // Make sure we aren't redeclaring the conversion function.
2279 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002280
2281 // C++ [class.conv.fct]p1:
2282 // [...] A conversion function is never used to convert a
2283 // (possibly cv-qualified) object to the (possibly cv-qualified)
2284 // same object type (or a reference to it), to a (possibly
2285 // cv-qualified) base class of that type (or a reference to it),
2286 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00002287 // FIXME: Suppress this warning if the conversion function ends up being a
2288 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00002289 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002290 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002291 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002292 ConvType = ConvTypeRef->getPointeeType();
2293 if (ConvType->isRecordType()) {
2294 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2295 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002296 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002297 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002298 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002299 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002300 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002301 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002302 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002303 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002304 }
2305
Douglas Gregor1dc98262008-12-26 15:00:45 +00002306 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002307 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump11289f42009-09-09 15:08:12 +00002308 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002309 = Conversion->getDescribedFunctionTemplate())
2310 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor1dc98262008-12-26 15:00:45 +00002311 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00002312 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor1dc98262008-12-26 15:00:45 +00002313 Conv = Conversions->function_begin(),
2314 ConvEnd = Conversions->function_end();
2315 Conv != ConvEnd; ++Conv) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002316 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor1dc98262008-12-26 15:00:45 +00002317 *Conv = Conversion;
Chris Lattner83f095c2009-03-28 19:18:32 +00002318 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00002319 }
2320 }
2321 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00002322 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002323 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002324 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00002325 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002326 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002327
Chris Lattner83f095c2009-03-28 19:18:32 +00002328 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002329}
2330
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002331//===----------------------------------------------------------------------===//
2332// Namespace Handling
2333//===----------------------------------------------------------------------===//
2334
2335/// ActOnStartNamespaceDef - This is called at the start of a namespace
2336/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00002337Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2338 SourceLocation IdentLoc,
2339 IdentifierInfo *II,
2340 SourceLocation LBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002341 NamespaceDecl *Namespc =
2342 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2343 Namespc->setLBracLoc(LBrace);
2344
2345 Scope *DeclRegionScope = NamespcScope->getParent();
2346
2347 if (II) {
2348 // C++ [namespace.def]p2:
2349 // The identifier in an original-namespace-definition shall not have been
2350 // previously defined in the declarative region in which the
2351 // original-namespace-definition appears. The identifier in an
2352 // original-namespace-definition is the name of the namespace. Subsequently
2353 // in that declarative region, it is treated as an original-namespace-name.
2354
Douglas Gregor2ada0482009-02-04 17:27:36 +00002355 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
2356 true);
Mike Stump11289f42009-09-09 15:08:12 +00002357
Douglas Gregor91f84212008-12-11 16:49:14 +00002358 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2359 // This is an extended namespace definition.
2360 // Attach this namespace decl to the chain of extended namespace
2361 // definitions.
2362 OrigNS->setNextNamespace(Namespc);
2363 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002364
Mike Stump11289f42009-09-09 15:08:12 +00002365 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002366 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00002367 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00002368 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002369 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002370 } else if (PrevDecl) {
2371 // This is an invalid name redefinition.
2372 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2373 << Namespc->getDeclName();
2374 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2375 Namespc->setInvalidDecl();
2376 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00002377 } else if (II->isStr("std") &&
2378 CurContext->getLookupContext()->isTranslationUnit()) {
2379 // This is the first "real" definition of the namespace "std", so update
2380 // our cache of the "std" namespace to point at this definition.
2381 if (StdNamespace) {
2382 // We had already defined a dummy namespace "std". Link this new
2383 // namespace definition to the dummy namespace "std".
2384 StdNamespace->setNextNamespace(Namespc);
2385 StdNamespace->setLocation(IdentLoc);
2386 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2387 }
2388
2389 // Make our StdNamespace cache point at the first real definition of the
2390 // "std" namespace.
2391 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00002392 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002393
2394 PushOnScopeChains(Namespc, DeclRegionScope);
2395 } else {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002396 // FIXME: Handle anonymous namespaces
2397 }
2398
2399 // Although we could have an invalid decl (i.e. the namespace name is a
2400 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00002401 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2402 // for the namespace has the declarations that showed up in that particular
2403 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00002404 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002405 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002406}
2407
2408/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2409/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00002410void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2411 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002412 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2413 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2414 Namespc->setRBracLoc(RBrace);
2415 PopDeclContext();
2416}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002417
Chris Lattner83f095c2009-03-28 19:18:32 +00002418Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2419 SourceLocation UsingLoc,
2420 SourceLocation NamespcLoc,
2421 const CXXScopeSpec &SS,
2422 SourceLocation IdentLoc,
2423 IdentifierInfo *NamespcName,
2424 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00002425 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2426 assert(NamespcName && "Invalid NamespcName.");
2427 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002428 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00002429
Douglas Gregor889ceb72009-02-03 19:21:40 +00002430 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00002431
Douglas Gregor34074322009-01-14 22:20:51 +00002432 // Lookup namespace name.
Douglas Gregor889ceb72009-02-03 19:21:40 +00002433 LookupResult R = LookupParsedName(S, &SS, NamespcName,
2434 LookupNamespaceName, false);
2435 if (R.isAmbiguous()) {
2436 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002437 return DeclPtrTy();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002438 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00002439 if (NamedDecl *NS = R) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00002440 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002441 // C++ [namespace.udir]p1:
2442 // A using-directive specifies that the names in the nominated
2443 // namespace can be used in the scope in which the
2444 // using-directive appears after the using-directive. During
2445 // unqualified name lookup (3.4.1), the names appear as if they
2446 // were declared in the nearest enclosing namespace which
2447 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00002448 // namespace. [Note: in this context, "contains" means "contains
2449 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00002450
2451 // Find enclosing context containing both using-directive and
2452 // nominated namespace.
2453 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2454 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2455 CommonAncestor = CommonAncestor->getParent();
2456
Mike Stump11289f42009-09-09 15:08:12 +00002457 UDir = UsingDirectiveDecl::Create(Context,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002458 CurContext, UsingLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002459 NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002460 SS.getRange(),
2461 (NestedNameSpecifier *)SS.getScopeRep(),
2462 IdentLoc,
Douglas Gregor889ceb72009-02-03 19:21:40 +00002463 cast<NamespaceDecl>(NS),
2464 CommonAncestor);
2465 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00002466 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00002467 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00002468 }
2469
Douglas Gregor889ceb72009-02-03 19:21:40 +00002470 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00002471 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00002472 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002473}
2474
2475void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2476 // If scope has associated entity, then using directive is at namespace
2477 // or translation unit scope. We add UsingDirectiveDecls, into
2478 // it's lookup structure.
2479 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002480 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002481 else
2482 // Otherwise it is block-sope. using-directives will affect lookup
2483 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002484 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00002485}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002486
Douglas Gregorfec52632009-06-20 00:51:54 +00002487
2488Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00002489 AccessSpecifier AS,
Anders Carlsson59140b32009-08-28 03:16:11 +00002490 SourceLocation UsingLoc,
2491 const CXXScopeSpec &SS,
2492 SourceLocation IdentLoc,
2493 IdentifierInfo *TargetName,
2494 OverloadedOperatorKind Op,
2495 AttributeList *AttrList,
2496 bool IsTypeName) {
Eli Friedman173e0b7a2009-06-27 05:59:59 +00002497 assert((TargetName || Op) && "Invalid TargetName.");
Douglas Gregorfec52632009-06-20 00:51:54 +00002498 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00002499
Anders Carlsson74d7f0d2009-06-27 00:27:47 +00002500 DeclarationName Name;
2501 if (TargetName)
2502 Name = TargetName;
2503 else
2504 Name = Context.DeclarationNames.getCXXOperatorName(Op);
Mike Stump11289f42009-09-09 15:08:12 +00002505
2506 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS, IdentLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00002507 Name, AttrList, IsTypeName);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002508 if (UD) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00002509 PushOnScopeChains(UD, S);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002510 UD->setAccess(AS);
2511 }
Mike Stump11289f42009-09-09 15:08:12 +00002512
Anders Carlsson696a3f12009-08-28 05:40:36 +00002513 return DeclPtrTy::make(UD);
2514}
2515
2516NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2517 const CXXScopeSpec &SS,
2518 SourceLocation IdentLoc,
2519 DeclarationName Name,
2520 AttributeList *AttrList,
2521 bool IsTypeName) {
2522 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2523 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00002524
Anders Carlssonf038fc22009-08-28 05:49:21 +00002525 // FIXME: We ignore attributes for now.
2526 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00002527
Anders Carlsson59140b32009-08-28 03:16:11 +00002528 if (SS.isEmpty()) {
2529 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00002530 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002531 }
Mike Stump11289f42009-09-09 15:08:12 +00002532
2533 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00002534 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2535
Anders Carlssonf038fc22009-08-28 05:49:21 +00002536 if (isUnknownSpecialization(SS)) {
2537 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2538 SS.getRange(), NNS,
2539 IdentLoc, Name, IsTypeName);
2540 }
Mike Stump11289f42009-09-09 15:08:12 +00002541
Anders Carlsson59140b32009-08-28 03:16:11 +00002542 DeclContext *LookupContext = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002543
Anders Carlsson59140b32009-08-28 03:16:11 +00002544 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2545 // C++0x N2914 [namespace.udecl]p3:
2546 // A using-declaration used as a member-declaration shall refer to a member
2547 // of a base class of the class being defined, shall refer to a member of an
2548 // anonymous union that is a member of a base class of the class being
Mike Stump11289f42009-09-09 15:08:12 +00002549 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlsson59140b32009-08-28 03:16:11 +00002550 // a member of a base class of the class being defined.
2551 const Type *Ty = NNS->getAsType();
2552 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) {
2553 Diag(SS.getRange().getBegin(),
2554 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2555 << NNS << RD->getDeclName();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002556 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002557 }
Anders Carlsson4bd78752009-08-28 15:18:15 +00002558
2559 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0));
2560 LookupContext = BaseTy->getAs<RecordType>()->getDecl();
Anders Carlsson59140b32009-08-28 03:16:11 +00002561 } else {
2562 // C++0x N2914 [namespace.udecl]p8:
2563 // A using-declaration for a class member shall be a member-declaration.
2564 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002565 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlsson59140b32009-08-28 03:16:11 +00002566 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002567 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002568 }
Mike Stump11289f42009-09-09 15:08:12 +00002569
Anders Carlsson59140b32009-08-28 03:16:11 +00002570 // C++0x N2914 [namespace.udecl]p9:
2571 // In a using-declaration, a prefix :: refers to the global namespace.
2572 if (NNS->getKind() == NestedNameSpecifier::Global)
2573 LookupContext = Context.getTranslationUnitDecl();
2574 else
2575 LookupContext = NNS->getAsNamespace();
2576 }
2577
2578
Douglas Gregorfec52632009-06-20 00:51:54 +00002579 // Lookup target name.
Mike Stump11289f42009-09-09 15:08:12 +00002580 LookupResult R = LookupQualifiedName(LookupContext,
Anders Carlsson59140b32009-08-28 03:16:11 +00002581 Name, LookupOrdinaryName);
Mike Stump11289f42009-09-09 15:08:12 +00002582
Anders Carlsson59140b32009-08-28 03:16:11 +00002583 if (!R) {
Anders Carlsson5167a462009-08-30 00:58:45 +00002584 DiagnoseMissingMember(IdentLoc, Name, NNS, SS.getRange());
Anders Carlsson696a3f12009-08-28 05:40:36 +00002585 return 0;
Douglas Gregorfec52632009-06-20 00:51:54 +00002586 }
2587
Anders Carlsson59140b32009-08-28 03:16:11 +00002588 NamedDecl *ND = R.getAsDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002589
Anders Carlsson59140b32009-08-28 03:16:11 +00002590 if (IsTypeName && !isa<TypeDecl>(ND)) {
2591 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlsson696a3f12009-08-28 05:40:36 +00002592 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002593 }
2594
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002595 // C++0x N2914 [namespace.udecl]p6:
2596 // A using-declaration shall not name a namespace.
2597 if (isa<NamespaceDecl>(ND)) {
2598 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2599 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002600 return 0;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002601 }
Mike Stump11289f42009-09-09 15:08:12 +00002602
Anders Carlsson696a3f12009-08-28 05:40:36 +00002603 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2604 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregorfec52632009-06-20 00:51:54 +00002605}
2606
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002607/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2608/// is a namespace alias, returns the namespace it points to.
2609static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2610 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2611 return AD->getNamespace();
2612 return dyn_cast_or_null<NamespaceDecl>(D);
2613}
2614
Mike Stump11289f42009-09-09 15:08:12 +00002615Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00002616 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00002617 SourceLocation AliasLoc,
2618 IdentifierInfo *Alias,
2619 const CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00002620 SourceLocation IdentLoc,
2621 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00002622
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002623 // Lookup the namespace name.
2624 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
2625
Anders Carlssondca83c42009-03-28 06:23:46 +00002626 // Check if we have a previous declaration with the same name.
Anders Carlsson36949352009-03-28 23:49:35 +00002627 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002628 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00002629 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002630 // namespace, so don't create a new one.
2631 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
2632 return DeclPtrTy();
2633 }
Mike Stump11289f42009-09-09 15:08:12 +00002634
Anders Carlssondca83c42009-03-28 06:23:46 +00002635 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2636 diag::err_redefinition_different_kind;
2637 Diag(AliasLoc, DiagID) << Alias;
2638 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00002639 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00002640 }
2641
Anders Carlssonac2c9652009-03-28 06:42:02 +00002642 if (R.isAmbiguous()) {
Anders Carlsson47952ae2009-03-28 22:53:22 +00002643 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002644 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00002645 }
Mike Stump11289f42009-09-09 15:08:12 +00002646
Anders Carlssonac2c9652009-03-28 06:42:02 +00002647 if (!R) {
2648 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00002649 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00002650 }
Mike Stump11289f42009-09-09 15:08:12 +00002651
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002652 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00002653 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2654 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00002655 (NestedNameSpecifier *)SS.getScopeRep(),
Anders Carlssonff25fdf2009-03-28 22:58:02 +00002656 IdentLoc, R);
Mike Stump11289f42009-09-09 15:08:12 +00002657
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002658 CurContext->addDecl(AliasDecl);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00002659 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00002660}
2661
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002662void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2663 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00002664 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2665 !Constructor->isUsed()) &&
2666 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00002667
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002668 CXXRecordDecl *ClassDecl
2669 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002670 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Mike Stump11289f42009-09-09 15:08:12 +00002671 // Before the implicitly-declared default constructor for a class is
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002672 // implicitly defined, all the implicitly-declared default constructors
2673 // for its base class and its non-static data members shall have been
2674 // implicitly defined.
2675 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00002676 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2677 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002678 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002679 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002680 if (!BaseClassDecl->hasTrivialConstructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00002681 if (CXXConstructorDecl *BaseCtor =
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00002682 BaseClassDecl->getDefaultConstructor(Context))
2683 MarkDeclarationReferenced(CurrentLocation, BaseCtor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002684 else {
Mike Stump11289f42009-09-09 15:08:12 +00002685 Diag(CurrentLocation, diag::err_defining_default_ctor)
2686 << Context.getTagDeclType(ClassDecl) << 1
Fariborz Jahanian1c9d5d92009-06-20 20:23:38 +00002687 << Context.getTagDeclType(BaseClassDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002688 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian1c9d5d92009-06-20 20:23:38 +00002689 << Context.getTagDeclType(BaseClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002690 err = true;
2691 }
2692 }
2693 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00002694 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2695 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002696 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2697 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2698 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002699 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002700 CXXRecordDecl *FieldClassDecl
2701 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Duncan Sands323fc2a2009-06-25 09:03:06 +00002702 if (!FieldClassDecl->hasTrivialConstructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00002703 if (CXXConstructorDecl *FieldCtor =
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00002704 FieldClassDecl->getDefaultConstructor(Context))
2705 MarkDeclarationReferenced(CurrentLocation, FieldCtor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002706 else {
Mike Stump11289f42009-09-09 15:08:12 +00002707 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian1c9d5d92009-06-20 20:23:38 +00002708 << Context.getTagDeclType(ClassDecl) << 0 <<
2709 Context.getTagDeclType(FieldClassDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002710 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian1c9d5d92009-06-20 20:23:38 +00002711 << Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002712 err = true;
2713 }
2714 }
Mike Stump12b8ce12009-08-04 21:02:39 +00002715 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002716 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson52b91802009-07-09 17:37:12 +00002717 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002718 Diag((*Field)->getLocation(), diag::note_declared_at);
2719 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002720 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00002721 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson52b91802009-07-09 17:37:12 +00002722 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002723 Diag((*Field)->getLocation(), diag::note_declared_at);
2724 err = true;
2725 }
2726 }
2727 if (!err)
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00002728 Constructor->setUsed();
2729 else
2730 Constructor->setInvalidDecl();
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002731}
2732
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002733void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00002734 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002735 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2736 "DefineImplicitDestructor - call it for implicit default dtor");
Mike Stump11289f42009-09-09 15:08:12 +00002737
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002738 CXXRecordDecl *ClassDecl
2739 = cast<CXXRecordDecl>(Destructor->getDeclContext());
2740 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2741 // C++ [class.dtor] p5
Mike Stump11289f42009-09-09 15:08:12 +00002742 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002743 // implicitly defined, all the implicitly-declared default destructors
2744 // for its base class and its non-static data members shall have been
2745 // implicitly defined.
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00002746 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2747 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002748 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002749 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002750 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00002751 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002752 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2753 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2754 else
Mike Stump11289f42009-09-09 15:08:12 +00002755 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002756 "DefineImplicitDestructor - missing dtor in a base class");
2757 }
2758 }
Mike Stump11289f42009-09-09 15:08:12 +00002759
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00002760 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2761 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002762 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2763 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2764 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002765 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002766 CXXRecordDecl *FieldClassDecl
2767 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2768 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00002769 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002770 const_cast<CXXDestructorDecl*>(
2771 FieldClassDecl->getDestructor(Context)))
2772 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
2773 else
Mike Stump11289f42009-09-09 15:08:12 +00002774 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002775 "DefineImplicitDestructor - missing dtor in class of a data member");
2776 }
2777 }
2778 }
2779 Destructor->setUsed();
2780}
2781
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002782void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
2783 CXXMethodDecl *MethodDecl) {
2784 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
2785 MethodDecl->getOverloadedOperator() == OO_Equal &&
2786 !MethodDecl->isUsed()) &&
2787 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump11289f42009-09-09 15:08:12 +00002788
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002789 CXXRecordDecl *ClassDecl
2790 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00002791
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00002792 // C++[class.copy] p12
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002793 // Before the implicitly-declared copy assignment operator for a class is
2794 // implicitly defined, all implicitly-declared copy assignment operators
2795 // for its direct base classes and its nonstatic data members shall have
2796 // been implicitly defined.
2797 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00002798 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2799 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002800 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002801 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002802 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002803 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
2804 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
2805 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00002806 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2807 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002808 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2809 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2810 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002811 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002812 CXXRecordDecl *FieldClassDecl
2813 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002814 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002815 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
2816 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump12b8ce12009-08-04 21:02:39 +00002817 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002818 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00002819 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
2820 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002821 Diag(CurrentLocation, diag::note_first_required_here);
2822 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002823 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00002824 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00002825 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
2826 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002827 Diag(CurrentLocation, diag::note_first_required_here);
2828 err = true;
2829 }
2830 }
2831 if (!err)
Mike Stump11289f42009-09-09 15:08:12 +00002832 MethodDecl->setUsed();
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002833}
2834
2835CXXMethodDecl *
2836Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
2837 CXXRecordDecl *ClassDecl) {
2838 QualType LHSType = Context.getTypeDeclType(ClassDecl);
2839 QualType RHSType(LHSType);
2840 // If class's assignment operator argument is const/volatile qualified,
Mike Stump11289f42009-09-09 15:08:12 +00002841 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002842 // operator = (B&).
2843 if (ParmDecl->getType().isConstQualified())
2844 RHSType.addConst();
2845 if (ParmDecl->getType().isVolatileQualified())
2846 RHSType.addVolatile();
Mike Stump11289f42009-09-09 15:08:12 +00002847 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
2848 LHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002849 SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00002850 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
2851 RHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002852 SourceLocation()));
2853 Expr *Args[2] = { &*LHS, &*RHS };
2854 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00002855 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002856 CandidateSet);
2857 OverloadCandidateSet::iterator Best;
Mike Stump11289f42009-09-09 15:08:12 +00002858 if (BestViableFunction(CandidateSet,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00002859 ClassDecl->getLocation(), Best) == OR_Success)
2860 return cast<CXXMethodDecl>(Best->Function);
2861 assert(false &&
2862 "getAssignOperatorMethod - copy assignment operator method not found");
2863 return 0;
2864}
2865
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002866void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2867 CXXConstructorDecl *CopyConstructor,
2868 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00002869 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002870 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
2871 !CopyConstructor->isUsed()) &&
2872 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00002873
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002874 CXXRecordDecl *ClassDecl
2875 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
2876 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00002877 // C++ [class.copy] p209
Mike Stump11289f42009-09-09 15:08:12 +00002878 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002879 // implicitly defined, all the implicitly-declared copy constructors
2880 // for its base class and its non-static data members shall have been
2881 // implicitly defined.
2882 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2883 Base != ClassDecl->bases_end(); ++Base) {
2884 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002885 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002886 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002887 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00002888 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002889 }
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002890 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2891 FieldEnd = ClassDecl->field_end();
2892 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002893 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2894 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2895 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002896 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002897 CXXRecordDecl *FieldClassDecl
2898 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002899 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002900 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00002901 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002902 }
2903 }
2904 CopyConstructor->setUsed();
2905}
2906
Anders Carlsson6eb55572009-08-25 05:12:04 +00002907Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00002908Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00002909 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00002910 MultiExprArg ExprArgs) {
Anders Carlsson250aada2009-08-16 05:13:48 +00002911 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00002912
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002913 // C++ [class.copy]p15:
2914 // Whenever a temporary class object is copied using a copy constructor, and
2915 // this object and the copy have the same cv-unqualified type, an
2916 // implementation is permitted to treat the original and the copy as two
2917 // different ways of referring to the same object and not perform a copy at
2918 // all, even if the class copy constructor or destructor have side effects.
Mike Stump11289f42009-09-09 15:08:12 +00002919
Anders Carlsson250aada2009-08-16 05:13:48 +00002920 // FIXME: Is this enough?
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002921 if (Constructor->isCopyConstructor(Context)) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00002922 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson250aada2009-08-16 05:13:48 +00002923 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2924 E = BE->getSubExpr();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002925 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2926 if (ICE->getCastKind() == CastExpr::CK_NoOp)
2927 E = ICE->getSubExpr();
2928
Anders Carlsson250aada2009-08-16 05:13:48 +00002929 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
2930 Elidable = true;
2931 }
Mike Stump11289f42009-09-09 15:08:12 +00002932
2933 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00002934 Elidable, move(ExprArgs));
Anders Carlsson250aada2009-08-16 05:13:48 +00002935}
2936
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00002937/// BuildCXXConstructExpr - Creates a complete call to a constructor,
2938/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00002939Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00002940Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2941 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00002942 MultiExprArg ExprArgs) {
2943 unsigned NumExprs = ExprArgs.size();
2944 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00002945
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002946 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
2947 Elidable, Exprs, NumExprs));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00002948}
2949
Anders Carlsson574315a2009-08-27 05:08:22 +00002950Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00002951Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
2952 QualType Ty,
2953 SourceLocation TyBeginLoc,
Anders Carlsson574315a2009-08-27 05:08:22 +00002954 MultiExprArg Args,
2955 SourceLocation RParenLoc) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002956 unsigned NumExprs = Args.size();
2957 Expr **Exprs = (Expr **)Args.release();
Mike Stump11289f42009-09-09 15:08:12 +00002958
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002959 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
2960 TyBeginLoc, Exprs,
2961 NumExprs, RParenLoc));
Anders Carlsson574315a2009-08-27 05:08:22 +00002962}
2963
2964
Mike Stump11289f42009-09-09 15:08:12 +00002965bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00002966 CXXConstructorDecl *Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00002967 QualType DeclInitType,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00002968 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00002969 OwningExprResult TempResult =
2970 BuildCXXConstructExpr(VD->getLocation(), DeclInitType, Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00002971 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00002972 if (TempResult.isInvalid())
2973 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002974
Anders Carlsson6eb55572009-08-25 05:12:04 +00002975 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00002976 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniand460cb42009-08-05 18:17:32 +00002977 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00002978 VD->setInit(Context, Temp);
Mike Stump11289f42009-09-09 15:08:12 +00002979
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00002980 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00002981}
2982
Mike Stump11289f42009-09-09 15:08:12 +00002983void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002984 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002985 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002986 if (!ClassDecl->hasTrivialDestructor())
Mike Stump11289f42009-09-09 15:08:12 +00002987 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002988 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahanian67828442009-08-03 19:13:25 +00002989 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002990}
2991
Mike Stump11289f42009-09-09 15:08:12 +00002992/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002993/// ActOnDeclarator, when a C++ direct initializer is present.
2994/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00002995void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
2996 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002997 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002998 SourceLocation *CommaLocs,
2999 SourceLocation RParenLoc) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003000 unsigned NumExprs = Exprs.size();
3001 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00003002 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003003
3004 // If there is no declaration, there was an error parsing it. Just ignore
3005 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00003006 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003007 return;
Mike Stump11289f42009-09-09 15:08:12 +00003008
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003009 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3010 if (!VDecl) {
3011 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3012 RealDecl->setInvalidDecl();
3013 return;
3014 }
3015
Douglas Gregor402250f2009-08-26 21:14:46 +00003016 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003017 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003018 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3019 //
3020 // Clients that want to distinguish between the two forms, can check for
3021 // direct initializer using VarDecl::hasCXXDirectInitializer().
3022 // A major benefit is that clients that don't particularly care about which
3023 // exactly form was it (like the CodeGen) can handle both cases without
3024 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003025
Douglas Gregor402250f2009-08-26 21:14:46 +00003026 // If either the declaration has a dependent type or if any of the expressions
3027 // is type-dependent, we represent the initialization via a ParenListExpr for
3028 // later use during template instantiation.
3029 if (VDecl->getType()->isDependentType() ||
3030 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3031 // Let clients know that initialization was done with a direct initializer.
3032 VDecl->setCXXDirectInitializer(true);
Mike Stump11289f42009-09-09 15:08:12 +00003033
Douglas Gregor402250f2009-08-26 21:14:46 +00003034 // Store the initialization expressions as a ParenListExpr.
3035 unsigned NumExprs = Exprs.size();
Mike Stump11289f42009-09-09 15:08:12 +00003036 VDecl->setInit(Context,
Douglas Gregor402250f2009-08-26 21:14:46 +00003037 new (Context) ParenListExpr(Context, LParenLoc,
3038 (Expr **)Exprs.release(),
3039 NumExprs, RParenLoc));
3040 return;
3041 }
Mike Stump11289f42009-09-09 15:08:12 +00003042
Douglas Gregor402250f2009-08-26 21:14:46 +00003043
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003044 // C++ 8.5p11:
3045 // The form of initialization (using parentheses or '=') is generally
3046 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003047 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003048 QualType DeclInitType = VDecl->getType();
3049 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
3050 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003051
Douglas Gregor4044d992009-03-24 16:43:20 +00003052 // FIXME: This isn't the right place to complete the type.
3053 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3054 diag::err_typecheck_decl_incomplete_type)) {
3055 VDecl->setInvalidDecl();
3056 return;
3057 }
3058
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003059 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003060 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3061
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003062 CXXConstructorDecl *Constructor
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003063 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003064 move(Exprs),
Douglas Gregor6f543152008-11-05 15:29:30 +00003065 VDecl->getLocation(),
3066 SourceRange(VDecl->getLocation(),
3067 RParenLoc),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003068 VDecl->getDeclName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003069 IK_Direct,
3070 ConstructorArgs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003071 if (!Constructor)
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003072 RealDecl->setInvalidDecl();
Anders Carlsson332ef552009-04-15 21:48:18 +00003073 else {
Anders Carlsson332ef552009-04-15 21:48:18 +00003074 VDecl->setCXXDirectInitializer(true);
Mike Stump11289f42009-09-09 15:08:12 +00003075 if (InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003076 move_arg(ConstructorArgs)))
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003077 RealDecl->setInvalidDecl();
Fariborz Jahanian67828442009-08-03 19:13:25 +00003078 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlsson332ef552009-04-15 21:48:18 +00003079 }
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003080 return;
3081 }
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003082
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003083 if (NumExprs > 1) {
Chris Lattnerf490e152008-11-19 05:27:50 +00003084 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3085 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003086 RealDecl->setInvalidDecl();
3087 return;
3088 }
3089
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003090 // Let clients know that initialization was done with a direct initializer.
3091 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003092
3093 assert(NumExprs == 1 && "Expected 1 expression");
3094 // Set the init expression, handles conversions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003095 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3096 /*DirectInit=*/true);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003097}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003098
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003099/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3100/// may occur as part of direct-initialization or copy-initialization.
3101///
3102/// \param ClassType the type of the object being initialized, which must have
3103/// class type.
3104///
3105/// \param ArgsPtr the arguments provided to initialize the object
3106///
3107/// \param Loc the source location where the initialization occurs
3108///
3109/// \param Range the source range that covers the entire initialization
3110///
3111/// \param InitEntity the name of the entity being initialized, if known
3112///
3113/// \param Kind the type of initialization being performed
3114///
3115/// \param ConvertedArgs a vector that will be filled in with the
3116/// appropriately-converted arguments to the constructor (if initialization
3117/// succeeded).
3118///
3119/// \returns the constructor used to initialize the object, if successful.
3120/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003121CXXConstructorDecl *
Douglas Gregor6f543152008-11-05 15:29:30 +00003122Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003123 MultiExprArg ArgsPtr,
Douglas Gregor6f543152008-11-05 15:29:30 +00003124 SourceLocation Loc, SourceRange Range,
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003125 DeclarationName InitEntity,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003126 InitializationKind Kind,
3127 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003128 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003129 assert(ClassRec && "Can only initialize a class type here");
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003130 Expr **Args = (Expr **)ArgsPtr.get();
3131 unsigned NumArgs = ArgsPtr.size();
3132
Mike Stump11289f42009-09-09 15:08:12 +00003133 // C++ [dcl.init]p14:
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003134 // If the initialization is direct-initialization, or if it is
3135 // copy-initialization where the cv-unqualified version of the
3136 // source type is the same class as, or a derived class of, the
3137 // class of the destination, constructors are considered. The
3138 // applicable constructors are enumerated (13.3.1.3), and the
3139 // best one is chosen through overload resolution (13.3). The
3140 // constructor so selected is called to initialize the object,
3141 // with the initializer expression(s) as its argument(s). If no
3142 // constructor applies, or the overload resolution is ambiguous,
3143 // the initialization is ill-formed.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003144 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3145 OverloadCandidateSet CandidateSet;
Douglas Gregor6f543152008-11-05 15:29:30 +00003146
3147 // Add constructors to the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00003148 DeclarationName ConstructorName
Douglas Gregor1349b452008-12-15 21:24:18 +00003149 = Context.DeclarationNames.getCXXConstructorName(
3150 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor55297ac2008-12-23 00:26:44 +00003151 DeclContext::lookup_const_iterator Con, ConEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003152 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor55297ac2008-12-23 00:26:44 +00003153 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003154 // Find the constructor (which may be a template).
3155 CXXConstructorDecl *Constructor = 0;
3156 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3157 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003158 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003159 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3160 else
3161 Constructor = cast<CXXConstructorDecl>(*Con);
3162
Douglas Gregor6f543152008-11-05 15:29:30 +00003163 if ((Kind == IK_Direct) ||
Mike Stump11289f42009-09-09 15:08:12 +00003164 (Kind == IK_Copy &&
Anders Carlssond20e7952009-08-28 16:57:08 +00003165 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003166 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
3167 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003168 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003169 Args, NumArgs, CandidateSet);
3170 else
3171 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3172 }
Douglas Gregor6f543152008-11-05 15:29:30 +00003173 }
3174
Douglas Gregor1349b452008-12-15 21:24:18 +00003175 // FIXME: When we decide not to synthesize the implicitly-declared
3176 // constructors, we'll need to make them appear here.
3177
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003178 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003179 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003180 case OR_Success:
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003181 // We found a constructor. Break out so that we can convert the arguments
3182 // appropriately.
3183 break;
Mike Stump11289f42009-09-09 15:08:12 +00003184
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003185 case OR_No_Viable_Function:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003186 if (InitEntity)
3187 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003188 << InitEntity << Range;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003189 else
3190 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003191 << ClassType << Range;
Sebastian Redl15b02d22008-11-22 13:44:36 +00003192 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003193 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003194
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003195 case OR_Ambiguous:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003196 if (InitEntity)
3197 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3198 else
3199 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003200 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3201 return 0;
Douglas Gregor171c45a2009-02-18 21:56:37 +00003202
3203 case OR_Deleted:
3204 if (InitEntity)
3205 Diag(Loc, diag::err_ovl_deleted_init)
3206 << Best->Function->isDeleted()
3207 << InitEntity << Range;
3208 else
3209 Diag(Loc, diag::err_ovl_deleted_init)
3210 << Best->Function->isDeleted()
3211 << InitEntity << Range;
3212 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3213 return 0;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003214 }
Mike Stump11289f42009-09-09 15:08:12 +00003215
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003216 // Convert the arguments, fill in default arguments, etc.
3217 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3218 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3219 return 0;
3220
3221 return Constructor;
3222}
3223
3224/// \brief Given a constructor and the set of arguments provided for the
3225/// constructor, convert the arguments and add any required default arguments
3226/// to form a proper call to this constructor.
3227///
3228/// \returns true if an error occurred, false otherwise.
3229bool
3230Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3231 MultiExprArg ArgsPtr,
3232 SourceLocation Loc,
3233 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3234 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3235 unsigned NumArgs = ArgsPtr.size();
3236 Expr **Args = (Expr **)ArgsPtr.get();
3237
3238 const FunctionProtoType *Proto
3239 = Constructor->getType()->getAs<FunctionProtoType>();
3240 assert(Proto && "Constructor without a prototype?");
3241 unsigned NumArgsInProto = Proto->getNumArgs();
3242 unsigned NumArgsToCheck = NumArgs;
3243
3244 // If too few arguments are available, we'll fill in the rest with defaults.
3245 if (NumArgs < NumArgsInProto) {
3246 NumArgsToCheck = NumArgsInProto;
3247 ConvertedArgs.reserve(NumArgsInProto);
3248 } else {
3249 ConvertedArgs.reserve(NumArgs);
3250 if (NumArgs > NumArgsInProto)
3251 NumArgsToCheck = NumArgsInProto;
3252 }
3253
3254 // Convert arguments
3255 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3256 QualType ProtoArgType = Proto->getArgType(i);
3257
3258 Expr *Arg;
3259 if (i < NumArgs) {
3260 Arg = Args[i];
Anders Carlssonc8bfc462009-09-15 21:14:33 +00003261
3262 // Pass the argument.
3263 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3264 return true;
3265
3266 Args[i] = 0;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003267 } else {
3268 ParmVarDecl *Param = Constructor->getParamDecl(i);
3269
3270 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3271 if (DefArg.isInvalid())
3272 return true;
3273
3274 Arg = DefArg.takeAs<Expr>();
3275 }
3276
3277 ConvertedArgs.push_back(Arg);
3278 }
3279
3280 // If this is a variadic call, handle args passed through "...".
3281 if (Proto->isVariadic()) {
3282 // Promote the arguments (C99 6.5.2.2p7).
3283 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3284 Expr *Arg = Args[i];
3285 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3286 return true;
3287
3288 ConvertedArgs.push_back(Arg);
3289 Args[i] = 0;
3290 }
3291 }
3292
3293 return false;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003294}
3295
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003296/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3297/// determine whether they are reference-related,
3298/// reference-compatible, reference-compatible with added
3299/// qualification, or incompatible, for use in C++ initialization by
3300/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3301/// type, and the first type (T1) is the pointee type of the reference
3302/// type being initialized.
Mike Stump11289f42009-09-09 15:08:12 +00003303Sema::ReferenceCompareResult
3304Sema::CompareReferenceRelationship(QualType T1, QualType T2,
Douglas Gregor786ab212008-10-29 02:00:59 +00003305 bool& DerivedToBase) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003306 assert(!T1->isReferenceType() &&
3307 "T1 must be the pointee type of the reference type");
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003308 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
3309
3310 T1 = Context.getCanonicalType(T1);
3311 T2 = Context.getCanonicalType(T2);
3312 QualType UnqualT1 = T1.getUnqualifiedType();
3313 QualType UnqualT2 = T2.getUnqualifiedType();
3314
3315 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003316 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump11289f42009-09-09 15:08:12 +00003317 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003318 // T1 is a base class of T2.
Douglas Gregor786ab212008-10-29 02:00:59 +00003319 if (UnqualT1 == UnqualT2)
3320 DerivedToBase = false;
3321 else if (IsDerivedFrom(UnqualT2, UnqualT1))
3322 DerivedToBase = true;
3323 else
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003324 return Ref_Incompatible;
3325
3326 // At this point, we know that T1 and T2 are reference-related (at
3327 // least).
3328
3329 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003330 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003331 // reference-related to T2 and cv1 is the same cv-qualification
3332 // as, or greater cv-qualification than, cv2. For purposes of
3333 // overload resolution, cases for which cv1 is greater
3334 // cv-qualification than cv2 are identified as
3335 // reference-compatible with added qualification (see 13.3.3.2).
3336 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3337 return Ref_Compatible;
3338 else if (T1.isMoreQualifiedThan(T2))
3339 return Ref_Compatible_With_Added_Qualification;
3340 else
3341 return Ref_Related;
3342}
3343
3344/// CheckReferenceInit - Check the initialization of a reference
3345/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3346/// the initializer (either a simple initializer or an initializer
Douglas Gregor23a1f192008-10-29 23:31:03 +00003347/// list), and DeclType is the type of the declaration. When ICS is
3348/// non-null, this routine will compute the implicit conversion
3349/// sequence according to C++ [over.ics.ref] and will not produce any
3350/// diagnostics; when ICS is null, it will emit diagnostics when any
3351/// errors are found. Either way, a return value of true indicates
3352/// that there was a failure, a return value of false indicates that
3353/// the reference initialization succeeded.
Douglas Gregor2fe98832008-11-03 19:09:14 +00003354///
3355/// When @p SuppressUserConversions, user-defined conversions are
3356/// suppressed.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003357/// When @p AllowExplicit, we also permit explicit user-defined
3358/// conversion functions.
Sebastian Redl42e92c42009-04-12 17:16:29 +00003359/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Mike Stump11289f42009-09-09 15:08:12 +00003360bool
Sebastian Redl1a99f442009-04-16 17:51:27 +00003361Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003362 bool SuppressUserConversions,
Anders Carlsson271e3a42009-08-27 17:30:43 +00003363 bool AllowExplicit, bool ForceRValue,
3364 ImplicitConversionSequence *ICS) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003365 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3366
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003367 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003368 QualType T2 = Init->getType();
3369
Douglas Gregorcd695e52008-11-10 20:40:00 +00003370 // If the initializer is the address of an overloaded function, try
3371 // to resolve the overloaded function. If all goes well, T2 is the
3372 // type of the resulting function.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003373 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump11289f42009-09-09 15:08:12 +00003374 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003375 ICS != 0);
3376 if (Fn) {
3377 // Since we're performing this reference-initialization for
3378 // real, update the initializer with the resulting function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003379 if (!ICS) {
3380 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
3381 return true;
3382
Douglas Gregorcd695e52008-11-10 20:40:00 +00003383 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor171c45a2009-02-18 21:56:37 +00003384 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003385
3386 T2 = Fn->getType();
3387 }
3388 }
3389
Douglas Gregor786ab212008-10-29 02:00:59 +00003390 // Compute some basic properties of the types and the initializer.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003391 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor786ab212008-10-29 02:00:59 +00003392 bool DerivedToBase = false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00003393 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3394 Init->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003395 ReferenceCompareResult RefRelationship
Douglas Gregor786ab212008-10-29 02:00:59 +00003396 = CompareReferenceRelationship(T1, T2, DerivedToBase);
3397
3398 // Most paths end in a failed conversion.
3399 if (ICS)
3400 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003401
3402 // C++ [dcl.init.ref]p5:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003403 // A reference to type "cv1 T1" is initialized by an expression
3404 // of type "cv2 T2" as follows:
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003405
3406 // -- If the initializer expression
3407
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003408 // Rvalue references cannot bind to lvalues (N2812).
3409 // There is absolutely no situation where they can. In particular, note that
3410 // this is ill-formed, even if B has a user-defined conversion to A&&:
3411 // B b;
3412 // A&& r = b;
3413 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3414 if (!ICS)
3415 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
3416 << Init->getSourceRange();
3417 return true;
3418 }
3419
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003420 bool BindsDirectly = false;
Eli Friedman44b83ee2009-08-05 19:21:58 +00003421 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3422 // reference-compatible with "cv2 T2," or
Douglas Gregor786ab212008-10-29 02:00:59 +00003423 //
3424 // Note that the bit-field check is skipped if we are just computing
3425 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor71235ec2009-05-02 02:18:30 +00003426 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003427 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003428 BindsDirectly = true;
3429
Douglas Gregor786ab212008-10-29 02:00:59 +00003430 if (ICS) {
3431 // C++ [over.ics.ref]p1:
3432 // When a parameter of reference type binds directly (8.5.3)
3433 // to an argument expression, the implicit conversion sequence
3434 // is the identity conversion, unless the argument expression
3435 // has a type that is a derived class of the parameter type,
3436 // in which case the implicit conversion sequence is a
3437 // derived-to-base Conversion (13.3.3.1).
3438 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3439 ICS->Standard.First = ICK_Identity;
3440 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3441 ICS->Standard.Third = ICK_Identity;
3442 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3443 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003444 ICS->Standard.ReferenceBinding = true;
3445 ICS->Standard.DirectBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003446 ICS->Standard.RRefBinding = false;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003447 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00003448
3449 // Nothing more to do: the inaccessibility/ambiguity check for
3450 // derived-to-base conversions is suppressed when we're
3451 // computing the implicit conversion sequence (C++
3452 // [over.best.ics]p2).
3453 return false;
3454 } else {
3455 // Perform the conversion.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003456 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3457 if (DerivedToBase)
3458 CK = CastExpr::CK_DerivedToBase;
3459 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003460 }
3461 }
3462
3463 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman44b83ee2009-08-05 19:21:58 +00003464 // implicitly converted to an lvalue of type "cv3 T3,"
3465 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003466 // 92) (this conversion is selected by enumerating the
3467 // applicable conversion functions (13.3.1.6) and choosing
3468 // the best one through overload resolution (13.3)),
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003469 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
3470 !RequireCompleteType(SourceLocation(), T2, 0)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003471 // FIXME: Look for conversions in base classes!
Mike Stump11289f42009-09-09 15:08:12 +00003472 CXXRecordDecl *T2RecordDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003473 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003474
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003475 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003476 OverloadedFunctionDecl *Conversions
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003477 = T2RecordDecl->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00003478 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003479 = Conversions->function_begin();
3480 Func != Conversions->function_end(); ++Func) {
Mike Stump11289f42009-09-09 15:08:12 +00003481 FunctionTemplateDecl *ConvTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00003482 = dyn_cast<FunctionTemplateDecl>(*Func);
3483 CXXConversionDecl *Conv;
3484 if (ConvTemplate)
3485 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3486 else
3487 Conv = cast<CXXConversionDecl>(*Func);
Sebastian Redlb7d64912009-03-22 21:28:55 +00003488
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003489 // If the conversion function doesn't return a reference type,
3490 // it can't be considered for this conversion.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003491 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor05155d82009-08-21 23:19:43 +00003492 (AllowExplicit || !Conv->isExplicit())) {
3493 if (ConvTemplate)
Mike Stump11289f42009-09-09 15:08:12 +00003494 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003495 CandidateSet);
3496 else
3497 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3498 }
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003499 }
3500
3501 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003502 switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003503 case OR_Success:
3504 // This is a direct binding.
3505 BindsDirectly = true;
3506
3507 if (ICS) {
3508 // C++ [over.ics.ref]p1:
3509 //
3510 // [...] If the parameter binds directly to the result of
3511 // applying a conversion function to the argument
3512 // expression, the implicit conversion sequence is a
3513 // user-defined conversion sequence (13.3.3.1.2), with the
3514 // second standard conversion sequence either an identity
3515 // conversion or, if the conversion function returns an
3516 // entity of a type that is a derived class of the parameter
3517 // type, a derived-to-base Conversion.
3518 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3519 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3520 ICS->UserDefined.After = Best->FinalConversion;
3521 ICS->UserDefined.ConversionFunction = Best->Function;
3522 assert(ICS->UserDefined.After.ReferenceBinding &&
3523 ICS->UserDefined.After.DirectBinding &&
3524 "Expected a direct reference binding!");
3525 return false;
3526 } else {
3527 // Perform the conversion.
Mike Stump87c57ac2009-05-16 07:39:55 +00003528 // FIXME: Binding to a subobject of the lvalue is going to require more
3529 // AST annotation than this.
Anders Carlssona076d142009-07-31 01:23:52 +00003530 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003531 }
3532 break;
3533
3534 case OR_Ambiguous:
3535 assert(false && "Ambiguous reference binding conversions not implemented.");
3536 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003537
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003538 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003539 case OR_Deleted:
3540 // There was no suitable conversion, or we found a deleted
3541 // conversion; continue with other checks.
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003542 break;
3543 }
3544 }
Mike Stump11289f42009-09-09 15:08:12 +00003545
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003546 if (BindsDirectly) {
3547 // C++ [dcl.init.ref]p4:
3548 // [...] In all cases where the reference-related or
3549 // reference-compatible relationship of two types is used to
3550 // establish the validity of a reference binding, and T1 is a
3551 // base class of T2, a program that necessitates such a binding
3552 // is ill-formed if T1 is an inaccessible (clause 11) or
3553 // ambiguous (10.2) base class of T2.
3554 //
3555 // Note that we only check this condition when we're allowed to
3556 // complain about errors, because we should not be checking for
3557 // ambiguity (or inaccessibility) unless the reference binding
3558 // actually happens.
Mike Stump11289f42009-09-09 15:08:12 +00003559 if (DerivedToBase)
3560 return CheckDerivedToBaseConversion(T2, T1,
Douglas Gregor786ab212008-10-29 02:00:59 +00003561 Init->getSourceRange().getBegin(),
3562 Init->getSourceRange());
3563 else
3564 return false;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003565 }
3566
3567 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003568 // type (i.e., cv1 shall be const), or the reference shall be an
3569 // rvalue reference and the initializer expression shall be an rvalue.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003570 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor786ab212008-10-29 02:00:59 +00003571 if (!ICS)
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003572 Diag(Init->getSourceRange().getBegin(),
Chris Lattner377d1f82008-11-18 22:52:51 +00003573 diag::err_not_reference_to_const_init)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003574 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3575 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003576 return true;
3577 }
3578
3579 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman44b83ee2009-08-05 19:21:58 +00003580 // class type, and "cv1 T1" is reference-compatible with
3581 // "cv2 T2," the reference is bound in one of the
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003582 // following ways (the choice is implementation-defined):
3583 //
3584 // -- The reference is bound to the object represented by
3585 // the rvalue (see 3.10) or to a sub-object within that
3586 // object.
3587 //
Eli Friedman44b83ee2009-08-05 19:21:58 +00003588 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003589 // a constructor is called to copy the entire rvalue
3590 // object into the temporary. The reference is bound to
3591 // the temporary or to a sub-object within the
3592 // temporary.
3593 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003594 // The constructor that would be used to make the copy
3595 // shall be callable whether or not the copy is actually
3596 // done.
3597 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003598 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003599 // freedom, so we will always take the first option and never build
3600 // a temporary in this case. FIXME: We will, however, have to check
3601 // for the presence of a copy constructor in C++98/03 mode.
3602 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003603 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3604 if (ICS) {
3605 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3606 ICS->Standard.First = ICK_Identity;
3607 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3608 ICS->Standard.Third = ICK_Identity;
3609 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3610 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003611 ICS->Standard.ReferenceBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003612 ICS->Standard.DirectBinding = false;
3613 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003614 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00003615 } else {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003616 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3617 if (DerivedToBase)
3618 CK = CastExpr::CK_DerivedToBase;
3619 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003620 }
3621 return false;
3622 }
3623
Eli Friedman44b83ee2009-08-05 19:21:58 +00003624 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003625 // initialized from the initializer expression using the
3626 // rules for a non-reference copy initialization (8.5). The
3627 // reference is then bound to the temporary. If T1 is
3628 // reference-related to T2, cv1 must be the same
3629 // cv-qualification as, or greater cv-qualification than,
3630 // cv2; otherwise, the program is ill-formed.
3631 if (RefRelationship == Ref_Related) {
3632 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3633 // we would be reference-compatible or reference-compatible with
3634 // added qualification. But that wasn't the case, so the reference
3635 // initialization fails.
Douglas Gregor786ab212008-10-29 02:00:59 +00003636 if (!ICS)
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003637 Diag(Init->getSourceRange().getBegin(),
Chris Lattner377d1f82008-11-18 22:52:51 +00003638 diag::err_reference_init_drops_quals)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003639 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3640 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003641 return true;
3642 }
3643
Douglas Gregor576e98c2009-01-30 23:27:23 +00003644 // If at least one of the types is a class type, the types are not
3645 // related, and we aren't allowed any user conversions, the
3646 // reference binding fails. This case is important for breaking
3647 // recursion, since TryImplicitConversion below will attempt to
3648 // create a temporary through the use of a copy constructor.
3649 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3650 (T1->isRecordType() || T2->isRecordType())) {
3651 if (!ICS)
3652 Diag(Init->getSourceRange().getBegin(),
3653 diag::err_typecheck_convert_incompatible)
3654 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3655 return true;
3656 }
3657
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003658 // Actually try to convert the initializer to T1.
Douglas Gregor786ab212008-10-29 02:00:59 +00003659 if (ICS) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003660 // C++ [over.ics.ref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00003661 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003662 // When a parameter of reference type is not bound directly to
3663 // an argument expression, the conversion sequence is the one
3664 // required to convert the argument expression to the
3665 // underlying type of the reference according to
3666 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3667 // to copy-initializing a temporary of the underlying type with
3668 // the argument expression. Any difference in top-level
3669 // cv-qualification is subsumed by the initialization itself
3670 // and does not constitute a conversion.
Anders Carlssonef4c7212009-08-27 17:24:15 +00003671 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
3672 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00003673 /*ForceRValue=*/false,
3674 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003675
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003676 // Of course, that's still a reference binding.
3677 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3678 ICS->Standard.ReferenceBinding = true;
3679 ICS->Standard.RRefBinding = isRValRef;
Mike Stump11289f42009-09-09 15:08:12 +00003680 } else if (ICS->ConversionKind ==
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003681 ImplicitConversionSequence::UserDefinedConversion) {
3682 ICS->UserDefined.After.ReferenceBinding = true;
3683 ICS->UserDefined.After.RRefBinding = isRValRef;
3684 }
Douglas Gregor786ab212008-10-29 02:00:59 +00003685 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3686 } else {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003687 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor786ab212008-10-29 02:00:59 +00003688 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003689}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003690
3691/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3692/// of this overloaded operator is well-formed. If so, returns false;
3693/// otherwise, emits appropriate diagnostics and returns true.
3694bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00003695 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003696 "Expected an overloaded operator declaration");
3697
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003698 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
3699
Mike Stump11289f42009-09-09 15:08:12 +00003700 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003701 // The allocation and deallocation functions, operator new,
3702 // operator new[], operator delete and operator delete[], are
3703 // described completely in 3.7.3. The attributes and restrictions
3704 // found in the rest of this subclause do not apply to them unless
3705 // explicitly stated in 3.7.3.
Mike Stump87c57ac2009-05-16 07:39:55 +00003706 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003707 if (Op == OO_New || Op == OO_Array_New ||
3708 Op == OO_Delete || Op == OO_Array_Delete)
3709 return false;
3710
3711 // C++ [over.oper]p6:
3712 // An operator function shall either be a non-static member
3713 // function or be a non-member function and have at least one
3714 // parameter whose type is a class, a reference to a class, an
3715 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00003716 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
3717 if (MethodDecl->isStatic())
3718 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003719 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003720 } else {
3721 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00003722 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
3723 ParamEnd = FnDecl->param_end();
3724 Param != ParamEnd; ++Param) {
3725 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00003726 if (ParamType->isDependentType() || ParamType->isRecordType() ||
3727 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003728 ClassOrEnumParam = true;
3729 break;
3730 }
3731 }
3732
Douglas Gregord69246b2008-11-17 16:14:12 +00003733 if (!ClassOrEnumParam)
3734 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00003735 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003736 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003737 }
3738
3739 // C++ [over.oper]p8:
3740 // An operator function cannot have default arguments (8.3.6),
3741 // except where explicitly stated below.
3742 //
Mike Stump11289f42009-09-09 15:08:12 +00003743 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003744 // (C++ [over.call]p1).
3745 if (Op != OO_Call) {
3746 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
3747 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor58354032008-12-24 00:01:03 +00003748 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00003749 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00003750 diag::err_operator_overload_default_arg)
3751 << FnDecl->getDeclName();
3752 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregord69246b2008-11-17 16:14:12 +00003753 return Diag((*Param)->getLocation(),
Chris Lattner29e812b2008-11-20 06:06:08 +00003754 diag::err_operator_overload_default_arg)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003755 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003756 }
3757 }
3758
Douglas Gregor6cf08062008-11-10 13:38:07 +00003759 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
3760 { false, false, false }
3761#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3762 , { Unary, Binary, MemberOnly }
3763#include "clang/Basic/OperatorKinds.def"
3764 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003765
Douglas Gregor6cf08062008-11-10 13:38:07 +00003766 bool CanBeUnaryOperator = OperatorUses[Op][0];
3767 bool CanBeBinaryOperator = OperatorUses[Op][1];
3768 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003769
3770 // C++ [over.oper]p8:
3771 // [...] Operator functions cannot have more or fewer parameters
3772 // than the number required for the corresponding operator, as
3773 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00003774 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00003775 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003776 if (Op != OO_Call &&
3777 ((NumParams == 1 && !CanBeUnaryOperator) ||
3778 (NumParams == 2 && !CanBeBinaryOperator) ||
3779 (NumParams < 1) || (NumParams > 2))) {
3780 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00003781 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00003782 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00003783 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00003784 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00003785 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00003786 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00003787 assert(CanBeBinaryOperator &&
3788 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00003789 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00003790 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003791
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00003792 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003793 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003794 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003795
Douglas Gregord69246b2008-11-17 16:14:12 +00003796 // Overloaded operators other than operator() cannot be variadic.
3797 if (Op != OO_Call &&
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003798 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00003799 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003800 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003801 }
3802
3803 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00003804 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
3805 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00003806 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003807 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003808 }
3809
3810 // C++ [over.inc]p1:
3811 // The user-defined function called operator++ implements the
3812 // prefix and postfix ++ operator. If this function is a member
3813 // function with no parameters, or a non-member function with one
3814 // parameter of class or enumeration type, it defines the prefix
3815 // increment operator ++ for objects of that type. If the function
3816 // is a member function with one parameter (which shall be of type
3817 // int) or a non-member function with two parameters (the second
3818 // of which shall be of type int), it defines the postfix
3819 // increment operator ++ for objects of that type.
3820 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
3821 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
3822 bool ParamIsInt = false;
3823 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
3824 ParamIsInt = BT->getKind() == BuiltinType::Int;
3825
Chris Lattner2b786902008-11-21 07:50:02 +00003826 if (!ParamIsInt)
3827 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003828 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003829 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003830 }
3831
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003832 // Notify the class if it got an assignment operator.
3833 if (Op == OO_Equal) {
3834 // Would have returned earlier otherwise.
3835 assert(isa<CXXMethodDecl>(FnDecl) &&
3836 "Overloaded = not member, but not filtered.");
3837 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Fariborz Jahanian4985b332009-08-13 21:09:41 +00003838 Method->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003839 Method->getParent()->addedAssignmentOperator(Context, Method);
3840 }
3841
Douglas Gregord69246b2008-11-17 16:14:12 +00003842 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003843}
Chris Lattner3b024a32008-12-17 07:09:26 +00003844
Douglas Gregor07665a62009-01-05 19:45:36 +00003845/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
3846/// linkage specification, including the language and (if present)
3847/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
3848/// the location of the language string literal, which is provided
3849/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
3850/// the '{' brace. Otherwise, this linkage specification does not
3851/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00003852Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
3853 SourceLocation ExternLoc,
3854 SourceLocation LangLoc,
3855 const char *Lang,
3856 unsigned StrSize,
3857 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00003858 LinkageSpecDecl::LanguageIDs Language;
3859 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3860 Language = LinkageSpecDecl::lang_c;
3861 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3862 Language = LinkageSpecDecl::lang_cxx;
3863 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00003864 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00003865 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00003866 }
Mike Stump11289f42009-09-09 15:08:12 +00003867
Chris Lattner438e5012008-12-17 07:13:27 +00003868 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00003869
Douglas Gregor07665a62009-01-05 19:45:36 +00003870 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00003871 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00003872 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003873 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00003874 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00003875 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00003876}
3877
Douglas Gregor07665a62009-01-05 19:45:36 +00003878/// ActOnFinishLinkageSpecification - Completely the definition of
3879/// the C++ linkage specification LinkageSpec. If RBraceLoc is
3880/// valid, it's the position of the closing '}' brace in a linkage
3881/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00003882Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
3883 DeclPtrTy LinkageSpec,
3884 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00003885 if (LinkageSpec)
3886 PopDeclContext();
3887 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00003888}
3889
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003890/// \brief Perform semantic analysis for the variable declaration that
3891/// occurs within a C++ catch clause, returning the newly-created
3892/// variable.
3893VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00003894 DeclaratorInfo *DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003895 IdentifierInfo *Name,
3896 SourceLocation Loc,
3897 SourceRange Range) {
3898 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00003899
3900 // Arrays and functions decay.
3901 if (ExDeclType->isArrayType())
3902 ExDeclType = Context.getArrayDecayedType(ExDeclType);
3903 else if (ExDeclType->isFunctionType())
3904 ExDeclType = Context.getPointerType(ExDeclType);
3905
3906 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
3907 // The exception-declaration shall not denote a pointer or reference to an
3908 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00003909 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00003910 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003911 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00003912 Invalid = true;
3913 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003914
Sebastian Redl54c04d42008-12-22 19:15:10 +00003915 QualType BaseType = ExDeclType;
3916 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00003917 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003918 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003919 BaseType = Ptr->getPointeeType();
3920 Mode = 1;
Douglas Gregordd430f72009-01-19 19:26:10 +00003921 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00003922 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00003923 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00003924 BaseType = Ref->getPointeeType();
3925 Mode = 2;
Douglas Gregordd430f72009-01-19 19:26:10 +00003926 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00003927 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00003928 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003929 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00003930 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00003931
Mike Stump11289f42009-09-09 15:08:12 +00003932 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003933 RequireNonAbstractType(Loc, ExDeclType,
3934 diag::err_abstract_type_in_decl,
3935 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00003936 Invalid = true;
3937
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003938 // FIXME: Need to test for ability to copy-construct and destroy the
3939 // exception variable.
3940
Sebastian Redl9b244a82008-12-22 21:35:02 +00003941 // FIXME: Need to check for abstract classes.
3942
Mike Stump11289f42009-09-09 15:08:12 +00003943 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003944 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003945
3946 if (Invalid)
3947 ExDecl->setInvalidDecl();
3948
3949 return ExDecl;
3950}
3951
3952/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
3953/// handler.
3954Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00003955 DeclaratorInfo *DInfo = 0;
3956 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003957
3958 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00003959 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor2ada0482009-02-04 17:27:36 +00003960 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003961 // The scope should be freshly made just for us. There is just no way
3962 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00003963 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00003964 if (PrevDecl->isTemplateParameter()) {
3965 // Maybe we will complain about the shadowed template parameter.
3966 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003967 }
3968 }
3969
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003970 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003971 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
3972 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003973 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00003974 }
3975
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00003976 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003977 D.getIdentifier(),
3978 D.getIdentifierLoc(),
3979 D.getDeclSpec().getSourceRange());
3980
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003981 if (Invalid)
3982 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003983
Sebastian Redl54c04d42008-12-22 19:15:10 +00003984 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00003985 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00003986 PushOnScopeChains(ExDecl, S);
3987 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003988 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003989
Douglas Gregor758a8692009-06-17 21:51:59 +00003990 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00003991 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003992}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00003993
Mike Stump11289f42009-09-09 15:08:12 +00003994Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00003995 ExprArg assertexpr,
3996 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00003997 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00003998 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00003999 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4000
Anders Carlsson54b26982009-03-14 00:33:21 +00004001 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4002 llvm::APSInt Value(32);
4003 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4004 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4005 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00004006 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00004007 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004008
Anders Carlsson54b26982009-03-14 00:33:21 +00004009 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00004010 std::string str(AssertMessage->getStrData(),
Anders Carlsson54b26982009-03-14 00:33:21 +00004011 AssertMessage->getByteLength());
Mike Stump11289f42009-09-09 15:08:12 +00004012 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson27de6a52009-03-15 18:44:04 +00004013 << str << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00004014 }
4015 }
Mike Stump11289f42009-09-09 15:08:12 +00004016
Anders Carlsson78e2bc02009-03-15 17:35:16 +00004017 assertexpr.release();
4018 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00004019 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004020 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00004021
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004022 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00004023 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004024}
Sebastian Redlf769df52009-03-24 22:27:57 +00004025
John McCall11083da2009-09-16 22:47:08 +00004026/// Handle a friend type declaration. This works in tandem with
4027/// ActOnTag.
4028///
4029/// Notes on friend class templates:
4030///
4031/// We generally treat friend class declarations as if they were
4032/// declaring a class. So, for example, the elaborated type specifier
4033/// in a friend declaration is required to obey the restrictions of a
4034/// class-head (i.e. no typedefs in the scope chain), template
4035/// parameters are required to match up with simple template-ids, &c.
4036/// However, unlike when declaring a template specialization, it's
4037/// okay to refer to a template specialization without an empty
4038/// template parameter declaration, e.g.
4039/// friend class A<T>::B<unsigned>;
4040/// We permit this as a special case; if there are any template
4041/// parameters present at all, require proper matching, i.e.
4042/// template <> template <class T> friend class A<int>::B;
John McCallaa74a0c2009-08-28 07:59:38 +00004043Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S,
John McCall27b5c252009-09-14 21:59:20 +00004044 const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00004045 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004046 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00004047
4048 assert(DS.isFriendSpecified());
4049 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4050
John McCall11083da2009-09-16 22:47:08 +00004051 // Try to convert the decl specifier to a type. This works for
4052 // friend templates because ActOnTag never produces a ClassTemplateDecl
4053 // for a TUK_Friend.
John McCalld8fe9af2009-09-08 17:47:29 +00004054 bool invalid = false;
4055 QualType T = ConvertDeclSpecToType(DS, Loc, invalid);
4056 if (invalid) return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00004057
John McCall11083da2009-09-16 22:47:08 +00004058 // This is definitely an error in C++98. It's probably meant to
4059 // be forbidden in C++0x, too, but the specification is just
4060 // poorly written.
4061 //
4062 // The problem is with declarations like the following:
4063 // template <T> friend A<T>::foo;
4064 // where deciding whether a class C is a friend or not now hinges
4065 // on whether there exists an instantiation of A that causes
4066 // 'foo' to equal C. There are restrictions on class-heads
4067 // (which we declare (by fiat) elaborated friend declarations to
4068 // be) that makes this tractable.
4069 //
4070 // FIXME: handle "template <> friend class A<T>;", which
4071 // is possibly well-formed? Who even knows?
4072 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4073 Diag(Loc, diag::err_tagless_friend_type_template)
4074 << DS.getSourceRange();
4075 return DeclPtrTy();
4076 }
4077
John McCallaa74a0c2009-08-28 07:59:38 +00004078 // C++ [class.friend]p2:
4079 // An elaborated-type-specifier shall be used in a friend declaration
4080 // for a class.*
4081 // * The class-key of the elaborated-type-specifier is required.
John McCalld8fe9af2009-09-08 17:47:29 +00004082 // This is one of the rare places in Clang where it's legitimate to
4083 // ask about the "spelling" of the type.
4084 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4085 // If we evaluated the type to a record type, suggest putting
4086 // a tag in front.
John McCallaa74a0c2009-08-28 07:59:38 +00004087 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00004088 RecordDecl *RD = RT->getDecl();
4089
4090 std::string InsertionText = std::string(" ") + RD->getKindName();
4091
4092 Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type)
4093 << (RD->isUnion())
4094 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4095 InsertionText);
John McCallaa74a0c2009-08-28 07:59:38 +00004096 return DeclPtrTy();
4097 }else {
John McCalld8fe9af2009-09-08 17:47:29 +00004098 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4099 << DS.getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004100 return DeclPtrTy();
John McCallaa74a0c2009-08-28 07:59:38 +00004101 }
4102 }
4103
John McCall2f212b32009-09-11 21:02:39 +00004104 bool IsDefinition = false;
John McCalld8fe9af2009-09-08 17:47:29 +00004105
John McCall2f212b32009-09-11 21:02:39 +00004106 // We want to do a few things differently if the type was declared with
4107 // a tag: specifically, we want to use the associated RecordDecl as
4108 // the object of our friend declaration, and we want to disallow
4109 // class definitions.
John McCalld8fe9af2009-09-08 17:47:29 +00004110 switch (DS.getTypeSpecType()) {
4111 default: break;
4112 case DeclSpec::TST_class:
4113 case DeclSpec::TST_struct:
4114 case DeclSpec::TST_union:
4115 CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep());
John McCall11083da2009-09-16 22:47:08 +00004116 if (RD)
John McCalld8fe9af2009-09-08 17:47:29 +00004117 IsDefinition |= RD->isDefinition();
John McCalld8fe9af2009-09-08 17:47:29 +00004118 break;
4119 }
John McCallaa74a0c2009-08-28 07:59:38 +00004120
4121 // C++ [class.friend]p2: A class shall not be defined inside
4122 // a friend declaration.
4123 if (IsDefinition) {
4124 Diag(DS.getFriendSpecLoc(), diag::err_friend_decl_defines_class)
4125 << DS.getSourceRange();
4126 return DeclPtrTy();
4127 }
4128
4129 // C++98 [class.friend]p1: A friend of a class is a function
4130 // or class that is not a member of the class . . .
4131 // But that's a silly restriction which nobody implements for
4132 // inner classes, and C++0x removes it anyway, so we only report
4133 // this (as a warning) if we're being pedantic.
John McCalld8fe9af2009-09-08 17:47:29 +00004134 if (!getLangOptions().CPlusPlus0x)
4135 if (const RecordType *RT = T->getAs<RecordType>())
4136 if (RT->getDecl()->getDeclContext() == CurContext)
4137 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCallaa74a0c2009-08-28 07:59:38 +00004138
John McCall11083da2009-09-16 22:47:08 +00004139 Decl *D;
4140 if (TempParams.size())
4141 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4142 TempParams.size(),
4143 (TemplateParameterList**) TempParams.release(),
4144 T.getTypePtr(),
4145 DS.getFriendSpecLoc());
4146 else
4147 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4148 DS.getFriendSpecLoc());
4149 D->setAccess(AS_public);
4150 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004151
John McCall11083da2009-09-16 22:47:08 +00004152 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004153}
4154
John McCall2f212b32009-09-11 21:02:39 +00004155Sema::DeclPtrTy
4156Sema::ActOnFriendFunctionDecl(Scope *S,
4157 Declarator &D,
4158 bool IsDefinition,
4159 MultiTemplateParamsArg TemplateParams) {
4160 // FIXME: do something with template parameters
4161
John McCallaa74a0c2009-08-28 07:59:38 +00004162 const DeclSpec &DS = D.getDeclSpec();
4163
4164 assert(DS.isFriendSpecified());
4165 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4166
4167 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004168 DeclaratorInfo *DInfo = 0;
John McCallaa74a0c2009-08-28 07:59:38 +00004169 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall07e91c02009-08-06 02:15:43 +00004170
4171 // C++ [class.friend]p1
4172 // A friend of a class is a function or class....
4173 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00004174 // It *doesn't* see through dependent types, which is correct
4175 // according to [temp.arg.type]p3:
4176 // If a declaration acquires a function type through a
4177 // type dependent on a template-parameter and this causes
4178 // a declaration that does not use the syntactic form of a
4179 // function declarator to have a function type, the program
4180 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00004181 if (!T->isFunctionType()) {
4182 Diag(Loc, diag::err_unexpected_friend);
4183
4184 // It might be worthwhile to try to recover by creating an
4185 // appropriate declaration.
4186 return DeclPtrTy();
4187 }
4188
4189 // C++ [namespace.memdef]p3
4190 // - If a friend declaration in a non-local class first declares a
4191 // class or function, the friend class or function is a member
4192 // of the innermost enclosing namespace.
4193 // - The name of the friend is not found by simple name lookup
4194 // until a matching declaration is provided in that namespace
4195 // scope (either before or after the class declaration granting
4196 // friendship).
4197 // - If a friend function is called, its name may be found by the
4198 // name lookup that considers functions from namespaces and
4199 // classes associated with the types of the function arguments.
4200 // - When looking for a prior declaration of a class or a function
4201 // declared as a friend, scopes outside the innermost enclosing
4202 // namespace scope are not considered.
4203
John McCallaa74a0c2009-08-28 07:59:38 +00004204 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4205 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00004206 assert(Name);
4207
4208 // The existing declaration we found.
4209 FunctionDecl *FD = NULL;
4210
4211 // The context we found the declaration in, or in which we should
4212 // create the declaration.
4213 DeclContext *DC;
4214
4215 // FIXME: handle local classes
4216
4217 // Recover from invalid scope qualifiers as if they just weren't there.
4218 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
4219 DC = computeDeclContext(ScopeQual);
4220
4221 // FIXME: handle dependent contexts
4222 if (!DC) return DeclPtrTy();
4223
4224 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
4225
4226 // If searching in that context implicitly found a declaration in
4227 // a different context, treat it like it wasn't found at all.
4228 // TODO: better diagnostics for this case. Suggesting the right
4229 // qualified scope would be nice...
4230 if (!Dec || Dec->getDeclContext() != DC) {
John McCallaa74a0c2009-08-28 07:59:38 +00004231 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00004232 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4233 return DeclPtrTy();
4234 }
4235
4236 // C++ [class.friend]p1: A friend of a class is a function or
4237 // class that is not a member of the class . . .
4238 if (DC == CurContext)
4239 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4240
4241 FD = cast<FunctionDecl>(Dec);
4242
4243 // Otherwise walk out to the nearest namespace scope looking for matches.
4244 } else {
4245 // TODO: handle local class contexts.
4246
4247 DC = CurContext;
4248 while (true) {
4249 // Skip class contexts. If someone can cite chapter and verse
4250 // for this behavior, that would be nice --- it's what GCC and
4251 // EDG do, and it seems like a reasonable intent, but the spec
4252 // really only says that checks for unqualified existing
4253 // declarations should stop at the nearest enclosing namespace,
4254 // not that they should only consider the nearest enclosing
4255 // namespace.
4256 while (DC->isRecord()) DC = DC->getParent();
4257
4258 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
4259
4260 // TODO: decide what we think about using declarations.
4261 if (Dec) {
4262 FD = cast<FunctionDecl>(Dec);
4263 break;
4264 }
4265 if (DC->isFileContext()) break;
4266 DC = DC->getParent();
4267 }
4268
4269 // C++ [class.friend]p1: A friend of a class is a function or
4270 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00004271 // C++0x changes this for both friend types and functions.
4272 // Most C++ 98 compilers do seem to give an error here, so
4273 // we do, too.
4274 if (FD && DC == CurContext && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00004275 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4276 }
4277
John McCalld1e9d832009-08-11 06:59:38 +00004278 bool Redeclaration = (FD != 0);
4279
4280 // If we found a match, create a friend function declaration with
4281 // that function as the previous declaration.
4282 if (Redeclaration) {
4283 // Create it in the semantic context of the original declaration.
4284 DC = FD->getDeclContext();
4285
John McCall07e91c02009-08-06 02:15:43 +00004286 // If we didn't find something matching the type exactly, create
4287 // a declaration. This declaration should only be findable via
4288 // argument-dependent lookup.
John McCalld1e9d832009-08-11 06:59:38 +00004289 } else {
John McCall07e91c02009-08-06 02:15:43 +00004290 assert(DC->isFileContext());
4291
4292 // This implies that it has to be an operator or function.
John McCallaa74a0c2009-08-28 07:59:38 +00004293 if (D.getKind() == Declarator::DK_Constructor ||
4294 D.getKind() == Declarator::DK_Destructor ||
4295 D.getKind() == Declarator::DK_Conversion) {
John McCall07e91c02009-08-06 02:15:43 +00004296 Diag(Loc, diag::err_introducing_special_friend) <<
John McCallaa74a0c2009-08-28 07:59:38 +00004297 (D.getKind() == Declarator::DK_Constructor ? 0 :
4298 D.getKind() == Declarator::DK_Destructor ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00004299 return DeclPtrTy();
4300 }
John McCall07e91c02009-08-06 02:15:43 +00004301 }
4302
John McCallaa74a0c2009-08-28 07:59:38 +00004303 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo,
John McCalld1e9d832009-08-11 06:59:38 +00004304 /* PrevDecl = */ FD,
4305 MultiTemplateParamsArg(*this),
4306 IsDefinition,
4307 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00004308 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00004309
4310 assert(cast<FunctionDecl>(ND)->getPreviousDeclaration() == FD &&
4311 "lost reference to previous declaration");
4312
John McCallaa74a0c2009-08-28 07:59:38 +00004313 FD = cast<FunctionDecl>(ND);
John McCalld1e9d832009-08-11 06:59:38 +00004314
John McCall5ed6e8f2009-08-18 00:00:49 +00004315 assert(FD->getDeclContext() == DC);
4316 assert(FD->getLexicalDeclContext() == CurContext);
4317
John McCall759e32b2009-08-31 22:39:49 +00004318 // Add the function declaration to the appropriate lookup tables,
4319 // adjusting the redeclarations list as necessary. We don't
4320 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00004321 //
John McCall759e32b2009-08-31 22:39:49 +00004322 // Also update the scope-based lookup if the target context's
4323 // lookup context is in lexical scope.
4324 if (!CurContext->isDependentContext()) {
4325 DC = DC->getLookupContext();
4326 DC->makeDeclVisibleInContext(FD, /* Recoverable=*/ false);
4327 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4328 PushOnScopeChains(FD, EnclosingScope, /*AddToContext=*/ false);
4329 }
John McCallaa74a0c2009-08-28 07:59:38 +00004330
4331 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
4332 D.getIdentifierLoc(), FD,
4333 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00004334 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00004335 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00004336
4337 return DeclPtrTy::make(FD);
Anders Carlsson38811702009-05-11 22:55:49 +00004338}
4339
Chris Lattner83f095c2009-03-28 19:18:32 +00004340void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004341 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004342
Chris Lattner83f095c2009-03-28 19:18:32 +00004343 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00004344 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4345 if (!Fn) {
4346 Diag(DelLoc, diag::err_deleted_non_function);
4347 return;
4348 }
4349 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4350 Diag(DelLoc, diag::err_deleted_decl_not_first);
4351 Diag(Prev->getLocation(), diag::note_previous_declaration);
4352 // If the declaration wasn't the first, we delete the function anyway for
4353 // recovery.
4354 }
4355 Fn->setDeleted();
4356}
Sebastian Redl4c018662009-04-27 21:33:24 +00004357
4358static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4359 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4360 ++CI) {
4361 Stmt *SubStmt = *CI;
4362 if (!SubStmt)
4363 continue;
4364 if (isa<ReturnStmt>(SubStmt))
4365 Self.Diag(SubStmt->getSourceRange().getBegin(),
4366 diag::err_return_in_constructor_handler);
4367 if (!isa<Expr>(SubStmt))
4368 SearchForReturnInStmt(Self, SubStmt);
4369 }
4370}
4371
4372void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4373 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4374 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4375 SearchForReturnInStmt(*this, Handler);
4376 }
4377}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004378
Mike Stump11289f42009-09-09 15:08:12 +00004379bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004380 const CXXMethodDecl *Old) {
4381 QualType NewTy = New->getType()->getAsFunctionType()->getResultType();
4382 QualType OldTy = Old->getType()->getAsFunctionType()->getResultType();
4383
4384 QualType CNewTy = Context.getCanonicalType(NewTy);
4385 QualType COldTy = Context.getCanonicalType(OldTy);
4386
Mike Stump11289f42009-09-09 15:08:12 +00004387 if (CNewTy == COldTy &&
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004388 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
4389 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004390
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004391 // Check if the return types are covariant
4392 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00004393
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004394 /// Both types must be pointers or references to classes.
4395 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4396 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4397 NewClassTy = NewPT->getPointeeType();
4398 OldClassTy = OldPT->getPointeeType();
4399 }
4400 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4401 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4402 NewClassTy = NewRT->getPointeeType();
4403 OldClassTy = OldRT->getPointeeType();
4404 }
4405 }
Mike Stump11289f42009-09-09 15:08:12 +00004406
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004407 // The return types aren't either both pointers or references to a class type.
4408 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00004409 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004410 diag::err_different_return_type_for_overriding_virtual_function)
4411 << New->getDeclName() << NewTy << OldTy;
4412 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00004413
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004414 return true;
4415 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004416
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004417 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
4418 // Check if the new class derives from the old class.
4419 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4420 Diag(New->getLocation(),
4421 diag::err_covariant_return_not_derived)
4422 << New->getDeclName() << NewTy << OldTy;
4423 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4424 return true;
4425 }
Mike Stump11289f42009-09-09 15:08:12 +00004426
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004427 // Check if we the conversion from derived to base is valid.
Mike Stump11289f42009-09-09 15:08:12 +00004428 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004429 diag::err_covariant_return_inaccessible_base,
4430 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4431 // FIXME: Should this point to the return type?
4432 New->getLocation(), SourceRange(), New->getDeclName())) {
4433 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4434 return true;
4435 }
4436 }
Mike Stump11289f42009-09-09 15:08:12 +00004437
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004438 // The qualifiers of the return types must be the same.
4439 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
4440 Diag(New->getLocation(),
4441 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004442 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004443 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4444 return true;
4445 };
Mike Stump11289f42009-09-09 15:08:12 +00004446
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004447
4448 // The new class type must have the same or less qualifiers as the old type.
4449 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4450 Diag(New->getLocation(),
4451 diag::err_covariant_return_type_class_type_more_qualified)
4452 << New->getDeclName() << NewTy << OldTy;
4453 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4454 return true;
4455 };
Mike Stump11289f42009-09-09 15:08:12 +00004456
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004457 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004458}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004459
Sebastian Redl86be8542009-07-07 20:29:57 +00004460bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
Mike Stump11289f42009-09-09 15:08:12 +00004461 const CXXMethodDecl *Old) {
Sebastian Redl86be8542009-07-07 20:29:57 +00004462 return CheckExceptionSpecSubset(diag::err_override_exception_spec,
4463 diag::note_overridden_virtual_function,
4464 Old->getType()->getAsFunctionProtoType(),
4465 Old->getLocation(),
4466 New->getType()->getAsFunctionProtoType(),
4467 New->getLocation());
4468}
4469
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004470/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4471/// initializer for the declaration 'Dcl'.
4472/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4473/// static data member of class X, names should be looked up in the scope of
4474/// class X.
4475void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004476 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004477
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004478 Decl *D = Dcl.getAs<Decl>();
4479 // If there is no declaration, there was an error parsing it.
4480 if (D == 0)
4481 return;
4482
4483 // Check whether it is a declaration with a nested name specifier like
4484 // int foo::bar;
4485 if (!D->isOutOfLine())
4486 return;
Mike Stump11289f42009-09-09 15:08:12 +00004487
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004488 // C++ [basic.lookup.unqual]p13
4489 //
4490 // A name used in the definition of a static data member of class X
4491 // (after the qualified-id of the static member) is looked up as if the name
4492 // was used in a member function of X.
Mike Stump11289f42009-09-09 15:08:12 +00004493
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004494 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004495 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004496}
4497
4498/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4499/// initializer for the declaration 'Dcl'.
4500void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004501 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004502
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004503 Decl *D = Dcl.getAs<Decl>();
4504 // If there is no declaration, there was an error parsing it.
4505 if (D == 0)
4506 return;
4507
4508 // Check whether it is a declaration with a nested name specifier like
4509 // int foo::bar;
4510 if (!D->isOutOfLine())
4511 return;
4512
4513 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004514 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004515}