blob: 075c945456049cc8a9f532dc1d0df1382c44428f [file] [log] [blame]
Chris Lattnerac7b83a2008-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 Gregora65e8dd2008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregorec93f442008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Anders Carlsson412c3402009-03-24 01:19:16 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregor05904022008-10-22 21:13:31 +000019#include "clang/AST/TypeOrdering.h"
Chris Lattner97316c02008-04-10 02:22:51 +000020#include "clang/AST/StmtVisitor.h"
Anders Carlssona21e7872009-08-26 23:45:07 +000021#include "clang/Basic/PartialDiagnostic.h"
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +000022#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000023#include "clang/Parse/DeclSpec.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Chris Lattner97316c02008-04-10 02:22:51 +000025#include "llvm/Support/Compiler.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000026#include <algorithm> // for std::equal
Douglas Gregorabed2172008-10-22 17:49:05 +000027#include <map>
Chris Lattnerac7b83a2008-04-08 05:04:30 +000028
29using namespace clang;
30
Chris Lattner97316c02008-04-10 02:22:51 +000031//===----------------------------------------------------------------------===//
32// CheckDefaultArgumentVisitor
33//===----------------------------------------------------------------------===//
34
Chris Lattnerb1856db2008-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.
41 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000042 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb1856db2008-04-12 23:52:44 +000043 Expr *DefaultArg;
44 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000045
Chris Lattnerb1856db2008-04-12 23:52:44 +000046 public:
47 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
48 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000049
Chris Lattnerb1856db2008-04-12 23:52:44 +000050 bool VisitExpr(Expr *Node);
51 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregora5b022a2008-11-04 14:32:21 +000052 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb1856db2008-04-12 23:52:44 +000053 };
Chris Lattner97316c02008-04-10 02:22:51 +000054
Chris Lattnerb1856db2008-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;
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000058 for (Stmt::child_iterator I = Node->child_begin(),
59 E = Node->child_end(); I != E; ++I)
60 IsInvalid |= Visit(*I);
Chris Lattnerb1856db2008-04-12 23:52:44 +000061 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000062 }
63
Chris Lattnerb1856db2008-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 Gregord2baafd2008-10-21 16:13:35 +000068 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb1856db2008-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.
78 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000079 diag::err_param_default_argument_references_param)
Chris Lattnerb1753422008-11-23 21:45:46 +000080 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff72a6ebc2008-04-15 22:42:06 +000081 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000082 // C++ [dcl.fct.default]p7
83 // Local variables shall not be used in default argument
84 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000085 if (VDecl->isBlockVarDecl())
86 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_local)
Chris Lattnerb1753422008-11-23 21:45:46 +000088 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +000089 }
Chris Lattner97316c02008-04-10 02:22:51 +000090
Douglas Gregor3c246952008-11-04 13:41:56 +000091 return false;
92 }
Chris Lattnerb1856db2008-04-12 23:52:44 +000093
Douglas Gregora5b022a2008-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 Lattner8ba580c2008-11-19 05:08:23 +0000100 diag::err_param_default_argument_references_this)
101 << ThisE->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +0000102 }
Chris Lattner97316c02008-04-10 02:22:51 +0000103}
104
Anders Carlsson60eb3be2009-08-25 02:29:20 +0000105bool
106Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
107 SourceLocation EqualLoc)
108{
109 QualType ParamType = Param->getType();
110
Anders Carlssonec926872009-08-25 13:46:13 +0000111 if (RequireCompleteType(Param->getLocation(), Param->getType(),
112 diag::err_typecheck_decl_incomplete_type)) {
113 Param->setInvalidDecl();
114 return true;
115 }
116
Anders Carlsson60eb3be2009-08-25 02:29:20 +0000117 Expr *Arg = (Expr *)DefaultArg.get();
118
119 // C++ [dcl.fct.default]p5
120 // A default argument expression is implicitly converted (clause
121 // 4) to the parameter type. The default argument expression has
122 // the same semantic constraints as the initializer expression in
123 // a declaration of a variable of the parameter type, using the
124 // copy-initialization semantics (8.5).
125 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
126 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson92936c42009-08-25 03:18:48 +0000127 return true;
Anders Carlsson60eb3be2009-08-25 02:29:20 +0000128
129 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
130
131 // Okay: add the default argument to the parameter
132 Param->setDefaultArg(Arg);
133
134 DefaultArg.release();
135
Anders Carlsson92936c42009-08-25 03:18:48 +0000136 return false;
Anders Carlsson60eb3be2009-08-25 02:29:20 +0000137}
138
Chris Lattner97316c02008-04-10 02:22:51 +0000139/// ActOnParamDefaultArgument - Check whether the default argument
140/// provided for a function parameter is well-formed. If so, attach it
141/// to the parameter declaration.
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000142void
Chris Lattner5261d0c2009-03-28 19:18:32 +0000143Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000144 ExprArg defarg) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000145 if (!param || !defarg.get())
146 return;
147
Chris Lattner5261d0c2009-03-28 19:18:32 +0000148 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlssona116e6e2009-06-12 16:51:40 +0000149 UnparsedDefaultArgLocs.erase(Param);
150
Anders Carlssonc154a722009-05-01 19:30:39 +0000151 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000152 QualType ParamType = Param->getType();
153
154 // Default arguments are only permitted in C++
155 if (!getLangOptions().CPlusPlus) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000156 Diag(EqualLoc, diag::err_param_default_argument)
157 << DefaultArg->getSourceRange();
Douglas Gregor605de8d2008-12-16 21:30:33 +0000158 Param->setInvalidDecl();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000159 return;
160 }
161
Anders Carlssone0498192009-08-25 01:02:06 +0000162 // Check that the default argument is well-formed
163 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
164 if (DefaultArgChecker.Visit(DefaultArg.get())) {
165 Param->setInvalidDecl();
166 return;
167 }
168
Anders Carlsson60eb3be2009-08-25 02:29:20 +0000169 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000170}
171
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000172/// ActOnParamUnparsedDefaultArgument - We've seen a default
173/// argument for a function parameter, but we can't parse it yet
174/// because we're inside a class definition. Note that this default
175/// argument will be parsed later.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000176void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlssona116e6e2009-06-12 16:51:40 +0000177 SourceLocation EqualLoc,
178 SourceLocation ArgLoc) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000179 if (!param)
180 return;
181
Chris Lattner5261d0c2009-03-28 19:18:32 +0000182 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000183 if (Param)
184 Param->setUnparsedDefaultArg();
Anders Carlssona116e6e2009-06-12 16:51:40 +0000185
186 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000187}
188
Douglas Gregor605de8d2008-12-16 21:30:33 +0000189/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
190/// the default argument for the parameter param failed.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000191void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000192 if (!param)
193 return;
194
Anders Carlssona116e6e2009-06-12 16:51:40 +0000195 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
196
197 Param->setInvalidDecl();
198
199 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor605de8d2008-12-16 21:30:33 +0000200}
201
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000202/// CheckExtraCXXDefaultArguments - Check for any extra default
203/// arguments in the declarator, which is not a function declaration
204/// or definition and therefore is not permitted to have default
205/// arguments. This routine should be invoked for every declarator
206/// that is not a function declaration or definition.
207void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
208 // C++ [dcl.fct.default]p3
209 // A default argument expression shall be specified only in the
210 // parameter-declaration-clause of a function declaration or in a
211 // template-parameter (14.1). It shall not be specified for a
212 // parameter pack. If it is specified in a
213 // parameter-declaration-clause, it shall not occur within a
214 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000215 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000216 DeclaratorChunk &chunk = D.getTypeObject(i);
217 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000218 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
219 ParmVarDecl *Param =
220 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000221 if (Param->hasUnparsedDefaultArg()) {
222 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor605de8d2008-12-16 21:30:33 +0000223 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
224 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
225 delete Toks;
226 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000227 } else if (Param->getDefaultArg()) {
228 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
229 << Param->getDefaultArg()->getSourceRange();
230 Param->setDefaultArg(0);
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000231 }
232 }
233 }
234 }
235}
236
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000237// MergeCXXFunctionDecl - Merge two declarations of the same C++
238// function, once we already know that they have the same
Douglas Gregor083c23e2009-02-16 17:45:42 +0000239// type. Subroutine of MergeFunctionDecl. Returns true if there was an
240// error, false otherwise.
241bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
242 bool Invalid = false;
243
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000244 // C++ [dcl.fct.default]p4:
245 //
246 // For non-template functions, default arguments can be added in
247 // later declarations of a function in the same
248 // scope. Declarations in different scopes have completely
249 // distinct sets of default arguments. That is, declarations in
250 // inner scopes do not acquire default arguments from
251 // declarations in outer scopes, and vice versa. In a given
252 // function declaration, all parameters subsequent to a
253 // parameter with a default argument shall have default
254 // arguments supplied in this or previous declarations. A
255 // default argument shall not be redefined by a later
256 // declaration (not even to the same value).
257 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
258 ParmVarDecl *OldParam = Old->getParamDecl(p);
259 ParmVarDecl *NewParam = New->getParamDecl(p);
260
261 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
262 Diag(NewParam->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000263 diag::err_param_default_argument_redefinition)
264 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner1336cab2008-11-23 23:12:31 +0000265 Diag(OldParam->getLocation(), diag::note_previous_definition);
Douglas Gregor083c23e2009-02-16 17:45:42 +0000266 Invalid = true;
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000267 } else if (OldParam->getDefaultArg()) {
268 // Merge the old default argument into the new parameter
269 NewParam->setDefaultArg(OldParam->getDefaultArg());
270 }
271 }
272
Sebastian Redl5e1e0a02009-07-04 11:39:00 +0000273 if (CheckEquivalentExceptionSpec(
274 Old->getType()->getAsFunctionProtoType(), Old->getLocation(),
275 New->getType()->getAsFunctionProtoType(), New->getLocation())) {
276 Invalid = true;
277 }
278
Douglas Gregor083c23e2009-02-16 17:45:42 +0000279 return Invalid;
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000280}
281
282/// CheckCXXDefaultArguments - Verify that the default arguments for a
283/// function declaration are well-formed according to C++
284/// [dcl.fct.default].
285void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
286 unsigned NumParams = FD->getNumParams();
287 unsigned p;
288
289 // Find first parameter with a default argument
290 for (p = 0; p < NumParams; ++p) {
291 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson73af5192009-08-25 01:23:32 +0000292 if (Param->hasDefaultArg())
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000293 break;
294 }
295
296 // C++ [dcl.fct.default]p4:
297 // In a given function declaration, all parameters
298 // subsequent to a parameter with a default argument shall
299 // have default arguments supplied in this or previous
300 // declarations. A default argument shall not be redefined
301 // by a later declaration (not even to the same value).
302 unsigned LastMissingDefaultArg = 0;
303 for(; p < NumParams; ++p) {
304 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson73af5192009-08-25 01:23:32 +0000305 if (!Param->hasDefaultArg()) {
Douglas Gregor605de8d2008-12-16 21:30:33 +0000306 if (Param->isInvalidDecl())
307 /* We already complained about this parameter. */;
308 else if (Param->getIdentifier())
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000309 Diag(Param->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000310 diag::err_param_default_argument_missing_name)
Chris Lattnere46b8792008-11-19 07:32:16 +0000311 << Param->getIdentifier();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000312 else
313 Diag(Param->getLocation(),
314 diag::err_param_default_argument_missing);
315
316 LastMissingDefaultArg = p;
317 }
318 }
319
320 if (LastMissingDefaultArg > 0) {
321 // Some default arguments were missing. Clear out all of the
322 // default arguments up to (and including) the last missing
323 // default argument, so that we leave the function parameters
324 // in a semantically valid state.
325 for (p = 0; p <= LastMissingDefaultArg; ++p) {
326 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlssona116e6e2009-06-12 16:51:40 +0000327 if (Param->hasDefaultArg()) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000328 if (!Param->hasUnparsedDefaultArg())
329 Param->getDefaultArg()->Destroy(Context);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000330 Param->setDefaultArg(0);
331 }
332 }
333 }
334}
Douglas Gregorec93f442008-04-13 21:30:24 +0000335
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000336/// isCurrentClassName - Determine whether the identifier II is the
337/// name of the class type currently being defined. In the case of
338/// nested classes, this will only return true if II is the name of
339/// the innermost class.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000340bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
341 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000342 CXXRecordDecl *CurDecl;
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000343 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregor0c3c9d02009-08-21 22:16:40 +0000344 DeclContext *DC = computeDeclContext(*SS, true);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000345 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
346 } else
347 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
348
349 if (CurDecl)
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000350 return &II == CurDecl->getIdentifier();
351 else
352 return false;
353}
354
Douglas Gregored3a3982009-03-03 04:44:36 +0000355/// \brief Check the validity of a C++ base class specifier.
356///
357/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
358/// and returns NULL otherwise.
359CXXBaseSpecifier *
360Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
361 SourceRange SpecifierRange,
362 bool Virtual, AccessSpecifier Access,
363 QualType BaseType,
364 SourceLocation BaseLoc) {
365 // C++ [class.union]p1:
366 // A union shall not have base classes.
367 if (Class->isUnion()) {
368 Diag(Class->getLocation(), diag::err_base_clause_on_union)
369 << SpecifierRange;
370 return 0;
371 }
372
373 if (BaseType->isDependentType())
Fariborz Jahanian1373b6f2009-07-22 17:41:53 +0000374 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregored3a3982009-03-03 04:44:36 +0000375 Class->getTagKind() == RecordDecl::TK_class,
376 Access, BaseType);
377
378 // Base specifiers must be record types.
379 if (!BaseType->isRecordType()) {
380 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
381 return 0;
382 }
383
384 // C++ [class.union]p1:
385 // A union shall not be used as a base class.
386 if (BaseType->isUnionType()) {
387 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
388 return 0;
389 }
390
391 // C++ [class.derived]p2:
392 // The class-name in a base-specifier shall not be an incompletely
393 // defined class.
Anders Carlssona21e7872009-08-26 23:45:07 +0000394 if (RequireCompleteType(BaseLoc, BaseType,
395 PDiag(diag::err_incomplete_base_class)
396 << SpecifierRange))
Douglas Gregored3a3982009-03-03 04:44:36 +0000397 return 0;
398
Eli Friedman10747ff2009-08-15 21:55:26 +0000399 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000400 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregored3a3982009-03-03 04:44:36 +0000401 assert(BaseDecl && "Record type has no declaration");
402 BaseDecl = BaseDecl->getDefinition(Context);
403 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman10747ff2009-08-15 21:55:26 +0000404 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
405 assert(CXXBaseDecl && "Base type is not a C++ type");
406 if (!CXXBaseDecl->isEmpty())
407 Class->setEmpty(false);
408 if (CXXBaseDecl->isPolymorphic())
Douglas Gregored3a3982009-03-03 04:44:36 +0000409 Class->setPolymorphic(true);
410
411 // C++ [dcl.init.aggr]p1:
412 // An aggregate is [...] a class with [...] no base classes [...].
413 Class->setAggregate(false);
414 Class->setPOD(false);
415
Anders Carlssonc6363712009-04-16 00:08:20 +0000416 if (Virtual) {
417 // C++ [class.ctor]p5:
418 // A constructor is trivial if its class has no virtual base classes.
419 Class->setHasTrivialConstructor(false);
Douglas Gregorf73c8512009-07-22 18:25:24 +0000420
421 // C++ [class.copy]p6:
422 // A copy constructor is trivial if its class has no virtual base classes.
423 Class->setHasTrivialCopyConstructor(false);
424
425 // C++ [class.copy]p11:
426 // A copy assignment operator is trivial if its class has no virtual
427 // base classes.
428 Class->setHasTrivialCopyAssignment(false);
Eli Friedman10747ff2009-08-15 21:55:26 +0000429
430 // C++0x [meta.unary.prop] is_empty:
431 // T is a class type, but not a union type, with ... no virtual base
432 // classes
433 Class->setEmpty(false);
Anders Carlssonc6363712009-04-16 00:08:20 +0000434 } else {
435 // C++ [class.ctor]p5:
436 // A constructor is trivial if all the direct base classes of its
437 // class have trivial constructors.
Douglas Gregorf73c8512009-07-22 18:25:24 +0000438 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
439 Class->setHasTrivialConstructor(false);
440
441 // C++ [class.copy]p6:
442 // A copy constructor is trivial if all the direct base classes of its
443 // class have trivial copy constructors.
444 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
445 Class->setHasTrivialCopyConstructor(false);
446
447 // C++ [class.copy]p11:
448 // A copy assignment operator is trivial if all the direct base classes
449 // of its class have trivial copy assignment operators.
450 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
451 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonc6363712009-04-16 00:08:20 +0000452 }
Anders Carlsson39a10db2009-04-17 02:34:54 +0000453
454 // C++ [class.ctor]p3:
455 // A destructor is trivial if all the direct base classes of its class
456 // have trivial destructors.
Douglas Gregorf73c8512009-07-22 18:25:24 +0000457 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
458 Class->setHasTrivialDestructor(false);
Anders Carlssonc6363712009-04-16 00:08:20 +0000459
Douglas Gregored3a3982009-03-03 04:44:36 +0000460 // Create the base specifier.
461 // FIXME: Allocate via ASTContext?
Fariborz Jahanian1373b6f2009-07-22 17:41:53 +0000462 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregored3a3982009-03-03 04:44:36 +0000463 Class->getTagKind() == RecordDecl::TK_class,
464 Access, BaseType);
465}
466
Douglas Gregorec93f442008-04-13 21:30:24 +0000467/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
468/// one entry in the base class list of a class specifier, for
469/// example:
470/// class foo : public bar, virtual private baz {
471/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorabed2172008-10-22 17:49:05 +0000472Sema::BaseResult
Chris Lattner5261d0c2009-03-28 19:18:32 +0000473Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorabed2172008-10-22 17:49:05 +0000474 bool Virtual, AccessSpecifier Access,
475 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000476 if (!classdecl)
477 return true;
478
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000479 AdjustDeclIfTemplate(classdecl);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000480 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000481 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregored3a3982009-03-03 04:44:36 +0000482 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
483 Virtual, Access,
484 BaseType, BaseLoc))
485 return BaseSpec;
486
487 return true;
Douglas Gregorabed2172008-10-22 17:49:05 +0000488}
Douglas Gregorec93f442008-04-13 21:30:24 +0000489
Douglas Gregored3a3982009-03-03 04:44:36 +0000490/// \brief Performs the actual work of attaching the given base class
491/// specifiers to a C++ class.
492bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
493 unsigned NumBases) {
494 if (NumBases == 0)
495 return false;
Douglas Gregorabed2172008-10-22 17:49:05 +0000496
497 // Used to keep track of which base types we have already seen, so
498 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000499 // that the key is always the unqualified canonical type of the base
500 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000501 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
502
503 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000504 unsigned NumGoodBases = 0;
Douglas Gregored3a3982009-03-03 04:44:36 +0000505 bool Invalid = false;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000506 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000507 QualType NewBaseType
Douglas Gregored3a3982009-03-03 04:44:36 +0000508 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor4fd85902008-10-23 18:13:27 +0000509 NewBaseType = NewBaseType.getUnqualifiedType();
510
Douglas Gregorabed2172008-10-22 17:49:05 +0000511 if (KnownBaseTypes[NewBaseType]) {
512 // C++ [class.mi]p3:
513 // A class shall not be specified as a direct base class of a
514 // derived class more than once.
Douglas Gregored3a3982009-03-03 04:44:36 +0000515 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000516 diag::err_duplicate_base_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000517 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregored3a3982009-03-03 04:44:36 +0000518 << Bases[idx]->getSourceRange();
Douglas Gregor4fd85902008-10-23 18:13:27 +0000519
520 // Delete the duplicate base class specifier; we're going to
521 // overwrite its pointer later.
Douglas Gregorf2fedc62009-07-22 20:55:49 +0000522 Context.Deallocate(Bases[idx]);
Douglas Gregored3a3982009-03-03 04:44:36 +0000523
524 Invalid = true;
Douglas Gregorabed2172008-10-22 17:49:05 +0000525 } else {
526 // Okay, add this new base class.
Douglas Gregored3a3982009-03-03 04:44:36 +0000527 KnownBaseTypes[NewBaseType] = Bases[idx];
528 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000529 }
530 }
531
532 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian9cd0a3c2009-07-02 18:26:15 +0000533 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor4fd85902008-10-23 18:13:27 +0000534
535 // Delete the remaining (good) base class specifiers, since their
536 // data has been copied into the CXXRecordDecl.
537 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorf2fedc62009-07-22 20:55:49 +0000538 Context.Deallocate(Bases[idx]);
Douglas Gregored3a3982009-03-03 04:44:36 +0000539
540 return Invalid;
541}
542
543/// ActOnBaseSpecifiers - Attach the given base specifiers to the
544/// class, after checking whether there are any duplicate base
545/// classes.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000546void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregored3a3982009-03-03 04:44:36 +0000547 unsigned NumBases) {
548 if (!ClassDecl || !Bases || !NumBases)
549 return;
550
551 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000552 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregored3a3982009-03-03 04:44:36 +0000553 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregorec93f442008-04-13 21:30:24 +0000554}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000555
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000556//===----------------------------------------------------------------------===//
557// C++ class member Handling
558//===----------------------------------------------------------------------===//
559
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000560/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
561/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
562/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerd6c78092009-04-12 22:37:57 +0000563/// any.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000564Sema::DeclPtrTy
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000565Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor398a8012009-08-20 22:52:58 +0000566 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redla55834a2009-04-12 17:16:29 +0000567 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000568 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor6704b312008-11-17 22:58:34 +0000569 DeclarationName Name = GetNameForDeclarator(D);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000570 Expr *BitWidth = static_cast<Expr*>(BW);
571 Expr *Init = static_cast<Expr*>(InitExpr);
572 SourceLocation Loc = D.getIdentifierLoc();
573
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000574 bool isFunc = D.isFunctionDeclarator();
575
John McCall140607b2009-08-06 02:15:43 +0000576 assert(!DS.isFriendSpecified());
577
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000578 // C++ 9.2p6: A member shall not be declared to have automatic storage
579 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000580 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
581 // data members and cannot be applied to names declared const or static,
582 // and cannot be applied to reference members.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000583 switch (DS.getStorageClassSpec()) {
584 case DeclSpec::SCS_unspecified:
585 case DeclSpec::SCS_typedef:
586 case DeclSpec::SCS_static:
587 // FALL THROUGH.
588 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000589 case DeclSpec::SCS_mutable:
590 if (isFunc) {
591 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000592 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000593 else
Chris Lattner8ba580c2008-11-19 05:08:23 +0000594 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
595
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000596 // FIXME: It would be nicer if the keyword was ignored only for this
597 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000598 D.getMutableDeclSpec().ClearStorageClassSpecs();
599 } else {
600 QualType T = GetTypeForDeclarator(D, S);
601 diag::kind err = static_cast<diag::kind>(0);
602 if (T->isReferenceType())
603 err = diag::err_mutable_reference;
604 else if (T.isConstQualified())
605 err = diag::err_mutable_const;
606 if (err != 0) {
607 if (DS.getStorageClassSpecLoc().isValid())
608 Diag(DS.getStorageClassSpecLoc(), err);
609 else
610 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000611 // FIXME: It would be nicer if the keyword was ignored only for this
612 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000613 D.getMutableDeclSpec().ClearStorageClassSpecs();
614 }
615 }
616 break;
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000617 default:
618 if (DS.getStorageClassSpecLoc().isValid())
619 Diag(DS.getStorageClassSpecLoc(),
620 diag::err_storageclass_invalid_for_member);
621 else
622 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
623 D.getMutableDeclSpec().ClearStorageClassSpecs();
624 }
625
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000626 if (!isFunc &&
Douglas Gregora60c62e2009-02-09 15:09:02 +0000627 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000628 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000629 // Check also for this case:
630 //
631 // typedef int f();
632 // f a;
633 //
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000634 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregora60c62e2009-02-09 15:09:02 +0000635 isFunc = TDType->isFunctionType();
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000636 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000637
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000638 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
639 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000640 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000641
642 Decl *Member;
Chris Lattner9cffefc2009-03-05 22:45:59 +0000643 if (isInstField) {
Douglas Gregor398a8012009-08-20 22:52:58 +0000644 // FIXME: Check for template parameters!
Douglas Gregor2f0ecef2009-03-11 20:50:30 +0000645 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
646 AS);
Chris Lattnere384c182009-03-05 23:03:49 +0000647 assert(Member && "HandleField never returns null");
Chris Lattner9cffefc2009-03-05 22:45:59 +0000648 } else {
Douglas Gregor398a8012009-08-20 22:52:58 +0000649 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
650 .getAs<Decl>();
Chris Lattnere384c182009-03-05 23:03:49 +0000651 if (!Member) {
652 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattnera17991f2009-03-29 16:50:03 +0000653 return DeclPtrTy();
Chris Lattnere384c182009-03-05 23:03:49 +0000654 }
Chris Lattner432780c2009-03-05 23:01:03 +0000655
656 // Non-instance-fields can't have a bitfield.
657 if (BitWidth) {
658 if (Member->isInvalidDecl()) {
659 // don't emit another diagnostic.
Douglas Gregor00660582009-03-11 20:22:50 +0000660 } else if (isa<VarDecl>(Member)) {
Chris Lattner432780c2009-03-05 23:01:03 +0000661 // C++ 9.6p3: A bit-field shall not be a static member.
662 // "static member 'A' cannot be a bit-field"
663 Diag(Loc, diag::err_static_not_bitfield)
664 << Name << BitWidth->getSourceRange();
665 } else if (isa<TypedefDecl>(Member)) {
666 // "typedef member 'x' cannot be a bit-field"
667 Diag(Loc, diag::err_typedef_not_bitfield)
668 << Name << BitWidth->getSourceRange();
669 } else {
670 // A function typedef ("typedef int f(); f a;").
671 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
672 Diag(Loc, diag::err_not_integral_type_bitfield)
Douglas Gregor0e518af2009-03-11 18:59:21 +0000673 << Name << cast<ValueDecl>(Member)->getType()
674 << BitWidth->getSourceRange();
Chris Lattner432780c2009-03-05 23:01:03 +0000675 }
676
677 DeleteExpr(BitWidth);
678 BitWidth = 0;
679 Member->setInvalidDecl();
680 }
Douglas Gregor2f0ecef2009-03-11 20:50:30 +0000681
682 Member->setAccess(AS);
Douglas Gregor398a8012009-08-20 22:52:58 +0000683
684 // If we have declared a member function template, set the access of the
685 // templated declaration as well.
686 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
687 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner9cffefc2009-03-05 22:45:59 +0000688 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000689
Douglas Gregor6704b312008-11-17 22:58:34 +0000690 assert((Name || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000691
Douglas Gregor8f53bb72009-03-11 23:00:04 +0000692 if (Init)
Chris Lattner5261d0c2009-03-28 19:18:32 +0000693 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redla55834a2009-04-12 17:16:29 +0000694 if (Deleted) // FIXME: Source location is not very good.
695 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000696
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000697 if (isInstField) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000698 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattnera17991f2009-03-29 16:50:03 +0000699 return DeclPtrTy();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000700 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000701 return DeclPtrTy::make(Member);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000702}
703
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000704/// ActOnMemInitializer - Handle a C++ member initializer.
705Sema::MemInitResult
Chris Lattner5261d0c2009-03-28 19:18:32 +0000706Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000707 Scope *S,
Fariborz Jahanianc37d3062009-06-30 23:26:25 +0000708 const CXXScopeSpec &SS,
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000709 IdentifierInfo *MemberOrBase,
Fariborz Jahanian2b2b7362009-07-01 19:21:19 +0000710 TypeTy *TemplateTypeTy,
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000711 SourceLocation IdLoc,
712 SourceLocation LParenLoc,
713 ExprTy **Args, unsigned NumArgs,
714 SourceLocation *CommaLocs,
715 SourceLocation RParenLoc) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000716 if (!ConstructorD)
717 return true;
718
Douglas Gregor84164f02009-08-24 11:57:43 +0000719 AdjustDeclIfTemplate(ConstructorD);
720
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000721 CXXConstructorDecl *Constructor
Chris Lattner5261d0c2009-03-28 19:18:32 +0000722 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000723 if (!Constructor) {
724 // The user wrote a constructor initializer on a function that is
725 // not a C++ constructor. Ignore the error for now, because we may
726 // have more member initializers coming; we'll diagnose it just
727 // once in ActOnMemInitializers.
728 return true;
729 }
730
731 CXXRecordDecl *ClassDecl = Constructor->getParent();
732
733 // C++ [class.base.init]p2:
734 // Names in a mem-initializer-id are looked up in the scope of the
735 // constructor’s class and, if not found in that scope, are looked
736 // up in the scope containing the constructor’s
737 // definition. [Note: if the constructor’s class contains a member
738 // with the same name as a direct or virtual base class of the
739 // class, a mem-initializer-id naming the member or base class and
740 // composed of a single identifier refers to the class member. A
741 // mem-initializer-id for the hidden base class may be specified
742 // using a qualified name. ]
Fariborz Jahanian2b2b7362009-07-01 19:21:19 +0000743 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianc37d3062009-06-30 23:26:25 +0000744 // Look for a member, first.
745 FieldDecl *Member = 0;
746 DeclContext::lookup_result Result
747 = ClassDecl->lookup(MemberOrBase);
748 if (Result.first != Result.second)
749 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000750
Fariborz Jahanianc37d3062009-06-30 23:26:25 +0000751 // FIXME: Handle members of an anonymous union.
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000752
Eli Friedman724478c2009-07-29 19:44:27 +0000753 if (Member)
754 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
755 RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000756 }
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000757 // It didn't name a member, so see if it names a class.
Fariborz Jahanian2b2b7362009-07-01 19:21:19 +0000758 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
759 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000760 if (!BaseTy)
Chris Lattner65cae292008-11-19 08:23:25 +0000761 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
762 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000763
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000764 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000765
Eli Friedman724478c2009-07-29 19:44:27 +0000766 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
767 RParenLoc, ClassDecl);
768}
769
770Sema::MemInitResult
771Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
772 unsigned NumArgs, SourceLocation IdLoc,
773 SourceLocation RParenLoc) {
774 bool HasDependentArg = false;
775 for (unsigned i = 0; i < NumArgs; i++)
776 HasDependentArg |= Args[i]->isTypeDependent();
777
778 CXXConstructorDecl *C = 0;
779 QualType FieldType = Member->getType();
780 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
781 FieldType = Array->getElementType();
782 if (FieldType->isDependentType()) {
783 // Can't check init for dependent type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000784 } else if (FieldType->getAs<RecordType>()) {
Eli Friedman724478c2009-07-29 19:44:27 +0000785 if (!HasDependentArg)
786 C = PerformInitializationByConstructor(
787 FieldType, (Expr **)Args, NumArgs, IdLoc,
788 SourceRange(IdLoc, RParenLoc), Member->getDeclName(), IK_Direct);
Fariborz Jahanian7c9f7832009-09-02 17:10:17 +0000789 } else if (NumArgs != 1 && NumArgs != 0) {
Eli Friedman724478c2009-07-29 19:44:27 +0000790 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
791 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
792 } else if (!HasDependentArg) {
Fariborz Jahanian7c9f7832009-09-02 17:10:17 +0000793 Expr *NewExp;
794 if (NumArgs == 0) {
Fariborz Jahanianf988e222009-09-03 19:36:46 +0000795 if (FieldType->isReferenceType()) {
796 Diag(IdLoc, diag::err_null_intialized_reference_member)
797 << Member->getDeclName();
798 return Diag(Member->getLocation(), diag::note_declared_at);
799 }
Fariborz Jahanian7c9f7832009-09-02 17:10:17 +0000800 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
801 NumArgs = 1;
802 }
803 else
804 NewExp = (Expr*)Args[0];
Eli Friedman724478c2009-07-29 19:44:27 +0000805 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
806 return true;
807 Args[0] = NewExp;
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000808 }
Eli Friedman724478c2009-07-29 19:44:27 +0000809 // FIXME: Perform direct initialization of the member.
810 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson6d68ad42009-08-29 01:31:33 +0000811 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman724478c2009-07-29 19:44:27 +0000812}
813
814Sema::MemInitResult
815Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
816 unsigned NumArgs, SourceLocation IdLoc,
817 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
818 bool HasDependentArg = false;
819 for (unsigned i = 0; i < NumArgs; i++)
820 HasDependentArg |= Args[i]->isTypeDependent();
821
822 if (!BaseType->isDependentType()) {
823 if (!BaseType->isRecordType())
824 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
825 << BaseType << SourceRange(IdLoc, RParenLoc);
826
827 // C++ [class.base.init]p2:
828 // [...] Unless the mem-initializer-id names a nonstatic data
829 // member of the constructor’s class or a direct or virtual base
830 // of that class, the mem-initializer is ill-formed. A
831 // mem-initializer-list can initialize a base class using any
832 // name that denotes that base class type.
833
834 // First, check for a direct base class.
835 const CXXBaseSpecifier *DirectBaseSpec = 0;
836 for (CXXRecordDecl::base_class_const_iterator Base =
837 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
838 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
839 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
840 // We found a direct base of this type. That's what we're
841 // initializing.
842 DirectBaseSpec = &*Base;
843 break;
844 }
845 }
846
847 // Check for a virtual base class.
848 // FIXME: We might be able to short-circuit this if we know in advance that
849 // there are no virtual bases.
850 const CXXBaseSpecifier *VirtualBaseSpec = 0;
851 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
852 // We haven't found a base yet; search the class hierarchy for a
853 // virtual base class.
854 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
855 /*DetectVirtual=*/false);
856 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
857 for (BasePaths::paths_iterator Path = Paths.begin();
858 Path != Paths.end(); ++Path) {
859 if (Path->back().Base->isVirtual()) {
860 VirtualBaseSpec = Path->back().Base;
861 break;
862 }
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000863 }
864 }
865 }
Eli Friedman724478c2009-07-29 19:44:27 +0000866
867 // C++ [base.class.init]p2:
868 // If a mem-initializer-id is ambiguous because it designates both
869 // a direct non-virtual base class and an inherited virtual base
870 // class, the mem-initializer is ill-formed.
871 if (DirectBaseSpec && VirtualBaseSpec)
872 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
873 << BaseType << SourceRange(IdLoc, RParenLoc);
874 // C++ [base.class.init]p2:
875 // Unless the mem-initializer-id names a nonstatic data membeer of the
876 // constructor's class ot a direst or virtual base of that class, the
877 // mem-initializer is ill-formed.
878 if (!DirectBaseSpec && !VirtualBaseSpec)
879 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
880 << BaseType << ClassDecl->getNameAsCString()
881 << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000882 }
883
Fariborz Jahanian898f5742009-07-23 00:42:24 +0000884 CXXConstructorDecl *C = 0;
Eli Friedman724478c2009-07-29 19:44:27 +0000885 if (!BaseType->isDependentType() && !HasDependentArg) {
886 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
887 Context.getCanonicalType(BaseType));
888 C = PerformInitializationByConstructor(BaseType, (Expr **)Args, NumArgs,
889 IdLoc, SourceRange(IdLoc, RParenLoc),
890 Name, IK_Direct);
891 }
892
893 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson6d68ad42009-08-29 01:31:33 +0000894 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000895}
896
Fariborz Jahanian7c1771c2009-07-23 23:32:59 +0000897void
Fariborz Jahanianf988e222009-09-03 19:36:46 +0000898Sema::setBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
899 CXXBaseOrMemberInitializer **Initializers,
900 unsigned NumInitializers,
901 llvm::SmallVectorImpl<CXXBaseSpecifier *>& Bases,
902 llvm::SmallVectorImpl<FieldDecl *>&Fields) {
903 // We need to build the initializer AST according to order of construction
904 // and not what user specified in the Initializers list.
905 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
906 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
907 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
908 bool HasDependentBaseInit = false;
909
910 for (unsigned i = 0; i < NumInitializers; i++) {
911 CXXBaseOrMemberInitializer *Member = Initializers[i];
912 if (Member->isBaseInitializer()) {
913 if (Member->getBaseClass()->isDependentType())
914 HasDependentBaseInit = true;
915 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
916 } else {
917 AllBaseFields[Member->getMember()] = Member;
918 }
919 }
920
921 if (HasDependentBaseInit) {
922 // FIXME. This does not preserve the ordering of the initializers.
923 // Try (with -Wreorder)
924 // template<class X> struct A {};
925 // template<class X> struct B : A<X> {
926 // B() : x1(10), A<X>() {}
927 // int x1;
928 // };
929 // B<int> x;
930 // On seeing one dependent type, we should essentially exit this routine
931 // while preserving user-declared initializer list. When this routine is
932 // called during instantiatiation process, this routine will rebuild the
933 // oderdered initializer list correctly.
934
935 // If we have a dependent base initialization, we can't determine the
936 // association between initializers and bases; just dump the known
937 // initializers into the list, and don't try to deal with other bases.
938 for (unsigned i = 0; i < NumInitializers; i++) {
939 CXXBaseOrMemberInitializer *Member = Initializers[i];
940 if (Member->isBaseInitializer())
941 AllToInit.push_back(Member);
942 }
943 } else {
944 // Push virtual bases before others.
945 for (CXXRecordDecl::base_class_iterator VBase =
946 ClassDecl->vbases_begin(),
947 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
948 if (VBase->getType()->isDependentType())
949 continue;
950 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian5da2f992009-09-03 21:32:41 +0000951 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
952 CXXRecordDecl *BaseDecl =
953 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
954 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
955 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
956 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanianf988e222009-09-03 19:36:46 +0000957 AllToInit.push_back(Value);
Fariborz Jahanian5da2f992009-09-03 21:32:41 +0000958 }
Fariborz Jahanianf988e222009-09-03 19:36:46 +0000959 else {
960 CXXRecordDecl *VBaseDecl =
961 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
962 assert(VBaseDecl && "setBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian5da2f992009-09-03 21:32:41 +0000963 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
964 if (!Ctor)
Fariborz Jahanianf988e222009-09-03 19:36:46 +0000965 Bases.push_back(VBase);
Fariborz Jahanian5da2f992009-09-03 21:32:41 +0000966 else
967 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
968
Fariborz Jahanianf988e222009-09-03 19:36:46 +0000969 CXXBaseOrMemberInitializer *Member =
970 new (Context) CXXBaseOrMemberInitializer(VBase->getType(), 0, 0,
Fariborz Jahanian5da2f992009-09-03 21:32:41 +0000971 Ctor,
Fariborz Jahanianf988e222009-09-03 19:36:46 +0000972 SourceLocation(),
973 SourceLocation());
974 AllToInit.push_back(Member);
975 }
976 }
977
978 for (CXXRecordDecl::base_class_iterator Base =
979 ClassDecl->bases_begin(),
980 E = ClassDecl->bases_end(); Base != E; ++Base) {
981 // Virtuals are in the virtual base list and already constructed.
982 if (Base->isVirtual())
983 continue;
984 // Skip dependent types.
985 if (Base->getType()->isDependentType())
986 continue;
987 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian5da2f992009-09-03 21:32:41 +0000988 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
989 CXXRecordDecl *BaseDecl =
990 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
991 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
992 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
993 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanianf988e222009-09-03 19:36:46 +0000994 AllToInit.push_back(Value);
Fariborz Jahanian5da2f992009-09-03 21:32:41 +0000995 }
Fariborz Jahanianf988e222009-09-03 19:36:46 +0000996 else {
997 CXXRecordDecl *BaseDecl =
Fariborz Jahanian5da2f992009-09-03 21:32:41 +0000998 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianf988e222009-09-03 19:36:46 +0000999 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian5da2f992009-09-03 21:32:41 +00001000 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
1001 if (!Ctor)
Fariborz Jahanianf988e222009-09-03 19:36:46 +00001002 Bases.push_back(Base);
Fariborz Jahanian5da2f992009-09-03 21:32:41 +00001003 else
1004 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1005
Fariborz Jahanianf988e222009-09-03 19:36:46 +00001006 CXXBaseOrMemberInitializer *Member =
1007 new (Context) CXXBaseOrMemberInitializer(Base->getType(), 0, 0,
1008 BaseDecl->getDefaultConstructor(Context),
1009 SourceLocation(),
1010 SourceLocation());
1011 AllToInit.push_back(Member);
1012 }
1013 }
1014 }
1015
1016 // non-static data members.
1017 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1018 E = ClassDecl->field_end(); Field != E; ++Field) {
1019 if ((*Field)->isAnonymousStructOrUnion()) {
1020 if (const RecordType *FieldClassType =
1021 Field->getType()->getAs<RecordType>()) {
1022 CXXRecordDecl *FieldClassDecl
1023 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1024 for(RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1025 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1026 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1027 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1028 // set to the anonymous union data member used in the initializer
1029 // list.
1030 Value->setMember(*Field);
1031 Value->setAnonUnionMember(*FA);
1032 AllToInit.push_back(Value);
1033 break;
1034 }
1035 }
1036 }
1037 continue;
1038 }
1039 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
Fariborz Jahanian5da2f992009-09-03 21:32:41 +00001040 QualType FT = (*Field)->getType();
1041 if (const RecordType* RT = FT->getAs<RecordType>()) {
1042 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl());
1043 assert(FieldRecDecl && "setBaseOrMemberInitializers - BaseDecl null");
1044 if (CXXConstructorDecl *Ctor =
1045 FieldRecDecl->getDefaultConstructor(Context))
1046 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
1047 }
Fariborz Jahanianf988e222009-09-03 19:36:46 +00001048 AllToInit.push_back(Value);
1049 continue;
1050 }
1051
1052 QualType FT = Context.getBaseElementType((*Field)->getType());
1053 if (const RecordType* RT = FT->getAs<RecordType>()) {
1054 CXXConstructorDecl *Ctor =
1055 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
1056 if (!Ctor && !FT->isDependentType())
1057 Fields.push_back(*Field);
1058 CXXBaseOrMemberInitializer *Member =
1059 new (Context) CXXBaseOrMemberInitializer((*Field), 0, 0,
1060 Ctor,
1061 SourceLocation(),
1062 SourceLocation());
1063 AllToInit.push_back(Member);
Fariborz Jahanian5da2f992009-09-03 21:32:41 +00001064 if (Ctor)
1065 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanianf988e222009-09-03 19:36:46 +00001066 if (FT.isConstQualified() && (!Ctor || Ctor->isTrivial())) {
1067 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1068 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1069 Diag((*Field)->getLocation(), diag::note_declared_at);
1070 }
1071 }
1072 else if (FT->isReferenceType()) {
1073 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1074 << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getDeclName();
1075 Diag((*Field)->getLocation(), diag::note_declared_at);
1076 }
1077 else if (FT.isConstQualified()) {
1078 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1079 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1080 Diag((*Field)->getLocation(), diag::note_declared_at);
1081 }
1082 }
1083
1084 NumInitializers = AllToInit.size();
1085 if (NumInitializers > 0) {
1086 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1087 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1088 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1089
1090 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1091 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1092 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1093 }
1094}
1095
1096void
Fariborz Jahanian7c1771c2009-07-23 23:32:59 +00001097Sema::BuildBaseOrMemberInitializers(ASTContext &C,
1098 CXXConstructorDecl *Constructor,
1099 CXXBaseOrMemberInitializer **Initializers,
1100 unsigned NumInitializers
1101 ) {
1102 llvm::SmallVector<CXXBaseSpecifier *, 4>Bases;
1103 llvm::SmallVector<FieldDecl *, 4>Members;
1104
Fariborz Jahanianf988e222009-09-03 19:36:46 +00001105 setBaseOrMemberInitializers(Constructor,
1106 Initializers, NumInitializers, Bases, Members);
Fariborz Jahanian7c1771c2009-07-23 23:32:59 +00001107 for (unsigned int i = 0; i < Bases.size(); i++)
1108 Diag(Bases[i]->getSourceRange().getBegin(),
1109 diag::err_missing_default_constructor) << 0 << Bases[i]->getType();
1110 for (unsigned int i = 0; i < Members.size(); i++)
1111 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor)
1112 << 1 << Members[i]->getType();
1113}
1114
Eli Friedman16a1ca72009-07-21 19:28:10 +00001115static void *GetKeyForTopLevelField(FieldDecl *Field) {
1116 // For anonymous unions, use the class declaration as the key.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001117 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman16a1ca72009-07-21 19:28:10 +00001118 if (RT->getDecl()->isAnonymousStructOrUnion())
1119 return static_cast<void *>(RT->getDecl());
1120 }
1121 return static_cast<void *>(Field);
1122}
1123
Anders Carlssonbc5aff52009-09-01 06:22:14 +00001124static void *GetKeyForBase(QualType BaseType) {
1125 if (const RecordType *RT = BaseType->getAs<RecordType>())
1126 return (void *)RT;
1127
1128 assert(0 && "Unexpected base type!");
1129 return 0;
1130}
1131
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001132static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssonbc5aff52009-09-01 06:22:14 +00001133 bool MemberMaybeAnon = false) {
Eli Friedman16a1ca72009-07-21 19:28:10 +00001134 // For fields injected into the class via declaration of an anonymous union,
1135 // use its anonymous union class declaration as the unique key.
Anders Carlssonbc5aff52009-09-01 06:22:14 +00001136 if (Member->isMemberInitializer()) {
1137 FieldDecl *Field = Member->getMember();
1138
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001139 // After BuildBaseOrMemberInitializers call, Field is the anonymous union
1140 // data member of the class. Data member used in the initializer list is
1141 // in AnonUnionMember field.
1142 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1143 Field = Member->getAnonUnionMember();
Eli Friedman16a1ca72009-07-21 19:28:10 +00001144 if (Field->getDeclContext()->isRecord()) {
1145 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1146 if (RD->isAnonymousStructOrUnion())
1147 return static_cast<void *>(RD);
1148 }
1149 return static_cast<void *>(Field);
1150 }
Anders Carlssonbc5aff52009-09-01 06:22:14 +00001151
1152 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman16a1ca72009-07-21 19:28:10 +00001153}
1154
Chris Lattner5261d0c2009-03-28 19:18:32 +00001155void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssonc7f87202009-03-25 02:58:17 +00001156 SourceLocation ColonLoc,
1157 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregorac77dd62009-06-22 23:20:33 +00001158 if (!ConstructorDecl)
1159 return;
Douglas Gregor84164f02009-08-24 11:57:43 +00001160
1161 AdjustDeclIfTemplate(ConstructorDecl);
Douglas Gregorac77dd62009-06-22 23:20:33 +00001162
1163 CXXConstructorDecl *Constructor
1164 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Anders Carlssonc7f87202009-03-25 02:58:17 +00001165
1166 if (!Constructor) {
1167 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1168 return;
1169 }
Anders Carlsson82b3fd22009-08-27 05:45:01 +00001170
Anders Carlsson897bb092009-08-27 05:57:30 +00001171 if (!Constructor->isDependentContext()) {
1172 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1173 bool err = false;
1174 for (unsigned i = 0; i < NumMemInits; i++) {
1175 CXXBaseOrMemberInitializer *Member =
1176 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1177 void *KeyToMember = GetKeyForMember(Member);
1178 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1179 if (!PrevMember) {
1180 PrevMember = Member;
1181 continue;
1182 }
1183 if (FieldDecl *Field = Member->getMember())
1184 Diag(Member->getSourceLocation(),
1185 diag::error_multiple_mem_initialization)
1186 << Field->getNameAsString();
1187 else {
1188 Type *BaseClass = Member->getBaseClass();
1189 assert(BaseClass && "ActOnMemInitializers - neither field or base");
1190 Diag(Member->getSourceLocation(),
1191 diag::error_multiple_base_initialization)
1192 << BaseClass->getDesugaredType(true);
1193 }
1194 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1195 << 0;
1196 err = true;
1197 }
1198
1199 if (err)
1200 return;
1201 }
Anders Carlsson82b3fd22009-08-27 05:45:01 +00001202
1203 BuildBaseOrMemberInitializers(Context, Constructor,
Fariborz Jahanian7c1771c2009-07-23 23:32:59 +00001204 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
1205 NumMemInits);
1206
Anders Carlsson897bb092009-08-27 05:57:30 +00001207 if (Constructor->isDependentContext())
1208 return;
Fariborz Jahanian5da2f992009-09-03 21:32:41 +00001209
Anders Carlsson82b3fd22009-08-27 05:45:01 +00001210 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
1211 Diagnostic::Ignored &&
1212 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
1213 Diagnostic::Ignored)
1214 return;
1215
1216 // Also issue warning if order of ctor-initializer list does not match order
1217 // of 1) base class declarations and 2) order of non-static data members.
1218 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
1219
1220 CXXRecordDecl *ClassDecl
1221 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1222 // Push virtual bases before others.
1223 for (CXXRecordDecl::base_class_iterator VBase =
1224 ClassDecl->vbases_begin(),
1225 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssonbc5aff52009-09-01 06:22:14 +00001226 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001227
Anders Carlsson82b3fd22009-08-27 05:45:01 +00001228 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1229 E = ClassDecl->bases_end(); Base != E; ++Base) {
1230 // Virtuals are alread in the virtual base list and are constructed
1231 // first.
1232 if (Base->isVirtual())
1233 continue;
Anders Carlssonbc5aff52009-09-01 06:22:14 +00001234 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson82b3fd22009-08-27 05:45:01 +00001235 }
1236
1237 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1238 E = ClassDecl->field_end(); Field != E; ++Field)
1239 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
1240
1241 int Last = AllBaseOrMembers.size();
1242 int curIndex = 0;
1243 CXXBaseOrMemberInitializer *PrevMember = 0;
1244 for (unsigned i = 0; i < NumMemInits; i++) {
1245 CXXBaseOrMemberInitializer *Member =
1246 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1247 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman16a1ca72009-07-21 19:28:10 +00001248
Anders Carlsson82b3fd22009-08-27 05:45:01 +00001249 for (; curIndex < Last; curIndex++)
1250 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1251 break;
1252 if (curIndex == Last) {
1253 assert(PrevMember && "Member not in member list?!");
1254 // Initializer as specified in ctor-initializer list is out of order.
1255 // Issue a warning diagnostic.
1256 if (PrevMember->isBaseInitializer()) {
1257 // Diagnostics is for an initialized base class.
1258 Type *BaseClass = PrevMember->getBaseClass();
1259 Diag(PrevMember->getSourceLocation(),
1260 diag::warn_base_initialized)
1261 << BaseClass->getDesugaredType(true);
1262 } else {
1263 FieldDecl *Field = PrevMember->getMember();
1264 Diag(PrevMember->getSourceLocation(),
1265 diag::warn_field_initialized)
1266 << Field->getNameAsString();
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001267 }
Anders Carlsson82b3fd22009-08-27 05:45:01 +00001268 // Also the note!
1269 if (FieldDecl *Field = Member->getMember())
1270 Diag(Member->getSourceLocation(),
1271 diag::note_fieldorbase_initialized_here) << 0
1272 << Field->getNameAsString();
1273 else {
1274 Type *BaseClass = Member->getBaseClass();
1275 Diag(Member->getSourceLocation(),
1276 diag::note_fieldorbase_initialized_here) << 1
1277 << BaseClass->getDesugaredType(true);
1278 }
1279 for (curIndex = 0; curIndex < Last; curIndex++)
1280 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1281 break;
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001282 }
Anders Carlsson82b3fd22009-08-27 05:45:01 +00001283 PrevMember = Member;
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001284 }
Anders Carlssonc7f87202009-03-25 02:58:17 +00001285}
1286
Fariborz Jahanian4e127232009-07-21 22:36:06 +00001287void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian21e25e72009-07-15 22:34:08 +00001288 if (!CDtorDecl)
Fariborz Jahanian9294d192009-07-14 18:24:21 +00001289 return;
1290
Douglas Gregor84164f02009-08-24 11:57:43 +00001291 AdjustDeclIfTemplate(CDtorDecl);
1292
Fariborz Jahanian9294d192009-07-14 18:24:21 +00001293 if (CXXConstructorDecl *Constructor
Fariborz Jahanian21e25e72009-07-15 22:34:08 +00001294 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Fariborz Jahanian7c1771c2009-07-23 23:32:59 +00001295 BuildBaseOrMemberInitializers(Context,
1296 Constructor,
1297 (CXXBaseOrMemberInitializer **)0, 0);
Fariborz Jahanian9294d192009-07-14 18:24:21 +00001298}
1299
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001300namespace {
1301 /// PureVirtualMethodCollector - traverses a class and its superclasses
1302 /// and determines if it has any pure virtual methods.
1303 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1304 ASTContext &Context;
1305
Sebastian Redl16ac38f2009-03-22 21:28:55 +00001306 public:
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001307 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redl16ac38f2009-03-22 21:28:55 +00001308
1309 private:
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001310 MethodList Methods;
1311
1312 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
1313
1314 public:
1315 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
1316 : Context(Ctx) {
1317
1318 MethodList List;
1319 Collect(RD, List);
1320
1321 // Copy the temporary list to methods, and make sure to ignore any
1322 // null entries.
1323 for (size_t i = 0, e = List.size(); i != e; ++i) {
1324 if (List[i])
1325 Methods.push_back(List[i]);
1326 }
1327 }
1328
Anders Carlssone1299b32009-03-22 20:18:17 +00001329 bool empty() const { return Methods.empty(); }
1330
1331 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1332 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001333 };
1334
1335 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
1336 MethodList& Methods) {
1337 // First, collect the pure virtual methods for the base classes.
1338 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1339 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001340 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner330a05b2009-03-29 05:01:10 +00001341 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001342 if (BaseDecl && BaseDecl->isAbstract())
1343 Collect(BaseDecl, Methods);
1344 }
1345 }
1346
1347 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson1eba0ac2009-05-17 00:00:05 +00001348 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
1349
1350 MethodSetTy OverriddenMethods;
1351 size_t MethodsSize = Methods.size();
1352
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001353 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson1eba0ac2009-05-17 00:00:05 +00001354 i != e; ++i) {
1355 // Traverse the record, looking for methods.
1356 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl953d12a2009-07-07 20:29:57 +00001357 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson1eba0ac2009-05-17 00:00:05 +00001358 if (MD->isPure()) {
1359 Methods.push_back(MD);
1360 continue;
1361 }
1362
1363 // Otherwise, record all the overridden methods in our set.
1364 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1365 E = MD->end_overridden_methods(); I != E; ++I) {
1366 // Keep track of the overridden methods.
1367 OverriddenMethods.insert(*I);
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001368 }
1369 }
1370 }
1371
Anders Carlsson1eba0ac2009-05-17 00:00:05 +00001372 // Now go through the methods and zero out all the ones we know are
1373 // overridden.
1374 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1375 if (OverriddenMethods.count(Methods[i]))
1376 Methods[i] = 0;
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001377 }
Anders Carlsson1eba0ac2009-05-17 00:00:05 +00001378
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001379 }
1380}
Douglas Gregora65e8dd2008-11-05 04:29:56 +00001381
Anders Carlsson62ce5832009-08-27 00:13:57 +00001382
Anders Carlssone1299b32009-03-22 20:18:17 +00001383bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonde9e7892009-03-24 17:23:42 +00001384 unsigned DiagID, AbstractDiagSelID SelID,
1385 const CXXRecordDecl *CurrentRD) {
Anders Carlsson62ce5832009-08-27 00:13:57 +00001386 if (SelID == -1)
1387 return RequireNonAbstractType(Loc, T,
1388 PDiag(DiagID), CurrentRD);
1389 else
1390 return RequireNonAbstractType(Loc, T,
1391 PDiag(DiagID) << SelID, CurrentRD);
1392}
Anders Carlssone1299b32009-03-22 20:18:17 +00001393
Anders Carlsson62ce5832009-08-27 00:13:57 +00001394bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1395 const PartialDiagnostic &PD,
1396 const CXXRecordDecl *CurrentRD) {
Anders Carlssone1299b32009-03-22 20:18:17 +00001397 if (!getLangOptions().CPlusPlus)
1398 return false;
Anders Carlssonc263c9b2009-03-23 19:10:31 +00001399
1400 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlsson62ce5832009-08-27 00:13:57 +00001401 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonde9e7892009-03-24 17:23:42 +00001402 CurrentRD);
Anders Carlssonce9240e2009-03-24 01:46:45 +00001403
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001404 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlssonce9240e2009-03-24 01:46:45 +00001405 // Find the innermost pointer type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001406 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlssonce9240e2009-03-24 01:46:45 +00001407 PT = T;
Anders Carlssone1299b32009-03-22 20:18:17 +00001408
Anders Carlssonce9240e2009-03-24 01:46:45 +00001409 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlsson62ce5832009-08-27 00:13:57 +00001410 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlssonce9240e2009-03-24 01:46:45 +00001411 }
1412
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001413 const RecordType *RT = T->getAs<RecordType>();
Anders Carlssone1299b32009-03-22 20:18:17 +00001414 if (!RT)
1415 return false;
1416
1417 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1418 if (!RD)
1419 return false;
1420
Anders Carlssonde9e7892009-03-24 17:23:42 +00001421 if (CurrentRD && CurrentRD != RD)
1422 return false;
1423
Anders Carlssone1299b32009-03-22 20:18:17 +00001424 if (!RD->isAbstract())
1425 return false;
1426
Anders Carlsson62ce5832009-08-27 00:13:57 +00001427 Diag(Loc, PD) << RD->getDeclName();
Anders Carlssone1299b32009-03-22 20:18:17 +00001428
1429 // Check if we've already emitted the list of pure virtual functions for this
1430 // class.
1431 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1432 return true;
1433
1434 PureVirtualMethodCollector Collector(Context, RD);
1435
1436 for (PureVirtualMethodCollector::MethodList::const_iterator I =
1437 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1438 const CXXMethodDecl *MD = *I;
1439
1440 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
1441 MD->getDeclName();
1442 }
1443
1444 if (!PureVirtualClassDiagSet)
1445 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1446 PureVirtualClassDiagSet->insert(RD);
1447
1448 return true;
1449}
1450
Anders Carlsson412c3402009-03-24 01:19:16 +00001451namespace {
1452 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
1453 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1454 Sema &SemaRef;
1455 CXXRecordDecl *AbstractClass;
1456
Anders Carlssonde9e7892009-03-24 17:23:42 +00001457 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson412c3402009-03-24 01:19:16 +00001458 bool Invalid = false;
1459
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001460 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1461 E = DC->decls_end(); I != E; ++I)
Anders Carlsson412c3402009-03-24 01:19:16 +00001462 Invalid |= Visit(*I);
Anders Carlssonde9e7892009-03-24 17:23:42 +00001463
Anders Carlsson412c3402009-03-24 01:19:16 +00001464 return Invalid;
1465 }
Anders Carlssonde9e7892009-03-24 17:23:42 +00001466
1467 public:
1468 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1469 : SemaRef(SemaRef), AbstractClass(ac) {
1470 Visit(SemaRef.Context.getTranslationUnitDecl());
1471 }
Anders Carlsson412c3402009-03-24 01:19:16 +00001472
Anders Carlssonde9e7892009-03-24 17:23:42 +00001473 bool VisitFunctionDecl(const FunctionDecl *FD) {
1474 if (FD->isThisDeclarationADefinition()) {
1475 // No need to do the check if we're in a definition, because it requires
1476 // that the return/param types are complete.
1477 // because that requires
1478 return VisitDeclContext(FD);
1479 }
1480
1481 // Check the return type.
1482 QualType RTy = FD->getType()->getAsFunctionType()->getResultType();
1483 bool Invalid =
1484 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1485 diag::err_abstract_type_in_decl,
1486 Sema::AbstractReturnType,
1487 AbstractClass);
1488
1489 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
1490 E = FD->param_end(); I != E; ++I) {
Anders Carlsson412c3402009-03-24 01:19:16 +00001491 const ParmVarDecl *VD = *I;
1492 Invalid |=
1493 SemaRef.RequireNonAbstractType(VD->getLocation(),
1494 VD->getOriginalType(),
1495 diag::err_abstract_type_in_decl,
Anders Carlssonde9e7892009-03-24 17:23:42 +00001496 Sema::AbstractParamType,
1497 AbstractClass);
Anders Carlsson412c3402009-03-24 01:19:16 +00001498 }
1499
1500 return Invalid;
1501 }
Anders Carlssonde9e7892009-03-24 17:23:42 +00001502
1503 bool VisitDecl(const Decl* D) {
1504 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1505 return VisitDeclContext(DC);
1506
1507 return false;
1508 }
Anders Carlsson412c3402009-03-24 01:19:16 +00001509 };
1510}
1511
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001512void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +00001513 DeclPtrTy TagDecl,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001514 SourceLocation LBrac,
1515 SourceLocation RBrac) {
Douglas Gregorac77dd62009-06-22 23:20:33 +00001516 if (!TagDecl)
1517 return;
1518
Douglas Gregor3eb20702009-05-11 19:58:34 +00001519 AdjustDeclIfTemplate(TagDecl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001520 ActOnFields(S, RLoc, TagDecl,
Chris Lattner5261d0c2009-03-28 19:18:32 +00001521 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +00001522 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregored3a3982009-03-03 04:44:36 +00001523
Chris Lattner5261d0c2009-03-28 19:18:32 +00001524 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001525 if (!RD->isAbstract()) {
1526 // Collect all the pure virtual methods and see if this is an abstract
1527 // class after all.
1528 PureVirtualMethodCollector Collector(Context, RD);
1529 if (!Collector.empty())
1530 RD->setAbstract(true);
1531 }
1532
Anders Carlssonde9e7892009-03-24 17:23:42 +00001533 if (RD->isAbstract())
1534 AbstractClassUsageDiagnoser(*this, RD);
Anders Carlsson412c3402009-03-24 01:19:16 +00001535
Douglas Gregor3eb20702009-05-11 19:58:34 +00001536 if (!RD->isDependentType())
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001537 AddImplicitlyDeclaredMembersToClass(RD);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001538}
1539
Douglas Gregore640ab62008-11-03 17:51:48 +00001540/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1541/// special functions, such as the default constructor, copy
1542/// constructor, or destructor, to the given C++ class (C++
1543/// [special]p1). This routine can only be executed just before the
1544/// definition of the class is complete.
1545void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregorcfe6ae52009-08-05 05:36:45 +00001546 CanQualType ClassType
1547 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001548
Sebastian Redl2767d882009-05-27 22:11:52 +00001549 // FIXME: Implicit declarations have exception specifications, which are
1550 // the union of the specifications of the implicitly called functions.
1551
Douglas Gregore640ab62008-11-03 17:51:48 +00001552 if (!ClassDecl->hasUserDeclaredConstructor()) {
1553 // C++ [class.ctor]p5:
1554 // A default constructor for a class X is a constructor of class X
1555 // that can be called without an argument. If there is no
1556 // user-declared constructor for class X, a default constructor is
1557 // implicitly declared. An implicitly-declared default constructor
1558 // is an inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001559 DeclarationName Name
1560 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +00001561 CXXConstructorDecl *DefaultCon =
1562 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001563 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +00001564 Context.getFunctionType(Context.VoidTy,
1565 0, 0, false, 0),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001566 /*DInfo=*/0,
Douglas Gregore640ab62008-11-03 17:51:48 +00001567 /*isExplicit=*/false,
1568 /*isInline=*/true,
1569 /*isImplicitlyDeclared=*/true);
1570 DefaultCon->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001571 DefaultCon->setImplicit();
Douglas Gregorf73c8512009-07-22 18:25:24 +00001572 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001573 ClassDecl->addDecl(DefaultCon);
Douglas Gregore640ab62008-11-03 17:51:48 +00001574 }
1575
1576 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1577 // C++ [class.copy]p4:
1578 // If the class definition does not explicitly declare a copy
1579 // constructor, one is declared implicitly.
1580
1581 // C++ [class.copy]p5:
1582 // The implicitly-declared copy constructor for a class X will
1583 // have the form
1584 //
1585 // X::X(const X&)
1586 //
1587 // if
1588 bool HasConstCopyConstructor = true;
1589
1590 // -- each direct or virtual base class B of X has a copy
1591 // constructor whose first parameter is of type const B& or
1592 // const volatile B&, and
1593 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1594 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1595 const CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001596 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregore640ab62008-11-03 17:51:48 +00001597 HasConstCopyConstructor
1598 = BaseClassDecl->hasConstCopyConstructor(Context);
1599 }
1600
1601 // -- for all the nonstatic data members of X that are of a
1602 // class type M (or array thereof), each such class type
1603 // has a copy constructor whose first parameter is of type
1604 // const M& or const volatile M&.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001605 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1606 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001607 ++Field) {
Douglas Gregore640ab62008-11-03 17:51:48 +00001608 QualType FieldType = (*Field)->getType();
1609 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1610 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001611 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregore640ab62008-11-03 17:51:48 +00001612 const CXXRecordDecl *FieldClassDecl
1613 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1614 HasConstCopyConstructor
1615 = FieldClassDecl->hasConstCopyConstructor(Context);
1616 }
1617 }
1618
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001619 // Otherwise, the implicitly declared copy constructor will have
1620 // the form
Douglas Gregore640ab62008-11-03 17:51:48 +00001621 //
1622 // X::X(X&)
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001623 QualType ArgType = ClassType;
Douglas Gregore640ab62008-11-03 17:51:48 +00001624 if (HasConstCopyConstructor)
1625 ArgType = ArgType.withConst();
Sebastian Redlce6fff02009-03-16 23:22:08 +00001626 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregore640ab62008-11-03 17:51:48 +00001627
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001628 // An implicitly-declared copy constructor is an inline public
1629 // member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001630 DeclarationName Name
1631 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +00001632 CXXConstructorDecl *CopyConstructor
1633 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001634 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +00001635 Context.getFunctionType(Context.VoidTy,
1636 &ArgType, 1,
1637 false, 0),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001638 /*DInfo=*/0,
Douglas Gregore640ab62008-11-03 17:51:48 +00001639 /*isExplicit=*/false,
1640 /*isInline=*/true,
1641 /*isImplicitlyDeclared=*/true);
1642 CopyConstructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001643 CopyConstructor->setImplicit();
Douglas Gregorf73c8512009-07-22 18:25:24 +00001644 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregore640ab62008-11-03 17:51:48 +00001645
1646 // Add the parameter to the constructor.
1647 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1648 ClassDecl->getLocation(),
1649 /*IdentifierInfo=*/0,
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001650 ArgType, /*DInfo=*/0,
1651 VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +00001652 CopyConstructor->setParams(Context, &FromParam, 1);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001653 ClassDecl->addDecl(CopyConstructor);
Douglas Gregore640ab62008-11-03 17:51:48 +00001654 }
1655
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001656 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1657 // Note: The following rules are largely analoguous to the copy
1658 // constructor rules. Note that virtual bases are not taken into account
1659 // for determining the argument type of the operator. Note also that
1660 // operators taking an object instead of a reference are allowed.
1661 //
1662 // C++ [class.copy]p10:
1663 // If the class definition does not explicitly declare a copy
1664 // assignment operator, one is declared implicitly.
1665 // The implicitly-defined copy assignment operator for a class X
1666 // will have the form
1667 //
1668 // X& X::operator=(const X&)
1669 //
1670 // if
1671 bool HasConstCopyAssignment = true;
1672
1673 // -- each direct base class B of X has a copy assignment operator
1674 // whose parameter is of type const B&, const volatile B& or B,
1675 // and
1676 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1677 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1678 const CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001679 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian04500242009-08-12 23:34:46 +00001680 const CXXMethodDecl *MD = 0;
1681 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
1682 MD);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001683 }
1684
1685 // -- for all the nonstatic data members of X that are of a class
1686 // type M (or array thereof), each such class type has a copy
1687 // assignment operator whose parameter is of type const M&,
1688 // const volatile M& or M.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001689 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1690 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001691 ++Field) {
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001692 QualType FieldType = (*Field)->getType();
1693 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1694 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001695 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001696 const CXXRecordDecl *FieldClassDecl
1697 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian04500242009-08-12 23:34:46 +00001698 const CXXMethodDecl *MD = 0;
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001699 HasConstCopyAssignment
Fariborz Jahanian04500242009-08-12 23:34:46 +00001700 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001701 }
1702 }
1703
1704 // Otherwise, the implicitly declared copy assignment operator will
1705 // have the form
1706 //
1707 // X& X::operator=(X&)
1708 QualType ArgType = ClassType;
Sebastian Redlce6fff02009-03-16 23:22:08 +00001709 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001710 if (HasConstCopyAssignment)
1711 ArgType = ArgType.withConst();
Sebastian Redlce6fff02009-03-16 23:22:08 +00001712 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001713
1714 // An implicitly-declared copy assignment operator is an inline public
1715 // member of its class.
1716 DeclarationName Name =
1717 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1718 CXXMethodDecl *CopyAssignment =
1719 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1720 Context.getFunctionType(RetType, &ArgType, 1,
1721 false, 0),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001722 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001723 CopyAssignment->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001724 CopyAssignment->setImplicit();
Douglas Gregorf73c8512009-07-22 18:25:24 +00001725 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001726 CopyAssignment->setCopyAssignment(true);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001727
1728 // Add the parameter to the operator.
1729 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1730 ClassDecl->getLocation(),
1731 /*IdentifierInfo=*/0,
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001732 ArgType, /*DInfo=*/0,
1733 VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +00001734 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001735
1736 // Don't call addedAssignmentOperator. There is no way to distinguish an
1737 // implicit from an explicit assignment operator.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001738 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001739 }
1740
Douglas Gregorb9213832008-12-15 21:24:18 +00001741 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001742 // C++ [class.dtor]p2:
1743 // If a class has no user-declared destructor, a destructor is
1744 // declared implicitly. An implicitly-declared destructor is an
1745 // inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001746 DeclarationName Name
1747 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001748 CXXDestructorDecl *Destructor
1749 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001750 ClassDecl->getLocation(), Name,
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001751 Context.getFunctionType(Context.VoidTy,
1752 0, 0, false, 0),
1753 /*isInline=*/true,
1754 /*isImplicitlyDeclared=*/true);
1755 Destructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001756 Destructor->setImplicit();
Douglas Gregorf73c8512009-07-22 18:25:24 +00001757 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001758 ClassDecl->addDecl(Destructor);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001759 }
Douglas Gregore640ab62008-11-03 17:51:48 +00001760}
1761
Douglas Gregora376cbd2009-05-27 23:11:45 +00001762void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
1763 TemplateDecl *Template = TemplateD.getAs<TemplateDecl>();
1764 if (!Template)
1765 return;
1766
1767 TemplateParameterList *Params = Template->getTemplateParameters();
1768 for (TemplateParameterList::iterator Param = Params->begin(),
1769 ParamEnd = Params->end();
1770 Param != ParamEnd; ++Param) {
1771 NamedDecl *Named = cast<NamedDecl>(*Param);
1772 if (Named->getDeclName()) {
1773 S->AddDecl(DeclPtrTy::make(Named));
1774 IdResolver.AddDecl(Named);
1775 }
1776 }
1777}
1778
Douglas Gregor605de8d2008-12-16 21:30:33 +00001779/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1780/// parsing a top-level (non-nested) C++ class, and we are now
1781/// parsing those parts of the given Method declaration that could
1782/// not be parsed earlier (C++ [class.mem]p2), such as default
1783/// arguments. This action should enter the scope of the given
1784/// Method declaration as if we had just parsed the qualified method
1785/// name. However, it should not bring the parameters into scope;
1786/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001787void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregorac77dd62009-06-22 23:20:33 +00001788 if (!MethodD)
1789 return;
1790
Douglas Gregor84164f02009-08-24 11:57:43 +00001791 AdjustDeclIfTemplate(MethodD);
1792
Douglas Gregor605de8d2008-12-16 21:30:33 +00001793 CXXScopeSpec SS;
Chris Lattner5261d0c2009-03-28 19:18:32 +00001794 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001795 QualType ClassTy
1796 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1797 SS.setScopeRep(
1798 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor605de8d2008-12-16 21:30:33 +00001799 ActOnCXXEnterDeclaratorScope(S, SS);
1800}
1801
1802/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1803/// C++ method declaration. We're (re-)introducing the given
1804/// function parameter into scope for use in parsing later parts of
1805/// the method declaration. For example, we could see an
1806/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001807void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregorac77dd62009-06-22 23:20:33 +00001808 if (!ParamD)
1809 return;
1810
Chris Lattner5261d0c2009-03-28 19:18:32 +00001811 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001812
1813 // If this parameter has an unparsed default argument, clear it out
1814 // to make way for the parsed default argument.
1815 if (Param->hasUnparsedDefaultArg())
1816 Param->setDefaultArg(0);
1817
Chris Lattner5261d0c2009-03-28 19:18:32 +00001818 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor605de8d2008-12-16 21:30:33 +00001819 if (Param->getDeclName())
1820 IdResolver.AddDecl(Param);
1821}
1822
1823/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1824/// processing the delayed method declaration for Method. The method
1825/// declaration is now considered finished. There may be a separate
1826/// ActOnStartOfFunctionDef action later (not necessarily
1827/// immediately!) for this method, if it was also defined inside the
1828/// class body.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001829void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregorac77dd62009-06-22 23:20:33 +00001830 if (!MethodD)
1831 return;
1832
Douglas Gregor84164f02009-08-24 11:57:43 +00001833 AdjustDeclIfTemplate(MethodD);
1834
Chris Lattner5261d0c2009-03-28 19:18:32 +00001835 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor605de8d2008-12-16 21:30:33 +00001836 CXXScopeSpec SS;
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001837 QualType ClassTy
1838 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1839 SS.setScopeRep(
1840 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor605de8d2008-12-16 21:30:33 +00001841 ActOnCXXExitDeclaratorScope(S, SS);
1842
1843 // Now that we have our default arguments, check the constructor
1844 // again. It could produce additional diagnostics or affect whether
1845 // the class has implicitly-declared destructors, among other
1846 // things.
Chris Lattner08da4772009-04-25 08:35:12 +00001847 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
1848 CheckConstructor(Constructor);
Douglas Gregor605de8d2008-12-16 21:30:33 +00001849
1850 // Check the default arguments, which we may have added.
1851 if (!Method->isInvalidDecl())
1852 CheckCXXDefaultArguments(Method);
1853}
1854
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001855/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor605de8d2008-12-16 21:30:33 +00001856/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001857/// R. If there are any errors in the declarator, this routine will
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001858/// emit diagnostics and set the invalid bit to true. In any case, the type
1859/// will be updated to reflect a well-formed type for the constructor and
1860/// returned.
1861QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
1862 FunctionDecl::StorageClass &SC) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001863 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001864
1865 // C++ [class.ctor]p3:
1866 // A constructor shall not be virtual (10.3) or static (9.4). A
1867 // constructor can be invoked for a const, volatile or const
1868 // volatile object. A constructor shall not be declared const,
1869 // volatile, or const volatile (9.3.2).
1870 if (isVirtual) {
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001871 if (!D.isInvalidType())
1872 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1873 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1874 << SourceRange(D.getIdentifierLoc());
1875 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001876 }
1877 if (SC == FunctionDecl::Static) {
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001878 if (!D.isInvalidType())
1879 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1880 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1881 << SourceRange(D.getIdentifierLoc());
1882 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001883 SC = FunctionDecl::None;
1884 }
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001885
1886 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1887 if (FTI.TypeQuals != 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001888 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001889 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1890 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001891 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001892 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1893 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001894 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001895 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1896 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001897 }
1898
1899 // Rebuild the function type "R" without any type qualifiers (in
1900 // case any of the errors above fired) and with "void" as the
1901 // return type, since constructors don't have return types. We
1902 // *always* have to do this, because GetTypeForDeclarator will
1903 // put in a result type of "int" when none was specified.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001904 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001905 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1906 Proto->getNumArgs(),
1907 Proto->isVariadic(), 0);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001908}
1909
Douglas Gregor605de8d2008-12-16 21:30:33 +00001910/// CheckConstructor - Checks a fully-formed constructor for
1911/// well-formedness, issuing any diagnostics required. Returns true if
1912/// the constructor declarator is invalid.
Chris Lattner08da4772009-04-25 08:35:12 +00001913void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Douglas Gregor869cabf2009-03-27 04:38:56 +00001914 CXXRecordDecl *ClassDecl
1915 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
1916 if (!ClassDecl)
Chris Lattner08da4772009-04-25 08:35:12 +00001917 return Constructor->setInvalidDecl();
Douglas Gregor605de8d2008-12-16 21:30:33 +00001918
1919 // C++ [class.copy]p3:
1920 // A declaration of a constructor for a class X is ill-formed if
1921 // its first parameter is of type (optionally cv-qualified) X and
1922 // either there are no other parameters or else all other
1923 // parameters have default arguments.
Douglas Gregor869cabf2009-03-27 04:38:56 +00001924 if (!Constructor->isInvalidDecl() &&
1925 ((Constructor->getNumParams() == 1) ||
1926 (Constructor->getNumParams() > 1 &&
Anders Carlssond2e57d92009-06-06 04:14:07 +00001927 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor605de8d2008-12-16 21:30:33 +00001928 QualType ParamType = Constructor->getParamDecl(0)->getType();
1929 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1930 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00001931 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
1932 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor133d2552009-04-02 01:08:08 +00001933 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattner08da4772009-04-25 08:35:12 +00001934 Constructor->setInvalidDecl();
Douglas Gregor605de8d2008-12-16 21:30:33 +00001935 }
1936 }
1937
1938 // Notify the class that we've added a constructor.
1939 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor605de8d2008-12-16 21:30:33 +00001940}
1941
Anders Carlssonfcfa2442009-04-30 23:18:11 +00001942static inline bool
1943FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
1944 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1945 FTI.ArgInfo[0].Param &&
1946 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
1947}
1948
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001949/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1950/// the well-formednes of the destructor declarator @p D with type @p
1951/// R. If there are any errors in the declarator, this routine will
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001952/// emit diagnostics and set the declarator to invalid. Even if this happens,
1953/// will be updated to reflect a well-formed type for the destructor and
1954/// returned.
1955QualType Sema::CheckDestructorDeclarator(Declarator &D,
1956 FunctionDecl::StorageClass& SC) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001957 // C++ [class.dtor]p1:
1958 // [...] A typedef-name that names a class is a class-name
1959 // (7.1.3); however, a typedef-name that names a class shall not
1960 // be used as the identifier in the declarator for a destructor
1961 // declaration.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001962 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType());
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001963 if (isa<TypedefType>(DeclaratorType)) {
1964 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregora60c62e2009-02-09 15:09:02 +00001965 << DeclaratorType;
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001966 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001967 }
1968
1969 // C++ [class.dtor]p2:
1970 // A destructor is used to destroy objects of its class type. A
1971 // destructor takes no parameters, and no return type can be
1972 // specified for it (not even void). The address of a destructor
1973 // shall not be taken. A destructor shall not be static. A
1974 // destructor can be invoked for a const, volatile or const
1975 // volatile object. A destructor shall not be declared const,
1976 // volatile or const volatile (9.3.2).
1977 if (SC == FunctionDecl::Static) {
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001978 if (!D.isInvalidType())
1979 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1980 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1981 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001982 SC = FunctionDecl::None;
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001983 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001984 }
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001985 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001986 // Destructors don't have return types, but the parser will
1987 // happily parse something like:
1988 //
1989 // class X {
1990 // float ~X();
1991 // };
1992 //
1993 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001994 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1995 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1996 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001997 }
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001998
1999 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2000 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00002001 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00002002 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2003 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00002004 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00002005 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2006 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00002007 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00002008 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2009 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattnerc82dcd42009-04-25 08:28:21 +00002010 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00002011 }
2012
2013 // Make sure we don't have any parameters.
Anders Carlssonfcfa2442009-04-30 23:18:11 +00002014 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00002015 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2016
2017 // Delete the parameters.
Chris Lattnerc82dcd42009-04-25 08:28:21 +00002018 FTI.freeArgs();
2019 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00002020 }
2021
2022 // Make sure the destructor isn't variadic.
Chris Lattnerc82dcd42009-04-25 08:28:21 +00002023 if (FTI.isVariadic) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00002024 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattnerc82dcd42009-04-25 08:28:21 +00002025 D.setInvalidType();
2026 }
Douglas Gregor8210a8e2008-11-05 20:51:48 +00002027
2028 // Rebuild the function type "R" without any type qualifiers or
2029 // parameters (in case any of the errors above fired) and with
2030 // "void" as the return type, since destructors don't have return
2031 // types. We *always* have to do this, because GetTypeForDeclarator
2032 // will put in a result type of "int" when none was specified.
Chris Lattnerc82dcd42009-04-25 08:28:21 +00002033 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00002034}
2035
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002036/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2037/// well-formednes of the conversion function declarator @p D with
2038/// type @p R. If there are any errors in the declarator, this routine
2039/// will emit diagnostics and return true. Otherwise, it will return
2040/// false. Either way, the type @p R will be updated to reflect a
2041/// well-formed type for the conversion operator.
Chris Lattner08da4772009-04-25 08:35:12 +00002042void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002043 FunctionDecl::StorageClass& SC) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002044 // C++ [class.conv.fct]p1:
2045 // Neither parameter types nor return type can be specified. The
Eli Friedmand5a72f02009-08-05 19:21:58 +00002046 // type of a conversion function (8.3.5) is "function taking no
2047 // parameter returning conversion-type-id."
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002048 if (SC == FunctionDecl::Static) {
Chris Lattner08da4772009-04-25 08:35:12 +00002049 if (!D.isInvalidType())
2050 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2051 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2052 << SourceRange(D.getIdentifierLoc());
2053 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002054 SC = FunctionDecl::None;
2055 }
Chris Lattner08da4772009-04-25 08:35:12 +00002056 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002057 // Conversion functions don't have return types, but the parser will
2058 // happily parse something like:
2059 //
2060 // class X {
2061 // float operator bool();
2062 // };
2063 //
2064 // The return type will be changed later anyway.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002065 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2066 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2067 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002068 }
2069
2070 // Make sure we don't have any parameters.
Douglas Gregor4fa58902009-02-26 23:50:07 +00002071 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002072 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2073
2074 // Delete the parameters.
Chris Lattner5c6139b2009-01-20 21:06:38 +00002075 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner08da4772009-04-25 08:35:12 +00002076 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002077 }
2078
2079 // Make sure the conversion function isn't variadic.
Chris Lattner08da4772009-04-25 08:35:12 +00002080 if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002081 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner08da4772009-04-25 08:35:12 +00002082 D.setInvalidType();
2083 }
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002084
2085 // C++ [class.conv.fct]p4:
2086 // The conversion-type-id shall not represent a function type nor
2087 // an array type.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00002088 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002089 if (ConvType->isArrayType()) {
2090 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2091 ConvType = Context.getPointerType(ConvType);
Chris Lattner08da4772009-04-25 08:35:12 +00002092 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002093 } else if (ConvType->isFunctionType()) {
2094 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2095 ConvType = Context.getPointerType(ConvType);
Chris Lattner08da4772009-04-25 08:35:12 +00002096 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002097 }
2098
2099 // Rebuild the function type "R" without any parameters (in case any
2100 // of the errors above fired) and with the conversion type as the
2101 // return type.
2102 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002103 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002104
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002105 // C++0x explicit conversion operators.
2106 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
2107 Diag(D.getDeclSpec().getExplicitSpecLoc(),
2108 diag::warn_explicit_conversion_functions)
2109 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002110}
2111
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002112/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2113/// the declaration of the given C++ conversion function. This routine
2114/// is responsible for recording the conversion function in the C++
2115/// class, if possible.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002116Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002117 assert(Conversion && "Expected to receive a conversion function declaration");
2118
Douglas Gregor98341042008-12-12 08:25:50 +00002119 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002120
2121 // Make sure we aren't redeclaring the conversion function.
2122 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002123
2124 // C++ [class.conv.fct]p1:
2125 // [...] A conversion function is never used to convert a
2126 // (possibly cv-qualified) object to the (possibly cv-qualified)
2127 // same object type (or a reference to it), to a (possibly
2128 // cv-qualified) base class of that type (or a reference to it),
2129 // or to (possibly cv-qualified) void.
Mike Stumpe127ae32009-05-16 07:39:55 +00002130 // FIXME: Suppress this warning if the conversion function ends up being a
2131 // virtual function that overrides a virtual function in a base class.
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002132 QualType ClassType
2133 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002134 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002135 ConvType = ConvTypeRef->getPointeeType();
2136 if (ConvType->isRecordType()) {
2137 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2138 if (ConvType == ClassType)
Chris Lattner8d756812008-11-20 06:13:02 +00002139 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002140 << ClassType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002141 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner8d756812008-11-20 06:13:02 +00002142 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002143 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002144 } else if (ConvType->isVoidType()) {
Chris Lattner8d756812008-11-20 06:13:02 +00002145 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002146 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002147 }
2148
Douglas Gregor853dd392008-12-26 15:00:45 +00002149 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002150 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
2151 if (FunctionTemplateDecl *ConversionTemplate
2152 = Conversion->getDescribedFunctionTemplate())
2153 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor853dd392008-12-26 15:00:45 +00002154 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
2155 for (OverloadedFunctionDecl::function_iterator
2156 Conv = Conversions->function_begin(),
2157 ConvEnd = Conversions->function_end();
2158 Conv != ConvEnd; ++Conv) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002159 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor853dd392008-12-26 15:00:45 +00002160 *Conv = Conversion;
Chris Lattner5261d0c2009-03-28 19:18:32 +00002161 return DeclPtrTy::make(Conversion);
Douglas Gregor853dd392008-12-26 15:00:45 +00002162 }
2163 }
2164 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Douglas Gregor8c860df2009-08-21 23:19:43 +00002165 } else if (FunctionTemplateDecl *ConversionTemplate
2166 = Conversion->getDescribedFunctionTemplate())
2167 ClassDecl->addConversionFunction(Context, ConversionTemplate);
2168 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Douglas Gregor853dd392008-12-26 15:00:45 +00002169 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002170
Chris Lattner5261d0c2009-03-28 19:18:32 +00002171 return DeclPtrTy::make(Conversion);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00002172}
2173
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002174//===----------------------------------------------------------------------===//
2175// Namespace Handling
2176//===----------------------------------------------------------------------===//
2177
2178/// ActOnStartNamespaceDef - This is called at the start of a namespace
2179/// definition.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002180Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2181 SourceLocation IdentLoc,
2182 IdentifierInfo *II,
2183 SourceLocation LBrace) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002184 NamespaceDecl *Namespc =
2185 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2186 Namespc->setLBracLoc(LBrace);
2187
2188 Scope *DeclRegionScope = NamespcScope->getParent();
2189
2190 if (II) {
2191 // C++ [namespace.def]p2:
2192 // The identifier in an original-namespace-definition shall not have been
2193 // previously defined in the declarative region in which the
2194 // original-namespace-definition appears. The identifier in an
2195 // original-namespace-definition is the name of the namespace. Subsequently
2196 // in that declarative region, it is treated as an original-namespace-name.
2197
Douglas Gregor09be81b2009-02-04 17:27:36 +00002198 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
2199 true);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002200
2201 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2202 // This is an extended namespace definition.
2203 // Attach this namespace decl to the chain of extended namespace
2204 // definitions.
2205 OrigNS->setNextNamespace(Namespc);
2206 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002207
Douglas Gregor8acb7272008-12-11 16:49:14 +00002208 // Remove the previous declaration from the scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002209 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor39677622008-12-11 20:41:00 +00002210 IdResolver.RemoveDecl(OrigNS);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002211 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002212 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00002213 } else if (PrevDecl) {
2214 // This is an invalid name redefinition.
2215 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2216 << Namespc->getDeclName();
2217 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2218 Namespc->setInvalidDecl();
2219 // Continue on to push Namespc as current DeclContext and return it.
2220 }
2221
2222 PushOnScopeChains(Namespc, DeclRegionScope);
2223 } else {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002224 // FIXME: Handle anonymous namespaces
2225 }
2226
2227 // Although we could have an invalid decl (i.e. the namespace name is a
2228 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stumpe127ae32009-05-16 07:39:55 +00002229 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2230 // for the namespace has the declarations that showed up in that particular
2231 // namespace definition.
Douglas Gregor8acb7272008-12-11 16:49:14 +00002232 PushDeclContext(NamespcScope, Namespc);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002233 return DeclPtrTy::make(Namespc);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002234}
2235
2236/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2237/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002238void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2239 Decl *Dcl = D.getAs<Decl>();
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002240 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2241 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2242 Namespc->setRBracLoc(RBrace);
2243 PopDeclContext();
2244}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002245
Chris Lattner5261d0c2009-03-28 19:18:32 +00002246Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2247 SourceLocation UsingLoc,
2248 SourceLocation NamespcLoc,
2249 const CXXScopeSpec &SS,
2250 SourceLocation IdentLoc,
2251 IdentifierInfo *NamespcName,
2252 AttributeList *AttrList) {
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002253 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2254 assert(NamespcName && "Invalid NamespcName.");
2255 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor7a7be652009-02-03 19:21:40 +00002256 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002257
Douglas Gregor7a7be652009-02-03 19:21:40 +00002258 UsingDirectiveDecl *UDir = 0;
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002259
Douglas Gregor78d70132009-01-14 22:20:51 +00002260 // Lookup namespace name.
Douglas Gregor7a7be652009-02-03 19:21:40 +00002261 LookupResult R = LookupParsedName(S, &SS, NamespcName,
2262 LookupNamespaceName, false);
2263 if (R.isAmbiguous()) {
2264 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002265 return DeclPtrTy();
Douglas Gregor7a7be652009-02-03 19:21:40 +00002266 }
Douglas Gregor09be81b2009-02-04 17:27:36 +00002267 if (NamedDecl *NS = R) {
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002268 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor7a7be652009-02-03 19:21:40 +00002269 // C++ [namespace.udir]p1:
2270 // A using-directive specifies that the names in the nominated
2271 // namespace can be used in the scope in which the
2272 // using-directive appears after the using-directive. During
2273 // unqualified name lookup (3.4.1), the names appear as if they
2274 // were declared in the nearest enclosing namespace which
2275 // contains both the using-directive and the nominated
Eli Friedmand5a72f02009-08-05 19:21:58 +00002276 // namespace. [Note: in this context, "contains" means "contains
2277 // directly or indirectly". ]
Douglas Gregor7a7be652009-02-03 19:21:40 +00002278
2279 // Find enclosing context containing both using-directive and
2280 // nominated namespace.
2281 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2282 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2283 CommonAncestor = CommonAncestor->getParent();
2284
Douglas Gregor1d27d692009-05-30 06:31:56 +00002285 UDir = UsingDirectiveDecl::Create(Context,
2286 CurContext, UsingLoc,
2287 NamespcLoc,
2288 SS.getRange(),
2289 (NestedNameSpecifier *)SS.getScopeRep(),
2290 IdentLoc,
Douglas Gregor7a7be652009-02-03 19:21:40 +00002291 cast<NamespaceDecl>(NS),
2292 CommonAncestor);
2293 PushUsingDirective(S, UDir);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002294 } else {
Chris Lattner954381a2009-01-06 07:24:29 +00002295 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002296 }
2297
Douglas Gregor7a7be652009-02-03 19:21:40 +00002298 // FIXME: We ignore attributes for now.
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002299 delete AttrList;
Chris Lattner5261d0c2009-03-28 19:18:32 +00002300 return DeclPtrTy::make(UDir);
Douglas Gregor7a7be652009-02-03 19:21:40 +00002301}
2302
2303void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2304 // If scope has associated entity, then using directive is at namespace
2305 // or translation unit scope. We add UsingDirectiveDecls, into
2306 // it's lookup structure.
2307 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002308 Ctx->addDecl(UDir);
Douglas Gregor7a7be652009-02-03 19:21:40 +00002309 else
2310 // Otherwise it is block-sope. using-directives will affect lookup
2311 // only to the end of scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002312 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002313}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002314
Douglas Gregor683a1142009-06-20 00:51:54 +00002315
2316Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlssone16b4fe2009-08-29 19:54:19 +00002317 AccessSpecifier AS,
Anders Carlssonb49f1bd2009-08-28 03:16:11 +00002318 SourceLocation UsingLoc,
2319 const CXXScopeSpec &SS,
2320 SourceLocation IdentLoc,
2321 IdentifierInfo *TargetName,
2322 OverloadedOperatorKind Op,
2323 AttributeList *AttrList,
2324 bool IsTypeName) {
Eli Friedmana73d6b12009-06-27 05:59:59 +00002325 assert((TargetName || Op) && "Invalid TargetName.");
Douglas Gregor683a1142009-06-20 00:51:54 +00002326 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Anders Carlsson348af322009-08-28 05:40:36 +00002327
Anders Carlssone8c36f22009-06-27 00:27:47 +00002328 DeclarationName Name;
2329 if (TargetName)
2330 Name = TargetName;
2331 else
2332 Name = Context.DeclarationNames.getCXXOperatorName(Op);
Anders Carlsson348af322009-08-28 05:40:36 +00002333
2334 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS, IdentLoc,
2335 Name, AttrList, IsTypeName);
Anders Carlssone16b4fe2009-08-29 19:54:19 +00002336 if (UD) {
Anders Carlsson348af322009-08-28 05:40:36 +00002337 PushOnScopeChains(UD, S);
Anders Carlssone16b4fe2009-08-29 19:54:19 +00002338 UD->setAccess(AS);
2339 }
Anders Carlsson348af322009-08-28 05:40:36 +00002340
2341 return DeclPtrTy::make(UD);
2342}
2343
2344NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2345 const CXXScopeSpec &SS,
2346 SourceLocation IdentLoc,
2347 DeclarationName Name,
2348 AttributeList *AttrList,
2349 bool IsTypeName) {
2350 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2351 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedmanb30f1c82009-08-27 05:09:36 +00002352
Anders Carlsson50bc7082009-08-28 05:49:21 +00002353 // FIXME: We ignore attributes for now.
2354 delete AttrList;
2355
Anders Carlssonb49f1bd2009-08-28 03:16:11 +00002356 if (SS.isEmpty()) {
2357 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson348af322009-08-28 05:40:36 +00002358 return 0;
Anders Carlssonb49f1bd2009-08-28 03:16:11 +00002359 }
2360
2361 NestedNameSpecifier *NNS =
2362 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2363
Anders Carlsson50bc7082009-08-28 05:49:21 +00002364 if (isUnknownSpecialization(SS)) {
2365 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2366 SS.getRange(), NNS,
2367 IdentLoc, Name, IsTypeName);
2368 }
2369
Anders Carlssonb49f1bd2009-08-28 03:16:11 +00002370 DeclContext *LookupContext = 0;
2371
2372 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2373 // C++0x N2914 [namespace.udecl]p3:
2374 // A using-declaration used as a member-declaration shall refer to a member
2375 // of a base class of the class being defined, shall refer to a member of an
2376 // anonymous union that is a member of a base class of the class being
2377 // defined, or shall refer to an enumerator for an enumeration type that is
2378 // a member of a base class of the class being defined.
2379 const Type *Ty = NNS->getAsType();
2380 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) {
2381 Diag(SS.getRange().getBegin(),
2382 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2383 << NNS << RD->getDeclName();
Anders Carlsson348af322009-08-28 05:40:36 +00002384 return 0;
Anders Carlssonb49f1bd2009-08-28 03:16:11 +00002385 }
Anders Carlsson61451732009-08-28 15:18:15 +00002386
2387 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0));
2388 LookupContext = BaseTy->getAs<RecordType>()->getDecl();
Anders Carlssonb49f1bd2009-08-28 03:16:11 +00002389 } else {
2390 // C++0x N2914 [namespace.udecl]p8:
2391 // A using-declaration for a class member shall be a member-declaration.
2392 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
Anders Carlsson66b082a2009-08-28 03:35:18 +00002393 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlssonb49f1bd2009-08-28 03:16:11 +00002394 << SS.getRange();
Anders Carlsson348af322009-08-28 05:40:36 +00002395 return 0;
Anders Carlssonb49f1bd2009-08-28 03:16:11 +00002396 }
2397
2398 // C++0x N2914 [namespace.udecl]p9:
2399 // In a using-declaration, a prefix :: refers to the global namespace.
2400 if (NNS->getKind() == NestedNameSpecifier::Global)
2401 LookupContext = Context.getTranslationUnitDecl();
2402 else
2403 LookupContext = NNS->getAsNamespace();
2404 }
2405
2406
Douglas Gregor683a1142009-06-20 00:51:54 +00002407 // Lookup target name.
Anders Carlssonb49f1bd2009-08-28 03:16:11 +00002408 LookupResult R = LookupQualifiedName(LookupContext,
2409 Name, LookupOrdinaryName);
2410
2411 if (!R) {
Anders Carlsson8c463c52009-08-30 00:58:45 +00002412 DiagnoseMissingMember(IdentLoc, Name, NNS, SS.getRange());
Anders Carlsson348af322009-08-28 05:40:36 +00002413 return 0;
Douglas Gregor683a1142009-06-20 00:51:54 +00002414 }
2415
Anders Carlssonb49f1bd2009-08-28 03:16:11 +00002416 NamedDecl *ND = R.getAsDecl();
2417
2418 if (IsTypeName && !isa<TypeDecl>(ND)) {
2419 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlsson348af322009-08-28 05:40:36 +00002420 return 0;
Anders Carlssonb49f1bd2009-08-28 03:16:11 +00002421 }
2422
Anders Carlsson66b082a2009-08-28 03:35:18 +00002423 // C++0x N2914 [namespace.udecl]p6:
2424 // A using-declaration shall not name a namespace.
2425 if (isa<NamespaceDecl>(ND)) {
2426 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2427 << SS.getRange();
Anders Carlsson348af322009-08-28 05:40:36 +00002428 return 0;
Anders Carlsson66b082a2009-08-28 03:35:18 +00002429 }
2430
Anders Carlsson348af322009-08-28 05:40:36 +00002431 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2432 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregor683a1142009-06-20 00:51:54 +00002433}
2434
Anders Carlsson7c1c5482009-03-28 23:53:49 +00002435/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2436/// is a namespace alias, returns the namespace it points to.
2437static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2438 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2439 return AD->getNamespace();
2440 return dyn_cast_or_null<NamespaceDecl>(D);
2441}
2442
Chris Lattner5261d0c2009-03-28 19:18:32 +00002443Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson26de7882009-03-28 22:53:22 +00002444 SourceLocation NamespaceLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +00002445 SourceLocation AliasLoc,
2446 IdentifierInfo *Alias,
2447 const CXXScopeSpec &SS,
Anders Carlsson26de7882009-03-28 22:53:22 +00002448 SourceLocation IdentLoc,
2449 IdentifierInfo *Ident) {
Anders Carlsson640eb7c2009-03-28 06:23:46 +00002450
Anders Carlsson7c1c5482009-03-28 23:53:49 +00002451 // Lookup the namespace name.
2452 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
2453
Anders Carlsson640eb7c2009-03-28 06:23:46 +00002454 // Check if we have a previous declaration with the same name.
Anders Carlsson1cd05f52009-03-28 23:49:35 +00002455 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlsson7c1c5482009-03-28 23:53:49 +00002456 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
2457 // We already have an alias with the same name that points to the same
2458 // namespace, so don't create a new one.
2459 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
2460 return DeclPtrTy();
2461 }
2462
Anders Carlsson640eb7c2009-03-28 06:23:46 +00002463 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2464 diag::err_redefinition_different_kind;
2465 Diag(AliasLoc, DiagID) << Alias;
2466 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002467 return DeclPtrTy();
Anders Carlsson640eb7c2009-03-28 06:23:46 +00002468 }
2469
Anders Carlsson279ebc42009-03-28 06:42:02 +00002470 if (R.isAmbiguous()) {
Anders Carlsson26de7882009-03-28 22:53:22 +00002471 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002472 return DeclPtrTy();
Anders Carlsson279ebc42009-03-28 06:42:02 +00002473 }
2474
2475 if (!R) {
2476 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner5261d0c2009-03-28 19:18:32 +00002477 return DeclPtrTy();
Anders Carlsson279ebc42009-03-28 06:42:02 +00002478 }
2479
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002480 NamespaceAliasDecl *AliasDecl =
Douglas Gregor8d8ddca2009-05-30 06:48:27 +00002481 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2482 Alias, SS.getRange(),
2483 (NestedNameSpecifier *)SS.getScopeRep(),
Anders Carlssonddb1d8b2009-03-28 22:58:02 +00002484 IdentLoc, R);
2485
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002486 CurContext->addDecl(AliasDecl);
Anders Carlssonddb1d8b2009-03-28 22:58:02 +00002487 return DeclPtrTy::make(AliasDecl);
Anders Carlsson8cffcd62009-03-28 05:27:17 +00002488}
2489
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002490void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2491 CXXConstructorDecl *Constructor) {
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00002492 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2493 !Constructor->isUsed()) &&
2494 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002495
2496 CXXRecordDecl *ClassDecl
2497 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002498 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002499 // Before the implicitly-declared default constructor for a class is
2500 // implicitly defined, all the implicitly-declared default constructors
2501 // for its base class and its non-static data members shall have been
2502 // implicitly defined.
2503 bool err = false;
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002504 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2505 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002506 CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002507 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002508 if (!BaseClassDecl->hasTrivialConstructor()) {
2509 if (CXXConstructorDecl *BaseCtor =
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002510 BaseClassDecl->getDefaultConstructor(Context))
2511 MarkDeclarationReferenced(CurrentLocation, BaseCtor);
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002512 else {
2513 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian16443602009-06-20 20:23:38 +00002514 << Context.getTagDeclType(ClassDecl) << 1
2515 << Context.getTagDeclType(BaseClassDecl);
2516 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
2517 << Context.getTagDeclType(BaseClassDecl);
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002518 err = true;
2519 }
2520 }
2521 }
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002522 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2523 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002524 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2525 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2526 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002527 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002528 CXXRecordDecl *FieldClassDecl
2529 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Duncan Sands78146712009-06-25 09:03:06 +00002530 if (!FieldClassDecl->hasTrivialConstructor()) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002531 if (CXXConstructorDecl *FieldCtor =
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002532 FieldClassDecl->getDefaultConstructor(Context))
2533 MarkDeclarationReferenced(CurrentLocation, FieldCtor);
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002534 else {
2535 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian16443602009-06-20 20:23:38 +00002536 << Context.getTagDeclType(ClassDecl) << 0 <<
2537 Context.getTagDeclType(FieldClassDecl);
2538 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
2539 << Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002540 err = true;
2541 }
2542 }
Mike Stump90fc78e2009-08-04 21:02:39 +00002543 } else if (FieldType->isReferenceType()) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002544 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson6a661262009-07-09 17:37:12 +00002545 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002546 Diag((*Field)->getLocation(), diag::note_declared_at);
2547 err = true;
Mike Stump90fc78e2009-08-04 21:02:39 +00002548 } else if (FieldType.isConstQualified()) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002549 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson6a661262009-07-09 17:37:12 +00002550 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002551 Diag((*Field)->getLocation(), diag::note_declared_at);
2552 err = true;
2553 }
2554 }
2555 if (!err)
Fariborz Jahanian2c313fb2009-06-26 16:08:57 +00002556 Constructor->setUsed();
2557 else
2558 Constructor->setInvalidDecl();
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002559}
2560
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002561void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
2562 CXXDestructorDecl *Destructor) {
2563 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2564 "DefineImplicitDestructor - call it for implicit default dtor");
2565
2566 CXXRecordDecl *ClassDecl
2567 = cast<CXXRecordDecl>(Destructor->getDeclContext());
2568 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2569 // C++ [class.dtor] p5
2570 // Before the implicitly-declared default destructor for a class is
2571 // implicitly defined, all the implicitly-declared default destructors
2572 // for its base class and its non-static data members shall have been
2573 // implicitly defined.
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002574 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2575 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002576 CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002577 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002578 if (!BaseClassDecl->hasTrivialDestructor()) {
2579 if (CXXDestructorDecl *BaseDtor =
2580 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2581 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2582 else
2583 assert(false &&
2584 "DefineImplicitDestructor - missing dtor in a base class");
2585 }
2586 }
2587
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002588 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2589 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002590 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2591 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2592 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002593 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002594 CXXRecordDecl *FieldClassDecl
2595 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2596 if (!FieldClassDecl->hasTrivialDestructor()) {
2597 if (CXXDestructorDecl *FieldDtor =
2598 const_cast<CXXDestructorDecl*>(
2599 FieldClassDecl->getDestructor(Context)))
2600 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
2601 else
2602 assert(false &&
2603 "DefineImplicitDestructor - missing dtor in class of a data member");
2604 }
2605 }
2606 }
2607 Destructor->setUsed();
2608}
2609
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002610void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
2611 CXXMethodDecl *MethodDecl) {
2612 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
2613 MethodDecl->getOverloadedOperator() == OO_Equal &&
2614 !MethodDecl->isUsed()) &&
2615 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
2616
2617 CXXRecordDecl *ClassDecl
2618 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002619
Fariborz Jahanian2c313fb2009-06-26 16:08:57 +00002620 // C++[class.copy] p12
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002621 // Before the implicitly-declared copy assignment operator for a class is
2622 // implicitly defined, all implicitly-declared copy assignment operators
2623 // for its direct base classes and its nonstatic data members shall have
2624 // been implicitly defined.
2625 bool err = false;
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002626 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2627 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002628 CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002629 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002630 if (CXXMethodDecl *BaseAssignOpMethod =
2631 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
2632 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
2633 }
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002634 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2635 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002636 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2637 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2638 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002639 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002640 CXXRecordDecl *FieldClassDecl
2641 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2642 if (CXXMethodDecl *FieldAssignOpMethod =
2643 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
2644 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump90fc78e2009-08-04 21:02:39 +00002645 } else if (FieldType->isReferenceType()) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002646 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson1c0c52c2009-07-09 17:47:25 +00002647 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
2648 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002649 Diag(CurrentLocation, diag::note_first_required_here);
2650 err = true;
Mike Stump90fc78e2009-08-04 21:02:39 +00002651 } else if (FieldType.isConstQualified()) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002652 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson1c0c52c2009-07-09 17:47:25 +00002653 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
2654 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002655 Diag(CurrentLocation, diag::note_first_required_here);
2656 err = true;
2657 }
2658 }
2659 if (!err)
2660 MethodDecl->setUsed();
2661}
2662
2663CXXMethodDecl *
2664Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
2665 CXXRecordDecl *ClassDecl) {
2666 QualType LHSType = Context.getTypeDeclType(ClassDecl);
2667 QualType RHSType(LHSType);
2668 // If class's assignment operator argument is const/volatile qualified,
2669 // look for operator = (const/volatile B&). Otherwise, look for
2670 // operator = (B&).
2671 if (ParmDecl->getType().isConstQualified())
2672 RHSType.addConst();
2673 if (ParmDecl->getType().isVolatileQualified())
2674 RHSType.addVolatile();
2675 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
2676 LHSType,
2677 SourceLocation()));
2678 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
2679 RHSType,
2680 SourceLocation()));
2681 Expr *Args[2] = { &*LHS, &*RHS };
2682 OverloadCandidateSet CandidateSet;
2683 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
2684 CandidateSet);
2685 OverloadCandidateSet::iterator Best;
2686 if (BestViableFunction(CandidateSet,
2687 ClassDecl->getLocation(), Best) == OR_Success)
2688 return cast<CXXMethodDecl>(Best->Function);
2689 assert(false &&
2690 "getAssignOperatorMethod - copy assignment operator method not found");
2691 return 0;
2692}
2693
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002694void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2695 CXXConstructorDecl *CopyConstructor,
2696 unsigned TypeQuals) {
2697 assert((CopyConstructor->isImplicit() &&
2698 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
2699 !CopyConstructor->isUsed()) &&
2700 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
2701
2702 CXXRecordDecl *ClassDecl
2703 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
2704 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002705 // C++ [class.copy] p209
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002706 // Before the implicitly-declared copy constructor for a class is
2707 // implicitly defined, all the implicitly-declared copy constructors
2708 // for its base class and its non-static data members shall have been
2709 // implicitly defined.
2710 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2711 Base != ClassDecl->bases_end(); ++Base) {
2712 CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002713 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002714 if (CXXConstructorDecl *BaseCopyCtor =
2715 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002716 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002717 }
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002718 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2719 FieldEnd = ClassDecl->field_end();
2720 Field != FieldEnd; ++Field) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002721 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2722 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2723 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002724 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002725 CXXRecordDecl *FieldClassDecl
2726 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2727 if (CXXConstructorDecl *FieldCopyCtor =
2728 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002729 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002730 }
2731 }
2732 CopyConstructor->setUsed();
2733}
2734
Anders Carlsson665e4692009-08-25 05:12:04 +00002735Sema::OwningExprResult
2736Sema::BuildCXXConstructExpr(QualType DeclInitType,
2737 CXXConstructorDecl *Constructor,
2738 Expr **Exprs, unsigned NumExprs) {
Anders Carlssonbd9f51a2009-08-16 05:13:48 +00002739 bool Elidable = false;
2740
2741 // [class.copy]p15:
2742 // Whenever a temporary class object is copied using a copy constructor, and
2743 // this object and the copy have the same cv-unqualified type, an
2744 // implementation is permitted to treat the original and the copy as two
2745 // different ways of referring to the same object and not perform a copy at
2746 //all, even if the class copy constructor or destructor have side effects.
2747
2748 // FIXME: Is this enough?
2749 if (Constructor->isCopyConstructor(Context) && NumExprs == 1) {
2750 Expr *E = Exprs[0];
2751 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2752 E = BE->getSubExpr();
2753
2754 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
2755 Elidable = true;
2756 }
2757
2758 return BuildCXXConstructExpr(DeclInitType, Constructor, Elidable,
2759 Exprs, NumExprs);
2760}
2761
Fariborz Jahanian1c30f262009-08-05 17:03:54 +00002762/// BuildCXXConstructExpr - Creates a complete call to a constructor,
2763/// including handling of its default argument expressions.
Anders Carlsson665e4692009-08-25 05:12:04 +00002764Sema::OwningExprResult
2765Sema::BuildCXXConstructExpr(QualType DeclInitType,
2766 CXXConstructorDecl *Constructor,
2767 bool Elidable,
2768 Expr **Exprs,
2769 unsigned NumExprs) {
Anders Carlsson3e03d832009-08-25 13:07:08 +00002770 ExprOwningPtr<CXXConstructExpr> Temp(this,
2771 CXXConstructExpr::Create(Context,
2772 DeclInitType,
2773 Constructor,
2774 Elidable,
2775 Exprs,
2776 NumExprs));
Anders Carlssonef8fd082009-08-27 05:08:22 +00002777 // Default arguments must be added to constructor call expression.
Fariborz Jahanianbeb68c42009-08-05 00:26:10 +00002778 FunctionDecl *FDecl = cast<FunctionDecl>(Constructor);
2779 unsigned NumArgsInProto = FDecl->param_size();
2780 for (unsigned j = NumExprs; j != NumArgsInProto; j++) {
Anders Carlsson3e03d832009-08-25 13:07:08 +00002781 ParmVarDecl *Param = FDecl->getParamDecl(j);
2782
2783 OwningExprResult ArgExpr =
2784 BuildCXXDefaultArgExpr(/*FIXME:*/SourceLocation(),
2785 FDecl, Param);
2786 if (ArgExpr.isInvalid())
2787 return ExprError();
2788
2789 Temp->setArg(j, ArgExpr.takeAs<Expr>());
Fariborz Jahanianbeb68c42009-08-05 00:26:10 +00002790 }
Anders Carlsson3e03d832009-08-25 13:07:08 +00002791 return move(Temp);
Fariborz Jahanian1c30f262009-08-05 17:03:54 +00002792}
2793
Anders Carlssonef8fd082009-08-27 05:08:22 +00002794Sema::OwningExprResult
2795Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
2796 QualType Ty,
2797 SourceLocation TyBeginLoc,
2798 MultiExprArg Args,
2799 SourceLocation RParenLoc) {
2800 CXXTemporaryObjectExpr *E
2801 = new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty, TyBeginLoc,
2802 (Expr **)Args.get(),
2803 Args.size(), RParenLoc);
2804
2805 ExprOwningPtr<CXXTemporaryObjectExpr> Temp(this, E);
2806
2807 // Default arguments must be added to constructor call expression.
2808 FunctionDecl *FDecl = cast<FunctionDecl>(Constructor);
2809 unsigned NumArgsInProto = FDecl->param_size();
2810 for (unsigned j = Args.size(); j != NumArgsInProto; j++) {
2811 ParmVarDecl *Param = FDecl->getParamDecl(j);
2812
2813 OwningExprResult ArgExpr = BuildCXXDefaultArgExpr(TyBeginLoc, FDecl, Param);
2814 if (ArgExpr.isInvalid())
2815 return ExprError();
2816
2817 Temp->setArg(j, ArgExpr.takeAs<Expr>());
2818 }
2819
2820 Args.release();
2821 return move(Temp);
2822}
2823
2824
Anders Carlssonbaa8a312009-08-25 05:18:00 +00002825bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanian1c30f262009-08-05 17:03:54 +00002826 CXXConstructorDecl *Constructor,
2827 QualType DeclInitType,
2828 Expr **Exprs, unsigned NumExprs) {
Anders Carlsson665e4692009-08-25 05:12:04 +00002829 OwningExprResult TempResult = BuildCXXConstructExpr(DeclInitType, Constructor,
2830 Exprs, NumExprs);
Anders Carlssonbaa8a312009-08-25 05:18:00 +00002831 if (TempResult.isInvalid())
2832 return true;
Anders Carlsson665e4692009-08-25 05:12:04 +00002833
2834 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregorcad27f62009-06-22 23:06:13 +00002835 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahanian88e09cc2009-08-05 18:17:32 +00002836 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor4833ff02009-05-26 18:54:04 +00002837 VD->setInit(Context, Temp);
Anders Carlssonbaa8a312009-08-25 05:18:00 +00002838
2839 return false;
Anders Carlsson05e59652009-04-16 23:50:50 +00002840}
2841
Fariborz Jahaniancd208112009-08-03 19:13:25 +00002842void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType)
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002843{
2844 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002845 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002846 if (!ClassDecl->hasTrivialDestructor())
2847 if (CXXDestructorDecl *Destructor =
2848 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniancd208112009-08-03 19:13:25 +00002849 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002850}
2851
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002852/// AddCXXDirectInitializerToDecl - This action is called immediately after
2853/// ActOnDeclarator, when a C++ direct initializer is present.
2854/// e.g: "int x(1);"
Chris Lattner5261d0c2009-03-28 19:18:32 +00002855void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
2856 SourceLocation LParenLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002857 MultiExprArg Exprs,
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002858 SourceLocation *CommaLocs,
2859 SourceLocation RParenLoc) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002860 unsigned NumExprs = Exprs.size();
2861 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner5261d0c2009-03-28 19:18:32 +00002862 Decl *RealDecl = Dcl.getAs<Decl>();
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002863
2864 // If there is no declaration, there was an error parsing it. Just ignore
2865 // the initializer.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002866 if (RealDecl == 0)
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002867 return;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002868
2869 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2870 if (!VDecl) {
2871 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
2872 RealDecl->setInvalidDecl();
2873 return;
2874 }
2875
Douglas Gregor52be1ca2009-08-26 21:14:46 +00002876 // We will represent direct-initialization similarly to copy-initialization:
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00002877 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002878 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
2879 //
2880 // Clients that want to distinguish between the two forms, can check for
2881 // direct initializer using VarDecl::hasCXXDirectInitializer().
2882 // A major benefit is that clients that don't particularly care about which
2883 // exactly form was it (like the CodeGen) can handle both cases without
2884 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002885
Douglas Gregor52be1ca2009-08-26 21:14:46 +00002886 // If either the declaration has a dependent type or if any of the expressions
2887 // is type-dependent, we represent the initialization via a ParenListExpr for
2888 // later use during template instantiation.
2889 if (VDecl->getType()->isDependentType() ||
2890 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
2891 // Let clients know that initialization was done with a direct initializer.
2892 VDecl->setCXXDirectInitializer(true);
2893
2894 // Store the initialization expressions as a ParenListExpr.
2895 unsigned NumExprs = Exprs.size();
2896 VDecl->setInit(Context,
2897 new (Context) ParenListExpr(Context, LParenLoc,
2898 (Expr **)Exprs.release(),
2899 NumExprs, RParenLoc));
2900 return;
2901 }
2902
2903
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002904 // C++ 8.5p11:
2905 // The form of initialization (using parentheses or '=') is generally
2906 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002907 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +00002908 QualType DeclInitType = VDecl->getType();
2909 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
2910 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002911
Douglas Gregorad7d1812009-03-24 16:43:20 +00002912 // FIXME: This isn't the right place to complete the type.
2913 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
2914 diag::err_typecheck_decl_incomplete_type)) {
2915 VDecl->setInvalidDecl();
2916 return;
2917 }
2918
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002919 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +00002920 CXXConstructorDecl *Constructor
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002921 = PerformInitializationByConstructor(DeclInitType,
2922 (Expr **)Exprs.get(), NumExprs,
Douglas Gregor6428e762008-11-05 15:29:30 +00002923 VDecl->getLocation(),
2924 SourceRange(VDecl->getLocation(),
2925 RParenLoc),
Chris Lattner271d4c22008-11-24 05:29:24 +00002926 VDecl->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00002927 IK_Direct);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002928 if (!Constructor)
Douglas Gregor5870a952008-11-03 20:45:27 +00002929 RealDecl->setInvalidDecl();
Anders Carlsson9c7b4922009-04-15 21:48:18 +00002930 else {
Anders Carlsson9c7b4922009-04-15 21:48:18 +00002931 VDecl->setCXXDirectInitializer(true);
Anders Carlssonbaa8a312009-08-25 05:18:00 +00002932 if (InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
2933 (Expr**)Exprs.release(), NumExprs))
2934 RealDecl->setInvalidDecl();
Fariborz Jahaniancd208112009-08-03 19:13:25 +00002935 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlsson9c7b4922009-04-15 21:48:18 +00002936 }
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002937 return;
2938 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002939
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00002940 if (NumExprs > 1) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00002941 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
2942 << SourceRange(VDecl->getLocation(), RParenLoc);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002943 RealDecl->setInvalidDecl();
2944 return;
2945 }
2946
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002947 // Let clients know that initialization was done with a direct initializer.
2948 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00002949
2950 assert(NumExprs == 1 && "Expected 1 expression");
2951 // Set the init expression, handles conversions.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002952 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
2953 /*DirectInit=*/true);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002954}
Douglas Gregor81c29152008-10-29 00:13:59 +00002955
Douglas Gregor6428e762008-11-05 15:29:30 +00002956/// PerformInitializationByConstructor - Perform initialization by
2957/// constructor (C++ [dcl.init]p14), which may occur as part of
2958/// direct-initialization or copy-initialization. We are initializing
2959/// an object of type @p ClassType with the given arguments @p
2960/// Args. @p Loc is the location in the source code where the
2961/// initializer occurs (e.g., a declaration, member initializer,
2962/// functional cast, etc.) while @p Range covers the whole
2963/// initialization. @p InitEntity is the entity being initialized,
2964/// which may by the name of a declaration or a type. @p Kind is the
2965/// kind of initialization we're performing, which affects whether
2966/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00002967/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00002968/// when the initialization fails, emits a diagnostic and returns
2969/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00002970CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00002971Sema::PerformInitializationByConstructor(QualType ClassType,
2972 Expr **Args, unsigned NumArgs,
2973 SourceLocation Loc, SourceRange Range,
Chris Lattner271d4c22008-11-24 05:29:24 +00002974 DeclarationName InitEntity,
Douglas Gregor6428e762008-11-05 15:29:30 +00002975 InitializationKind Kind) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002976 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregor5870a952008-11-03 20:45:27 +00002977 assert(ClassRec && "Can only initialize a class type here");
2978
2979 // C++ [dcl.init]p14:
2980 //
2981 // If the initialization is direct-initialization, or if it is
2982 // copy-initialization where the cv-unqualified version of the
2983 // source type is the same class as, or a derived class of, the
2984 // class of the destination, constructors are considered. The
2985 // applicable constructors are enumerated (13.3.1.3), and the
2986 // best one is chosen through overload resolution (13.3). The
2987 // constructor so selected is called to initialize the object,
2988 // with the initializer expression(s) as its argument(s). If no
2989 // constructor applies, or the overload resolution is ambiguous,
2990 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00002991 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
2992 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00002993
2994 // Add constructors to the overload set.
Douglas Gregorb9213832008-12-15 21:24:18 +00002995 DeclarationName ConstructorName
2996 = Context.DeclarationNames.getCXXConstructorName(
2997 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002998 DeclContext::lookup_const_iterator Con, ConEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002999 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003000 Con != ConEnd; ++Con) {
Douglas Gregor050cabf2009-08-21 18:42:58 +00003001 // Find the constructor (which may be a template).
3002 CXXConstructorDecl *Constructor = 0;
3003 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3004 if (ConstructorTmpl)
3005 Constructor
3006 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3007 else
3008 Constructor = cast<CXXConstructorDecl>(*Con);
3009
Douglas Gregor6428e762008-11-05 15:29:30 +00003010 if ((Kind == IK_Direct) ||
Anders Carlsson94894572009-08-28 16:57:08 +00003011 (Kind == IK_Copy &&
3012 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor050cabf2009-08-21 18:42:58 +00003013 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
3014 if (ConstructorTmpl)
3015 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
3016 Args, NumArgs, CandidateSet);
3017 else
3018 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3019 }
Douglas Gregor6428e762008-11-05 15:29:30 +00003020 }
3021
Douglas Gregorb9213832008-12-15 21:24:18 +00003022 // FIXME: When we decide not to synthesize the implicitly-declared
3023 // constructors, we'll need to make them appear here.
3024
Douglas Gregor5870a952008-11-03 20:45:27 +00003025 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00003026 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor5870a952008-11-03 20:45:27 +00003027 case OR_Success:
3028 // We found a constructor. Return it.
3029 return cast<CXXConstructorDecl>(Best->Function);
3030
3031 case OR_No_Viable_Function:
Douglas Gregor538a4c22009-02-02 17:43:21 +00003032 if (InitEntity)
3033 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00003034 << InitEntity << Range;
Douglas Gregor538a4c22009-02-02 17:43:21 +00003035 else
3036 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00003037 << ClassType << Range;
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00003038 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor5870a952008-11-03 20:45:27 +00003039 return 0;
3040
3041 case OR_Ambiguous:
Douglas Gregor538a4c22009-02-02 17:43:21 +00003042 if (InitEntity)
3043 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3044 else
3045 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor5870a952008-11-03 20:45:27 +00003046 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3047 return 0;
Douglas Gregoraa57e862009-02-18 21:56:37 +00003048
3049 case OR_Deleted:
3050 if (InitEntity)
3051 Diag(Loc, diag::err_ovl_deleted_init)
3052 << Best->Function->isDeleted()
3053 << InitEntity << Range;
3054 else
3055 Diag(Loc, diag::err_ovl_deleted_init)
3056 << Best->Function->isDeleted()
3057 << InitEntity << Range;
3058 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3059 return 0;
Douglas Gregor5870a952008-11-03 20:45:27 +00003060 }
3061
3062 return 0;
3063}
3064
Douglas Gregor81c29152008-10-29 00:13:59 +00003065/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3066/// determine whether they are reference-related,
3067/// reference-compatible, reference-compatible with added
3068/// qualification, or incompatible, for use in C++ initialization by
3069/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3070/// type, and the first type (T1) is the pointee type of the reference
3071/// type being initialized.
3072Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003073Sema::CompareReferenceRelationship(QualType T1, QualType T2,
3074 bool& DerivedToBase) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003075 assert(!T1->isReferenceType() &&
3076 "T1 must be the pointee type of the reference type");
Douglas Gregor81c29152008-10-29 00:13:59 +00003077 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
3078
3079 T1 = Context.getCanonicalType(T1);
3080 T2 = Context.getCanonicalType(T2);
3081 QualType UnqualT1 = T1.getUnqualifiedType();
3082 QualType UnqualT2 = T2.getUnqualifiedType();
3083
3084 // C++ [dcl.init.ref]p4:
Eli Friedmand5a72f02009-08-05 19:21:58 +00003085 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3086 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor81c29152008-10-29 00:13:59 +00003087 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003088 if (UnqualT1 == UnqualT2)
3089 DerivedToBase = false;
3090 else if (IsDerivedFrom(UnqualT2, UnqualT1))
3091 DerivedToBase = true;
3092 else
Douglas Gregor81c29152008-10-29 00:13:59 +00003093 return Ref_Incompatible;
3094
3095 // At this point, we know that T1 and T2 are reference-related (at
3096 // least).
3097
3098 // C++ [dcl.init.ref]p4:
Eli Friedmand5a72f02009-08-05 19:21:58 +00003099 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor81c29152008-10-29 00:13:59 +00003100 // reference-related to T2 and cv1 is the same cv-qualification
3101 // as, or greater cv-qualification than, cv2. For purposes of
3102 // overload resolution, cases for which cv1 is greater
3103 // cv-qualification than cv2 are identified as
3104 // reference-compatible with added qualification (see 13.3.3.2).
3105 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3106 return Ref_Compatible;
3107 else if (T1.isMoreQualifiedThan(T2))
3108 return Ref_Compatible_With_Added_Qualification;
3109 else
3110 return Ref_Related;
3111}
3112
3113/// CheckReferenceInit - Check the initialization of a reference
3114/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3115/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00003116/// list), and DeclType is the type of the declaration. When ICS is
3117/// non-null, this routine will compute the implicit conversion
3118/// sequence according to C++ [over.ics.ref] and will not produce any
3119/// diagnostics; when ICS is null, it will emit diagnostics when any
3120/// errors are found. Either way, a return value of true indicates
3121/// that there was a failure, a return value of false indicates that
3122/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00003123///
3124/// When @p SuppressUserConversions, user-defined conversions are
3125/// suppressed.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003126/// When @p AllowExplicit, we also permit explicit user-defined
3127/// conversion functions.
Sebastian Redla55834a2009-04-12 17:16:29 +00003128/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003129bool
Sebastian Redlbd261962009-04-16 17:51:27 +00003130Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003131 bool SuppressUserConversions,
Anders Carlsson8f809f92009-08-27 17:30:43 +00003132 bool AllowExplicit, bool ForceRValue,
3133 ImplicitConversionSequence *ICS) {
Douglas Gregor81c29152008-10-29 00:13:59 +00003134 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3135
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003136 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor81c29152008-10-29 00:13:59 +00003137 QualType T2 = Init->getType();
3138
Douglas Gregor45014fd2008-11-10 20:40:00 +00003139 // If the initializer is the address of an overloaded function, try
3140 // to resolve the overloaded function. If all goes well, T2 is the
3141 // type of the resulting function.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003142 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003143 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
3144 ICS != 0);
3145 if (Fn) {
3146 // Since we're performing this reference-initialization for
3147 // real, update the initializer with the resulting function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003148 if (!ICS) {
3149 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
3150 return true;
3151
Douglas Gregor45014fd2008-11-10 20:40:00 +00003152 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregoraa57e862009-02-18 21:56:37 +00003153 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003154
3155 T2 = Fn->getType();
3156 }
3157 }
3158
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003159 // Compute some basic properties of the types and the initializer.
Sebastian Redlce6fff02009-03-16 23:22:08 +00003160 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003161 bool DerivedToBase = false;
Sebastian Redla55834a2009-04-12 17:16:29 +00003162 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3163 Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003164 ReferenceCompareResult RefRelationship
3165 = CompareReferenceRelationship(T1, T2, DerivedToBase);
3166
3167 // Most paths end in a failed conversion.
3168 if (ICS)
3169 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00003170
3171 // C++ [dcl.init.ref]p5:
Eli Friedmand5a72f02009-08-05 19:21:58 +00003172 // A reference to type "cv1 T1" is initialized by an expression
3173 // of type "cv2 T2" as follows:
Douglas Gregor81c29152008-10-29 00:13:59 +00003174
3175 // -- If the initializer expression
3176
Sebastian Redldfc30332009-03-29 15:27:50 +00003177 // Rvalue references cannot bind to lvalues (N2812).
3178 // There is absolutely no situation where they can. In particular, note that
3179 // this is ill-formed, even if B has a user-defined conversion to A&&:
3180 // B b;
3181 // A&& r = b;
3182 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3183 if (!ICS)
3184 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
3185 << Init->getSourceRange();
3186 return true;
3187 }
3188
Douglas Gregor81c29152008-10-29 00:13:59 +00003189 bool BindsDirectly = false;
Eli Friedmand5a72f02009-08-05 19:21:58 +00003190 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3191 // reference-compatible with "cv2 T2," or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003192 //
3193 // Note that the bit-field check is skipped if we are just computing
3194 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor531434b2009-05-02 02:18:30 +00003195 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003196 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00003197 BindsDirectly = true;
3198
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003199 if (ICS) {
3200 // C++ [over.ics.ref]p1:
3201 // When a parameter of reference type binds directly (8.5.3)
3202 // to an argument expression, the implicit conversion sequence
3203 // is the identity conversion, unless the argument expression
3204 // has a type that is a derived class of the parameter type,
3205 // in which case the implicit conversion sequence is a
3206 // derived-to-base Conversion (13.3.3.1).
3207 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3208 ICS->Standard.First = ICK_Identity;
3209 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3210 ICS->Standard.Third = ICK_Identity;
3211 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3212 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00003213 ICS->Standard.ReferenceBinding = true;
3214 ICS->Standard.DirectBinding = true;
Sebastian Redldfc30332009-03-29 15:27:50 +00003215 ICS->Standard.RRefBinding = false;
Sebastian Redld3169132009-04-17 16:30:52 +00003216 ICS->Standard.CopyConstructor = 0;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003217
3218 // Nothing more to do: the inaccessibility/ambiguity check for
3219 // derived-to-base conversions is suppressed when we're
3220 // computing the implicit conversion sequence (C++
3221 // [over.best.ics]p2).
3222 return false;
3223 } else {
3224 // Perform the conversion.
Mike Stumpe127ae32009-05-16 07:39:55 +00003225 // FIXME: Binding to a subobject of the lvalue is going to require more
3226 // AST annotation than this.
Anders Carlsson85186942009-07-31 01:23:52 +00003227 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00003228 }
3229 }
3230
3231 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedmand5a72f02009-08-05 19:21:58 +00003232 // implicitly converted to an lvalue of type "cv3 T3,"
3233 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor81c29152008-10-29 00:13:59 +00003234 // 92) (this conversion is selected by enumerating the
3235 // applicable conversion functions (13.3.1.6) and choosing
3236 // the best one through overload resolution (13.3)),
Douglas Gregorb35c7992009-08-24 15:23:48 +00003237 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
3238 !RequireCompleteType(SourceLocation(), T2, 0)) {
Douglas Gregore6985fe2008-11-10 16:14:15 +00003239 // FIXME: Look for conversions in base classes!
3240 CXXRecordDecl *T2RecordDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003241 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor81c29152008-10-29 00:13:59 +00003242
Douglas Gregore6985fe2008-11-10 16:14:15 +00003243 OverloadCandidateSet CandidateSet;
3244 OverloadedFunctionDecl *Conversions
3245 = T2RecordDecl->getConversionFunctions();
3246 for (OverloadedFunctionDecl::function_iterator Func
3247 = Conversions->function_begin();
3248 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00003249 FunctionTemplateDecl *ConvTemplate
3250 = dyn_cast<FunctionTemplateDecl>(*Func);
3251 CXXConversionDecl *Conv;
3252 if (ConvTemplate)
3253 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3254 else
3255 Conv = cast<CXXConversionDecl>(*Func);
Sebastian Redl16ac38f2009-03-22 21:28:55 +00003256
Douglas Gregore6985fe2008-11-10 16:14:15 +00003257 // If the conversion function doesn't return a reference type,
3258 // it can't be considered for this conversion.
Sebastian Redlce6fff02009-03-16 23:22:08 +00003259 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor8c860df2009-08-21 23:19:43 +00003260 (AllowExplicit || !Conv->isExplicit())) {
3261 if (ConvTemplate)
3262 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
3263 CandidateSet);
3264 else
3265 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3266 }
Douglas Gregore6985fe2008-11-10 16:14:15 +00003267 }
3268
3269 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00003270 switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) {
Douglas Gregore6985fe2008-11-10 16:14:15 +00003271 case OR_Success:
3272 // This is a direct binding.
3273 BindsDirectly = true;
3274
3275 if (ICS) {
3276 // C++ [over.ics.ref]p1:
3277 //
3278 // [...] If the parameter binds directly to the result of
3279 // applying a conversion function to the argument
3280 // expression, the implicit conversion sequence is a
3281 // user-defined conversion sequence (13.3.3.1.2), with the
3282 // second standard conversion sequence either an identity
3283 // conversion or, if the conversion function returns an
3284 // entity of a type that is a derived class of the parameter
3285 // type, a derived-to-base Conversion.
3286 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3287 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3288 ICS->UserDefined.After = Best->FinalConversion;
3289 ICS->UserDefined.ConversionFunction = Best->Function;
3290 assert(ICS->UserDefined.After.ReferenceBinding &&
3291 ICS->UserDefined.After.DirectBinding &&
3292 "Expected a direct reference binding!");
3293 return false;
3294 } else {
3295 // Perform the conversion.
Mike Stumpe127ae32009-05-16 07:39:55 +00003296 // FIXME: Binding to a subobject of the lvalue is going to require more
3297 // AST annotation than this.
Anders Carlsson85186942009-07-31 01:23:52 +00003298 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true);
Douglas Gregore6985fe2008-11-10 16:14:15 +00003299 }
3300 break;
3301
3302 case OR_Ambiguous:
3303 assert(false && "Ambiguous reference binding conversions not implemented.");
3304 return true;
3305
3306 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00003307 case OR_Deleted:
3308 // There was no suitable conversion, or we found a deleted
3309 // conversion; continue with other checks.
Douglas Gregore6985fe2008-11-10 16:14:15 +00003310 break;
3311 }
3312 }
3313
Douglas Gregor81c29152008-10-29 00:13:59 +00003314 if (BindsDirectly) {
3315 // C++ [dcl.init.ref]p4:
3316 // [...] In all cases where the reference-related or
3317 // reference-compatible relationship of two types is used to
3318 // establish the validity of a reference binding, and T1 is a
3319 // base class of T2, a program that necessitates such a binding
3320 // is ill-formed if T1 is an inaccessible (clause 11) or
3321 // ambiguous (10.2) base class of T2.
3322 //
3323 // Note that we only check this condition when we're allowed to
3324 // complain about errors, because we should not be checking for
3325 // ambiguity (or inaccessibility) unless the reference binding
3326 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003327 if (DerivedToBase)
3328 return CheckDerivedToBaseConversion(T2, T1,
3329 Init->getSourceRange().getBegin(),
3330 Init->getSourceRange());
3331 else
3332 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00003333 }
3334
3335 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redldfc30332009-03-29 15:27:50 +00003336 // type (i.e., cv1 shall be const), or the reference shall be an
3337 // rvalue reference and the initializer expression shall be an rvalue.
Sebastian Redlce6fff02009-03-16 23:22:08 +00003338 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003339 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00003340 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00003341 diag::err_not_reference_to_const_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003342 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3343 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00003344 return true;
3345 }
3346
3347 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedmand5a72f02009-08-05 19:21:58 +00003348 // class type, and "cv1 T1" is reference-compatible with
3349 // "cv2 T2," the reference is bound in one of the
Douglas Gregor81c29152008-10-29 00:13:59 +00003350 // following ways (the choice is implementation-defined):
3351 //
3352 // -- The reference is bound to the object represented by
3353 // the rvalue (see 3.10) or to a sub-object within that
3354 // object.
3355 //
Eli Friedmand5a72f02009-08-05 19:21:58 +00003356 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor81c29152008-10-29 00:13:59 +00003357 // a constructor is called to copy the entire rvalue
3358 // object into the temporary. The reference is bound to
3359 // the temporary or to a sub-object within the
3360 // temporary.
3361 //
Douglas Gregor81c29152008-10-29 00:13:59 +00003362 // The constructor that would be used to make the copy
3363 // shall be callable whether or not the copy is actually
3364 // done.
3365 //
Sebastian Redldfc30332009-03-29 15:27:50 +00003366 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor81c29152008-10-29 00:13:59 +00003367 // freedom, so we will always take the first option and never build
3368 // a temporary in this case. FIXME: We will, however, have to check
3369 // for the presence of a copy constructor in C++98/03 mode.
3370 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003371 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3372 if (ICS) {
3373 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3374 ICS->Standard.First = ICK_Identity;
3375 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3376 ICS->Standard.Third = ICK_Identity;
3377 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3378 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00003379 ICS->Standard.ReferenceBinding = true;
Sebastian Redldfc30332009-03-29 15:27:50 +00003380 ICS->Standard.DirectBinding = false;
3381 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redld3169132009-04-17 16:30:52 +00003382 ICS->Standard.CopyConstructor = 0;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003383 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +00003384 // FIXME: Binding to a subobject of the rvalue is going to require more
3385 // AST annotation than this.
Anders Carlsson85186942009-07-31 01:23:52 +00003386 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/false);
Douglas Gregor81c29152008-10-29 00:13:59 +00003387 }
3388 return false;
3389 }
3390
Eli Friedmand5a72f02009-08-05 19:21:58 +00003391 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor81c29152008-10-29 00:13:59 +00003392 // initialized from the initializer expression using the
3393 // rules for a non-reference copy initialization (8.5). The
3394 // reference is then bound to the temporary. If T1 is
3395 // reference-related to T2, cv1 must be the same
3396 // cv-qualification as, or greater cv-qualification than,
3397 // cv2; otherwise, the program is ill-formed.
3398 if (RefRelationship == Ref_Related) {
3399 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3400 // we would be reference-compatible or reference-compatible with
3401 // added qualification. But that wasn't the case, so the reference
3402 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003403 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00003404 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00003405 diag::err_reference_init_drops_quals)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003406 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3407 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00003408 return true;
3409 }
3410
Douglas Gregorb206cc42009-01-30 23:27:23 +00003411 // If at least one of the types is a class type, the types are not
3412 // related, and we aren't allowed any user conversions, the
3413 // reference binding fails. This case is important for breaking
3414 // recursion, since TryImplicitConversion below will attempt to
3415 // create a temporary through the use of a copy constructor.
3416 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3417 (T1->isRecordType() || T2->isRecordType())) {
3418 if (!ICS)
3419 Diag(Init->getSourceRange().getBegin(),
3420 diag::err_typecheck_convert_incompatible)
3421 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3422 return true;
3423 }
3424
Douglas Gregor81c29152008-10-29 00:13:59 +00003425 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003426 if (ICS) {
Sebastian Redldfc30332009-03-29 15:27:50 +00003427 // C++ [over.ics.ref]p2:
3428 //
3429 // When a parameter of reference type is not bound directly to
3430 // an argument expression, the conversion sequence is the one
3431 // required to convert the argument expression to the
3432 // underlying type of the reference according to
3433 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3434 // to copy-initializing a temporary of the underlying type with
3435 // the argument expression. Any difference in top-level
3436 // cv-qualification is subsumed by the initialization itself
3437 // and does not constitute a conversion.
Anders Carlsson6ed4a612009-08-27 17:24:15 +00003438 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
3439 /*AllowExplicit=*/false,
Anders Carlsson8e4c1692009-08-28 15:33:32 +00003440 /*ForceRValue=*/false,
3441 /*InOverloadResolution=*/false);
Anders Carlsson6ed4a612009-08-27 17:24:15 +00003442
Sebastian Redldfc30332009-03-29 15:27:50 +00003443 // Of course, that's still a reference binding.
3444 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3445 ICS->Standard.ReferenceBinding = true;
3446 ICS->Standard.RRefBinding = isRValRef;
3447 } else if(ICS->ConversionKind ==
3448 ImplicitConversionSequence::UserDefinedConversion) {
3449 ICS->UserDefined.After.ReferenceBinding = true;
3450 ICS->UserDefined.After.RRefBinding = isRValRef;
3451 }
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003452 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3453 } else {
Douglas Gregor6fd35572008-12-19 17:40:08 +00003454 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003455 }
Douglas Gregor81c29152008-10-29 00:13:59 +00003456}
Douglas Gregore60e5d32008-11-06 22:13:31 +00003457
3458/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3459/// of this overloaded operator is well-formed. If so, returns false;
3460/// otherwise, emits appropriate diagnostics and returns true.
3461bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003462 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregore60e5d32008-11-06 22:13:31 +00003463 "Expected an overloaded operator declaration");
3464
Douglas Gregore60e5d32008-11-06 22:13:31 +00003465 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
3466
3467 // C++ [over.oper]p5:
3468 // The allocation and deallocation functions, operator new,
3469 // operator new[], operator delete and operator delete[], are
3470 // described completely in 3.7.3. The attributes and restrictions
3471 // found in the rest of this subclause do not apply to them unless
3472 // explicitly stated in 3.7.3.
Mike Stumpe127ae32009-05-16 07:39:55 +00003473 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregore60e5d32008-11-06 22:13:31 +00003474 if (Op == OO_New || Op == OO_Array_New ||
3475 Op == OO_Delete || Op == OO_Array_Delete)
3476 return false;
3477
3478 // C++ [over.oper]p6:
3479 // An operator function shall either be a non-static member
3480 // function or be a non-member function and have at least one
3481 // parameter whose type is a class, a reference to a class, an
3482 // enumeration, or a reference to an enumeration.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003483 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
3484 if (MethodDecl->isStatic())
3485 return Diag(FnDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00003486 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00003487 } else {
3488 bool ClassOrEnumParam = false;
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003489 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
3490 ParamEnd = FnDecl->param_end();
3491 Param != ParamEnd; ++Param) {
3492 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedmana73d6b12009-06-27 05:59:59 +00003493 if (ParamType->isDependentType() || ParamType->isRecordType() ||
3494 ParamType->isEnumeralType()) {
Douglas Gregore60e5d32008-11-06 22:13:31 +00003495 ClassOrEnumParam = true;
3496 break;
3497 }
3498 }
3499
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003500 if (!ClassOrEnumParam)
3501 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003502 diag::err_operator_overload_needs_class_or_enum)
Chris Lattner271d4c22008-11-24 05:29:24 +00003503 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00003504 }
3505
3506 // C++ [over.oper]p8:
3507 // An operator function cannot have default arguments (8.3.6),
3508 // except where explicitly stated below.
3509 //
3510 // Only the function-call operator allows default arguments
3511 // (C++ [over.call]p1).
3512 if (Op != OO_Call) {
3513 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
3514 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +00003515 if ((*Param)->hasUnparsedDefaultArg())
3516 return Diag((*Param)->getLocation(),
3517 diag::err_operator_overload_default_arg)
3518 << FnDecl->getDeclName();
3519 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003520 return Diag((*Param)->getLocation(),
Chris Lattner77d52da2008-11-20 06:06:08 +00003521 diag::err_operator_overload_default_arg)
Chris Lattner271d4c22008-11-24 05:29:24 +00003522 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregore60e5d32008-11-06 22:13:31 +00003523 }
3524 }
3525
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003526 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
3527 { false, false, false }
3528#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3529 , { Unary, Binary, MemberOnly }
3530#include "clang/Basic/OperatorKinds.def"
3531 };
Douglas Gregore60e5d32008-11-06 22:13:31 +00003532
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003533 bool CanBeUnaryOperator = OperatorUses[Op][0];
3534 bool CanBeBinaryOperator = OperatorUses[Op][1];
3535 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregore60e5d32008-11-06 22:13:31 +00003536
3537 // C++ [over.oper]p8:
3538 // [...] Operator functions cannot have more or fewer parameters
3539 // than the number required for the corresponding operator, as
3540 // described in the rest of this subclause.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003541 unsigned NumParams = FnDecl->getNumParams()
3542 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregore60e5d32008-11-06 22:13:31 +00003543 if (Op != OO_Call &&
3544 ((NumParams == 1 && !CanBeUnaryOperator) ||
3545 (NumParams == 2 && !CanBeBinaryOperator) ||
3546 (NumParams < 1) || (NumParams > 2))) {
3547 // We have the wrong number of parameters.
Chris Lattnerbb002332008-11-21 07:57:12 +00003548 unsigned ErrorKind;
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003549 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00003550 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003551 } else if (CanBeUnaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00003552 ErrorKind = 0; // 0 -> unary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003553 } else {
Chris Lattnera7021ee2008-11-21 07:50:02 +00003554 assert(CanBeBinaryOperator &&
3555 "All non-call overloaded operators are unary or binary!");
Chris Lattnerbb002332008-11-21 07:57:12 +00003556 ErrorKind = 1; // 1 -> binary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003557 }
Douglas Gregore60e5d32008-11-06 22:13:31 +00003558
Chris Lattnerbb002332008-11-21 07:57:12 +00003559 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattner271d4c22008-11-24 05:29:24 +00003560 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregore60e5d32008-11-06 22:13:31 +00003561 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003562
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003563 // Overloaded operators other than operator() cannot be variadic.
3564 if (Op != OO_Call &&
Douglas Gregor4fa58902009-02-26 23:50:07 +00003565 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003566 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattner271d4c22008-11-24 05:29:24 +00003567 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00003568 }
3569
3570 // Some operators must be non-static member functions.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003571 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
3572 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003573 diag::err_operator_overload_must_be_member)
Chris Lattner271d4c22008-11-24 05:29:24 +00003574 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00003575 }
3576
3577 // C++ [over.inc]p1:
3578 // The user-defined function called operator++ implements the
3579 // prefix and postfix ++ operator. If this function is a member
3580 // function with no parameters, or a non-member function with one
3581 // parameter of class or enumeration type, it defines the prefix
3582 // increment operator ++ for objects of that type. If the function
3583 // is a member function with one parameter (which shall be of type
3584 // int) or a non-member function with two parameters (the second
3585 // of which shall be of type int), it defines the postfix
3586 // increment operator ++ for objects of that type.
3587 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
3588 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
3589 bool ParamIsInt = false;
3590 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
3591 ParamIsInt = BT->getKind() == BuiltinType::Int;
3592
Chris Lattnera7021ee2008-11-21 07:50:02 +00003593 if (!ParamIsInt)
3594 return Diag(LastParam->getLocation(),
3595 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003596 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregore60e5d32008-11-06 22:13:31 +00003597 }
3598
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003599 // Notify the class if it got an assignment operator.
3600 if (Op == OO_Equal) {
3601 // Would have returned earlier otherwise.
3602 assert(isa<CXXMethodDecl>(FnDecl) &&
3603 "Overloaded = not member, but not filtered.");
3604 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Fariborz Jahanian9da58e42009-08-13 21:09:41 +00003605 Method->setCopyAssignment(true);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003606 Method->getParent()->addedAssignmentOperator(Context, Method);
3607 }
3608
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003609 return false;
Douglas Gregore60e5d32008-11-06 22:13:31 +00003610}
Chris Lattnerf58d52b2008-12-17 07:09:26 +00003611
Douglas Gregord8028382009-01-05 19:45:36 +00003612/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
3613/// linkage specification, including the language and (if present)
3614/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
3615/// the location of the language string literal, which is provided
3616/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
3617/// the '{' brace. Otherwise, this linkage specification does not
3618/// have any braces.
Chris Lattner5261d0c2009-03-28 19:18:32 +00003619Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
3620 SourceLocation ExternLoc,
3621 SourceLocation LangLoc,
3622 const char *Lang,
3623 unsigned StrSize,
3624 SourceLocation LBraceLoc) {
Chris Lattner9bb9abf2008-12-17 07:13:27 +00003625 LinkageSpecDecl::LanguageIDs Language;
3626 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3627 Language = LinkageSpecDecl::lang_c;
3628 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3629 Language = LinkageSpecDecl::lang_cxx;
3630 else {
Douglas Gregord8028382009-01-05 19:45:36 +00003631 Diag(LangLoc, diag::err_bad_language);
Chris Lattner5261d0c2009-03-28 19:18:32 +00003632 return DeclPtrTy();
Chris Lattner9bb9abf2008-12-17 07:13:27 +00003633 }
3634
3635 // FIXME: Add all the various semantics of linkage specifications
3636
Douglas Gregord8028382009-01-05 19:45:36 +00003637 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
3638 LangLoc, Language,
3639 LBraceLoc.isValid());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003640 CurContext->addDecl(D);
Douglas Gregord8028382009-01-05 19:45:36 +00003641 PushDeclContext(S, D);
Chris Lattner5261d0c2009-03-28 19:18:32 +00003642 return DeclPtrTy::make(D);
Chris Lattner9bb9abf2008-12-17 07:13:27 +00003643}
3644
Douglas Gregord8028382009-01-05 19:45:36 +00003645/// ActOnFinishLinkageSpecification - Completely the definition of
3646/// the C++ linkage specification LinkageSpec. If RBraceLoc is
3647/// valid, it's the position of the closing '}' brace in a linkage
3648/// specification that uses braces.
Chris Lattner5261d0c2009-03-28 19:18:32 +00003649Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
3650 DeclPtrTy LinkageSpec,
3651 SourceLocation RBraceLoc) {
Douglas Gregord8028382009-01-05 19:45:36 +00003652 if (LinkageSpec)
3653 PopDeclContext();
3654 return LinkageSpec;
Chris Lattnerf58d52b2008-12-17 07:09:26 +00003655}
3656
Douglas Gregor57420b42009-05-18 20:51:54 +00003657/// \brief Perform semantic analysis for the variable declaration that
3658/// occurs within a C++ catch clause, returning the newly-created
3659/// variable.
3660VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00003661 DeclaratorInfo *DInfo,
Douglas Gregor57420b42009-05-18 20:51:54 +00003662 IdentifierInfo *Name,
3663 SourceLocation Loc,
3664 SourceRange Range) {
3665 bool Invalid = false;
Sebastian Redl743c8162008-12-22 19:15:10 +00003666
3667 // Arrays and functions decay.
3668 if (ExDeclType->isArrayType())
3669 ExDeclType = Context.getArrayDecayedType(ExDeclType);
3670 else if (ExDeclType->isFunctionType())
3671 ExDeclType = Context.getPointerType(ExDeclType);
3672
3673 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
3674 // The exception-declaration shall not denote a pointer or reference to an
3675 // incomplete type, other than [cv] void*.
Sebastian Redl8a8b3512009-03-22 23:49:27 +00003676 // N2844 forbids rvalue references.
Douglas Gregor3b7e9112009-05-18 21:08:14 +00003677 if(!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor57420b42009-05-18 20:51:54 +00003678 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00003679 Invalid = true;
3680 }
Douglas Gregor57420b42009-05-18 20:51:54 +00003681
Sebastian Redl743c8162008-12-22 19:15:10 +00003682 QualType BaseType = ExDeclType;
3683 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003684 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003685 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl743c8162008-12-22 19:15:10 +00003686 BaseType = Ptr->getPointeeType();
3687 Mode = 1;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003688 DK = diag::err_catch_incomplete_ptr;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003689 } else if(const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00003690 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl743c8162008-12-22 19:15:10 +00003691 BaseType = Ref->getPointeeType();
3692 Mode = 2;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003693 DK = diag::err_catch_incomplete_ref;
Sebastian Redl743c8162008-12-22 19:15:10 +00003694 }
Sebastian Redl8a8b3512009-03-22 23:49:27 +00003695 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor57420b42009-05-18 20:51:54 +00003696 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl743c8162008-12-22 19:15:10 +00003697 Invalid = true;
Sebastian Redl743c8162008-12-22 19:15:10 +00003698
Douglas Gregor57420b42009-05-18 20:51:54 +00003699 if (!Invalid && !ExDeclType->isDependentType() &&
3700 RequireNonAbstractType(Loc, ExDeclType,
3701 diag::err_abstract_type_in_decl,
3702 AbstractVariableType))
Sebastian Redl54198652009-04-27 21:03:30 +00003703 Invalid = true;
3704
Douglas Gregor57420b42009-05-18 20:51:54 +00003705 // FIXME: Need to test for ability to copy-construct and destroy the
3706 // exception variable.
3707
Sebastian Redl237116b2008-12-22 21:35:02 +00003708 // FIXME: Need to check for abstract classes.
3709
Douglas Gregor57420b42009-05-18 20:51:54 +00003710 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argiris Kirtzidis42556e42009-08-21 00:31:54 +00003711 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregor57420b42009-05-18 20:51:54 +00003712
3713 if (Invalid)
3714 ExDecl->setInvalidDecl();
3715
3716 return ExDecl;
3717}
3718
3719/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
3720/// handler.
3721Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00003722 DeclaratorInfo *DInfo = 0;
3723 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor57420b42009-05-18 20:51:54 +00003724
3725 bool Invalid = D.isInvalidType();
Sebastian Redl743c8162008-12-22 19:15:10 +00003726 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor09be81b2009-02-04 17:27:36 +00003727 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl743c8162008-12-22 19:15:10 +00003728 // The scope should be freshly made just for us. There is just no way
3729 // it contains any previous declaration.
Chris Lattner5261d0c2009-03-28 19:18:32 +00003730 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl743c8162008-12-22 19:15:10 +00003731 if (PrevDecl->isTemplateParameter()) {
3732 // Maybe we will complain about the shadowed template parameter.
3733 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl743c8162008-12-22 19:15:10 +00003734 }
3735 }
3736
Chris Lattner34c61332009-04-25 08:06:05 +00003737 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl743c8162008-12-22 19:15:10 +00003738 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
3739 << D.getCXXScopeSpec().getRange();
Chris Lattner34c61332009-04-25 08:06:05 +00003740 Invalid = true;
Sebastian Redl743c8162008-12-22 19:15:10 +00003741 }
3742
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00003743 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregor57420b42009-05-18 20:51:54 +00003744 D.getIdentifier(),
3745 D.getIdentifierLoc(),
3746 D.getDeclSpec().getSourceRange());
3747
Chris Lattner34c61332009-04-25 08:06:05 +00003748 if (Invalid)
3749 ExDecl->setInvalidDecl();
3750
Sebastian Redl743c8162008-12-22 19:15:10 +00003751 // Add the exception declaration into this scope.
Sebastian Redl743c8162008-12-22 19:15:10 +00003752 if (II)
Douglas Gregor57420b42009-05-18 20:51:54 +00003753 PushOnScopeChains(ExDecl, S);
3754 else
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003755 CurContext->addDecl(ExDecl);
Sebastian Redl743c8162008-12-22 19:15:10 +00003756
Douglas Gregor2a2e0402009-06-17 21:51:59 +00003757 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner5261d0c2009-03-28 19:18:32 +00003758 return DeclPtrTy::make(ExDecl);
Sebastian Redl743c8162008-12-22 19:15:10 +00003759}
Anders Carlssoned691562009-03-14 00:25:26 +00003760
Chris Lattner5261d0c2009-03-28 19:18:32 +00003761Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
3762 ExprArg assertexpr,
3763 ExprArg assertmessageexpr) {
Anders Carlssoned691562009-03-14 00:25:26 +00003764 Expr *AssertExpr = (Expr *)assertexpr.get();
3765 StringLiteral *AssertMessage =
3766 cast<StringLiteral>((Expr *)assertmessageexpr.get());
3767
Anders Carlsson8b842c52009-03-14 00:33:21 +00003768 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
3769 llvm::APSInt Value(32);
3770 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
3771 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
3772 AssertExpr->getSourceRange();
Chris Lattner5261d0c2009-03-28 19:18:32 +00003773 return DeclPtrTy();
Anders Carlsson8b842c52009-03-14 00:33:21 +00003774 }
Anders Carlssoned691562009-03-14 00:25:26 +00003775
Anders Carlsson8b842c52009-03-14 00:33:21 +00003776 if (Value == 0) {
3777 std::string str(AssertMessage->getStrData(),
3778 AssertMessage->getByteLength());
Anders Carlssonc45057a2009-03-15 18:44:04 +00003779 Diag(AssertLoc, diag::err_static_assert_failed)
3780 << str << AssertExpr->getSourceRange();
Anders Carlsson8b842c52009-03-14 00:33:21 +00003781 }
3782 }
3783
Anders Carlsson0f4942b2009-03-15 17:35:16 +00003784 assertexpr.release();
3785 assertmessageexpr.release();
Anders Carlssoned691562009-03-14 00:25:26 +00003786 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
3787 AssertExpr, AssertMessage);
Anders Carlssoned691562009-03-14 00:25:26 +00003788
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003789 CurContext->addDecl(Decl);
Chris Lattner5261d0c2009-03-28 19:18:32 +00003790 return DeclPtrTy::make(Decl);
Anders Carlssoned691562009-03-14 00:25:26 +00003791}
Sebastian Redla8cecf62009-03-24 22:27:57 +00003792
John McCall140607b2009-08-06 02:15:43 +00003793Sema::DeclPtrTy Sema::ActOnFriendDecl(Scope *S,
John McCall36493082009-08-11 06:59:38 +00003794 llvm::PointerUnion<const DeclSpec*,Declarator*> DU,
3795 bool IsDefinition) {
John McCall7de15912009-08-28 07:59:38 +00003796 if (DU.is<Declarator*>())
3797 return ActOnFriendFunctionDecl(S, *DU.get<Declarator*>(), IsDefinition);
3798 else
3799 return ActOnFriendTypeDecl(S, *DU.get<const DeclSpec*>(), IsDefinition);
3800}
3801
3802Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S,
3803 const DeclSpec &DS,
3804 bool IsDefinition) {
3805 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall140607b2009-08-06 02:15:43 +00003806
3807 assert(DS.isFriendSpecified());
3808 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
3809
John McCall7de15912009-08-28 07:59:38 +00003810 // Check to see if the decl spec was syntactically like "struct foo".
3811 RecordDecl *RD = NULL;
John McCall140607b2009-08-06 02:15:43 +00003812
John McCall7de15912009-08-28 07:59:38 +00003813 switch (DS.getTypeSpecType()) {
3814 case DeclSpec::TST_class:
3815 case DeclSpec::TST_struct:
3816 case DeclSpec::TST_union:
3817 RD = dyn_cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep());
3818 if (!RD) return DeclPtrTy();
John McCall140607b2009-08-06 02:15:43 +00003819
John McCall7de15912009-08-28 07:59:38 +00003820 // The parser doesn't quite handle
3821 // friend class A {}
3822 // as we'd like, because it might have been the (valid) prefix of
3823 // friend class A {} foo();
3824 // So even in C++0x mode we don't want to
3825 IsDefinition |= RD->isDefinition();
3826 break;
John McCall140607b2009-08-06 02:15:43 +00003827
John McCall7de15912009-08-28 07:59:38 +00003828 default: break;
Anders Carlssonb56d8b32009-05-11 22:55:49 +00003829 }
John McCall140607b2009-08-06 02:15:43 +00003830
John McCall7de15912009-08-28 07:59:38 +00003831 FriendDecl::FriendUnion FU = RD;
John McCall140607b2009-08-06 02:15:43 +00003832
John McCall7de15912009-08-28 07:59:38 +00003833 // C++ [class.friend]p2:
3834 // An elaborated-type-specifier shall be used in a friend declaration
3835 // for a class.*
3836 // * The class-key of the elaborated-type-specifier is required.
3837 // So if we didn't get a record decl above, we're invalid in C++98 mode.
3838 if (!RD) {
3839 bool invalid = false;
3840 QualType T = ConvertDeclSpecToType(DS, Loc, invalid);
3841 if (invalid) return DeclPtrTy();
3842
3843 if (const RecordType *RT = T->getAs<RecordType>()) {
3844 FU = RD = cast<CXXRecordDecl>(RT->getDecl());
3845
3846 // Untagged typenames are invalid prior to C++0x, but we can
3847 // suggest an easy fix which should work.
3848 if (!getLangOptions().CPlusPlus0x) {
3849 Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type)
3850 << (RD->isUnion())
3851 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
3852 RD->isUnion() ? " union" : " class");
3853 return DeclPtrTy();
3854 }
3855 }else if (!getLangOptions().CPlusPlus0x) {
3856 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
3857 << DS.getSourceRange();
3858 return DeclPtrTy();
3859 }else {
3860 FU = T.getTypePtr();
3861 }
3862 }
3863
3864 assert(FU && "should have a friend decl/type by here!");
3865
3866 // C++ [class.friend]p2: A class shall not be defined inside
3867 // a friend declaration.
3868 if (IsDefinition) {
3869 Diag(DS.getFriendSpecLoc(), diag::err_friend_decl_defines_class)
3870 << DS.getSourceRange();
3871 return DeclPtrTy();
3872 }
3873
3874 // C++98 [class.friend]p1: A friend of a class is a function
3875 // or class that is not a member of the class . . .
3876 // But that's a silly restriction which nobody implements for
3877 // inner classes, and C++0x removes it anyway, so we only report
3878 // this (as a warning) if we're being pedantic.
3879 if (!getLangOptions().CPlusPlus0x) {
3880 assert(RD && "must have a record decl in C++98 mode");
3881 if (RD->getDeclContext() == CurContext)
3882 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
3883 }
3884
3885 FriendDecl *FD = FriendDecl::Create(Context, CurContext, Loc, FU,
3886 DS.getFriendSpecLoc());
John McCall73e4dbc2009-08-29 03:50:18 +00003887 FD->setAccess(AS_public);
John McCall7de15912009-08-28 07:59:38 +00003888 CurContext->addDecl(FD);
3889
3890 return DeclPtrTy::make(FD);
3891}
3892
3893Sema::DeclPtrTy Sema::ActOnFriendFunctionDecl(Scope *S,
3894 Declarator &D,
3895 bool IsDefinition) {
3896 const DeclSpec &DS = D.getDeclSpec();
3897
3898 assert(DS.isFriendSpecified());
3899 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
3900
3901 SourceLocation Loc = D.getIdentifierLoc();
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00003902 DeclaratorInfo *DInfo = 0;
John McCall7de15912009-08-28 07:59:38 +00003903 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall140607b2009-08-06 02:15:43 +00003904
3905 // C++ [class.friend]p1
3906 // A friend of a class is a function or class....
3907 // Note that this sees through typedefs, which is intended.
John McCall7de15912009-08-28 07:59:38 +00003908 // It *doesn't* see through dependent types, which is correct
3909 // according to [temp.arg.type]p3:
3910 // If a declaration acquires a function type through a
3911 // type dependent on a template-parameter and this causes
3912 // a declaration that does not use the syntactic form of a
3913 // function declarator to have a function type, the program
3914 // is ill-formed.
John McCall140607b2009-08-06 02:15:43 +00003915 if (!T->isFunctionType()) {
3916 Diag(Loc, diag::err_unexpected_friend);
3917
3918 // It might be worthwhile to try to recover by creating an
3919 // appropriate declaration.
3920 return DeclPtrTy();
3921 }
3922
3923 // C++ [namespace.memdef]p3
3924 // - If a friend declaration in a non-local class first declares a
3925 // class or function, the friend class or function is a member
3926 // of the innermost enclosing namespace.
3927 // - The name of the friend is not found by simple name lookup
3928 // until a matching declaration is provided in that namespace
3929 // scope (either before or after the class declaration granting
3930 // friendship).
3931 // - If a friend function is called, its name may be found by the
3932 // name lookup that considers functions from namespaces and
3933 // classes associated with the types of the function arguments.
3934 // - When looking for a prior declaration of a class or a function
3935 // declared as a friend, scopes outside the innermost enclosing
3936 // namespace scope are not considered.
3937
John McCall7de15912009-08-28 07:59:38 +00003938 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
3939 DeclarationName Name = GetNameForDeclarator(D);
John McCall140607b2009-08-06 02:15:43 +00003940 assert(Name);
3941
3942 // The existing declaration we found.
3943 FunctionDecl *FD = NULL;
3944
3945 // The context we found the declaration in, or in which we should
3946 // create the declaration.
3947 DeclContext *DC;
3948
3949 // FIXME: handle local classes
3950
3951 // Recover from invalid scope qualifiers as if they just weren't there.
3952 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
3953 DC = computeDeclContext(ScopeQual);
3954
3955 // FIXME: handle dependent contexts
3956 if (!DC) return DeclPtrTy();
3957
3958 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
3959
3960 // If searching in that context implicitly found a declaration in
3961 // a different context, treat it like it wasn't found at all.
3962 // TODO: better diagnostics for this case. Suggesting the right
3963 // qualified scope would be nice...
3964 if (!Dec || Dec->getDeclContext() != DC) {
John McCall7de15912009-08-28 07:59:38 +00003965 D.setInvalidType();
John McCall140607b2009-08-06 02:15:43 +00003966 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
3967 return DeclPtrTy();
3968 }
3969
3970 // C++ [class.friend]p1: A friend of a class is a function or
3971 // class that is not a member of the class . . .
3972 if (DC == CurContext)
3973 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
3974
3975 FD = cast<FunctionDecl>(Dec);
3976
3977 // Otherwise walk out to the nearest namespace scope looking for matches.
3978 } else {
3979 // TODO: handle local class contexts.
3980
3981 DC = CurContext;
3982 while (true) {
3983 // Skip class contexts. If someone can cite chapter and verse
3984 // for this behavior, that would be nice --- it's what GCC and
3985 // EDG do, and it seems like a reasonable intent, but the spec
3986 // really only says that checks for unqualified existing
3987 // declarations should stop at the nearest enclosing namespace,
3988 // not that they should only consider the nearest enclosing
3989 // namespace.
3990 while (DC->isRecord()) DC = DC->getParent();
3991
3992 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
3993
3994 // TODO: decide what we think about using declarations.
3995 if (Dec) {
3996 FD = cast<FunctionDecl>(Dec);
3997 break;
3998 }
3999 if (DC->isFileContext()) break;
4000 DC = DC->getParent();
4001 }
4002
4003 // C++ [class.friend]p1: A friend of a class is a function or
4004 // class that is not a member of the class . . .
John McCall392245a2009-08-06 20:49:32 +00004005 // C++0x changes this for both friend types and functions.
4006 // Most C++ 98 compilers do seem to give an error here, so
4007 // we do, too.
4008 if (FD && DC == CurContext && !getLangOptions().CPlusPlus0x)
John McCall140607b2009-08-06 02:15:43 +00004009 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4010 }
4011
John McCall36493082009-08-11 06:59:38 +00004012 bool Redeclaration = (FD != 0);
4013
4014 // If we found a match, create a friend function declaration with
4015 // that function as the previous declaration.
4016 if (Redeclaration) {
4017 // Create it in the semantic context of the original declaration.
4018 DC = FD->getDeclContext();
4019
John McCall140607b2009-08-06 02:15:43 +00004020 // If we didn't find something matching the type exactly, create
4021 // a declaration. This declaration should only be findable via
4022 // argument-dependent lookup.
John McCall36493082009-08-11 06:59:38 +00004023 } else {
John McCall140607b2009-08-06 02:15:43 +00004024 assert(DC->isFileContext());
4025
4026 // This implies that it has to be an operator or function.
John McCall7de15912009-08-28 07:59:38 +00004027 if (D.getKind() == Declarator::DK_Constructor ||
4028 D.getKind() == Declarator::DK_Destructor ||
4029 D.getKind() == Declarator::DK_Conversion) {
John McCall140607b2009-08-06 02:15:43 +00004030 Diag(Loc, diag::err_introducing_special_friend) <<
John McCall7de15912009-08-28 07:59:38 +00004031 (D.getKind() == Declarator::DK_Constructor ? 0 :
4032 D.getKind() == Declarator::DK_Destructor ? 1 : 2);
John McCall140607b2009-08-06 02:15:43 +00004033 return DeclPtrTy();
4034 }
John McCall140607b2009-08-06 02:15:43 +00004035 }
4036
John McCall7de15912009-08-28 07:59:38 +00004037 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo,
John McCall36493082009-08-11 06:59:38 +00004038 /* PrevDecl = */ FD,
4039 MultiTemplateParamsArg(*this),
4040 IsDefinition,
4041 Redeclaration);
John McCall7de15912009-08-28 07:59:38 +00004042 if (!ND) return DeclPtrTy();
John McCallea7c7ce2009-08-31 22:39:49 +00004043
4044 assert(cast<FunctionDecl>(ND)->getPreviousDeclaration() == FD &&
4045 "lost reference to previous declaration");
4046
John McCall7de15912009-08-28 07:59:38 +00004047 FD = cast<FunctionDecl>(ND);
John McCall36493082009-08-11 06:59:38 +00004048
John McCallbcee9272009-08-18 00:00:49 +00004049 assert(FD->getDeclContext() == DC);
4050 assert(FD->getLexicalDeclContext() == CurContext);
4051
John McCallea7c7ce2009-08-31 22:39:49 +00004052 // Add the function declaration to the appropriate lookup tables,
4053 // adjusting the redeclarations list as necessary. We don't
4054 // want to do this yet if the friending class is dependent.
4055 //
4056 // Also update the scope-based lookup if the target context's
4057 // lookup context is in lexical scope.
4058 if (!CurContext->isDependentContext()) {
4059 DC = DC->getLookupContext();
4060 DC->makeDeclVisibleInContext(FD, /* Recoverable=*/ false);
4061 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4062 PushOnScopeChains(FD, EnclosingScope, /*AddToContext=*/ false);
4063 }
John McCall7de15912009-08-28 07:59:38 +00004064
4065 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
4066 D.getIdentifierLoc(), FD,
4067 DS.getFriendSpecLoc());
John McCall73e4dbc2009-08-29 03:50:18 +00004068 FrD->setAccess(AS_public);
John McCall7de15912009-08-28 07:59:38 +00004069 CurContext->addDecl(FrD);
John McCall140607b2009-08-06 02:15:43 +00004070
4071 return DeclPtrTy::make(FD);
Anders Carlssonb56d8b32009-05-11 22:55:49 +00004072}
4073
Chris Lattner5261d0c2009-03-28 19:18:32 +00004074void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregor84164f02009-08-24 11:57:43 +00004075 AdjustDeclIfTemplate(dcl);
4076
Chris Lattner5261d0c2009-03-28 19:18:32 +00004077 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redla8cecf62009-03-24 22:27:57 +00004078 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4079 if (!Fn) {
4080 Diag(DelLoc, diag::err_deleted_non_function);
4081 return;
4082 }
4083 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4084 Diag(DelLoc, diag::err_deleted_decl_not_first);
4085 Diag(Prev->getLocation(), diag::note_previous_declaration);
4086 // If the declaration wasn't the first, we delete the function anyway for
4087 // recovery.
4088 }
4089 Fn->setDeleted();
4090}
Sebastian Redl3b1ef312009-04-27 21:33:24 +00004091
4092static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4093 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4094 ++CI) {
4095 Stmt *SubStmt = *CI;
4096 if (!SubStmt)
4097 continue;
4098 if (isa<ReturnStmt>(SubStmt))
4099 Self.Diag(SubStmt->getSourceRange().getBegin(),
4100 diag::err_return_in_constructor_handler);
4101 if (!isa<Expr>(SubStmt))
4102 SearchForReturnInStmt(Self, SubStmt);
4103 }
4104}
4105
4106void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4107 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4108 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4109 SearchForReturnInStmt(*this, Handler);
4110 }
4111}
Anders Carlssone80e29c2009-05-14 01:09:04 +00004112
4113bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
4114 const CXXMethodDecl *Old) {
4115 QualType NewTy = New->getType()->getAsFunctionType()->getResultType();
4116 QualType OldTy = Old->getType()->getAsFunctionType()->getResultType();
4117
4118 QualType CNewTy = Context.getCanonicalType(NewTy);
4119 QualType COldTy = Context.getCanonicalType(OldTy);
4120
4121 if (CNewTy == COldTy &&
4122 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
4123 return false;
4124
Anders Carlssonee7177b2009-05-14 19:52:19 +00004125 // Check if the return types are covariant
4126 QualType NewClassTy, OldClassTy;
4127
4128 /// Both types must be pointers or references to classes.
4129 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4130 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4131 NewClassTy = NewPT->getPointeeType();
4132 OldClassTy = OldPT->getPointeeType();
4133 }
4134 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4135 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4136 NewClassTy = NewRT->getPointeeType();
4137 OldClassTy = OldRT->getPointeeType();
4138 }
4139 }
4140
4141 // The return types aren't either both pointers or references to a class type.
4142 if (NewClassTy.isNull()) {
4143 Diag(New->getLocation(),
4144 diag::err_different_return_type_for_overriding_virtual_function)
4145 << New->getDeclName() << NewTy << OldTy;
4146 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4147
4148 return true;
4149 }
Anders Carlssone80e29c2009-05-14 01:09:04 +00004150
Anders Carlssonee7177b2009-05-14 19:52:19 +00004151 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
4152 // Check if the new class derives from the old class.
4153 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4154 Diag(New->getLocation(),
4155 diag::err_covariant_return_not_derived)
4156 << New->getDeclName() << NewTy << OldTy;
4157 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4158 return true;
4159 }
4160
4161 // Check if we the conversion from derived to base is valid.
4162 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
4163 diag::err_covariant_return_inaccessible_base,
4164 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4165 // FIXME: Should this point to the return type?
4166 New->getLocation(), SourceRange(), New->getDeclName())) {
4167 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4168 return true;
4169 }
4170 }
4171
4172 // The qualifiers of the return types must be the same.
4173 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
4174 Diag(New->getLocation(),
4175 diag::err_covariant_return_type_different_qualifications)
Anders Carlssone80e29c2009-05-14 01:09:04 +00004176 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonee7177b2009-05-14 19:52:19 +00004177 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4178 return true;
4179 };
4180
4181
4182 // The new class type must have the same or less qualifiers as the old type.
4183 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4184 Diag(New->getLocation(),
4185 diag::err_covariant_return_type_class_type_more_qualified)
4186 << New->getDeclName() << NewTy << OldTy;
4187 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4188 return true;
4189 };
4190
4191 return false;
Anders Carlssone80e29c2009-05-14 01:09:04 +00004192}
Argiris Kirtzidis68370592009-06-17 22:50:06 +00004193
Sebastian Redl953d12a2009-07-07 20:29:57 +00004194bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
4195 const CXXMethodDecl *Old)
4196{
4197 return CheckExceptionSpecSubset(diag::err_override_exception_spec,
4198 diag::note_overridden_virtual_function,
4199 Old->getType()->getAsFunctionProtoType(),
4200 Old->getLocation(),
4201 New->getType()->getAsFunctionProtoType(),
4202 New->getLocation());
4203}
4204
Argiris Kirtzidis68370592009-06-17 22:50:06 +00004205/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4206/// initializer for the declaration 'Dcl'.
4207/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4208/// static data member of class X, names should be looked up in the scope of
4209/// class X.
4210void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregor84164f02009-08-24 11:57:43 +00004211 AdjustDeclIfTemplate(Dcl);
4212
Argiris Kirtzidis68370592009-06-17 22:50:06 +00004213 Decl *D = Dcl.getAs<Decl>();
4214 // If there is no declaration, there was an error parsing it.
4215 if (D == 0)
4216 return;
4217
4218 // Check whether it is a declaration with a nested name specifier like
4219 // int foo::bar;
4220 if (!D->isOutOfLine())
4221 return;
4222
4223 // C++ [basic.lookup.unqual]p13
4224 //
4225 // A name used in the definition of a static data member of class X
4226 // (after the qualified-id of the static member) is looked up as if the name
4227 // was used in a member function of X.
4228
4229 // Change current context into the context of the initializing declaration.
Argiris Kirtzidisa0b19fe2009-06-17 23:15:40 +00004230 EnterDeclaratorContext(S, D->getDeclContext());
Argiris Kirtzidis68370592009-06-17 22:50:06 +00004231}
4232
4233/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4234/// initializer for the declaration 'Dcl'.
4235void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregor84164f02009-08-24 11:57:43 +00004236 AdjustDeclIfTemplate(Dcl);
4237
Argiris Kirtzidis68370592009-06-17 22:50:06 +00004238 Decl *D = Dcl.getAs<Decl>();
4239 // If there is no declaration, there was an error parsing it.
4240 if (D == 0)
4241 return;
4242
4243 // Check whether it is a declaration with a nested name specifier like
4244 // int foo::bar;
4245 if (!D->isOutOfLine())
4246 return;
4247
4248 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argiris Kirtzidisa0b19fe2009-06-17 23:15:40 +00004249 ExitDeclaratorContext(S);
Argiris Kirtzidis68370592009-06-17 22:50:06 +00004250}