blob: 9e30af8f18789098ebe4cc0381f0b27be8c97602 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000019#include "clang/AST/RecordLayout.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000022#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000023#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000025#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000030#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000031#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000032
33using namespace clang;
34
Chris Lattner8123a952008-04-10 02:22:51 +000035//===----------------------------------------------------------------------===//
36// CheckDefaultArgumentVisitor
37//===----------------------------------------------------------------------===//
38
Chris Lattner9e979552008-04-12 23:52:44 +000039namespace {
40 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
41 /// the default argument of a parameter to determine whether it
42 /// contains any ill-formed subexpressions. For example, this will
43 /// diagnose the use of local variables or parameters within the
44 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000045 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000046 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000047 Expr *DefaultArg;
48 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000049
Chris Lattner9e979552008-04-12 23:52:44 +000050 public:
Mike Stump1eb44332009-09-09 15:08:12 +000051 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000052 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 bool VisitExpr(Expr *Node);
55 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000056 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000057 };
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-04-12 23:52:44 +000059 /// VisitExpr - Visit all of the children of this expression.
60 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
61 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000062 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000063 E = Node->child_end(); I != E; ++I)
64 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000065 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000066 }
67
Chris Lattner9e979552008-04-12 23:52:44 +000068 /// VisitDeclRefExpr - Visit a reference to a declaration, to
69 /// determine whether this declaration can be used in the default
70 /// argument expression.
71 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000072 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000073 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
74 // C++ [dcl.fct.default]p9
75 // Default arguments are evaluated each time the function is
76 // called. The order of evaluation of function arguments is
77 // unspecified. Consequently, parameters of a function shall not
78 // be used in default argument expressions, even if they are not
79 // evaluated. Parameters of a function declared before a default
80 // argument expression are in scope and can hide namespace and
81 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000082 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000083 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000084 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000085 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000086 // C++ [dcl.fct.default]p7
87 // Local variables shall not be used in default argument
88 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000089 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000090 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000092 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000093 }
Chris Lattner8123a952008-04-10 02:22:51 +000094
Douglas Gregor3996f232008-11-04 13:41:56 +000095 return false;
96 }
Chris Lattner9e979552008-04-12 23:52:44 +000097
Douglas Gregor796da182008-11-04 14:32:21 +000098 /// VisitCXXThisExpr - Visit a C++ "this" expression.
99 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
100 // C++ [dcl.fct.default]p8:
101 // The keyword this shall not be used in a default argument of a
102 // member function.
103 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_this)
105 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000106 }
Chris Lattner8123a952008-04-10 02:22:51 +0000107}
108
Anders Carlssoned961f92009-08-25 02:29:20 +0000109bool
110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000111 SourceLocation EqualLoc) {
Anders Carlssoned961f92009-08-25 02:29:20 +0000112 QualType ParamType = Param->getType();
113
Anders Carlsson5653ca52009-08-25 13:46:13 +0000114 if (RequireCompleteType(Param->getLocation(), Param->getType(),
115 diag::err_typecheck_decl_incomplete_type)) {
116 Param->setInvalidDecl();
117 return true;
118 }
119
Anders Carlssoned961f92009-08-25 02:29:20 +0000120 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Anders Carlssoned961f92009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Douglas Gregor99a2e602009-12-16 01:38:02 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
129 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
130 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000131 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
132 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
133 MultiExprArg(*this, (void**)&Arg, 1));
134 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000135 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000136 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000137
Anders Carlsson0ece4912009-12-15 20:51:39 +0000138 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Anders Carlssoned961f92009-08-25 02:29:20 +0000140 // Okay: add the default argument to the parameter
141 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Anders Carlssoned961f92009-08-25 02:29:20 +0000143 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Anders Carlsson9351c172009-08-25 03:18:48 +0000145 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000146}
147
Chris Lattner8123a952008-04-10 02:22:51 +0000148/// ActOnParamDefaultArgument - Check whether the default argument
149/// provided for a function parameter is well-formed. If so, attach it
150/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000151void
Mike Stump1eb44332009-09-09 15:08:12 +0000152Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000153 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000154 if (!param || !defarg.get())
155 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000156
Chris Lattnerb28317a2009-03-28 19:18:32 +0000157 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000158 UnparsedDefaultArgLocs.erase(Param);
159
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000160 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000161 QualType ParamType = Param->getType();
162
163 // Default arguments are only permitted in C++
164 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000165 Diag(EqualLoc, diag::err_param_default_argument)
166 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000167 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000168 return;
169 }
170
Anders Carlsson66e30672009-08-25 01:02:06 +0000171 // Check that the default argument is well-formed
172 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
173 if (DefaultArgChecker.Visit(DefaultArg.get())) {
174 Param->setInvalidDecl();
175 return;
176 }
Mike Stump1eb44332009-09-09 15:08:12 +0000177
Anders Carlssoned961f92009-08-25 02:29:20 +0000178 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000179}
180
Douglas Gregor61366e92008-12-24 00:01:03 +0000181/// ActOnParamUnparsedDefaultArgument - We've seen a default
182/// argument for a function parameter, but we can't parse it yet
183/// because we're inside a class definition. Note that this default
184/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000185void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000186 SourceLocation EqualLoc,
187 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000188 if (!param)
189 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Chris Lattnerb28317a2009-03-28 19:18:32 +0000191 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000192 if (Param)
193 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Anders Carlsson5e300d12009-06-12 16:51:40 +0000195 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000196}
197
Douglas Gregor72b505b2008-12-16 21:30:33 +0000198/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
199/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000200void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000201 if (!param)
202 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Anders Carlsson5e300d12009-06-12 16:51:40 +0000204 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000205
Anders Carlsson5e300d12009-06-12 16:51:40 +0000206 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000207
Anders Carlsson5e300d12009-06-12 16:51:40 +0000208 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000209}
210
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000211/// CheckExtraCXXDefaultArguments - Check for any extra default
212/// arguments in the declarator, which is not a function declaration
213/// or definition and therefore is not permitted to have default
214/// arguments. This routine should be invoked for every declarator
215/// that is not a function declaration or definition.
216void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
217 // C++ [dcl.fct.default]p3
218 // A default argument expression shall be specified only in the
219 // parameter-declaration-clause of a function declaration or in a
220 // template-parameter (14.1). It shall not be specified for a
221 // parameter pack. If it is specified in a
222 // parameter-declaration-clause, it shall not occur within a
223 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000224 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000225 DeclaratorChunk &chunk = D.getTypeObject(i);
226 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000227 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
228 ParmVarDecl *Param =
229 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000230 if (Param->hasUnparsedDefaultArg()) {
231 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000232 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
233 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
234 delete Toks;
235 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000236 } else if (Param->getDefaultArg()) {
237 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
238 << Param->getDefaultArg()->getSourceRange();
239 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000240 }
241 }
242 }
243 }
244}
245
Chris Lattner3d1cee32008-04-08 05:04:30 +0000246// MergeCXXFunctionDecl - Merge two declarations of the same C++
247// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000248// type. Subroutine of MergeFunctionDecl. Returns true if there was an
249// error, false otherwise.
250bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
251 bool Invalid = false;
252
Chris Lattner3d1cee32008-04-08 05:04:30 +0000253 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000254 // For non-template functions, default arguments can be added in
255 // later declarations of a function in the same
256 // scope. Declarations in different scopes have completely
257 // distinct sets of default arguments. That is, declarations in
258 // inner scopes do not acquire default arguments from
259 // declarations in outer scopes, and vice versa. In a given
260 // function declaration, all parameters subsequent to a
261 // parameter with a default argument shall have default
262 // arguments supplied in this or previous declarations. A
263 // default argument shall not be redefined by a later
264 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000265 //
266 // C++ [dcl.fct.default]p6:
267 // Except for member functions of class templates, the default arguments
268 // in a member function definition that appears outside of the class
269 // definition are added to the set of default arguments provided by the
270 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000271 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
272 ParmVarDecl *OldParam = Old->getParamDecl(p);
273 ParmVarDecl *NewParam = New->getParamDecl(p);
274
Douglas Gregor6cc15182009-09-11 18:44:32 +0000275 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Anders Carlssonad26b732009-11-10 03:24:44 +0000276 // FIXME: If the parameter doesn't have an identifier then the location
277 // points to the '=' which means that the fixit hint won't remove any
278 // extra spaces between the type and the '='.
279 SourceLocation Begin = NewParam->getLocation();
Anders Carlsson4881b992009-11-10 03:32:44 +0000280 if (NewParam->getIdentifier())
281 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlssonad26b732009-11-10 03:24:44 +0000282
Mike Stump1eb44332009-09-09 15:08:12 +0000283 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000284 diag::err_param_default_argument_redefinition)
Anders Carlssonad26b732009-11-10 03:24:44 +0000285 << NewParam->getDefaultArgRange()
286 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
287 NewParam->getLocEnd()));
Douglas Gregor6cc15182009-09-11 18:44:32 +0000288
289 // Look for the function declaration where the default argument was
290 // actually written, which may be a declaration prior to Old.
291 for (FunctionDecl *Older = Old->getPreviousDeclaration();
292 Older; Older = Older->getPreviousDeclaration()) {
293 if (!Older->getParamDecl(p)->hasDefaultArg())
294 break;
295
296 OldParam = Older->getParamDecl(p);
297 }
298
299 Diag(OldParam->getLocation(), diag::note_previous_definition)
300 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000301 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000302 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000303 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000304 if (OldParam->hasUninstantiatedDefaultArg())
305 NewParam->setUninstantiatedDefaultArg(
306 OldParam->getUninstantiatedDefaultArg());
307 else
308 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000309 } else if (NewParam->hasDefaultArg()) {
310 if (New->getDescribedFunctionTemplate()) {
311 // Paragraph 4, quoted above, only applies to non-template functions.
312 Diag(NewParam->getLocation(),
313 diag::err_param_default_argument_template_redecl)
314 << NewParam->getDefaultArgRange();
315 Diag(Old->getLocation(), diag::note_template_prev_declaration)
316 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000317 } else if (New->getTemplateSpecializationKind()
318 != TSK_ImplicitInstantiation &&
319 New->getTemplateSpecializationKind() != TSK_Undeclared) {
320 // C++ [temp.expr.spec]p21:
321 // Default function arguments shall not be specified in a declaration
322 // or a definition for one of the following explicit specializations:
323 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000324 // - the explicit specialization of a member function template;
325 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000326 // template where the class template specialization to which the
327 // member function specialization belongs is implicitly
328 // instantiated.
329 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
330 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
331 << New->getDeclName()
332 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000333 } else if (New->getDeclContext()->isDependentContext()) {
334 // C++ [dcl.fct.default]p6 (DR217):
335 // Default arguments for a member function of a class template shall
336 // be specified on the initial declaration of the member function
337 // within the class template.
338 //
339 // Reading the tea leaves a bit in DR217 and its reference to DR205
340 // leads me to the conclusion that one cannot add default function
341 // arguments for an out-of-line definition of a member function of a
342 // dependent type.
343 int WhichKind = 2;
344 if (CXXRecordDecl *Record
345 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
346 if (Record->getDescribedClassTemplate())
347 WhichKind = 0;
348 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
349 WhichKind = 1;
350 else
351 WhichKind = 2;
352 }
353
354 Diag(NewParam->getLocation(),
355 diag::err_param_default_argument_member_template_redecl)
356 << WhichKind
357 << NewParam->getDefaultArgRange();
358 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000359 }
360 }
361
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000362 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000363 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000364 New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000365 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000366
Douglas Gregorcda9c672009-02-16 17:45:42 +0000367 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000368}
369
370/// CheckCXXDefaultArguments - Verify that the default arguments for a
371/// function declaration are well-formed according to C++
372/// [dcl.fct.default].
373void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
374 unsigned NumParams = FD->getNumParams();
375 unsigned p;
376
377 // Find first parameter with a default argument
378 for (p = 0; p < NumParams; ++p) {
379 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000380 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000381 break;
382 }
383
384 // C++ [dcl.fct.default]p4:
385 // In a given function declaration, all parameters
386 // subsequent to a parameter with a default argument shall
387 // have default arguments supplied in this or previous
388 // declarations. A default argument shall not be redefined
389 // by a later declaration (not even to the same value).
390 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000391 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000392 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000393 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000394 if (Param->isInvalidDecl())
395 /* We already complained about this parameter. */;
396 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000397 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000398 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000399 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000400 else
Mike Stump1eb44332009-09-09 15:08:12 +0000401 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000402 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Chris Lattner3d1cee32008-04-08 05:04:30 +0000404 LastMissingDefaultArg = p;
405 }
406 }
407
408 if (LastMissingDefaultArg > 0) {
409 // Some default arguments were missing. Clear out all of the
410 // default arguments up to (and including) the last missing
411 // default argument, so that we leave the function parameters
412 // in a semantically valid state.
413 for (p = 0; p <= LastMissingDefaultArg; ++p) {
414 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000415 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000416 if (!Param->hasUnparsedDefaultArg())
417 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000418 Param->setDefaultArg(0);
419 }
420 }
421 }
422}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000423
Douglas Gregorb48fe382008-10-31 09:07:45 +0000424/// isCurrentClassName - Determine whether the identifier II is the
425/// name of the class type currently being defined. In the case of
426/// nested classes, this will only return true if II is the name of
427/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000428bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
429 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000430 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000431 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000432 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000433 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
434 } else
435 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
436
437 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000438 return &II == CurDecl->getIdentifier();
439 else
440 return false;
441}
442
Mike Stump1eb44332009-09-09 15:08:12 +0000443/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000444///
445/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
446/// and returns NULL otherwise.
447CXXBaseSpecifier *
448Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
449 SourceRange SpecifierRange,
450 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000451 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000452 SourceLocation BaseLoc) {
453 // C++ [class.union]p1:
454 // A union shall not have base classes.
455 if (Class->isUnion()) {
456 Diag(Class->getLocation(), diag::err_base_clause_on_union)
457 << SpecifierRange;
458 return 0;
459 }
460
461 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000462 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000463 Class->getTagKind() == RecordDecl::TK_class,
464 Access, BaseType);
465
466 // Base specifiers must be record types.
467 if (!BaseType->isRecordType()) {
468 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
469 return 0;
470 }
471
472 // C++ [class.union]p1:
473 // A union shall not be used as a base class.
474 if (BaseType->isUnionType()) {
475 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
476 return 0;
477 }
478
479 // C++ [class.derived]p2:
480 // The class-name in a base-specifier shall not be an incompletely
481 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000482 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000483 PDiag(diag::err_incomplete_base_class)
484 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000485 return 0;
486
Eli Friedman1d954f62009-08-15 21:55:26 +0000487 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000488 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000489 assert(BaseDecl && "Record type has no declaration");
490 BaseDecl = BaseDecl->getDefinition(Context);
491 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000492 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
493 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000494
Sean Huntbbd37c62009-11-21 08:43:09 +0000495 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
496 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
497 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000498 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
499 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000500 return 0;
501 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000502
Eli Friedmand0137332009-12-05 23:03:49 +0000503 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlsson51f94042009-12-03 17:49:57 +0000504
505 // Create the base specifier.
506 // FIXME: Allocate via ASTContext?
507 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
508 Class->getTagKind() == RecordDecl::TK_class,
509 Access, BaseType);
510}
511
512void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
513 const CXXRecordDecl *BaseClass,
514 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000515 // A class with a non-empty base class is not empty.
516 // FIXME: Standard ref?
517 if (!BaseClass->isEmpty())
518 Class->setEmpty(false);
519
520 // C++ [class.virtual]p1:
521 // A class that [...] inherits a virtual function is called a polymorphic
522 // class.
523 if (BaseClass->isPolymorphic())
524 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000525
Douglas Gregor2943aed2009-03-03 04:44:36 +0000526 // C++ [dcl.init.aggr]p1:
527 // An aggregate is [...] a class with [...] no base classes [...].
528 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000529
530 // C++ [class]p4:
531 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000532 Class->setPOD(false);
533
Anders Carlsson51f94042009-12-03 17:49:57 +0000534 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000535 // C++ [class.ctor]p5:
536 // A constructor is trivial if its class has no virtual base classes.
537 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000538
539 // C++ [class.copy]p6:
540 // A copy constructor is trivial if its class has no virtual base classes.
541 Class->setHasTrivialCopyConstructor(false);
542
543 // C++ [class.copy]p11:
544 // A copy assignment operator is trivial if its class has no virtual
545 // base classes.
546 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000547
548 // C++0x [meta.unary.prop] is_empty:
549 // T is a class type, but not a union type, with ... no virtual base
550 // classes
551 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000552 } else {
553 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000554 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000555 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000556 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000557 Class->setHasTrivialConstructor(false);
558
559 // C++ [class.copy]p6:
560 // A copy constructor is trivial if all the direct base classes of its
561 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000562 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000563 Class->setHasTrivialCopyConstructor(false);
564
565 // C++ [class.copy]p11:
566 // A copy assignment operator is trivial if all the direct base classes
567 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000568 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000569 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000570 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000571
572 // C++ [class.ctor]p3:
573 // A destructor is trivial if all the direct base classes of its class
574 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000575 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000576 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000577}
578
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000579/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
580/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000581/// example:
582/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000583/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000584Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000585Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000586 bool Virtual, AccessSpecifier Access,
587 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000588 if (!classdecl)
589 return true;
590
Douglas Gregor40808ce2009-03-09 23:48:35 +0000591 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000592 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000593 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000594 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
595 Virtual, Access,
596 BaseType, BaseLoc))
597 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000598
Douglas Gregor2943aed2009-03-03 04:44:36 +0000599 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000600}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000601
Douglas Gregor2943aed2009-03-03 04:44:36 +0000602/// \brief Performs the actual work of attaching the given base class
603/// specifiers to a C++ class.
604bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
605 unsigned NumBases) {
606 if (NumBases == 0)
607 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000608
609 // Used to keep track of which base types we have already seen, so
610 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000611 // that the key is always the unqualified canonical type of the base
612 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000613 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
614
615 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000616 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000617 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000618 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000619 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000620 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000621 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000622
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000623 if (KnownBaseTypes[NewBaseType]) {
624 // C++ [class.mi]p3:
625 // A class shall not be specified as a direct base class of a
626 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000628 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000629 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000630 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000631
632 // Delete the duplicate base class specifier; we're going to
633 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000634 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000635
636 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000637 } else {
638 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000639 KnownBaseTypes[NewBaseType] = Bases[idx];
640 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000641 }
642 }
643
644 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000645 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000646
647 // Delete the remaining (good) base class specifiers, since their
648 // data has been copied into the CXXRecordDecl.
649 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000650 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000651
652 return Invalid;
653}
654
655/// ActOnBaseSpecifiers - Attach the given base specifiers to the
656/// class, after checking whether there are any duplicate base
657/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000658void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000659 unsigned NumBases) {
660 if (!ClassDecl || !Bases || !NumBases)
661 return;
662
663 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000664 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000665 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000666}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000667
Douglas Gregora8f32e02009-10-06 17:59:45 +0000668/// \brief Determine whether the type \p Derived is a C++ class that is
669/// derived from the type \p Base.
670bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
671 if (!getLangOptions().CPlusPlus)
672 return false;
673
674 const RecordType *DerivedRT = Derived->getAs<RecordType>();
675 if (!DerivedRT)
676 return false;
677
678 const RecordType *BaseRT = Base->getAs<RecordType>();
679 if (!BaseRT)
680 return false;
681
682 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
683 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
684 return DerivedRD->isDerivedFrom(BaseRD);
685}
686
687/// \brief Determine whether the type \p Derived is a C++ class that is
688/// derived from the type \p Base.
689bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
690 if (!getLangOptions().CPlusPlus)
691 return false;
692
693 const RecordType *DerivedRT = Derived->getAs<RecordType>();
694 if (!DerivedRT)
695 return false;
696
697 const RecordType *BaseRT = Base->getAs<RecordType>();
698 if (!BaseRT)
699 return false;
700
701 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
702 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
703 return DerivedRD->isDerivedFrom(BaseRD, Paths);
704}
705
706/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
707/// conversion (where Derived and Base are class types) is
708/// well-formed, meaning that the conversion is unambiguous (and
709/// that all of the base classes are accessible). Returns true
710/// and emits a diagnostic if the code is ill-formed, returns false
711/// otherwise. Loc is the location where this routine should point to
712/// if there is an error, and Range is the source range to highlight
713/// if there is an error.
714bool
715Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
716 unsigned InaccessibleBaseID,
717 unsigned AmbigiousBaseConvID,
718 SourceLocation Loc, SourceRange Range,
719 DeclarationName Name) {
720 // First, determine whether the path from Derived to Base is
721 // ambiguous. This is slightly more expensive than checking whether
722 // the Derived to Base conversion exists, because here we need to
723 // explore multiple paths to determine if there is an ambiguity.
724 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
725 /*DetectVirtual=*/false);
726 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
727 assert(DerivationOkay &&
728 "Can only be used with a derived-to-base conversion");
729 (void)DerivationOkay;
730
731 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000732 if (InaccessibleBaseID == 0)
733 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000734 // Check that the base class can be accessed.
735 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
736 Name);
737 }
738
739 // We know that the derived-to-base conversion is ambiguous, and
740 // we're going to produce a diagnostic. Perform the derived-to-base
741 // search just one more time to compute all of the possible paths so
742 // that we can print them out. This is more expensive than any of
743 // the previous derived-to-base checks we've done, but at this point
744 // performance isn't as much of an issue.
745 Paths.clear();
746 Paths.setRecordingPaths(true);
747 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
748 assert(StillOkay && "Can only be used with a derived-to-base conversion");
749 (void)StillOkay;
750
751 // Build up a textual representation of the ambiguous paths, e.g.,
752 // D -> B -> A, that will be used to illustrate the ambiguous
753 // conversions in the diagnostic. We only print one of the paths
754 // to each base class subobject.
755 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
756
757 Diag(Loc, AmbigiousBaseConvID)
758 << Derived << Base << PathDisplayStr << Range << Name;
759 return true;
760}
761
762bool
763Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000764 SourceLocation Loc, SourceRange Range,
765 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000766 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000767 IgnoreAccess ? 0 :
768 diag::err_conv_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000769 diag::err_ambiguous_derived_to_base_conv,
770 Loc, Range, DeclarationName());
771}
772
773
774/// @brief Builds a string representing ambiguous paths from a
775/// specific derived class to different subobjects of the same base
776/// class.
777///
778/// This function builds a string that can be used in error messages
779/// to show the different paths that one can take through the
780/// inheritance hierarchy to go from the derived class to different
781/// subobjects of a base class. The result looks something like this:
782/// @code
783/// struct D -> struct B -> struct A
784/// struct D -> struct C -> struct A
785/// @endcode
786std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
787 std::string PathDisplayStr;
788 std::set<unsigned> DisplayedPaths;
789 for (CXXBasePaths::paths_iterator Path = Paths.begin();
790 Path != Paths.end(); ++Path) {
791 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
792 // We haven't displayed a path to this particular base
793 // class subobject yet.
794 PathDisplayStr += "\n ";
795 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
796 for (CXXBasePath::const_iterator Element = Path->begin();
797 Element != Path->end(); ++Element)
798 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
799 }
800 }
801
802 return PathDisplayStr;
803}
804
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000805//===----------------------------------------------------------------------===//
806// C++ class member Handling
807//===----------------------------------------------------------------------===//
808
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000809/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
810/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
811/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000812/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000813Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000814Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000815 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000816 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
817 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000818 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000819 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000820 Expr *BitWidth = static_cast<Expr*>(BW);
821 Expr *Init = static_cast<Expr*>(InitExpr);
822 SourceLocation Loc = D.getIdentifierLoc();
823
Sebastian Redl669d5d72008-11-14 23:42:31 +0000824 bool isFunc = D.isFunctionDeclarator();
825
John McCall67d1a672009-08-06 02:15:43 +0000826 assert(!DS.isFriendSpecified());
827
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000828 // C++ 9.2p6: A member shall not be declared to have automatic storage
829 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000830 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
831 // data members and cannot be applied to names declared const or static,
832 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000833 switch (DS.getStorageClassSpec()) {
834 case DeclSpec::SCS_unspecified:
835 case DeclSpec::SCS_typedef:
836 case DeclSpec::SCS_static:
837 // FALL THROUGH.
838 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000839 case DeclSpec::SCS_mutable:
840 if (isFunc) {
841 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000842 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000843 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000844 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Sebastian Redla11f42f2008-11-17 23:24:37 +0000846 // FIXME: It would be nicer if the keyword was ignored only for this
847 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000848 D.getMutableDeclSpec().ClearStorageClassSpecs();
849 } else {
850 QualType T = GetTypeForDeclarator(D, S);
851 diag::kind err = static_cast<diag::kind>(0);
852 if (T->isReferenceType())
853 err = diag::err_mutable_reference;
854 else if (T.isConstQualified())
855 err = diag::err_mutable_const;
856 if (err != 0) {
857 if (DS.getStorageClassSpecLoc().isValid())
858 Diag(DS.getStorageClassSpecLoc(), err);
859 else
860 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000861 // FIXME: It would be nicer if the keyword was ignored only for this
862 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000863 D.getMutableDeclSpec().ClearStorageClassSpecs();
864 }
865 }
866 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000867 default:
868 if (DS.getStorageClassSpecLoc().isValid())
869 Diag(DS.getStorageClassSpecLoc(),
870 diag::err_storageclass_invalid_for_member);
871 else
872 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
873 D.getMutableDeclSpec().ClearStorageClassSpecs();
874 }
875
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000876 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000877 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000878 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000879 // Check also for this case:
880 //
881 // typedef int f();
882 // f a;
883 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000884 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000885 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000886 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000887
Sebastian Redl669d5d72008-11-14 23:42:31 +0000888 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
889 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000890 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000891
892 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000893 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000894 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000895 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
896 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000897 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000898 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000899 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000900 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000901 if (!Member) {
902 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000903 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000904 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000905
906 // Non-instance-fields can't have a bitfield.
907 if (BitWidth) {
908 if (Member->isInvalidDecl()) {
909 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000910 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000911 // C++ 9.6p3: A bit-field shall not be a static member.
912 // "static member 'A' cannot be a bit-field"
913 Diag(Loc, diag::err_static_not_bitfield)
914 << Name << BitWidth->getSourceRange();
915 } else if (isa<TypedefDecl>(Member)) {
916 // "typedef member 'x' cannot be a bit-field"
917 Diag(Loc, diag::err_typedef_not_bitfield)
918 << Name << BitWidth->getSourceRange();
919 } else {
920 // A function typedef ("typedef int f(); f a;").
921 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
922 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000923 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000924 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000925 }
Mike Stump1eb44332009-09-09 15:08:12 +0000926
Chris Lattner8b963ef2009-03-05 23:01:03 +0000927 DeleteExpr(BitWidth);
928 BitWidth = 0;
929 Member->setInvalidDecl();
930 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000931
932 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000933
Douglas Gregor37b372b2009-08-20 22:52:58 +0000934 // If we have declared a member function template, set the access of the
935 // templated declaration as well.
936 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
937 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000938 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000939
Douglas Gregor10bd3682008-11-17 22:58:34 +0000940 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000941
Douglas Gregor021c3b32009-03-11 23:00:04 +0000942 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000943 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000944 if (Deleted) // FIXME: Source location is not very good.
945 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000946
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000947 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000948 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000949 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000950 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000951 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000952}
953
Douglas Gregor7ad83902008-11-05 04:29:56 +0000954/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000955Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000956Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000957 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000958 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000959 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000960 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000961 SourceLocation IdLoc,
962 SourceLocation LParenLoc,
963 ExprTy **Args, unsigned NumArgs,
964 SourceLocation *CommaLocs,
965 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000966 if (!ConstructorD)
967 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000969 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +0000970
971 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000972 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000973 if (!Constructor) {
974 // The user wrote a constructor initializer on a function that is
975 // not a C++ constructor. Ignore the error for now, because we may
976 // have more member initializers coming; we'll diagnose it just
977 // once in ActOnMemInitializers.
978 return true;
979 }
980
981 CXXRecordDecl *ClassDecl = Constructor->getParent();
982
983 // C++ [class.base.init]p2:
984 // Names in a mem-initializer-id are looked up in the scope of the
985 // constructor’s class and, if not found in that scope, are looked
986 // up in the scope containing the constructor’s
987 // definition. [Note: if the constructor’s class contains a member
988 // with the same name as a direct or virtual base class of the
989 // class, a mem-initializer-id naming the member or base class and
990 // composed of a single identifier refers to the class member. A
991 // mem-initializer-id for the hidden base class may be specified
992 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000993 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000994 // Look for a member, first.
995 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000996 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000997 = ClassDecl->lookup(MemberOrBase);
998 if (Result.first != Result.second)
999 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001000
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001001 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001002
Eli Friedman59c04372009-07-29 19:44:27 +00001003 if (Member)
1004 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001005 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001006 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001007 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001008 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001009 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001010
1011 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001012 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001013 } else {
1014 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1015 LookupParsedName(R, S, &SS);
1016
1017 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1018 if (!TyD) {
1019 if (R.isAmbiguous()) return true;
1020
1021 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1022 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1023 return true;
1024 }
1025
1026 BaseType = Context.getTypeDeclType(TyD);
1027 if (SS.isSet()) {
1028 NestedNameSpecifier *Qualifier =
1029 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1030
1031 // FIXME: preserve source range information
1032 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1033 }
1034 }
Mike Stump1eb44332009-09-09 15:08:12 +00001035
John McCalla93c9342009-12-07 02:54:59 +00001036 if (!TInfo)
1037 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001038
John McCalla93c9342009-12-07 02:54:59 +00001039 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001040 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001041}
1042
John McCallb4190042009-11-04 23:02:40 +00001043/// Checks an initializer expression for use of uninitialized fields, such as
1044/// containing the field that is being initialized. Returns true if there is an
1045/// uninitialized field was used an updates the SourceLocation parameter; false
1046/// otherwise.
1047static bool InitExprContainsUninitializedFields(const Stmt* S,
1048 const FieldDecl* LhsField,
1049 SourceLocation* L) {
1050 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1051 if (ME) {
1052 const NamedDecl* RhsField = ME->getMemberDecl();
1053 if (RhsField == LhsField) {
1054 // Initializing a field with itself. Throw a warning.
1055 // But wait; there are exceptions!
1056 // Exception #1: The field may not belong to this record.
1057 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1058 const Expr* base = ME->getBase();
1059 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1060 // Even though the field matches, it does not belong to this record.
1061 return false;
1062 }
1063 // None of the exceptions triggered; return true to indicate an
1064 // uninitialized field was used.
1065 *L = ME->getMemberLoc();
1066 return true;
1067 }
1068 }
1069 bool found = false;
1070 for (Stmt::const_child_iterator it = S->child_begin();
1071 it != S->child_end() && found == false;
1072 ++it) {
1073 if (isa<CallExpr>(S)) {
1074 // Do not descend into function calls or constructors, as the use
1075 // of an uninitialized field may be valid. One would have to inspect
1076 // the contents of the function/ctor to determine if it is safe or not.
1077 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1078 // may be safe, depending on what the function/ctor does.
1079 continue;
1080 }
1081 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1082 }
1083 return found;
1084}
1085
Eli Friedman59c04372009-07-29 19:44:27 +00001086Sema::MemInitResult
1087Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1088 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001089 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001090 SourceLocation RParenLoc) {
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001091 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1092 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1093 ExprTemporaries.clear();
1094
John McCallb4190042009-11-04 23:02:40 +00001095 // Diagnose value-uses of fields to initialize themselves, e.g.
1096 // foo(foo)
1097 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001098 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001099 for (unsigned i = 0; i < NumArgs; ++i) {
1100 SourceLocation L;
1101 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1102 // FIXME: Return true in the case when other fields are used before being
1103 // uninitialized. For example, let this field be the i'th field. When
1104 // initializing the i'th field, throw a warning if any of the >= i'th
1105 // fields are used, as they are not yet initialized.
1106 // Right now we are only handling the case where the i'th field uses
1107 // itself in its initializer.
1108 Diag(L, diag::warn_field_is_uninit);
1109 }
1110 }
1111
Eli Friedman59c04372009-07-29 19:44:27 +00001112 bool HasDependentArg = false;
1113 for (unsigned i = 0; i < NumArgs; i++)
1114 HasDependentArg |= Args[i]->isTypeDependent();
1115
1116 CXXConstructorDecl *C = 0;
1117 QualType FieldType = Member->getType();
1118 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1119 FieldType = Array->getElementType();
1120 if (FieldType->isDependentType()) {
1121 // Can't check init for dependent type.
John McCall6aee6212009-11-04 23:13:52 +00001122 } else if (FieldType->isRecordType()) {
1123 // Member is a record (struct/union/class), so pass the initializer
1124 // arguments down to the record's constructor.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001125 if (!HasDependentArg) {
1126 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1127
1128 C = PerformInitializationByConstructor(FieldType,
1129 MultiExprArg(*this,
1130 (void**)Args,
1131 NumArgs),
1132 IdLoc,
1133 SourceRange(IdLoc, RParenLoc),
Douglas Gregor20093b42009-12-09 23:02:17 +00001134 Member->getDeclName(),
1135 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001136 ConstructorArgs);
1137
1138 if (C) {
1139 // Take over the constructor arguments as our own.
1140 NumArgs = ConstructorArgs.size();
1141 Args = (Expr **)ConstructorArgs.take();
1142 }
1143 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001144 } else if (NumArgs != 1 && NumArgs != 0) {
John McCall6aee6212009-11-04 23:13:52 +00001145 // The member type is not a record type (or an array of record
1146 // types), so it can be only be default- or copy-initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00001147 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +00001148 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1149 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001150 Expr *NewExp;
1151 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001152 if (FieldType->isReferenceType()) {
1153 Diag(IdLoc, diag::err_null_intialized_reference_member)
1154 << Member->getDeclName();
1155 return Diag(Member->getLocation(), diag::note_declared_at);
1156 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001157 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1158 NumArgs = 1;
1159 }
1160 else
1161 NewExp = (Expr*)Args[0];
Douglas Gregor68647482009-12-16 03:45:30 +00001162 if (PerformCopyInitialization(NewExp, FieldType, AA_Passing))
Eli Friedman59c04372009-07-29 19:44:27 +00001163 return true;
1164 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +00001165 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001166
1167 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1168 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1169 ExprTemporaries.clear();
1170
Eli Friedman59c04372009-07-29 19:44:27 +00001171 // FIXME: Perform direct initialization of the member.
Douglas Gregor802ab452009-12-02 22:36:29 +00001172 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1173 C, LParenLoc, (Expr **)Args,
1174 NumArgs, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001175}
1176
1177Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001178Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001179 Expr **Args, unsigned NumArgs,
1180 SourceLocation LParenLoc, SourceLocation RParenLoc,
1181 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001182 bool HasDependentArg = false;
1183 for (unsigned i = 0; i < NumArgs; i++)
1184 HasDependentArg |= Args[i]->isTypeDependent();
1185
John McCalla93c9342009-12-07 02:54:59 +00001186 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Eli Friedman59c04372009-07-29 19:44:27 +00001187 if (!BaseType->isDependentType()) {
1188 if (!BaseType->isRecordType())
Douglas Gregor802ab452009-12-02 22:36:29 +00001189 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
John McCalla93c9342009-12-07 02:54:59 +00001190 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00001191
1192 // C++ [class.base.init]p2:
1193 // [...] Unless the mem-initializer-id names a nonstatic data
1194 // member of the constructor’s class or a direct or virtual base
1195 // of that class, the mem-initializer is ill-formed. A
1196 // mem-initializer-list can initialize a base class using any
1197 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Eli Friedman59c04372009-07-29 19:44:27 +00001199 // First, check for a direct base class.
1200 const CXXBaseSpecifier *DirectBaseSpec = 0;
1201 for (CXXRecordDecl::base_class_const_iterator Base =
1202 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00001203 if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
Eli Friedman59c04372009-07-29 19:44:27 +00001204 // We found a direct base of this type. That's what we're
1205 // initializing.
1206 DirectBaseSpec = &*Base;
1207 break;
1208 }
1209 }
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Eli Friedman59c04372009-07-29 19:44:27 +00001211 // Check for a virtual base class.
1212 // FIXME: We might be able to short-circuit this if we know in advance that
1213 // there are no virtual bases.
1214 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1215 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1216 // We haven't found a base yet; search the class hierarchy for a
1217 // virtual base class.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001218 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1219 /*DetectVirtual=*/false);
Eli Friedman59c04372009-07-29 19:44:27 +00001220 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001221 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +00001222 Path != Paths.end(); ++Path) {
1223 if (Path->back().Base->isVirtual()) {
1224 VirtualBaseSpec = Path->back().Base;
1225 break;
1226 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001227 }
1228 }
1229 }
Eli Friedman59c04372009-07-29 19:44:27 +00001230
1231 // C++ [base.class.init]p2:
1232 // If a mem-initializer-id is ambiguous because it designates both
1233 // a direct non-virtual base class and an inherited virtual base
1234 // class, the mem-initializer is ill-formed.
1235 if (DirectBaseSpec && VirtualBaseSpec)
Douglas Gregor802ab452009-12-02 22:36:29 +00001236 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
John McCalla93c9342009-12-07 02:54:59 +00001237 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00001238 // C++ [base.class.init]p2:
1239 // Unless the mem-initializer-id names a nonstatic data membeer of the
1240 // constructor's class ot a direst or virtual base of that class, the
1241 // mem-initializer is ill-formed.
1242 if (!DirectBaseSpec && !VirtualBaseSpec)
Douglas Gregor802ab452009-12-02 22:36:29 +00001243 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1244 << BaseType << ClassDecl->getNameAsCString()
John McCalla93c9342009-12-07 02:54:59 +00001245 << BaseTInfo->getTypeLoc().getSourceRange();
Douglas Gregor7ad83902008-11-05 04:29:56 +00001246 }
1247
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +00001248 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +00001249 if (!BaseType->isDependentType() && !HasDependentArg) {
1250 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3eaa9ff2009-11-08 07:12:55 +00001251 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor39da0b82009-09-09 23:08:42 +00001252 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1253
1254 C = PerformInitializationByConstructor(BaseType,
1255 MultiExprArg(*this,
1256 (void**)Args, NumArgs),
Douglas Gregor802ab452009-12-02 22:36:29 +00001257 BaseLoc,
1258 SourceRange(BaseLoc, RParenLoc),
Douglas Gregor20093b42009-12-09 23:02:17 +00001259 Name,
1260 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001261 ConstructorArgs);
1262 if (C) {
1263 // Take over the constructor arguments as our own.
1264 NumArgs = ConstructorArgs.size();
1265 Args = (Expr **)ConstructorArgs.take();
1266 }
Eli Friedman59c04372009-07-29 19:44:27 +00001267 }
1268
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001269 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1270 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1271 ExprTemporaries.clear();
1272
John McCalla93c9342009-12-07 02:54:59 +00001273 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, C,
Douglas Gregor802ab452009-12-02 22:36:29 +00001274 LParenLoc, (Expr **)Args,
1275 NumArgs, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001276}
1277
Eli Friedman80c30da2009-11-09 19:20:36 +00001278bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001279Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001280 CXXBaseOrMemberInitializer **Initializers,
1281 unsigned NumInitializers,
Eli Friedman49c16da2009-11-09 01:05:47 +00001282 bool IsImplicitConstructor) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001283 // We need to build the initializer AST according to order of construction
1284 // and not what user specified in the Initializers list.
1285 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1286 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1287 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1288 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001289 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001291 for (unsigned i = 0; i < NumInitializers; i++) {
1292 CXXBaseOrMemberInitializer *Member = Initializers[i];
1293 if (Member->isBaseInitializer()) {
1294 if (Member->getBaseClass()->isDependentType())
1295 HasDependentBaseInit = true;
1296 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1297 } else {
1298 AllBaseFields[Member->getMember()] = Member;
1299 }
1300 }
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001302 if (HasDependentBaseInit) {
1303 // FIXME. This does not preserve the ordering of the initializers.
1304 // Try (with -Wreorder)
1305 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001306 // template<class X> struct B : A<X> {
1307 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001308 // int x1;
1309 // };
1310 // B<int> x;
1311 // On seeing one dependent type, we should essentially exit this routine
1312 // while preserving user-declared initializer list. When this routine is
1313 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001314 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001316 // If we have a dependent base initialization, we can't determine the
1317 // association between initializers and bases; just dump the known
1318 // initializers into the list, and don't try to deal with other bases.
1319 for (unsigned i = 0; i < NumInitializers; i++) {
1320 CXXBaseOrMemberInitializer *Member = Initializers[i];
1321 if (Member->isBaseInitializer())
1322 AllToInit.push_back(Member);
1323 }
1324 } else {
1325 // Push virtual bases before others.
1326 for (CXXRecordDecl::base_class_iterator VBase =
1327 ClassDecl->vbases_begin(),
1328 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1329 if (VBase->getType()->isDependentType())
1330 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001331 if (CXXBaseOrMemberInitializer *Value
1332 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001333 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001334 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001335 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001336 CXXRecordDecl *VBaseDecl =
Douglas Gregor802ab452009-12-02 22:36:29 +00001337 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001338 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001339 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001340 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001341 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1342 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1343 << 0 << VBase->getType();
Douglas Gregor9af2f522009-12-01 16:58:18 +00001344 Diag(VBaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001345 << Context.getTagDeclType(VBaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001346 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001347 continue;
1348 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001349
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001350 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1351 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1352 Constructor->getLocation(), CtorArgs))
1353 continue;
1354
1355 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1356
Anders Carlsson8db68da2009-11-13 20:11:49 +00001357 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregor802ab452009-12-02 22:36:29 +00001358 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1359 // necessary.
1360 // FIXME: Is there any better source-location information we can give?
Anders Carlsson8db68da2009-11-13 20:11:49 +00001361 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001362 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001363 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001364 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001365 SourceLocation()),
1366 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001367 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001368 CtorArgs.takeAs<Expr>(),
1369 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001370 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001371 AllToInit.push_back(Member);
1372 }
1373 }
Mike Stump1eb44332009-09-09 15:08:12 +00001374
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001375 for (CXXRecordDecl::base_class_iterator Base =
1376 ClassDecl->bases_begin(),
1377 E = ClassDecl->bases_end(); Base != E; ++Base) {
1378 // Virtuals are in the virtual base list and already constructed.
1379 if (Base->isVirtual())
1380 continue;
1381 // Skip dependent types.
1382 if (Base->getType()->isDependentType())
1383 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001384 if (CXXBaseOrMemberInitializer *Value
1385 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001386 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001387 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001388 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001389 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001390 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001391 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001392 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001393 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001394 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1395 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1396 << 0 << Base->getType();
Douglas Gregor9af2f522009-12-01 16:58:18 +00001397 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001398 << Context.getTagDeclType(BaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001399 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001400 continue;
1401 }
1402
1403 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1404 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1405 Constructor->getLocation(), CtorArgs))
1406 continue;
1407
1408 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001409
Anders Carlsson8db68da2009-11-13 20:11:49 +00001410 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregor802ab452009-12-02 22:36:29 +00001411 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1412 // necessary.
1413 // FIXME: Is there any better source-location information we can give?
Anders Carlsson8db68da2009-11-13 20:11:49 +00001414 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001415 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001416 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001417 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001418 SourceLocation()),
1419 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001420 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001421 CtorArgs.takeAs<Expr>(),
1422 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001423 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001424 AllToInit.push_back(Member);
1425 }
1426 }
1427 }
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001429 // non-static data members.
1430 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1431 E = ClassDecl->field_end(); Field != E; ++Field) {
1432 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001433 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001434 Field->getType()->getAs<RecordType>()) {
1435 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001436 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001437 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001438 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1439 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1440 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1441 // set to the anonymous union data member used in the initializer
1442 // list.
1443 Value->setMember(*Field);
1444 Value->setAnonUnionMember(*FA);
1445 AllToInit.push_back(Value);
1446 break;
1447 }
1448 }
1449 }
1450 continue;
1451 }
1452 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1453 AllToInit.push_back(Value);
1454 continue;
1455 }
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Eli Friedman49c16da2009-11-09 01:05:47 +00001457 if ((*Field)->getType()->isDependentType())
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001458 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001459
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001460 QualType FT = Context.getBaseElementType((*Field)->getType());
1461 if (const RecordType* RT = FT->getAs<RecordType>()) {
1462 CXXConstructorDecl *Ctor =
1463 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001464 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001465 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1466 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1467 << 1 << (*Field)->getDeclName();
1468 Diag(Field->getLocation(), diag::note_field_decl);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001469 Diag(RT->getDecl()->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001470 << Context.getTagDeclType(RT->getDecl());
Eli Friedman80c30da2009-11-09 19:20:36 +00001471 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001472 continue;
1473 }
Eli Friedmane73d3bc2009-11-16 23:07:59 +00001474
1475 if (FT.isConstQualified() && Ctor->isTrivial()) {
1476 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1477 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1478 << 1 << (*Field)->getDeclName();
1479 Diag((*Field)->getLocation(), diag::note_declared_at);
1480 HadError = true;
1481 }
1482
1483 // Don't create initializers for trivial constructors, since they don't
1484 // actually need to be run.
1485 if (Ctor->isTrivial())
1486 continue;
1487
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001488 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1489 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1490 Constructor->getLocation(), CtorArgs))
1491 continue;
1492
Anders Carlsson8db68da2009-11-13 20:11:49 +00001493 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1494 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1495 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001496 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001497 new (Context) CXXBaseOrMemberInitializer(Context,
1498 *Field, SourceLocation(),
1499 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001500 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001501 CtorArgs.takeAs<Expr>(),
1502 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001503 SourceLocation());
1504
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001505 AllToInit.push_back(Member);
Eli Friedman49c16da2009-11-09 01:05:47 +00001506 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001507 }
1508 else if (FT->isReferenceType()) {
1509 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001510 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1511 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001512 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001513 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001514 }
1515 else if (FT.isConstQualified()) {
1516 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001517 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1518 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001519 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001520 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001521 }
1522 }
Mike Stump1eb44332009-09-09 15:08:12 +00001523
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001524 NumInitializers = AllToInit.size();
1525 if (NumInitializers > 0) {
1526 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1527 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1528 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001530 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1531 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1532 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1533 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001534
1535 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001536}
1537
Eli Friedman6347f422009-07-21 19:28:10 +00001538static void *GetKeyForTopLevelField(FieldDecl *Field) {
1539 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001540 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001541 if (RT->getDecl()->isAnonymousStructOrUnion())
1542 return static_cast<void *>(RT->getDecl());
1543 }
1544 return static_cast<void *>(Field);
1545}
1546
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001547static void *GetKeyForBase(QualType BaseType) {
1548 if (const RecordType *RT = BaseType->getAs<RecordType>())
1549 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001550
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001551 assert(0 && "Unexpected base type!");
1552 return 0;
1553}
1554
Mike Stump1eb44332009-09-09 15:08:12 +00001555static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001556 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001557 // For fields injected into the class via declaration of an anonymous union,
1558 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001559 if (Member->isMemberInitializer()) {
1560 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Eli Friedman49c16da2009-11-09 01:05:47 +00001562 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001563 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001564 // in AnonUnionMember field.
1565 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1566 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001567 if (Field->getDeclContext()->isRecord()) {
1568 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1569 if (RD->isAnonymousStructOrUnion())
1570 return static_cast<void *>(RD);
1571 }
1572 return static_cast<void *>(Field);
1573 }
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001575 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001576}
1577
John McCall6aee6212009-11-04 23:13:52 +00001578/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001579void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001580 SourceLocation ColonLoc,
1581 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001582 if (!ConstructorDecl)
1583 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001584
1585 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001586
1587 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001588 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Anders Carlssona7b35212009-03-25 02:58:17 +00001590 if (!Constructor) {
1591 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1592 return;
1593 }
Mike Stump1eb44332009-09-09 15:08:12 +00001594
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001595 if (!Constructor->isDependentContext()) {
1596 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1597 bool err = false;
1598 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001599 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001600 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1601 void *KeyToMember = GetKeyForMember(Member);
1602 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1603 if (!PrevMember) {
1604 PrevMember = Member;
1605 continue;
1606 }
1607 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001608 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001609 diag::error_multiple_mem_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001610 << Field->getNameAsString()
1611 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001612 else {
1613 Type *BaseClass = Member->getBaseClass();
1614 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001615 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001616 diag::error_multiple_base_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001617 << QualType(BaseClass, 0)
1618 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001619 }
1620 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1621 << 0;
1622 err = true;
1623 }
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001625 if (err)
1626 return;
1627 }
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Eli Friedman49c16da2009-11-09 01:05:47 +00001629 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001630 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedman49c16da2009-11-09 01:05:47 +00001631 NumMemInits, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001633 if (Constructor->isDependentContext())
1634 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001635
1636 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001637 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001638 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001639 Diagnostic::Ignored)
1640 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001642 // Also issue warning if order of ctor-initializer list does not match order
1643 // of 1) base class declarations and 2) order of non-static data members.
1644 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001646 CXXRecordDecl *ClassDecl
1647 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1648 // Push virtual bases before others.
1649 for (CXXRecordDecl::base_class_iterator VBase =
1650 ClassDecl->vbases_begin(),
1651 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001652 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001654 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1655 E = ClassDecl->bases_end(); Base != E; ++Base) {
1656 // Virtuals are alread in the virtual base list and are constructed
1657 // first.
1658 if (Base->isVirtual())
1659 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001660 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001661 }
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001663 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1664 E = ClassDecl->field_end(); Field != E; ++Field)
1665 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001666
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001667 int Last = AllBaseOrMembers.size();
1668 int curIndex = 0;
1669 CXXBaseOrMemberInitializer *PrevMember = 0;
1670 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001671 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001672 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1673 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001674
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001675 for (; curIndex < Last; curIndex++)
1676 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1677 break;
1678 if (curIndex == Last) {
1679 assert(PrevMember && "Member not in member list?!");
1680 // Initializer as specified in ctor-initializer list is out of order.
1681 // Issue a warning diagnostic.
1682 if (PrevMember->isBaseInitializer()) {
1683 // Diagnostics is for an initialized base class.
1684 Type *BaseClass = PrevMember->getBaseClass();
1685 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001686 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001687 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001688 } else {
1689 FieldDecl *Field = PrevMember->getMember();
1690 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001691 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001692 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001693 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001694 // Also the note!
1695 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001696 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001697 diag::note_fieldorbase_initialized_here) << 0
1698 << Field->getNameAsString();
1699 else {
1700 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001701 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001702 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001703 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001704 }
1705 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001706 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001707 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001708 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001709 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001710 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001711}
1712
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001713void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001714Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1715 // Ignore dependent destructors.
1716 if (Destructor->isDependentContext())
1717 return;
1718
1719 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Anders Carlsson9f853df2009-11-17 04:44:12 +00001721 // Non-static data members.
1722 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1723 E = ClassDecl->field_end(); I != E; ++I) {
1724 FieldDecl *Field = *I;
1725
1726 QualType FieldType = Context.getBaseElementType(Field->getType());
1727
1728 const RecordType* RT = FieldType->getAs<RecordType>();
1729 if (!RT)
1730 continue;
1731
1732 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1733 if (FieldClassDecl->hasTrivialDestructor())
1734 continue;
1735
1736 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1737 MarkDeclarationReferenced(Destructor->getLocation(),
1738 const_cast<CXXDestructorDecl*>(Dtor));
1739 }
1740
1741 // Bases.
1742 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1743 E = ClassDecl->bases_end(); Base != E; ++Base) {
1744 // Ignore virtual bases.
1745 if (Base->isVirtual())
1746 continue;
1747
1748 // Ignore trivial destructors.
1749 CXXRecordDecl *BaseClassDecl
1750 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1751 if (BaseClassDecl->hasTrivialDestructor())
1752 continue;
1753
1754 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1755 MarkDeclarationReferenced(Destructor->getLocation(),
1756 const_cast<CXXDestructorDecl*>(Dtor));
1757 }
1758
1759 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001760 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1761 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001762 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001763 CXXRecordDecl *BaseClassDecl
1764 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1765 if (BaseClassDecl->hasTrivialDestructor())
1766 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001767
1768 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1769 MarkDeclarationReferenced(Destructor->getLocation(),
1770 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001771 }
1772}
1773
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001774void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001775 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001776 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001777
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001778 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001779
1780 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001781 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedman49c16da2009-11-09 01:05:47 +00001782 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001783}
1784
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001785namespace {
1786 /// PureVirtualMethodCollector - traverses a class and its superclasses
1787 /// and determines if it has any pure virtual methods.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001788 class PureVirtualMethodCollector {
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001789 ASTContext &Context;
1790
Sebastian Redldfe292d2009-03-22 21:28:55 +00001791 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001792 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001793
1794 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001795 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001797 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001799 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001800 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001801 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001803 MethodList List;
1804 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001806 // Copy the temporary list to methods, and make sure to ignore any
1807 // null entries.
1808 for (size_t i = 0, e = List.size(); i != e; ++i) {
1809 if (List[i])
1810 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001811 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001812 }
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001814 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001815
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001816 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1817 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001818 };
Mike Stump1eb44332009-09-09 15:08:12 +00001819
1820 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001821 MethodList& Methods) {
1822 // First, collect the pure virtual methods for the base classes.
1823 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1824 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001825 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001826 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001827 if (BaseDecl && BaseDecl->isAbstract())
1828 Collect(BaseDecl, Methods);
1829 }
1830 }
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001832 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001833 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001835 MethodSetTy OverriddenMethods;
1836 size_t MethodsSize = Methods.size();
1837
Mike Stump1eb44332009-09-09 15:08:12 +00001838 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001839 i != e; ++i) {
1840 // Traverse the record, looking for methods.
1841 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001842 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001843 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001844 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Anders Carlsson27823022009-10-18 19:34:08 +00001846 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001847 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1848 E = MD->end_overridden_methods(); I != E; ++I) {
1849 // Keep track of the overridden methods.
1850 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001851 }
1852 }
1853 }
Mike Stump1eb44332009-09-09 15:08:12 +00001854
1855 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001856 // overridden.
1857 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1858 if (OverriddenMethods.count(Methods[i]))
1859 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001860 }
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001862 }
1863}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001864
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001865
Mike Stump1eb44332009-09-09 15:08:12 +00001866bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001867 unsigned DiagID, AbstractDiagSelID SelID,
1868 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001869 if (SelID == -1)
1870 return RequireNonAbstractType(Loc, T,
1871 PDiag(DiagID), CurrentRD);
1872 else
1873 return RequireNonAbstractType(Loc, T,
1874 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001875}
1876
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001877bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1878 const PartialDiagnostic &PD,
1879 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001880 if (!getLangOptions().CPlusPlus)
1881 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Anders Carlsson11f21a02009-03-23 19:10:31 +00001883 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001884 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001885 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Ted Kremenek6217b802009-07-29 21:53:49 +00001887 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001888 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001889 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001890 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001892 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001893 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001894 }
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Ted Kremenek6217b802009-07-29 21:53:49 +00001896 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001897 if (!RT)
1898 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001900 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1901 if (!RD)
1902 return false;
1903
Anders Carlssone65a3c82009-03-24 17:23:42 +00001904 if (CurrentRD && CurrentRD != RD)
1905 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001907 if (!RD->isAbstract())
1908 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001910 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001912 // Check if we've already emitted the list of pure virtual functions for this
1913 // class.
1914 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1915 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001917 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001918
1919 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001920 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1921 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001922
1923 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001924 MD->getDeclName();
1925 }
1926
1927 if (!PureVirtualClassDiagSet)
1928 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1929 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001930
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001931 return true;
1932}
1933
Anders Carlsson8211eff2009-03-24 01:19:16 +00001934namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00001935 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001936 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1937 Sema &SemaRef;
1938 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Anders Carlssone65a3c82009-03-24 17:23:42 +00001940 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001941 bool Invalid = false;
1942
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001943 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1944 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001945 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001946
Anders Carlsson8211eff2009-03-24 01:19:16 +00001947 return Invalid;
1948 }
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Anders Carlssone65a3c82009-03-24 17:23:42 +00001950 public:
1951 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1952 : SemaRef(SemaRef), AbstractClass(ac) {
1953 Visit(SemaRef.Context.getTranslationUnitDecl());
1954 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001955
Anders Carlssone65a3c82009-03-24 17:23:42 +00001956 bool VisitFunctionDecl(const FunctionDecl *FD) {
1957 if (FD->isThisDeclarationADefinition()) {
1958 // No need to do the check if we're in a definition, because it requires
1959 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00001960 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001961 return VisitDeclContext(FD);
1962 }
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Anders Carlssone65a3c82009-03-24 17:23:42 +00001964 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00001965 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001966 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00001967 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1968 diag::err_abstract_type_in_decl,
1969 Sema::AbstractReturnType,
1970 AbstractClass);
1971
Mike Stump1eb44332009-09-09 15:08:12 +00001972 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001973 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001974 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001975 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001976 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001977 VD->getOriginalType(),
1978 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001979 Sema::AbstractParamType,
1980 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001981 }
1982
1983 return Invalid;
1984 }
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Anders Carlssone65a3c82009-03-24 17:23:42 +00001986 bool VisitDecl(const Decl* D) {
1987 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1988 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Anders Carlssone65a3c82009-03-24 17:23:42 +00001990 return false;
1991 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001992 };
1993}
1994
Douglas Gregor1ab537b2009-12-03 18:33:45 +00001995/// \brief Perform semantic checks on a class definition that has been
1996/// completing, introducing implicitly-declared members, checking for
1997/// abstract types, etc.
1998void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
1999 if (!Record || Record->isInvalidDecl())
2000 return;
2001
Eli Friedmanff2d8782009-12-16 20:00:27 +00002002 if (!Record->isDependentType())
2003 AddImplicitlyDeclaredMembersToClass(Record);
2004
2005 if (Record->isInvalidDecl())
2006 return;
2007
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002008 if (!Record->isAbstract()) {
2009 // Collect all the pure virtual methods and see if this is an abstract
2010 // class after all.
2011 PureVirtualMethodCollector Collector(Context, Record);
2012 if (!Collector.empty())
2013 Record->setAbstract(true);
2014 }
2015
2016 if (Record->isAbstract())
2017 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002018}
2019
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002020void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002021 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002022 SourceLocation LBrac,
2023 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002024 if (!TagDecl)
2025 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Douglas Gregor42af25f2009-05-11 19:58:34 +00002027 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002028
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002029 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002030 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002031 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002032
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002033 CheckCompletedCXXClass(
2034 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002035}
2036
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002037/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2038/// special functions, such as the default constructor, copy
2039/// constructor, or destructor, to the given C++ class (C++
2040/// [special]p1). This routine can only be executed just before the
2041/// definition of the class is complete.
2042void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002043 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002044 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002045
Sebastian Redl465226e2009-05-27 22:11:52 +00002046 // FIXME: Implicit declarations have exception specifications, which are
2047 // the union of the specifications of the implicitly called functions.
2048
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002049 if (!ClassDecl->hasUserDeclaredConstructor()) {
2050 // C++ [class.ctor]p5:
2051 // A default constructor for a class X is a constructor of class X
2052 // that can be called without an argument. If there is no
2053 // user-declared constructor for class X, a default constructor is
2054 // implicitly declared. An implicitly-declared default constructor
2055 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002056 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002057 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002058 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002059 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002060 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002061 Context.getFunctionType(Context.VoidTy,
2062 0, 0, false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002063 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002064 /*isExplicit=*/false,
2065 /*isInline=*/true,
2066 /*isImplicitlyDeclared=*/true);
2067 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002068 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002069 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002070 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002071 }
2072
2073 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2074 // C++ [class.copy]p4:
2075 // If the class definition does not explicitly declare a copy
2076 // constructor, one is declared implicitly.
2077
2078 // C++ [class.copy]p5:
2079 // The implicitly-declared copy constructor for a class X will
2080 // have the form
2081 //
2082 // X::X(const X&)
2083 //
2084 // if
2085 bool HasConstCopyConstructor = true;
2086
2087 // -- each direct or virtual base class B of X has a copy
2088 // constructor whose first parameter is of type const B& or
2089 // const volatile B&, and
2090 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2091 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2092 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002093 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002094 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002095 = BaseClassDecl->hasConstCopyConstructor(Context);
2096 }
2097
2098 // -- for all the nonstatic data members of X that are of a
2099 // class type M (or array thereof), each such class type
2100 // has a copy constructor whose first parameter is of type
2101 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002102 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2103 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002104 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002105 QualType FieldType = (*Field)->getType();
2106 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2107 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002108 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002109 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002110 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002111 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002112 = FieldClassDecl->hasConstCopyConstructor(Context);
2113 }
2114 }
2115
Sebastian Redl64b45f72009-01-05 20:52:13 +00002116 // Otherwise, the implicitly declared copy constructor will have
2117 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002118 //
2119 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002120 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002121 if (HasConstCopyConstructor)
2122 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002123 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002124
Sebastian Redl64b45f72009-01-05 20:52:13 +00002125 // An implicitly-declared copy constructor is an inline public
2126 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002127 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002128 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002129 CXXConstructorDecl *CopyConstructor
2130 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002131 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002132 Context.getFunctionType(Context.VoidTy,
2133 &ArgType, 1,
2134 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002135 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002136 /*isExplicit=*/false,
2137 /*isInline=*/true,
2138 /*isImplicitlyDeclared=*/true);
2139 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002140 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002141 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002142
2143 // Add the parameter to the constructor.
2144 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2145 ClassDecl->getLocation(),
2146 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002147 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002148 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002149 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002150 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002151 }
2152
Sebastian Redl64b45f72009-01-05 20:52:13 +00002153 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2154 // Note: The following rules are largely analoguous to the copy
2155 // constructor rules. Note that virtual bases are not taken into account
2156 // for determining the argument type of the operator. Note also that
2157 // operators taking an object instead of a reference are allowed.
2158 //
2159 // C++ [class.copy]p10:
2160 // If the class definition does not explicitly declare a copy
2161 // assignment operator, one is declared implicitly.
2162 // The implicitly-defined copy assignment operator for a class X
2163 // will have the form
2164 //
2165 // X& X::operator=(const X&)
2166 //
2167 // if
2168 bool HasConstCopyAssignment = true;
2169
2170 // -- each direct base class B of X has a copy assignment operator
2171 // whose parameter is of type const B&, const volatile B& or B,
2172 // and
2173 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2174 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002175 assert(!Base->getType()->isDependentType() &&
2176 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002177 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002178 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002179 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002180 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002181 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002182 }
2183
2184 // -- for all the nonstatic data members of X that are of a class
2185 // type M (or array thereof), each such class type has a copy
2186 // assignment operator whose parameter is of type const M&,
2187 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002188 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2189 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002190 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002191 QualType FieldType = (*Field)->getType();
2192 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2193 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002194 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002195 const CXXRecordDecl *FieldClassDecl
2196 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002197 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002198 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002199 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002200 }
2201 }
2202
2203 // Otherwise, the implicitly declared copy assignment operator will
2204 // have the form
2205 //
2206 // X& X::operator=(X&)
2207 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002208 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002209 if (HasConstCopyAssignment)
2210 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002211 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002212
2213 // An implicitly-declared copy assignment operator is an inline public
2214 // member of its class.
2215 DeclarationName Name =
2216 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2217 CXXMethodDecl *CopyAssignment =
2218 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2219 Context.getFunctionType(RetType, &ArgType, 1,
2220 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002221 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002222 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002223 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002224 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002225 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002226
2227 // Add the parameter to the operator.
2228 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2229 ClassDecl->getLocation(),
2230 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002231 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002232 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002233 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002234
2235 // Don't call addedAssignmentOperator. There is no way to distinguish an
2236 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002237 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002238 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002239 }
2240
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002241 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002242 // C++ [class.dtor]p2:
2243 // If a class has no user-declared destructor, a destructor is
2244 // declared implicitly. An implicitly-declared destructor is an
2245 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002246 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002247 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002248 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002249 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002250 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002251 Context.getFunctionType(Context.VoidTy,
2252 0, 0, false, 0),
2253 /*isInline=*/true,
2254 /*isImplicitlyDeclared=*/true);
2255 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002256 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002257 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002258 ClassDecl->addDecl(Destructor);
Anders Carlssond5a942b2009-11-26 21:25:09 +00002259
2260 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002261 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002262}
2263
Douglas Gregor6569d682009-05-27 23:11:45 +00002264void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002265 Decl *D = TemplateD.getAs<Decl>();
2266 if (!D)
2267 return;
2268
2269 TemplateParameterList *Params = 0;
2270 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2271 Params = Template->getTemplateParameters();
2272 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2273 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2274 Params = PartialSpec->getTemplateParameters();
2275 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002276 return;
2277
Douglas Gregor6569d682009-05-27 23:11:45 +00002278 for (TemplateParameterList::iterator Param = Params->begin(),
2279 ParamEnd = Params->end();
2280 Param != ParamEnd; ++Param) {
2281 NamedDecl *Named = cast<NamedDecl>(*Param);
2282 if (Named->getDeclName()) {
2283 S->AddDecl(DeclPtrTy::make(Named));
2284 IdResolver.AddDecl(Named);
2285 }
2286 }
2287}
2288
John McCall7a1dc562009-12-19 10:49:29 +00002289void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2290 if (!RecordD) return;
2291 AdjustDeclIfTemplate(RecordD);
2292 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2293 PushDeclContext(S, Record);
2294}
2295
2296void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2297 if (!RecordD) return;
2298 PopDeclContext();
2299}
2300
Douglas Gregor72b505b2008-12-16 21:30:33 +00002301/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2302/// parsing a top-level (non-nested) C++ class, and we are now
2303/// parsing those parts of the given Method declaration that could
2304/// not be parsed earlier (C++ [class.mem]p2), such as default
2305/// arguments. This action should enter the scope of the given
2306/// Method declaration as if we had just parsed the qualified method
2307/// name. However, it should not bring the parameters into scope;
2308/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002309void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002310}
2311
2312/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2313/// C++ method declaration. We're (re-)introducing the given
2314/// function parameter into scope for use in parsing later parts of
2315/// the method declaration. For example, we could see an
2316/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002317void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002318 if (!ParamD)
2319 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002320
Chris Lattnerb28317a2009-03-28 19:18:32 +00002321 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002322
2323 // If this parameter has an unparsed default argument, clear it out
2324 // to make way for the parsed default argument.
2325 if (Param->hasUnparsedDefaultArg())
2326 Param->setDefaultArg(0);
2327
Chris Lattnerb28317a2009-03-28 19:18:32 +00002328 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002329 if (Param->getDeclName())
2330 IdResolver.AddDecl(Param);
2331}
2332
2333/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2334/// processing the delayed method declaration for Method. The method
2335/// declaration is now considered finished. There may be a separate
2336/// ActOnStartOfFunctionDef action later (not necessarily
2337/// immediately!) for this method, if it was also defined inside the
2338/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002339void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002340 if (!MethodD)
2341 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002342
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002343 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002344
Chris Lattnerb28317a2009-03-28 19:18:32 +00002345 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002346
2347 // Now that we have our default arguments, check the constructor
2348 // again. It could produce additional diagnostics or affect whether
2349 // the class has implicitly-declared destructors, among other
2350 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002351 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2352 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002353
2354 // Check the default arguments, which we may have added.
2355 if (!Method->isInvalidDecl())
2356 CheckCXXDefaultArguments(Method);
2357}
2358
Douglas Gregor42a552f2008-11-05 20:51:48 +00002359/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002360/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002361/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002362/// emit diagnostics and set the invalid bit to true. In any case, the type
2363/// will be updated to reflect a well-formed type for the constructor and
2364/// returned.
2365QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2366 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002367 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002368
2369 // C++ [class.ctor]p3:
2370 // A constructor shall not be virtual (10.3) or static (9.4). A
2371 // constructor can be invoked for a const, volatile or const
2372 // volatile object. A constructor shall not be declared const,
2373 // volatile, or const volatile (9.3.2).
2374 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002375 if (!D.isInvalidType())
2376 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2377 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2378 << SourceRange(D.getIdentifierLoc());
2379 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002380 }
2381 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002382 if (!D.isInvalidType())
2383 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2384 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2385 << SourceRange(D.getIdentifierLoc());
2386 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002387 SC = FunctionDecl::None;
2388 }
Mike Stump1eb44332009-09-09 15:08:12 +00002389
Chris Lattner65401802009-04-25 08:28:21 +00002390 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2391 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002392 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002393 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2394 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002395 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002396 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2397 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002398 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002399 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2400 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002401 }
Mike Stump1eb44332009-09-09 15:08:12 +00002402
Douglas Gregor42a552f2008-11-05 20:51:48 +00002403 // Rebuild the function type "R" without any type qualifiers (in
2404 // case any of the errors above fired) and with "void" as the
2405 // return type, since constructors don't have return types. We
2406 // *always* have to do this, because GetTypeForDeclarator will
2407 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002408 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002409 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2410 Proto->getNumArgs(),
2411 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002412}
2413
Douglas Gregor72b505b2008-12-16 21:30:33 +00002414/// CheckConstructor - Checks a fully-formed constructor for
2415/// well-formedness, issuing any diagnostics required. Returns true if
2416/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002417void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002418 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002419 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2420 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002421 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002422
2423 // C++ [class.copy]p3:
2424 // A declaration of a constructor for a class X is ill-formed if
2425 // its first parameter is of type (optionally cv-qualified) X and
2426 // either there are no other parameters or else all other
2427 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002428 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002429 ((Constructor->getNumParams() == 1) ||
2430 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002431 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2432 Constructor->getTemplateSpecializationKind()
2433 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002434 QualType ParamType = Constructor->getParamDecl(0)->getType();
2435 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2436 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002437 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2438 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002439 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002440
2441 // FIXME: Rather that making the constructor invalid, we should endeavor
2442 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002443 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002444 }
2445 }
Mike Stump1eb44332009-09-09 15:08:12 +00002446
Douglas Gregor72b505b2008-12-16 21:30:33 +00002447 // Notify the class that we've added a constructor.
2448 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002449}
2450
Anders Carlsson37909802009-11-30 21:24:50 +00002451/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2452/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002453bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002454 CXXRecordDecl *RD = Destructor->getParent();
2455
2456 if (Destructor->isVirtual()) {
2457 SourceLocation Loc;
2458
2459 if (!Destructor->isImplicit())
2460 Loc = Destructor->getLocation();
2461 else
2462 Loc = RD->getLocation();
2463
2464 // If we have a virtual destructor, look up the deallocation function
2465 FunctionDecl *OperatorDelete = 0;
2466 DeclarationName Name =
2467 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002468 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002469 return true;
2470
2471 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002472 }
Anders Carlsson37909802009-11-30 21:24:50 +00002473
2474 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002475}
2476
Mike Stump1eb44332009-09-09 15:08:12 +00002477static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002478FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2479 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2480 FTI.ArgInfo[0].Param &&
2481 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2482}
2483
Douglas Gregor42a552f2008-11-05 20:51:48 +00002484/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2485/// the well-formednes of the destructor declarator @p D with type @p
2486/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002487/// emit diagnostics and set the declarator to invalid. Even if this happens,
2488/// will be updated to reflect a well-formed type for the destructor and
2489/// returned.
2490QualType Sema::CheckDestructorDeclarator(Declarator &D,
2491 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002492 // C++ [class.dtor]p1:
2493 // [...] A typedef-name that names a class is a class-name
2494 // (7.1.3); however, a typedef-name that names a class shall not
2495 // be used as the identifier in the declarator for a destructor
2496 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002497 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002498 if (isa<TypedefType>(DeclaratorType)) {
2499 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002500 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002501 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002502 }
2503
2504 // C++ [class.dtor]p2:
2505 // A destructor is used to destroy objects of its class type. A
2506 // destructor takes no parameters, and no return type can be
2507 // specified for it (not even void). The address of a destructor
2508 // shall not be taken. A destructor shall not be static. A
2509 // destructor can be invoked for a const, volatile or const
2510 // volatile object. A destructor shall not be declared const,
2511 // volatile or const volatile (9.3.2).
2512 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002513 if (!D.isInvalidType())
2514 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2515 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2516 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002517 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002518 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002519 }
Chris Lattner65401802009-04-25 08:28:21 +00002520 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002521 // Destructors don't have return types, but the parser will
2522 // happily parse something like:
2523 //
2524 // class X {
2525 // float ~X();
2526 // };
2527 //
2528 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002529 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2530 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2531 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002532 }
Mike Stump1eb44332009-09-09 15:08:12 +00002533
Chris Lattner65401802009-04-25 08:28:21 +00002534 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2535 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002536 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002537 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2538 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002539 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002540 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2541 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002542 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002543 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2544 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002545 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002546 }
2547
2548 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002549 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002550 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2551
2552 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002553 FTI.freeArgs();
2554 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002555 }
2556
Mike Stump1eb44332009-09-09 15:08:12 +00002557 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002558 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002559 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002560 D.setInvalidType();
2561 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002562
2563 // Rebuild the function type "R" without any type qualifiers or
2564 // parameters (in case any of the errors above fired) and with
2565 // "void" as the return type, since destructors don't have return
2566 // types. We *always* have to do this, because GetTypeForDeclarator
2567 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002568 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002569}
2570
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002571/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2572/// well-formednes of the conversion function declarator @p D with
2573/// type @p R. If there are any errors in the declarator, this routine
2574/// will emit diagnostics and return true. Otherwise, it will return
2575/// false. Either way, the type @p R will be updated to reflect a
2576/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002577void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002578 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002579 // C++ [class.conv.fct]p1:
2580 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002581 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002582 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002583 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002584 if (!D.isInvalidType())
2585 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2586 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2587 << SourceRange(D.getIdentifierLoc());
2588 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002589 SC = FunctionDecl::None;
2590 }
Chris Lattner6e475012009-04-25 08:35:12 +00002591 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002592 // Conversion functions don't have return types, but the parser will
2593 // happily parse something like:
2594 //
2595 // class X {
2596 // float operator bool();
2597 // };
2598 //
2599 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002600 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2601 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2602 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002603 }
2604
2605 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002606 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002607 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2608
2609 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002610 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002611 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002612 }
2613
Mike Stump1eb44332009-09-09 15:08:12 +00002614 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002615 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002616 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002617 D.setInvalidType();
2618 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002619
2620 // C++ [class.conv.fct]p4:
2621 // The conversion-type-id shall not represent a function type nor
2622 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002623 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002624 if (ConvType->isArrayType()) {
2625 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2626 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002627 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002628 } else if (ConvType->isFunctionType()) {
2629 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2630 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002631 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002632 }
2633
2634 // Rebuild the function type "R" without any parameters (in case any
2635 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002636 // return type.
2637 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002638 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002639
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002640 // C++0x explicit conversion operators.
2641 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002642 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002643 diag::warn_explicit_conversion_functions)
2644 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002645}
2646
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002647/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2648/// the declaration of the given C++ conversion function. This routine
2649/// is responsible for recording the conversion function in the C++
2650/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002651Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002652 assert(Conversion && "Expected to receive a conversion function declaration");
2653
Douglas Gregor9d350972008-12-12 08:25:50 +00002654 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002655
2656 // Make sure we aren't redeclaring the conversion function.
2657 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002658
2659 // C++ [class.conv.fct]p1:
2660 // [...] A conversion function is never used to convert a
2661 // (possibly cv-qualified) object to the (possibly cv-qualified)
2662 // same object type (or a reference to it), to a (possibly
2663 // cv-qualified) base class of that type (or a reference to it),
2664 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002665 // FIXME: Suppress this warning if the conversion function ends up being a
2666 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002667 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002668 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002669 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002670 ConvType = ConvTypeRef->getPointeeType();
2671 if (ConvType->isRecordType()) {
2672 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2673 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002674 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002675 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002676 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002677 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002678 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002679 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002680 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002681 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002682 }
2683
Douglas Gregor70316a02008-12-26 15:00:45 +00002684 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002685 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002686 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002687 = Conversion->getDescribedFunctionTemplate())
2688 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
John McCallba135432009-11-21 08:51:07 +00002689 if (ClassDecl->replaceConversion(ExpectedPrevDecl, Conversion))
2690 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002691 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002692 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002693 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002694 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002695 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002696 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002697
Chris Lattnerb28317a2009-03-28 19:18:32 +00002698 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002699}
2700
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002701//===----------------------------------------------------------------------===//
2702// Namespace Handling
2703//===----------------------------------------------------------------------===//
2704
2705/// ActOnStartNamespaceDef - This is called at the start of a namespace
2706/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002707Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2708 SourceLocation IdentLoc,
2709 IdentifierInfo *II,
2710 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002711 NamespaceDecl *Namespc =
2712 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2713 Namespc->setLBracLoc(LBrace);
2714
2715 Scope *DeclRegionScope = NamespcScope->getParent();
2716
2717 if (II) {
2718 // C++ [namespace.def]p2:
2719 // The identifier in an original-namespace-definition shall not have been
2720 // previously defined in the declarative region in which the
2721 // original-namespace-definition appears. The identifier in an
2722 // original-namespace-definition is the name of the namespace. Subsequently
2723 // in that declarative region, it is treated as an original-namespace-name.
2724
John McCallf36e02d2009-10-09 21:13:30 +00002725 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002726 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002727 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002728
Douglas Gregor44b43212008-12-11 16:49:14 +00002729 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2730 // This is an extended namespace definition.
2731 // Attach this namespace decl to the chain of extended namespace
2732 // definitions.
2733 OrigNS->setNextNamespace(Namespc);
2734 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002735
Mike Stump1eb44332009-09-09 15:08:12 +00002736 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002737 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002738 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002739 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002740 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002741 } else if (PrevDecl) {
2742 // This is an invalid name redefinition.
2743 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2744 << Namespc->getDeclName();
2745 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2746 Namespc->setInvalidDecl();
2747 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002748 } else if (II->isStr("std") &&
2749 CurContext->getLookupContext()->isTranslationUnit()) {
2750 // This is the first "real" definition of the namespace "std", so update
2751 // our cache of the "std" namespace to point at this definition.
2752 if (StdNamespace) {
2753 // We had already defined a dummy namespace "std". Link this new
2754 // namespace definition to the dummy namespace "std".
2755 StdNamespace->setNextNamespace(Namespc);
2756 StdNamespace->setLocation(IdentLoc);
2757 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2758 }
2759
2760 // Make our StdNamespace cache point at the first real definition of the
2761 // "std" namespace.
2762 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002763 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002764
2765 PushOnScopeChains(Namespc, DeclRegionScope);
2766 } else {
John McCall9aeed322009-10-01 00:25:31 +00002767 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00002768 assert(Namespc->isAnonymousNamespace());
2769 CurContext->addDecl(Namespc);
2770
2771 // Link the anonymous namespace into its parent.
2772 NamespaceDecl *PrevDecl;
2773 DeclContext *Parent = CurContext->getLookupContext();
2774 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2775 PrevDecl = TU->getAnonymousNamespace();
2776 TU->setAnonymousNamespace(Namespc);
2777 } else {
2778 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2779 PrevDecl = ND->getAnonymousNamespace();
2780 ND->setAnonymousNamespace(Namespc);
2781 }
2782
2783 // Link the anonymous namespace with its previous declaration.
2784 if (PrevDecl) {
2785 assert(PrevDecl->isAnonymousNamespace());
2786 assert(!PrevDecl->getNextNamespace());
2787 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2788 PrevDecl->setNextNamespace(Namespc);
2789 }
John McCall9aeed322009-10-01 00:25:31 +00002790
2791 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2792 // behaves as if it were replaced by
2793 // namespace unique { /* empty body */ }
2794 // using namespace unique;
2795 // namespace unique { namespace-body }
2796 // where all occurrences of 'unique' in a translation unit are
2797 // replaced by the same identifier and this identifier differs
2798 // from all other identifiers in the entire program.
2799
2800 // We just create the namespace with an empty name and then add an
2801 // implicit using declaration, just like the standard suggests.
2802 //
2803 // CodeGen enforces the "universally unique" aspect by giving all
2804 // declarations semantically contained within an anonymous
2805 // namespace internal linkage.
2806
John McCall5fdd7642009-12-16 02:06:49 +00002807 if (!PrevDecl) {
2808 UsingDirectiveDecl* UD
2809 = UsingDirectiveDecl::Create(Context, CurContext,
2810 /* 'using' */ LBrace,
2811 /* 'namespace' */ SourceLocation(),
2812 /* qualifier */ SourceRange(),
2813 /* NNS */ NULL,
2814 /* identifier */ SourceLocation(),
2815 Namespc,
2816 /* Ancestor */ CurContext);
2817 UD->setImplicit();
2818 CurContext->addDecl(UD);
2819 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002820 }
2821
2822 // Although we could have an invalid decl (i.e. the namespace name is a
2823 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002824 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2825 // for the namespace has the declarations that showed up in that particular
2826 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002827 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002828 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002829}
2830
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002831/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2832/// is a namespace alias, returns the namespace it points to.
2833static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2834 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2835 return AD->getNamespace();
2836 return dyn_cast_or_null<NamespaceDecl>(D);
2837}
2838
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002839/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2840/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002841void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2842 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002843 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2844 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2845 Namespc->setRBracLoc(RBrace);
2846 PopDeclContext();
2847}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002848
Chris Lattnerb28317a2009-03-28 19:18:32 +00002849Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2850 SourceLocation UsingLoc,
2851 SourceLocation NamespcLoc,
2852 const CXXScopeSpec &SS,
2853 SourceLocation IdentLoc,
2854 IdentifierInfo *NamespcName,
2855 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002856 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2857 assert(NamespcName && "Invalid NamespcName.");
2858 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002859 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002860
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002861 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002862
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002863 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00002864 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2865 LookupParsedName(R, S, &SS);
2866 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00002867 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00002868
John McCallf36e02d2009-10-09 21:13:30 +00002869 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002870 NamedDecl *Named = R.getFoundDecl();
2871 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2872 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002873 // C++ [namespace.udir]p1:
2874 // A using-directive specifies that the names in the nominated
2875 // namespace can be used in the scope in which the
2876 // using-directive appears after the using-directive. During
2877 // unqualified name lookup (3.4.1), the names appear as if they
2878 // were declared in the nearest enclosing namespace which
2879 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002880 // namespace. [Note: in this context, "contains" means "contains
2881 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002882
2883 // Find enclosing context containing both using-directive and
2884 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002885 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002886 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2887 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2888 CommonAncestor = CommonAncestor->getParent();
2889
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002890 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002891 SS.getRange(),
2892 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002893 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002894 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002895 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002896 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002897 }
2898
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002899 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002900 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002901 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002902}
2903
2904void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2905 // If scope has associated entity, then using directive is at namespace
2906 // or translation unit scope. We add UsingDirectiveDecls, into
2907 // it's lookup structure.
2908 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002909 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002910 else
2911 // Otherwise it is block-sope. using-directives will affect lookup
2912 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002913 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002914}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002915
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002916
2917Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002918 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00002919 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002920 SourceLocation UsingLoc,
2921 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002922 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002923 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00002924 bool IsTypeName,
2925 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002926 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002927
Douglas Gregor12c118a2009-11-04 16:30:06 +00002928 switch (Name.getKind()) {
2929 case UnqualifiedId::IK_Identifier:
2930 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00002931 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00002932 case UnqualifiedId::IK_ConversionFunctionId:
2933 break;
2934
2935 case UnqualifiedId::IK_ConstructorName:
John McCall604e7f12009-12-08 07:46:18 +00002936 // C++0x inherited constructors.
2937 if (getLangOptions().CPlusPlus0x) break;
2938
Douglas Gregor12c118a2009-11-04 16:30:06 +00002939 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2940 << SS.getRange();
2941 return DeclPtrTy();
2942
2943 case UnqualifiedId::IK_DestructorName:
2944 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2945 << SS.getRange();
2946 return DeclPtrTy();
2947
2948 case UnqualifiedId::IK_TemplateId:
2949 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2950 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2951 return DeclPtrTy();
2952 }
2953
2954 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00002955 if (!TargetName)
2956 return DeclPtrTy();
2957
John McCall60fa3cf2009-12-11 02:10:03 +00002958 // Warn about using declarations.
2959 // TODO: store that the declaration was written without 'using' and
2960 // talk about access decls instead of using decls in the
2961 // diagnostics.
2962 if (!HasUsingKeyword) {
2963 UsingLoc = Name.getSourceRange().getBegin();
2964
2965 Diag(UsingLoc, diag::warn_access_decl_deprecated)
2966 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
2967 "using ");
2968 }
2969
John McCall9488ea12009-11-17 05:59:44 +00002970 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002971 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00002972 TargetName, AttrList,
2973 /* IsInstantiation */ false,
2974 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00002975 if (UD)
2976 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00002977
Anders Carlssonc72160b2009-08-28 05:40:36 +00002978 return DeclPtrTy::make(UD);
2979}
2980
John McCall9f54ad42009-12-10 09:41:52 +00002981/// Determines whether to create a using shadow decl for a particular
2982/// decl, given the set of decls existing prior to this using lookup.
2983bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
2984 const LookupResult &Previous) {
2985 // Diagnose finding a decl which is not from a base class of the
2986 // current class. We do this now because there are cases where this
2987 // function will silently decide not to build a shadow decl, which
2988 // will pre-empt further diagnostics.
2989 //
2990 // We don't need to do this in C++0x because we do the check once on
2991 // the qualifier.
2992 //
2993 // FIXME: diagnose the following if we care enough:
2994 // struct A { int foo; };
2995 // struct B : A { using A::foo; };
2996 // template <class T> struct C : A {};
2997 // template <class T> struct D : C<T> { using B::foo; } // <---
2998 // This is invalid (during instantiation) in C++03 because B::foo
2999 // resolves to the using decl in B, which is not a base class of D<T>.
3000 // We can't diagnose it immediately because C<T> is an unknown
3001 // specialization. The UsingShadowDecl in D<T> then points directly
3002 // to A::foo, which will look well-formed when we instantiate.
3003 // The right solution is to not collapse the shadow-decl chain.
3004 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3005 DeclContext *OrigDC = Orig->getDeclContext();
3006
3007 // Handle enums and anonymous structs.
3008 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3009 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3010 while (OrigRec->isAnonymousStructOrUnion())
3011 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3012
3013 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3014 if (OrigDC == CurContext) {
3015 Diag(Using->getLocation(),
3016 diag::err_using_decl_nested_name_specifier_is_current_class)
3017 << Using->getNestedNameRange();
3018 Diag(Orig->getLocation(), diag::note_using_decl_target);
3019 return true;
3020 }
3021
3022 Diag(Using->getNestedNameRange().getBegin(),
3023 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3024 << Using->getTargetNestedNameDecl()
3025 << cast<CXXRecordDecl>(CurContext)
3026 << Using->getNestedNameRange();
3027 Diag(Orig->getLocation(), diag::note_using_decl_target);
3028 return true;
3029 }
3030 }
3031
3032 if (Previous.empty()) return false;
3033
3034 NamedDecl *Target = Orig;
3035 if (isa<UsingShadowDecl>(Target))
3036 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3037
John McCalld7533ec2009-12-11 02:33:26 +00003038 // If the target happens to be one of the previous declarations, we
3039 // don't have a conflict.
3040 //
3041 // FIXME: but we might be increasing its access, in which case we
3042 // should redeclare it.
3043 NamedDecl *NonTag = 0, *Tag = 0;
3044 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3045 I != E; ++I) {
3046 NamedDecl *D = (*I)->getUnderlyingDecl();
3047 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3048 return false;
3049
3050 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3051 }
3052
John McCall9f54ad42009-12-10 09:41:52 +00003053 if (Target->isFunctionOrFunctionTemplate()) {
3054 FunctionDecl *FD;
3055 if (isa<FunctionTemplateDecl>(Target))
3056 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3057 else
3058 FD = cast<FunctionDecl>(Target);
3059
3060 NamedDecl *OldDecl = 0;
3061 switch (CheckOverload(FD, Previous, OldDecl)) {
3062 case Ovl_Overload:
3063 return false;
3064
3065 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003066 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003067 break;
3068
3069 // We found a decl with the exact signature.
3070 case Ovl_Match:
3071 if (isa<UsingShadowDecl>(OldDecl)) {
3072 // Silently ignore the possible conflict.
3073 return false;
3074 }
3075
3076 // If we're in a record, we want to hide the target, so we
3077 // return true (without a diagnostic) to tell the caller not to
3078 // build a shadow decl.
3079 if (CurContext->isRecord())
3080 return true;
3081
3082 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003083 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003084 break;
3085 }
3086
3087 Diag(Target->getLocation(), diag::note_using_decl_target);
3088 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3089 return true;
3090 }
3091
3092 // Target is not a function.
3093
John McCall9f54ad42009-12-10 09:41:52 +00003094 if (isa<TagDecl>(Target)) {
3095 // No conflict between a tag and a non-tag.
3096 if (!Tag) return false;
3097
John McCall41ce66f2009-12-10 19:51:03 +00003098 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003099 Diag(Target->getLocation(), diag::note_using_decl_target);
3100 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3101 return true;
3102 }
3103
3104 // No conflict between a tag and a non-tag.
3105 if (!NonTag) return false;
3106
John McCall41ce66f2009-12-10 19:51:03 +00003107 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003108 Diag(Target->getLocation(), diag::note_using_decl_target);
3109 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3110 return true;
3111}
3112
John McCall9488ea12009-11-17 05:59:44 +00003113/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003114UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003115 UsingDecl *UD,
3116 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003117
3118 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003119 NamedDecl *Target = Orig;
3120 if (isa<UsingShadowDecl>(Target)) {
3121 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3122 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003123 }
3124
3125 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003126 = UsingShadowDecl::Create(Context, CurContext,
3127 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003128 UD->addShadowDecl(Shadow);
3129
3130 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003131 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003132 else
John McCall604e7f12009-12-08 07:46:18 +00003133 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003134 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003135
John McCall604e7f12009-12-08 07:46:18 +00003136 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3137 Shadow->setInvalidDecl();
3138
John McCall9f54ad42009-12-10 09:41:52 +00003139 return Shadow;
3140}
John McCall604e7f12009-12-08 07:46:18 +00003141
John McCall9f54ad42009-12-10 09:41:52 +00003142/// Hides a using shadow declaration. This is required by the current
3143/// using-decl implementation when a resolvable using declaration in a
3144/// class is followed by a declaration which would hide or override
3145/// one or more of the using decl's targets; for example:
3146///
3147/// struct Base { void foo(int); };
3148/// struct Derived : Base {
3149/// using Base::foo;
3150/// void foo(int);
3151/// };
3152///
3153/// The governing language is C++03 [namespace.udecl]p12:
3154///
3155/// When a using-declaration brings names from a base class into a
3156/// derived class scope, member functions in the derived class
3157/// override and/or hide member functions with the same name and
3158/// parameter types in a base class (rather than conflicting).
3159///
3160/// There are two ways to implement this:
3161/// (1) optimistically create shadow decls when they're not hidden
3162/// by existing declarations, or
3163/// (2) don't create any shadow decls (or at least don't make them
3164/// visible) until we've fully parsed/instantiated the class.
3165/// The problem with (1) is that we might have to retroactively remove
3166/// a shadow decl, which requires several O(n) operations because the
3167/// decl structures are (very reasonably) not designed for removal.
3168/// (2) avoids this but is very fiddly and phase-dependent.
3169void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3170 // Remove it from the DeclContext...
3171 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003172
John McCall9f54ad42009-12-10 09:41:52 +00003173 // ...and the scope, if applicable...
3174 if (S) {
3175 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3176 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003177 }
3178
John McCall9f54ad42009-12-10 09:41:52 +00003179 // ...and the using decl.
3180 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3181
3182 // TODO: complain somehow if Shadow was used. It shouldn't
3183 // be possible for this to happen, because
John McCall9488ea12009-11-17 05:59:44 +00003184}
3185
John McCall7ba107a2009-11-18 02:36:19 +00003186/// Builds a using declaration.
3187///
3188/// \param IsInstantiation - Whether this call arises from an
3189/// instantiation of an unresolved using declaration. We treat
3190/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003191NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3192 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003193 const CXXScopeSpec &SS,
3194 SourceLocation IdentLoc,
3195 DeclarationName Name,
3196 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003197 bool IsInstantiation,
3198 bool IsTypeName,
3199 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003200 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3201 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003202
Anders Carlsson550b14b2009-08-28 05:49:21 +00003203 // FIXME: We ignore attributes for now.
3204 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003205
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003206 if (SS.isEmpty()) {
3207 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003208 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003209 }
Mike Stump1eb44332009-09-09 15:08:12 +00003210
John McCall9f54ad42009-12-10 09:41:52 +00003211 // Do the redeclaration lookup in the current scope.
3212 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3213 ForRedeclaration);
3214 Previous.setHideTags(false);
3215 if (S) {
3216 LookupName(Previous, S);
3217
3218 // It is really dumb that we have to do this.
3219 LookupResult::Filter F = Previous.makeFilter();
3220 while (F.hasNext()) {
3221 NamedDecl *D = F.next();
3222 if (!isDeclInScope(D, CurContext, S))
3223 F.erase();
3224 }
3225 F.done();
3226 } else {
3227 assert(IsInstantiation && "no scope in non-instantiation");
3228 assert(CurContext->isRecord() && "scope not record in instantiation");
3229 LookupQualifiedName(Previous, CurContext);
3230 }
3231
Mike Stump1eb44332009-09-09 15:08:12 +00003232 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003233 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3234
John McCall9f54ad42009-12-10 09:41:52 +00003235 // Check for invalid redeclarations.
3236 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3237 return 0;
3238
3239 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003240 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3241 return 0;
3242
John McCallaf8e6ed2009-11-12 03:15:40 +00003243 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003244 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003245 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003246 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003247 // FIXME: not all declaration name kinds are legal here
3248 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3249 UsingLoc, TypenameLoc,
3250 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003251 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003252 } else {
3253 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3254 UsingLoc, SS.getRange(), NNS,
3255 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003256 }
John McCalled976492009-12-04 22:46:56 +00003257 } else {
3258 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3259 SS.getRange(), UsingLoc, NNS, Name,
3260 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003261 }
John McCalled976492009-12-04 22:46:56 +00003262 D->setAccess(AS);
3263 CurContext->addDecl(D);
3264
3265 if (!LookupContext) return D;
3266 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003267
John McCall604e7f12009-12-08 07:46:18 +00003268 if (RequireCompleteDeclContext(SS)) {
3269 UD->setInvalidDecl();
3270 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003271 }
3272
John McCall604e7f12009-12-08 07:46:18 +00003273 // Look up the target name.
3274
John McCalla24dc2e2009-11-17 02:14:36 +00003275 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003276
John McCall604e7f12009-12-08 07:46:18 +00003277 // Unlike most lookups, we don't always want to hide tag
3278 // declarations: tag names are visible through the using declaration
3279 // even if hidden by ordinary names, *except* in a dependent context
3280 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003281 if (!IsInstantiation)
3282 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003283
John McCalla24dc2e2009-11-17 02:14:36 +00003284 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003285
John McCallf36e02d2009-10-09 21:13:30 +00003286 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003287 Diag(IdentLoc, diag::err_no_member)
3288 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003289 UD->setInvalidDecl();
3290 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003291 }
3292
John McCalled976492009-12-04 22:46:56 +00003293 if (R.isAmbiguous()) {
3294 UD->setInvalidDecl();
3295 return UD;
3296 }
Mike Stump1eb44332009-09-09 15:08:12 +00003297
John McCall7ba107a2009-11-18 02:36:19 +00003298 if (IsTypeName) {
3299 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003300 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003301 Diag(IdentLoc, diag::err_using_typename_non_type);
3302 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3303 Diag((*I)->getUnderlyingDecl()->getLocation(),
3304 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003305 UD->setInvalidDecl();
3306 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003307 }
3308 } else {
3309 // If we asked for a non-typename and we got a type, error out,
3310 // but only if this is an instantiation of an unresolved using
3311 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003312 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003313 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3314 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003315 UD->setInvalidDecl();
3316 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003317 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003318 }
3319
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003320 // C++0x N2914 [namespace.udecl]p6:
3321 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003322 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003323 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3324 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003325 UD->setInvalidDecl();
3326 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003327 }
Mike Stump1eb44332009-09-09 15:08:12 +00003328
John McCall9f54ad42009-12-10 09:41:52 +00003329 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3330 if (!CheckUsingShadowDecl(UD, *I, Previous))
3331 BuildUsingShadowDecl(S, UD, *I);
3332 }
John McCall9488ea12009-11-17 05:59:44 +00003333
3334 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003335}
3336
John McCall9f54ad42009-12-10 09:41:52 +00003337/// Checks that the given using declaration is not an invalid
3338/// redeclaration. Note that this is checking only for the using decl
3339/// itself, not for any ill-formedness among the UsingShadowDecls.
3340bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3341 bool isTypeName,
3342 const CXXScopeSpec &SS,
3343 SourceLocation NameLoc,
3344 const LookupResult &Prev) {
3345 // C++03 [namespace.udecl]p8:
3346 // C++0x [namespace.udecl]p10:
3347 // A using-declaration is a declaration and can therefore be used
3348 // repeatedly where (and only where) multiple declarations are
3349 // allowed.
3350 // That's only in file contexts.
3351 if (CurContext->getLookupContext()->isFileContext())
3352 return false;
3353
3354 NestedNameSpecifier *Qual
3355 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3356
3357 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3358 NamedDecl *D = *I;
3359
3360 bool DTypename;
3361 NestedNameSpecifier *DQual;
3362 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3363 DTypename = UD->isTypeName();
3364 DQual = UD->getTargetNestedNameDecl();
3365 } else if (UnresolvedUsingValueDecl *UD
3366 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3367 DTypename = false;
3368 DQual = UD->getTargetNestedNameSpecifier();
3369 } else if (UnresolvedUsingTypenameDecl *UD
3370 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3371 DTypename = true;
3372 DQual = UD->getTargetNestedNameSpecifier();
3373 } else continue;
3374
3375 // using decls differ if one says 'typename' and the other doesn't.
3376 // FIXME: non-dependent using decls?
3377 if (isTypeName != DTypename) continue;
3378
3379 // using decls differ if they name different scopes (but note that
3380 // template instantiation can cause this check to trigger when it
3381 // didn't before instantiation).
3382 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3383 Context.getCanonicalNestedNameSpecifier(DQual))
3384 continue;
3385
3386 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003387 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003388 return true;
3389 }
3390
3391 return false;
3392}
3393
John McCall604e7f12009-12-08 07:46:18 +00003394
John McCalled976492009-12-04 22:46:56 +00003395/// Checks that the given nested-name qualifier used in a using decl
3396/// in the current context is appropriately related to the current
3397/// scope. If an error is found, diagnoses it and returns true.
3398bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3399 const CXXScopeSpec &SS,
3400 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003401 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003402
John McCall604e7f12009-12-08 07:46:18 +00003403 if (!CurContext->isRecord()) {
3404 // C++03 [namespace.udecl]p3:
3405 // C++0x [namespace.udecl]p8:
3406 // A using-declaration for a class member shall be a member-declaration.
3407
3408 // If we weren't able to compute a valid scope, it must be a
3409 // dependent class scope.
3410 if (!NamedContext || NamedContext->isRecord()) {
3411 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3412 << SS.getRange();
3413 return true;
3414 }
3415
3416 // Otherwise, everything is known to be fine.
3417 return false;
3418 }
3419
3420 // The current scope is a record.
3421
3422 // If the named context is dependent, we can't decide much.
3423 if (!NamedContext) {
3424 // FIXME: in C++0x, we can diagnose if we can prove that the
3425 // nested-name-specifier does not refer to a base class, which is
3426 // still possible in some cases.
3427
3428 // Otherwise we have to conservatively report that things might be
3429 // okay.
3430 return false;
3431 }
3432
3433 if (!NamedContext->isRecord()) {
3434 // Ideally this would point at the last name in the specifier,
3435 // but we don't have that level of source info.
3436 Diag(SS.getRange().getBegin(),
3437 diag::err_using_decl_nested_name_specifier_is_not_class)
3438 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3439 return true;
3440 }
3441
3442 if (getLangOptions().CPlusPlus0x) {
3443 // C++0x [namespace.udecl]p3:
3444 // In a using-declaration used as a member-declaration, the
3445 // nested-name-specifier shall name a base class of the class
3446 // being defined.
3447
3448 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3449 cast<CXXRecordDecl>(NamedContext))) {
3450 if (CurContext == NamedContext) {
3451 Diag(NameLoc,
3452 diag::err_using_decl_nested_name_specifier_is_current_class)
3453 << SS.getRange();
3454 return true;
3455 }
3456
3457 Diag(SS.getRange().getBegin(),
3458 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3459 << (NestedNameSpecifier*) SS.getScopeRep()
3460 << cast<CXXRecordDecl>(CurContext)
3461 << SS.getRange();
3462 return true;
3463 }
3464
3465 return false;
3466 }
3467
3468 // C++03 [namespace.udecl]p4:
3469 // A using-declaration used as a member-declaration shall refer
3470 // to a member of a base class of the class being defined [etc.].
3471
3472 // Salient point: SS doesn't have to name a base class as long as
3473 // lookup only finds members from base classes. Therefore we can
3474 // diagnose here only if we can prove that that can't happen,
3475 // i.e. if the class hierarchies provably don't intersect.
3476
3477 // TODO: it would be nice if "definitely valid" results were cached
3478 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3479 // need to be repeated.
3480
3481 struct UserData {
3482 llvm::DenseSet<const CXXRecordDecl*> Bases;
3483
3484 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3485 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3486 Data->Bases.insert(Base);
3487 return true;
3488 }
3489
3490 bool hasDependentBases(const CXXRecordDecl *Class) {
3491 return !Class->forallBases(collect, this);
3492 }
3493
3494 /// Returns true if the base is dependent or is one of the
3495 /// accumulated base classes.
3496 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3497 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3498 return !Data->Bases.count(Base);
3499 }
3500
3501 bool mightShareBases(const CXXRecordDecl *Class) {
3502 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3503 }
3504 };
3505
3506 UserData Data;
3507
3508 // Returns false if we find a dependent base.
3509 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3510 return false;
3511
3512 // Returns false if the class has a dependent base or if it or one
3513 // of its bases is present in the base set of the current context.
3514 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3515 return false;
3516
3517 Diag(SS.getRange().getBegin(),
3518 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3519 << (NestedNameSpecifier*) SS.getScopeRep()
3520 << cast<CXXRecordDecl>(CurContext)
3521 << SS.getRange();
3522
3523 return true;
John McCalled976492009-12-04 22:46:56 +00003524}
3525
Mike Stump1eb44332009-09-09 15:08:12 +00003526Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003527 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003528 SourceLocation AliasLoc,
3529 IdentifierInfo *Alias,
3530 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003531 SourceLocation IdentLoc,
3532 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003533
Anders Carlsson81c85c42009-03-28 23:53:49 +00003534 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003535 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3536 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003537
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003538 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003539 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003540 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003541 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003542 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003543 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003544 if (!R.isAmbiguous() && !R.empty() &&
3545 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003546 return DeclPtrTy();
3547 }
Mike Stump1eb44332009-09-09 15:08:12 +00003548
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003549 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3550 diag::err_redefinition_different_kind;
3551 Diag(AliasLoc, DiagID) << Alias;
3552 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003553 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003554 }
3555
John McCalla24dc2e2009-11-17 02:14:36 +00003556 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003557 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003558
John McCallf36e02d2009-10-09 21:13:30 +00003559 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003560 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003561 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003562 }
Mike Stump1eb44332009-09-09 15:08:12 +00003563
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003564 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003565 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3566 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003567 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003568 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003569
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003570 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00003571 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003572}
3573
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003574void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3575 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003576 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3577 !Constructor->isUsed()) &&
3578 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003579
Eli Friedman80c30da2009-11-09 19:20:36 +00003580 CXXRecordDecl *ClassDecl
3581 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3582 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003583
Eli Friedman80c30da2009-11-09 19:20:36 +00003584 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
Anders Carlsson37909802009-11-30 21:24:50 +00003585 Diag(CurrentLocation, diag::note_member_synthesized_at)
3586 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00003587 Constructor->setInvalidDecl();
3588 } else {
3589 Constructor->setUsed();
3590 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003591}
3592
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003593void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003594 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003595 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3596 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003597 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003598 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3599 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003600 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003601 // implicitly defined, all the implicitly-declared default destructors
3602 // for its base class and its non-static data members shall have been
3603 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003604 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3605 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003606 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003607 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003608 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003609 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003610 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3611 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3612 else
Mike Stump1eb44332009-09-09 15:08:12 +00003613 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003614 "DefineImplicitDestructor - missing dtor in a base class");
3615 }
3616 }
Mike Stump1eb44332009-09-09 15:08:12 +00003617
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003618 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3619 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003620 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3621 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3622 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003623 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003624 CXXRecordDecl *FieldClassDecl
3625 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3626 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003627 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003628 const_cast<CXXDestructorDecl*>(
3629 FieldClassDecl->getDestructor(Context)))
3630 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3631 else
Mike Stump1eb44332009-09-09 15:08:12 +00003632 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003633 "DefineImplicitDestructor - missing dtor in class of a data member");
3634 }
3635 }
3636 }
Anders Carlsson37909802009-11-30 21:24:50 +00003637
3638 // FIXME: If CheckDestructor fails, we should emit a note about where the
3639 // implicit destructor was needed.
3640 if (CheckDestructor(Destructor)) {
3641 Diag(CurrentLocation, diag::note_member_synthesized_at)
3642 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3643
3644 Destructor->setInvalidDecl();
3645 return;
3646 }
3647
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003648 Destructor->setUsed();
3649}
3650
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003651void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3652 CXXMethodDecl *MethodDecl) {
3653 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3654 MethodDecl->getOverloadedOperator() == OO_Equal &&
3655 !MethodDecl->isUsed()) &&
3656 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003657
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003658 CXXRecordDecl *ClassDecl
3659 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003660
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003661 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003662 // Before the implicitly-declared copy assignment operator for a class is
3663 // implicitly defined, all implicitly-declared copy assignment operators
3664 // for its direct base classes and its nonstatic data members shall have
3665 // been implicitly defined.
3666 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003667 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3668 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003669 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003670 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003671 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003672 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3673 BaseClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003674 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3675 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003676 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3677 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003678 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3679 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3680 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003681 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003682 CXXRecordDecl *FieldClassDecl
3683 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003684 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003685 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3686 FieldClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003687 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003688 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003689 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003690 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3691 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003692 Diag(CurrentLocation, diag::note_first_required_here);
3693 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003694 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003695 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003696 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3697 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003698 Diag(CurrentLocation, diag::note_first_required_here);
3699 err = true;
3700 }
3701 }
3702 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003703 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003704}
3705
3706CXXMethodDecl *
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003707Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3708 ParmVarDecl *ParmDecl,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003709 CXXRecordDecl *ClassDecl) {
3710 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3711 QualType RHSType(LHSType);
3712 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003713 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003714 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003715 RHSType = Context.getCVRQualifiedType(RHSType,
3716 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003717 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003718 LHSType,
3719 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003720 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003721 RHSType,
3722 CurrentLocation));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003723 Expr *Args[2] = { &*LHS, &*RHS };
3724 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003725 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003726 CandidateSet);
3727 OverloadCandidateSet::iterator Best;
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003728 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003729 return cast<CXXMethodDecl>(Best->Function);
3730 assert(false &&
3731 "getAssignOperatorMethod - copy assignment operator method not found");
3732 return 0;
3733}
3734
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003735void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3736 CXXConstructorDecl *CopyConstructor,
3737 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003738 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003739 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003740 !CopyConstructor->isUsed()) &&
3741 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003742
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003743 CXXRecordDecl *ClassDecl
3744 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3745 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003746 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003747 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003748 // implicitly defined, all the implicitly-declared copy constructors
3749 // for its base class and its non-static data members shall have been
3750 // implicitly defined.
3751 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3752 Base != ClassDecl->bases_end(); ++Base) {
3753 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003754 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003755 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003756 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003757 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003758 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003759 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3760 FieldEnd = ClassDecl->field_end();
3761 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003762 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3763 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3764 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003765 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003766 CXXRecordDecl *FieldClassDecl
3767 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003768 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003769 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003770 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003771 }
3772 }
3773 CopyConstructor->setUsed();
3774}
3775
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003776Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003777Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003778 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003779 MultiExprArg ExprArgs,
3780 bool RequiresZeroInit) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003781 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003782
Douglas Gregor39da0b82009-09-09 23:08:42 +00003783 // C++ [class.copy]p15:
3784 // Whenever a temporary class object is copied using a copy constructor, and
3785 // this object and the copy have the same cv-unqualified type, an
3786 // implementation is permitted to treat the original and the copy as two
3787 // different ways of referring to the same object and not perform a copy at
3788 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003789
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003790 // FIXME: Is this enough?
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003791 if (Constructor->isCopyConstructor()) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003792 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003793 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3794 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3795 E = ICE->getSubExpr();
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003796 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3797 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003798 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3799 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3800 E = ICE->getSubExpr();
Eli Friedman03368432009-12-06 09:26:33 +00003801
3802 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3803 Elidable = !CE->getCallReturnType()->isReferenceType();
3804 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003805 Elidable = true;
3806 }
Mike Stump1eb44332009-09-09 15:08:12 +00003807
3808 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003809 Elidable, move(ExprArgs), RequiresZeroInit);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003810}
3811
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003812/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3813/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003814Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003815Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3816 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00003817 MultiExprArg ExprArgs,
3818 bool RequiresZeroInit) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003819 unsigned NumExprs = ExprArgs.size();
3820 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003821
Douglas Gregor7edfb692009-11-23 12:27:39 +00003822 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003823 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00003824 Constructor, Elidable, Exprs, NumExprs,
3825 RequiresZeroInit));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003826}
3827
Anders Carlssone7624a72009-08-27 05:08:22 +00003828Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00003829Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3830 QualType Ty,
3831 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00003832 MultiExprArg Args,
3833 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003834 unsigned NumExprs = Args.size();
3835 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003836
Douglas Gregor7edfb692009-11-23 12:27:39 +00003837 MarkDeclarationReferenced(TyBeginLoc, Constructor);
Douglas Gregor39da0b82009-09-09 23:08:42 +00003838 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3839 TyBeginLoc, Exprs,
3840 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00003841}
3842
3843
Mike Stump1eb44332009-09-09 15:08:12 +00003844bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003845 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003846 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003847 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003848 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003849 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003850 if (TempResult.isInvalid())
3851 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003852
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003853 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003854 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00003855 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor78d15832009-05-26 18:54:04 +00003856 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003857
Anders Carlssonfe2de492009-08-25 05:18:00 +00003858 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003859}
3860
Mike Stump1eb44332009-09-09 15:08:12 +00003861void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003862 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00003863 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003864 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00003865 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003866 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003867 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003868}
3869
Mike Stump1eb44332009-09-09 15:08:12 +00003870/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003871/// ActOnDeclarator, when a C++ direct initializer is present.
3872/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00003873void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3874 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00003875 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003876 SourceLocation *CommaLocs,
3877 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00003878 unsigned NumExprs = Exprs.size();
3879 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00003880 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003881
3882 // If there is no declaration, there was an error parsing it. Just ignore
3883 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003884 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003885 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003886
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003887 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3888 if (!VDecl) {
3889 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3890 RealDecl->setInvalidDecl();
3891 return;
3892 }
3893
Douglas Gregor83ddad32009-08-26 21:14:46 +00003894 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003895 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003896 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3897 //
3898 // Clients that want to distinguish between the two forms, can check for
3899 // direct initializer using VarDecl::hasCXXDirectInitializer().
3900 // A major benefit is that clients that don't particularly care about which
3901 // exactly form was it (like the CodeGen) can handle both cases without
3902 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003903
Douglas Gregor83ddad32009-08-26 21:14:46 +00003904 // If either the declaration has a dependent type or if any of the expressions
3905 // is type-dependent, we represent the initialization via a ParenListExpr for
3906 // later use during template instantiation.
3907 if (VDecl->getType()->isDependentType() ||
3908 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3909 // Let clients know that initialization was done with a direct initializer.
3910 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003911
Douglas Gregor83ddad32009-08-26 21:14:46 +00003912 // Store the initialization expressions as a ParenListExpr.
3913 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003914 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003915 new (Context) ParenListExpr(Context, LParenLoc,
3916 (Expr **)Exprs.release(),
3917 NumExprs, RParenLoc));
3918 return;
3919 }
Mike Stump1eb44332009-09-09 15:08:12 +00003920
Douglas Gregor83ddad32009-08-26 21:14:46 +00003921
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003922 // C++ 8.5p11:
3923 // The form of initialization (using parentheses or '=') is generally
3924 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003925 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003926 QualType DeclInitType = VDecl->getType();
3927 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00003928 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003929
Douglas Gregor615c5d42009-03-24 16:43:20 +00003930 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3931 diag::err_typecheck_decl_incomplete_type)) {
3932 VDecl->setInvalidDecl();
3933 return;
3934 }
3935
Douglas Gregor90f93822009-12-22 22:17:25 +00003936 // The variable can not have an abstract class type.
3937 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
3938 diag::err_abstract_type_in_decl,
3939 AbstractVariableType))
3940 VDecl->setInvalidDecl();
3941
3942 const VarDecl *Def = 0;
3943 if (VDecl->getDefinition(Def)) {
3944 Diag(VDecl->getLocation(), diag::err_redefinition)
3945 << VDecl->getDeclName();
3946 Diag(Def->getLocation(), diag::note_previous_definition);
3947 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003948 return;
3949 }
Douglas Gregor90f93822009-12-22 22:17:25 +00003950
3951 // Capture the variable that is being initialized and the style of
3952 // initialization.
3953 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
3954
3955 // FIXME: Poor source location information.
3956 InitializationKind Kind
3957 = InitializationKind::CreateDirect(VDecl->getLocation(),
3958 LParenLoc, RParenLoc);
3959
3960 InitializationSequence InitSeq(*this, Entity, Kind,
3961 (Expr**)Exprs.get(), Exprs.size());
3962 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
3963 if (Result.isInvalid()) {
3964 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003965 return;
3966 }
Douglas Gregor90f93822009-12-22 22:17:25 +00003967
3968 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
3969 VDecl->setInit(Context, Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003970 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003971
Douglas Gregor90f93822009-12-22 22:17:25 +00003972 if (VDecl->getType()->getAs<RecordType>())
3973 FinalizeVarWithDestructor(VDecl, DeclInitType);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003974}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003975
Douglas Gregor19aeac62009-11-14 03:27:21 +00003976/// \brief Add the applicable constructor candidates for an initialization
3977/// by constructor.
3978static void AddConstructorInitializationCandidates(Sema &SemaRef,
3979 QualType ClassType,
3980 Expr **Args,
3981 unsigned NumArgs,
Douglas Gregor20093b42009-12-09 23:02:17 +00003982 InitializationKind Kind,
Douglas Gregor19aeac62009-11-14 03:27:21 +00003983 OverloadCandidateSet &CandidateSet) {
3984 // C++ [dcl.init]p14:
3985 // If the initialization is direct-initialization, or if it is
3986 // copy-initialization where the cv-unqualified version of the
3987 // source type is the same class as, or a derived class of, the
3988 // class of the destination, constructors are considered. The
3989 // applicable constructors are enumerated (13.3.1.3), and the
3990 // best one is chosen through overload resolution (13.3). The
3991 // constructor so selected is called to initialize the object,
3992 // with the initializer expression(s) as its argument(s). If no
3993 // constructor applies, or the overload resolution is ambiguous,
3994 // the initialization is ill-formed.
3995 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3996 assert(ClassRec && "Can only initialize a class type here");
3997
3998 // FIXME: When we decide not to synthesize the implicitly-declared
3999 // constructors, we'll need to make them appear here.
4000
4001 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4002 DeclarationName ConstructorName
4003 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4004 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4005 DeclContext::lookup_const_iterator Con, ConEnd;
4006 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4007 Con != ConEnd; ++Con) {
4008 // Find the constructor (which may be a template).
4009 CXXConstructorDecl *Constructor = 0;
4010 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4011 if (ConstructorTmpl)
4012 Constructor
4013 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4014 else
4015 Constructor = cast<CXXConstructorDecl>(*Con);
4016
Douglas Gregor20093b42009-12-09 23:02:17 +00004017 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4018 (Kind.getKind() == InitializationKind::IK_Value) ||
4019 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregor19aeac62009-11-14 03:27:21 +00004020 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00004021 ((Kind.getKind() == InitializationKind::IK_Default) &&
4022 Constructor->isDefaultConstructor())) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004023 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00004024 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
4025 /*ExplicitArgs*/ 0,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004026 Args, NumArgs, CandidateSet);
4027 else
4028 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
4029 }
4030 }
4031}
4032
4033/// \brief Attempt to perform initialization by constructor
4034/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4035/// copy-initialization.
4036///
4037/// This routine determines whether initialization by constructor is possible,
4038/// but it does not emit any diagnostics in the case where the initialization
4039/// is ill-formed.
4040///
4041/// \param ClassType the type of the object being initialized, which must have
4042/// class type.
4043///
4044/// \param Args the arguments provided to initialize the object
4045///
4046/// \param NumArgs the number of arguments provided to initialize the object
4047///
4048/// \param Kind the type of initialization being performed
4049///
4050/// \returns the constructor used to initialize the object, if successful.
4051/// Otherwise, emits a diagnostic and returns NULL.
4052CXXConstructorDecl *
4053Sema::TryInitializationByConstructor(QualType ClassType,
4054 Expr **Args, unsigned NumArgs,
4055 SourceLocation Loc,
4056 InitializationKind Kind) {
4057 // Build the overload candidate set
4058 OverloadCandidateSet CandidateSet;
4059 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4060 CandidateSet);
4061
4062 // Determine whether we found a constructor we can use.
4063 OverloadCandidateSet::iterator Best;
4064 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4065 case OR_Success:
4066 case OR_Deleted:
4067 // We found a constructor. Return it.
4068 return cast<CXXConstructorDecl>(Best->Function);
4069
4070 case OR_No_Viable_Function:
4071 case OR_Ambiguous:
4072 // Overload resolution failed. Return nothing.
4073 return 0;
4074 }
4075
4076 // Silence GCC warning
4077 return 0;
4078}
4079
Douglas Gregor39da0b82009-09-09 23:08:42 +00004080/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
4081/// may occur as part of direct-initialization or copy-initialization.
4082///
4083/// \param ClassType the type of the object being initialized, which must have
4084/// class type.
4085///
4086/// \param ArgsPtr the arguments provided to initialize the object
4087///
4088/// \param Loc the source location where the initialization occurs
4089///
4090/// \param Range the source range that covers the entire initialization
4091///
4092/// \param InitEntity the name of the entity being initialized, if known
4093///
4094/// \param Kind the type of initialization being performed
4095///
4096/// \param ConvertedArgs a vector that will be filled in with the
4097/// appropriately-converted arguments to the constructor (if initialization
4098/// succeeded).
4099///
4100/// \returns the constructor used to initialize the object, if successful.
4101/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004102CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00004103Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00004104 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00004105 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004106 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00004107 InitializationKind Kind,
4108 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004109
4110 // Build the overload candidate set
Douglas Gregor39da0b82009-09-09 23:08:42 +00004111 Expr **Args = (Expr **)ArgsPtr.get();
4112 unsigned NumArgs = ArgsPtr.size();
Douglas Gregor18fe5682008-11-03 20:45:27 +00004113 OverloadCandidateSet CandidateSet;
Douglas Gregor19aeac62009-11-14 03:27:21 +00004114 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4115 CandidateSet);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00004116
Douglas Gregor18fe5682008-11-03 20:45:27 +00004117 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004118 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00004119 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00004120 // We found a constructor. Break out so that we can convert the arguments
4121 // appropriately.
4122 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004123
Douglas Gregor18fe5682008-11-03 20:45:27 +00004124 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00004125 if (InitEntity)
4126 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00004127 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00004128 else
4129 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00004130 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00004131 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00004132 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004133
Douglas Gregor18fe5682008-11-03 20:45:27 +00004134 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00004135 if (InitEntity)
4136 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
4137 else
4138 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004139 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4140 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004141
4142 case OR_Deleted:
4143 if (InitEntity)
4144 Diag(Loc, diag::err_ovl_deleted_init)
4145 << Best->Function->isDeleted()
4146 << InitEntity << Range;
Fariborz Jahanian6a587cb2009-11-25 21:53:11 +00004147 else {
4148 const CXXRecordDecl *RD =
4149 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl());
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004150 Diag(Loc, diag::err_ovl_deleted_init)
4151 << Best->Function->isDeleted()
Fariborz Jahanian6a587cb2009-11-25 21:53:11 +00004152 << RD->getDeclName() << Range;
4153 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004154 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4155 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004156 }
Mike Stump1eb44332009-09-09 15:08:12 +00004157
Douglas Gregor39da0b82009-09-09 23:08:42 +00004158 // Convert the arguments, fill in default arguments, etc.
4159 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4160 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
4161 return 0;
4162
4163 return Constructor;
4164}
4165
4166/// \brief Given a constructor and the set of arguments provided for the
4167/// constructor, convert the arguments and add any required default arguments
4168/// to form a proper call to this constructor.
4169///
4170/// \returns true if an error occurred, false otherwise.
4171bool
4172Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4173 MultiExprArg ArgsPtr,
4174 SourceLocation Loc,
4175 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4176 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4177 unsigned NumArgs = ArgsPtr.size();
4178 Expr **Args = (Expr **)ArgsPtr.get();
4179
4180 const FunctionProtoType *Proto
4181 = Constructor->getType()->getAs<FunctionProtoType>();
4182 assert(Proto && "Constructor without a prototype?");
4183 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004184
4185 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004186 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004187 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004188 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004189 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004190
4191 VariadicCallType CallType =
4192 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4193 llvm::SmallVector<Expr *, 8> AllArgs;
4194 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4195 Proto, 0, Args, NumArgs, AllArgs,
4196 CallType);
4197 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4198 ConvertedArgs.push_back(AllArgs[i]);
4199 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004200}
4201
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004202/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4203/// determine whether they are reference-related,
4204/// reference-compatible, reference-compatible with added
4205/// qualification, or incompatible, for use in C++ initialization by
4206/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4207/// type, and the first type (T1) is the pointee type of the reference
4208/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00004209Sema::ReferenceCompareResult
Douglas Gregor393896f2009-11-05 13:06:35 +00004210Sema::CompareReferenceRelationship(SourceLocation Loc,
4211 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00004212 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00004213 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004214 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00004215 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004216
Douglas Gregor393896f2009-11-05 13:06:35 +00004217 QualType T1 = Context.getCanonicalType(OrigT1);
4218 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregora4923eb2009-11-16 21:35:15 +00004219 QualType UnqualT1 = T1.getLocalUnqualifiedType();
4220 QualType UnqualT2 = T2.getLocalUnqualifiedType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004221
4222 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004223 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00004224 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004225 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004226 if (UnqualT1 == UnqualT2)
4227 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00004228 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4229 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4230 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00004231 DerivedToBase = true;
4232 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004233 return Ref_Incompatible;
4234
4235 // At this point, we know that T1 and T2 are reference-related (at
4236 // least).
4237
4238 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004239 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004240 // reference-related to T2 and cv1 is the same cv-qualification
4241 // as, or greater cv-qualification than, cv2. For purposes of
4242 // overload resolution, cases for which cv1 is greater
4243 // cv-qualification than cv2 are identified as
4244 // reference-compatible with added qualification (see 13.3.3.2).
4245 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
4246 return Ref_Compatible;
4247 else if (T1.isMoreQualifiedThan(T2))
4248 return Ref_Compatible_With_Added_Qualification;
4249 else
4250 return Ref_Related;
4251}
4252
4253/// CheckReferenceInit - Check the initialization of a reference
4254/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4255/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00004256/// list), and DeclType is the type of the declaration. When ICS is
4257/// non-null, this routine will compute the implicit conversion
4258/// sequence according to C++ [over.ics.ref] and will not produce any
4259/// diagnostics; when ICS is null, it will emit diagnostics when any
4260/// errors are found. Either way, a return value of true indicates
4261/// that there was a failure, a return value of false indicates that
4262/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00004263///
4264/// When @p SuppressUserConversions, user-defined conversions are
4265/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004266/// When @p AllowExplicit, we also permit explicit user-defined
4267/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00004268/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004269/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4270/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004271bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004272Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00004273 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004274 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00004275 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004276 ImplicitConversionSequence *ICS,
4277 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004278 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4279
Ted Kremenek6217b802009-07-29 21:53:49 +00004280 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004281 QualType T2 = Init->getType();
4282
Douglas Gregor904eed32008-11-10 20:40:00 +00004283 // If the initializer is the address of an overloaded function, try
4284 // to resolve the overloaded function. If all goes well, T2 is the
4285 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00004286 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00004287 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004288 ICS != 0);
4289 if (Fn) {
4290 // Since we're performing this reference-initialization for
4291 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004292 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00004293 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor20093b42009-12-09 23:02:17 +00004294 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004295
Anders Carlsson96ad5332009-10-21 17:16:23 +00004296 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004297 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004298
4299 T2 = Fn->getType();
4300 }
4301 }
4302
Douglas Gregor15da57e2008-10-29 02:00:59 +00004303 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004304 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004305 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00004306 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4307 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00004308 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00004309 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004310
4311 // Most paths end in a failed conversion.
4312 if (ICS)
4313 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004314
4315 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00004316 // A reference to type "cv1 T1" is initialized by an expression
4317 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004318
4319 // -- If the initializer expression
4320
Sebastian Redla9845802009-03-29 15:27:50 +00004321 // Rvalue references cannot bind to lvalues (N2812).
4322 // There is absolutely no situation where they can. In particular, note that
4323 // this is ill-formed, even if B has a user-defined conversion to A&&:
4324 // B b;
4325 // A&& r = b;
4326 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4327 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004328 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00004329 << Init->getSourceRange();
4330 return true;
4331 }
4332
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004333 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00004334 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4335 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00004336 //
4337 // Note that the bit-field check is skipped if we are just computing
4338 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00004339 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004340 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004341 BindsDirectly = true;
4342
Douglas Gregor15da57e2008-10-29 02:00:59 +00004343 if (ICS) {
4344 // C++ [over.ics.ref]p1:
4345 // When a parameter of reference type binds directly (8.5.3)
4346 // to an argument expression, the implicit conversion sequence
4347 // is the identity conversion, unless the argument expression
4348 // has a type that is a derived class of the parameter type,
4349 // in which case the implicit conversion sequence is a
4350 // derived-to-base Conversion (13.3.3.1).
4351 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4352 ICS->Standard.First = ICK_Identity;
4353 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4354 ICS->Standard.Third = ICK_Identity;
4355 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4356 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004357 ICS->Standard.ReferenceBinding = true;
4358 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004359 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00004360 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004361
4362 // Nothing more to do: the inaccessibility/ambiguity check for
4363 // derived-to-base conversions is suppressed when we're
4364 // computing the implicit conversion sequence (C++
4365 // [over.best.ics]p2).
4366 return false;
4367 } else {
4368 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00004369 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4370 if (DerivedToBase)
4371 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004372 else if(CheckExceptionSpecCompatibility(Init, T1))
4373 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004374 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004375 }
4376 }
4377
4378 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00004379 // implicitly converted to an lvalue of type "cv3 T3,"
4380 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004381 // 92) (this conversion is selected by enumerating the
4382 // applicable conversion functions (13.3.1.6) and choosing
4383 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00004384 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00004385 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004386 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004387 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004388
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004389 OverloadCandidateSet CandidateSet;
John McCallba135432009-11-21 08:51:07 +00004390 const UnresolvedSet *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004391 = T2RecordDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00004392 for (UnresolvedSet::iterator I = Conversions->begin(),
4393 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00004394 NamedDecl *D = *I;
4395 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4396 if (isa<UsingShadowDecl>(D))
4397 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4398
Mike Stump1eb44332009-09-09 15:08:12 +00004399 FunctionTemplateDecl *ConvTemplate
John McCall701c89e2009-12-03 04:06:58 +00004400 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004401 CXXConversionDecl *Conv;
4402 if (ConvTemplate)
4403 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4404 else
John McCall701c89e2009-12-03 04:06:58 +00004405 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004406
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004407 // If the conversion function doesn't return a reference type,
4408 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004409 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004410 (AllowExplicit || !Conv->isExplicit())) {
4411 if (ConvTemplate)
John McCall701c89e2009-12-03 04:06:58 +00004412 AddTemplateConversionCandidate(ConvTemplate, ActingDC,
4413 Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004414 else
John McCall701c89e2009-12-03 04:06:58 +00004415 AddConversionCandidate(Conv, ActingDC, Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004416 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004417 }
4418
4419 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00004420 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004421 case OR_Success:
4422 // This is a direct binding.
4423 BindsDirectly = true;
4424
4425 if (ICS) {
4426 // C++ [over.ics.ref]p1:
4427 //
4428 // [...] If the parameter binds directly to the result of
4429 // applying a conversion function to the argument
4430 // expression, the implicit conversion sequence is a
4431 // user-defined conversion sequence (13.3.3.1.2), with the
4432 // second standard conversion sequence either an identity
4433 // conversion or, if the conversion function returns an
4434 // entity of a type that is a derived class of the parameter
4435 // type, a derived-to-base Conversion.
4436 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
4437 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4438 ICS->UserDefined.After = Best->FinalConversion;
4439 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004440 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004441 assert(ICS->UserDefined.After.ReferenceBinding &&
4442 ICS->UserDefined.After.DirectBinding &&
4443 "Expected a direct reference binding!");
4444 return false;
4445 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004446 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00004447 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004448 CastExpr::CK_UserDefinedConversion,
4449 cast<CXXMethodDecl>(Best->Function),
4450 Owned(Init));
4451 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004452
4453 if (CheckExceptionSpecCompatibility(Init, T1))
4454 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004455 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4456 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004457 }
4458 break;
4459
4460 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004461 if (ICS) {
4462 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4463 Cand != CandidateSet.end(); ++Cand)
4464 if (Cand->Viable)
4465 ICS->ConversionFunctionSet.push_back(Cand->Function);
4466 break;
4467 }
4468 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4469 << Init->getSourceRange();
4470 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004471 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004472
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004473 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004474 case OR_Deleted:
4475 // There was no suitable conversion, or we found a deleted
4476 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004477 break;
4478 }
4479 }
Mike Stump1eb44332009-09-09 15:08:12 +00004480
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004481 if (BindsDirectly) {
4482 // C++ [dcl.init.ref]p4:
4483 // [...] In all cases where the reference-related or
4484 // reference-compatible relationship of two types is used to
4485 // establish the validity of a reference binding, and T1 is a
4486 // base class of T2, a program that necessitates such a binding
4487 // is ill-formed if T1 is an inaccessible (clause 11) or
4488 // ambiguous (10.2) base class of T2.
4489 //
4490 // Note that we only check this condition when we're allowed to
4491 // complain about errors, because we should not be checking for
4492 // ambiguity (or inaccessibility) unless the reference binding
4493 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00004494 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00004495 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004496 Init->getSourceRange(),
4497 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004498 else
4499 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004500 }
4501
4502 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00004503 // type (i.e., cv1 shall be const), or the reference shall be an
4504 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00004505 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00004506 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004507 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004508 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004509 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004510 return true;
4511 }
4512
4513 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00004514 // class type, and "cv1 T1" is reference-compatible with
4515 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004516 // following ways (the choice is implementation-defined):
4517 //
4518 // -- The reference is bound to the object represented by
4519 // the rvalue (see 3.10) or to a sub-object within that
4520 // object.
4521 //
Eli Friedman33a31382009-08-05 19:21:58 +00004522 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004523 // a constructor is called to copy the entire rvalue
4524 // object into the temporary. The reference is bound to
4525 // the temporary or to a sub-object within the
4526 // temporary.
4527 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004528 // The constructor that would be used to make the copy
4529 // shall be callable whether or not the copy is actually
4530 // done.
4531 //
Sebastian Redla9845802009-03-29 15:27:50 +00004532 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004533 // freedom, so we will always take the first option and never build
4534 // a temporary in this case. FIXME: We will, however, have to check
4535 // for the presence of a copy constructor in C++98/03 mode.
4536 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004537 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4538 if (ICS) {
4539 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4540 ICS->Standard.First = ICK_Identity;
4541 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4542 ICS->Standard.Third = ICK_Identity;
4543 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4544 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004545 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004546 ICS->Standard.DirectBinding = false;
4547 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004548 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004549 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004550 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4551 if (DerivedToBase)
4552 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004553 else if(CheckExceptionSpecCompatibility(Init, T1))
4554 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004555 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004556 }
4557 return false;
4558 }
4559
Eli Friedman33a31382009-08-05 19:21:58 +00004560 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004561 // initialized from the initializer expression using the
4562 // rules for a non-reference copy initialization (8.5). The
4563 // reference is then bound to the temporary. If T1 is
4564 // reference-related to T2, cv1 must be the same
4565 // cv-qualification as, or greater cv-qualification than,
4566 // cv2; otherwise, the program is ill-formed.
4567 if (RefRelationship == Ref_Related) {
4568 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4569 // we would be reference-compatible or reference-compatible with
4570 // added qualification. But that wasn't the case, so the reference
4571 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004572 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004573 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004574 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004575 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004576 return true;
4577 }
4578
Douglas Gregor734d9862009-01-30 23:27:23 +00004579 // If at least one of the types is a class type, the types are not
4580 // related, and we aren't allowed any user conversions, the
4581 // reference binding fails. This case is important for breaking
4582 // recursion, since TryImplicitConversion below will attempt to
4583 // create a temporary through the use of a copy constructor.
4584 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4585 (T1->isRecordType() || T2->isRecordType())) {
4586 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004587 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00004588 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor734d9862009-01-30 23:27:23 +00004589 return true;
4590 }
4591
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004592 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004593 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004594 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004595 //
Sebastian Redla9845802009-03-29 15:27:50 +00004596 // When a parameter of reference type is not bound directly to
4597 // an argument expression, the conversion sequence is the one
4598 // required to convert the argument expression to the
4599 // underlying type of the reference according to
4600 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4601 // to copy-initializing a temporary of the underlying type with
4602 // the argument expression. Any difference in top-level
4603 // cv-qualification is subsumed by the initialization itself
4604 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004605 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4606 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004607 /*ForceRValue=*/false,
4608 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004609
Sebastian Redla9845802009-03-29 15:27:50 +00004610 // Of course, that's still a reference binding.
4611 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4612 ICS->Standard.ReferenceBinding = true;
4613 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004614 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00004615 ImplicitConversionSequence::UserDefinedConversion) {
4616 ICS->UserDefined.After.ReferenceBinding = true;
4617 ICS->UserDefined.After.RRefBinding = isRValRef;
4618 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00004619 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4620 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004621 ImplicitConversionSequence Conversions;
Douglas Gregor68647482009-12-16 03:45:30 +00004622 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004623 false, false,
4624 Conversions);
4625 if (badConversion) {
4626 if ((Conversions.ConversionKind ==
4627 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian82ad87b2009-09-28 22:03:07 +00004628 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004629 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004630 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4631 for (int j = Conversions.ConversionFunctionSet.size()-1;
4632 j >= 0; j--) {
4633 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4634 Diag(Func->getLocation(), diag::err_ovl_candidate);
4635 }
4636 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004637 else {
4638 if (isRValRef)
4639 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4640 << Init->getSourceRange();
4641 else
4642 Diag(DeclLoc, diag::err_invalid_initialization)
4643 << DeclType << Init->getType() << Init->getSourceRange();
4644 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004645 }
4646 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004647 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004648}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004649
Anders Carlsson20d45d22009-12-12 00:32:00 +00004650static inline bool
4651CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4652 const FunctionDecl *FnDecl) {
4653 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4654 if (isa<NamespaceDecl>(DC)) {
4655 return SemaRef.Diag(FnDecl->getLocation(),
4656 diag::err_operator_new_delete_declared_in_namespace)
4657 << FnDecl->getDeclName();
4658 }
4659
4660 if (isa<TranslationUnitDecl>(DC) &&
4661 FnDecl->getStorageClass() == FunctionDecl::Static) {
4662 return SemaRef.Diag(FnDecl->getLocation(),
4663 diag::err_operator_new_delete_declared_static)
4664 << FnDecl->getDeclName();
4665 }
4666
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004667 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004668}
4669
Anders Carlsson156c78e2009-12-13 17:53:43 +00004670static inline bool
4671CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4672 CanQualType ExpectedResultType,
4673 CanQualType ExpectedFirstParamType,
4674 unsigned DependentParamTypeDiag,
4675 unsigned InvalidParamTypeDiag) {
4676 QualType ResultType =
4677 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4678
4679 // Check that the result type is not dependent.
4680 if (ResultType->isDependentType())
4681 return SemaRef.Diag(FnDecl->getLocation(),
4682 diag::err_operator_new_delete_dependent_result_type)
4683 << FnDecl->getDeclName() << ExpectedResultType;
4684
4685 // Check that the result type is what we expect.
4686 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4687 return SemaRef.Diag(FnDecl->getLocation(),
4688 diag::err_operator_new_delete_invalid_result_type)
4689 << FnDecl->getDeclName() << ExpectedResultType;
4690
4691 // A function template must have at least 2 parameters.
4692 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4693 return SemaRef.Diag(FnDecl->getLocation(),
4694 diag::err_operator_new_delete_template_too_few_parameters)
4695 << FnDecl->getDeclName();
4696
4697 // The function decl must have at least 1 parameter.
4698 if (FnDecl->getNumParams() == 0)
4699 return SemaRef.Diag(FnDecl->getLocation(),
4700 diag::err_operator_new_delete_too_few_parameters)
4701 << FnDecl->getDeclName();
4702
4703 // Check the the first parameter type is not dependent.
4704 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4705 if (FirstParamType->isDependentType())
4706 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4707 << FnDecl->getDeclName() << ExpectedFirstParamType;
4708
4709 // Check that the first parameter type is what we expect.
4710 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4711 ExpectedFirstParamType)
4712 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4713 << FnDecl->getDeclName() << ExpectedFirstParamType;
4714
4715 return false;
4716}
4717
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004718static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004719CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004720 // C++ [basic.stc.dynamic.allocation]p1:
4721 // A program is ill-formed if an allocation function is declared in a
4722 // namespace scope other than global scope or declared static in global
4723 // scope.
4724 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4725 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004726
4727 CanQualType SizeTy =
4728 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4729
4730 // C++ [basic.stc.dynamic.allocation]p1:
4731 // The return type shall be void*. The first parameter shall have type
4732 // std::size_t.
4733 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4734 SizeTy,
4735 diag::err_operator_new_dependent_param_type,
4736 diag::err_operator_new_param_type))
4737 return true;
4738
4739 // C++ [basic.stc.dynamic.allocation]p1:
4740 // The first parameter shall not have an associated default argument.
4741 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00004742 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00004743 diag::err_operator_new_default_arg)
4744 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4745
4746 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00004747}
4748
4749static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004750CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4751 // C++ [basic.stc.dynamic.deallocation]p1:
4752 // A program is ill-formed if deallocation functions are declared in a
4753 // namespace scope other than global scope or declared static in global
4754 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00004755 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4756 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004757
4758 // C++ [basic.stc.dynamic.deallocation]p2:
4759 // Each deallocation function shall return void and its first parameter
4760 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00004761 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4762 SemaRef.Context.VoidPtrTy,
4763 diag::err_operator_delete_dependent_param_type,
4764 diag::err_operator_delete_param_type))
4765 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004766
Anders Carlsson46991d62009-12-12 00:16:02 +00004767 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4768 if (FirstParamType->isDependentType())
4769 return SemaRef.Diag(FnDecl->getLocation(),
4770 diag::err_operator_delete_dependent_param_type)
4771 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4772
4773 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4774 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004775 return SemaRef.Diag(FnDecl->getLocation(),
4776 diag::err_operator_delete_param_type)
4777 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004778
4779 return false;
4780}
4781
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004782/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4783/// of this overloaded operator is well-formed. If so, returns false;
4784/// otherwise, emits appropriate diagnostics and returns true.
4785bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004786 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004787 "Expected an overloaded operator declaration");
4788
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004789 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4790
Mike Stump1eb44332009-09-09 15:08:12 +00004791 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004792 // The allocation and deallocation functions, operator new,
4793 // operator new[], operator delete and operator delete[], are
4794 // described completely in 3.7.3. The attributes and restrictions
4795 // found in the rest of this subclause do not apply to them unless
4796 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004797 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004798 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004799
Anders Carlssona3ccda52009-12-12 00:26:23 +00004800 if (Op == OO_New || Op == OO_Array_New)
4801 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004802
4803 // C++ [over.oper]p6:
4804 // An operator function shall either be a non-static member
4805 // function or be a non-member function and have at least one
4806 // parameter whose type is a class, a reference to a class, an
4807 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004808 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4809 if (MethodDecl->isStatic())
4810 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004811 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004812 } else {
4813 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004814 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4815 ParamEnd = FnDecl->param_end();
4816 Param != ParamEnd; ++Param) {
4817 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004818 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4819 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004820 ClassOrEnumParam = true;
4821 break;
4822 }
4823 }
4824
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004825 if (!ClassOrEnumParam)
4826 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004827 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004828 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004829 }
4830
4831 // C++ [over.oper]p8:
4832 // An operator function cannot have default arguments (8.3.6),
4833 // except where explicitly stated below.
4834 //
Mike Stump1eb44332009-09-09 15:08:12 +00004835 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004836 // (C++ [over.call]p1).
4837 if (Op != OO_Call) {
4838 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4839 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00004840 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004841 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004842 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00004843 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004844 }
4845 }
4846
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004847 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4848 { false, false, false }
4849#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4850 , { Unary, Binary, MemberOnly }
4851#include "clang/Basic/OperatorKinds.def"
4852 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004853
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004854 bool CanBeUnaryOperator = OperatorUses[Op][0];
4855 bool CanBeBinaryOperator = OperatorUses[Op][1];
4856 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004857
4858 // C++ [over.oper]p8:
4859 // [...] Operator functions cannot have more or fewer parameters
4860 // than the number required for the corresponding operator, as
4861 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004862 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004863 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004864 if (Op != OO_Call &&
4865 ((NumParams == 1 && !CanBeUnaryOperator) ||
4866 (NumParams == 2 && !CanBeBinaryOperator) ||
4867 (NumParams < 1) || (NumParams > 2))) {
4868 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004869 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004870 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004871 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004872 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004873 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004874 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004875 assert(CanBeBinaryOperator &&
4876 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004877 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004878 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004879
Chris Lattner416e46f2008-11-21 07:57:12 +00004880 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004881 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004882 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004883
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004884 // Overloaded operators other than operator() cannot be variadic.
4885 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004886 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004887 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004888 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004889 }
4890
4891 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004892 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4893 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004894 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004895 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004896 }
4897
4898 // C++ [over.inc]p1:
4899 // The user-defined function called operator++ implements the
4900 // prefix and postfix ++ operator. If this function is a member
4901 // function with no parameters, or a non-member function with one
4902 // parameter of class or enumeration type, it defines the prefix
4903 // increment operator ++ for objects of that type. If the function
4904 // is a member function with one parameter (which shall be of type
4905 // int) or a non-member function with two parameters (the second
4906 // of which shall be of type int), it defines the postfix
4907 // increment operator ++ for objects of that type.
4908 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4909 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4910 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004911 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004912 ParamIsInt = BT->getKind() == BuiltinType::Int;
4913
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004914 if (!ParamIsInt)
4915 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004916 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004917 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004918 }
4919
Sebastian Redl64b45f72009-01-05 20:52:13 +00004920 // Notify the class if it got an assignment operator.
4921 if (Op == OO_Equal) {
4922 // Would have returned earlier otherwise.
4923 assert(isa<CXXMethodDecl>(FnDecl) &&
4924 "Overloaded = not member, but not filtered.");
4925 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4926 Method->getParent()->addedAssignmentOperator(Context, Method);
4927 }
4928
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004929 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004930}
Chris Lattner5a003a42008-12-17 07:09:26 +00004931
Douglas Gregor074149e2009-01-05 19:45:36 +00004932/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4933/// linkage specification, including the language and (if present)
4934/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4935/// the location of the language string literal, which is provided
4936/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4937/// the '{' brace. Otherwise, this linkage specification does not
4938/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004939Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4940 SourceLocation ExternLoc,
4941 SourceLocation LangLoc,
4942 const char *Lang,
4943 unsigned StrSize,
4944 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00004945 LinkageSpecDecl::LanguageIDs Language;
4946 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4947 Language = LinkageSpecDecl::lang_c;
4948 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4949 Language = LinkageSpecDecl::lang_cxx;
4950 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00004951 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004952 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00004953 }
Mike Stump1eb44332009-09-09 15:08:12 +00004954
Chris Lattnercc98eac2008-12-17 07:13:27 +00004955 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00004956
Douglas Gregor074149e2009-01-05 19:45:36 +00004957 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00004958 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00004959 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004960 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00004961 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004962 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00004963}
4964
Douglas Gregor074149e2009-01-05 19:45:36 +00004965/// ActOnFinishLinkageSpecification - Completely the definition of
4966/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4967/// valid, it's the position of the closing '}' brace in a linkage
4968/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004969Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4970 DeclPtrTy LinkageSpec,
4971 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00004972 if (LinkageSpec)
4973 PopDeclContext();
4974 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00004975}
4976
Douglas Gregord308e622009-05-18 20:51:54 +00004977/// \brief Perform semantic analysis for the variable declaration that
4978/// occurs within a C++ catch clause, returning the newly-created
4979/// variable.
4980VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00004981 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004982 IdentifierInfo *Name,
4983 SourceLocation Loc,
4984 SourceRange Range) {
4985 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004986
4987 // Arrays and functions decay.
4988 if (ExDeclType->isArrayType())
4989 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4990 else if (ExDeclType->isFunctionType())
4991 ExDeclType = Context.getPointerType(ExDeclType);
4992
4993 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4994 // The exception-declaration shall not denote a pointer or reference to an
4995 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004996 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00004997 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00004998 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004999 Invalid = true;
5000 }
Douglas Gregord308e622009-05-18 20:51:54 +00005001
Sebastian Redl4b07b292008-12-22 19:15:10 +00005002 QualType BaseType = ExDeclType;
5003 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005004 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00005005 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005006 BaseType = Ptr->getPointeeType();
5007 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005008 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00005009 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005010 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005011 BaseType = Ref->getPointeeType();
5012 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005013 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005014 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005015 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00005016 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00005017 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005018
Mike Stump1eb44332009-09-09 15:08:12 +00005019 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00005020 RequireNonAbstractType(Loc, ExDeclType,
5021 diag::err_abstract_type_in_decl,
5022 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00005023 Invalid = true;
5024
Douglas Gregord308e622009-05-18 20:51:54 +00005025 // FIXME: Need to test for ability to copy-construct and destroy the
5026 // exception variable.
5027
Sebastian Redl8351da02008-12-22 21:35:02 +00005028 // FIXME: Need to check for abstract classes.
5029
Mike Stump1eb44332009-09-09 15:08:12 +00005030 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalla93c9342009-12-07 02:54:59 +00005031 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00005032
5033 if (Invalid)
5034 ExDecl->setInvalidDecl();
5035
5036 return ExDecl;
5037}
5038
5039/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5040/// handler.
5041Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00005042 TypeSourceInfo *TInfo = 0;
5043 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00005044
5045 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00005046 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00005047 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005048 // The scope should be freshly made just for us. There is just no way
5049 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005050 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00005051 if (PrevDecl->isTemplateParameter()) {
5052 // Maybe we will complain about the shadowed template parameter.
5053 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005054 }
5055 }
5056
Chris Lattnereaaebc72009-04-25 08:06:05 +00005057 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005058 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5059 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005060 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005061 }
5062
John McCalla93c9342009-12-07 02:54:59 +00005063 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005064 D.getIdentifier(),
5065 D.getIdentifierLoc(),
5066 D.getDeclSpec().getSourceRange());
5067
Chris Lattnereaaebc72009-04-25 08:06:05 +00005068 if (Invalid)
5069 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005070
Sebastian Redl4b07b292008-12-22 19:15:10 +00005071 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005072 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00005073 PushOnScopeChains(ExDecl, S);
5074 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005075 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005076
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005077 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005078 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005079}
Anders Carlssonfb311762009-03-14 00:25:26 +00005080
Mike Stump1eb44332009-09-09 15:08:12 +00005081Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005082 ExprArg assertexpr,
5083 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00005084 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005085 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00005086 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5087
Anders Carlssonc3082412009-03-14 00:33:21 +00005088 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5089 llvm::APSInt Value(32);
5090 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5091 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5092 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005093 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005094 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005095
Anders Carlssonc3082412009-03-14 00:33:21 +00005096 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005097 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005098 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005099 }
5100 }
Mike Stump1eb44332009-09-09 15:08:12 +00005101
Anders Carlsson77d81422009-03-15 17:35:16 +00005102 assertexpr.release();
5103 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005104 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005105 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005106
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005107 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005108 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005109}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005110
John McCalldd4a3b02009-09-16 22:47:08 +00005111/// Handle a friend type declaration. This works in tandem with
5112/// ActOnTag.
5113///
5114/// Notes on friend class templates:
5115///
5116/// We generally treat friend class declarations as if they were
5117/// declaring a class. So, for example, the elaborated type specifier
5118/// in a friend declaration is required to obey the restrictions of a
5119/// class-head (i.e. no typedefs in the scope chain), template
5120/// parameters are required to match up with simple template-ids, &c.
5121/// However, unlike when declaring a template specialization, it's
5122/// okay to refer to a template specialization without an empty
5123/// template parameter declaration, e.g.
5124/// friend class A<T>::B<unsigned>;
5125/// We permit this as a special case; if there are any template
5126/// parameters present at all, require proper matching, i.e.
5127/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005128Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005129 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005130 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005131
5132 assert(DS.isFriendSpecified());
5133 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5134
John McCalldd4a3b02009-09-16 22:47:08 +00005135 // Try to convert the decl specifier to a type. This works for
5136 // friend templates because ActOnTag never produces a ClassTemplateDecl
5137 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005138 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005139 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5140 if (TheDeclarator.isInvalidType())
5141 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005142
John McCalldd4a3b02009-09-16 22:47:08 +00005143 // This is definitely an error in C++98. It's probably meant to
5144 // be forbidden in C++0x, too, but the specification is just
5145 // poorly written.
5146 //
5147 // The problem is with declarations like the following:
5148 // template <T> friend A<T>::foo;
5149 // where deciding whether a class C is a friend or not now hinges
5150 // on whether there exists an instantiation of A that causes
5151 // 'foo' to equal C. There are restrictions on class-heads
5152 // (which we declare (by fiat) elaborated friend declarations to
5153 // be) that makes this tractable.
5154 //
5155 // FIXME: handle "template <> friend class A<T>;", which
5156 // is possibly well-formed? Who even knows?
5157 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5158 Diag(Loc, diag::err_tagless_friend_type_template)
5159 << DS.getSourceRange();
5160 return DeclPtrTy();
5161 }
5162
John McCall02cace72009-08-28 07:59:38 +00005163 // C++ [class.friend]p2:
5164 // An elaborated-type-specifier shall be used in a friend declaration
5165 // for a class.*
5166 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00005167 // This is one of the rare places in Clang where it's legitimate to
5168 // ask about the "spelling" of the type.
5169 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5170 // If we evaluated the type to a record type, suggest putting
5171 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00005172 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00005173 RecordDecl *RD = RT->getDecl();
5174
5175 std::string InsertionText = std::string(" ") + RD->getKindName();
5176
John McCalle3af0232009-10-07 23:34:25 +00005177 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5178 << (unsigned) RD->getTagKind()
5179 << T
5180 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00005181 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5182 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00005183 return DeclPtrTy();
5184 }else {
John McCall6b2becf2009-09-08 17:47:29 +00005185 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5186 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005187 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00005188 }
5189 }
5190
John McCalle3af0232009-10-07 23:34:25 +00005191 // Enum types cannot be friends.
5192 if (T->getAs<EnumType>()) {
5193 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5194 << SourceRange(DS.getFriendSpecLoc());
5195 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00005196 }
John McCall02cace72009-08-28 07:59:38 +00005197
John McCall02cace72009-08-28 07:59:38 +00005198 // C++98 [class.friend]p1: A friend of a class is a function
5199 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00005200 // This is fixed in DR77, which just barely didn't make the C++03
5201 // deadline. It's also a very silly restriction that seriously
5202 // affects inner classes and which nobody else seems to implement;
5203 // thus we never diagnose it, not even in -pedantic.
John McCall02cace72009-08-28 07:59:38 +00005204
John McCalldd4a3b02009-09-16 22:47:08 +00005205 Decl *D;
5206 if (TempParams.size())
5207 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5208 TempParams.size(),
5209 (TemplateParameterList**) TempParams.release(),
5210 T.getTypePtr(),
5211 DS.getFriendSpecLoc());
5212 else
5213 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5214 DS.getFriendSpecLoc());
5215 D->setAccess(AS_public);
5216 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005217
John McCalldd4a3b02009-09-16 22:47:08 +00005218 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005219}
5220
John McCallbbbcdd92009-09-11 21:02:39 +00005221Sema::DeclPtrTy
5222Sema::ActOnFriendFunctionDecl(Scope *S,
5223 Declarator &D,
5224 bool IsDefinition,
5225 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005226 const DeclSpec &DS = D.getDeclSpec();
5227
5228 assert(DS.isFriendSpecified());
5229 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5230
5231 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005232 TypeSourceInfo *TInfo = 0;
5233 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005234
5235 // C++ [class.friend]p1
5236 // A friend of a class is a function or class....
5237 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005238 // It *doesn't* see through dependent types, which is correct
5239 // according to [temp.arg.type]p3:
5240 // If a declaration acquires a function type through a
5241 // type dependent on a template-parameter and this causes
5242 // a declaration that does not use the syntactic form of a
5243 // function declarator to have a function type, the program
5244 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005245 if (!T->isFunctionType()) {
5246 Diag(Loc, diag::err_unexpected_friend);
5247
5248 // It might be worthwhile to try to recover by creating an
5249 // appropriate declaration.
5250 return DeclPtrTy();
5251 }
5252
5253 // C++ [namespace.memdef]p3
5254 // - If a friend declaration in a non-local class first declares a
5255 // class or function, the friend class or function is a member
5256 // of the innermost enclosing namespace.
5257 // - The name of the friend is not found by simple name lookup
5258 // until a matching declaration is provided in that namespace
5259 // scope (either before or after the class declaration granting
5260 // friendship).
5261 // - If a friend function is called, its name may be found by the
5262 // name lookup that considers functions from namespaces and
5263 // classes associated with the types of the function arguments.
5264 // - When looking for a prior declaration of a class or a function
5265 // declared as a friend, scopes outside the innermost enclosing
5266 // namespace scope are not considered.
5267
John McCall02cace72009-08-28 07:59:38 +00005268 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5269 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005270 assert(Name);
5271
John McCall67d1a672009-08-06 02:15:43 +00005272 // The context we found the declaration in, or in which we should
5273 // create the declaration.
5274 DeclContext *DC;
5275
5276 // FIXME: handle local classes
5277
5278 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005279 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5280 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005281 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00005282 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00005283 DC = computeDeclContext(ScopeQual);
5284
5285 // FIXME: handle dependent contexts
5286 if (!DC) return DeclPtrTy();
5287
John McCall68263142009-11-18 22:49:29 +00005288 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005289
5290 // If searching in that context implicitly found a declaration in
5291 // a different context, treat it like it wasn't found at all.
5292 // TODO: better diagnostics for this case. Suggesting the right
5293 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005294 // FIXME: getRepresentativeDecl() is not right here at all
5295 if (Previous.empty() ||
5296 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005297 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005298 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5299 return DeclPtrTy();
5300 }
5301
5302 // C++ [class.friend]p1: A friend of a class is a function or
5303 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005304 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005305 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5306
John McCall67d1a672009-08-06 02:15:43 +00005307 // Otherwise walk out to the nearest namespace scope looking for matches.
5308 } else {
5309 // TODO: handle local class contexts.
5310
5311 DC = CurContext;
5312 while (true) {
5313 // Skip class contexts. If someone can cite chapter and verse
5314 // for this behavior, that would be nice --- it's what GCC and
5315 // EDG do, and it seems like a reasonable intent, but the spec
5316 // really only says that checks for unqualified existing
5317 // declarations should stop at the nearest enclosing namespace,
5318 // not that they should only consider the nearest enclosing
5319 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005320 while (DC->isRecord())
5321 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005322
John McCall68263142009-11-18 22:49:29 +00005323 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005324
5325 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005326 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005327 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005328
John McCall67d1a672009-08-06 02:15:43 +00005329 if (DC->isFileContext()) break;
5330 DC = DC->getParent();
5331 }
5332
5333 // C++ [class.friend]p1: A friend of a class is a function or
5334 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005335 // C++0x changes this for both friend types and functions.
5336 // Most C++ 98 compilers do seem to give an error here, so
5337 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005338 if (!Previous.empty() && DC->Equals(CurContext)
5339 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005340 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5341 }
5342
Douglas Gregor182ddf02009-09-28 00:08:27 +00005343 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005344 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005345 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5346 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5347 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005348 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005349 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5350 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005351 return DeclPtrTy();
5352 }
John McCall67d1a672009-08-06 02:15:43 +00005353 }
5354
Douglas Gregor182ddf02009-09-28 00:08:27 +00005355 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005356 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005357 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005358 IsDefinition,
5359 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005360 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005361
Douglas Gregor182ddf02009-09-28 00:08:27 +00005362 assert(ND->getDeclContext() == DC);
5363 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005364
John McCallab88d972009-08-31 22:39:49 +00005365 // Add the function declaration to the appropriate lookup tables,
5366 // adjusting the redeclarations list as necessary. We don't
5367 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005368 //
John McCallab88d972009-08-31 22:39:49 +00005369 // Also update the scope-based lookup if the target context's
5370 // lookup context is in lexical scope.
5371 if (!CurContext->isDependentContext()) {
5372 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005373 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005374 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005375 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005376 }
John McCall02cace72009-08-28 07:59:38 +00005377
5378 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005379 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005380 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005381 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005382 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005383
Douglas Gregor182ddf02009-09-28 00:08:27 +00005384 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005385}
5386
Chris Lattnerb28317a2009-03-28 19:18:32 +00005387void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005388 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005389
Chris Lattnerb28317a2009-03-28 19:18:32 +00005390 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005391 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5392 if (!Fn) {
5393 Diag(DelLoc, diag::err_deleted_non_function);
5394 return;
5395 }
5396 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5397 Diag(DelLoc, diag::err_deleted_decl_not_first);
5398 Diag(Prev->getLocation(), diag::note_previous_declaration);
5399 // If the declaration wasn't the first, we delete the function anyway for
5400 // recovery.
5401 }
5402 Fn->setDeleted();
5403}
Sebastian Redl13e88542009-04-27 21:33:24 +00005404
5405static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5406 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5407 ++CI) {
5408 Stmt *SubStmt = *CI;
5409 if (!SubStmt)
5410 continue;
5411 if (isa<ReturnStmt>(SubStmt))
5412 Self.Diag(SubStmt->getSourceRange().getBegin(),
5413 diag::err_return_in_constructor_handler);
5414 if (!isa<Expr>(SubStmt))
5415 SearchForReturnInStmt(Self, SubStmt);
5416 }
5417}
5418
5419void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5420 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5421 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5422 SearchForReturnInStmt(*this, Handler);
5423 }
5424}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005425
Mike Stump1eb44332009-09-09 15:08:12 +00005426bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005427 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005428 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5429 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005430
5431 QualType CNewTy = Context.getCanonicalType(NewTy);
5432 QualType COldTy = Context.getCanonicalType(OldTy);
5433
Mike Stump1eb44332009-09-09 15:08:12 +00005434 if (CNewTy == COldTy &&
Douglas Gregora4923eb2009-11-16 21:35:15 +00005435 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005436 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005437
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005438 // Check if the return types are covariant
5439 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005440
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005441 /// Both types must be pointers or references to classes.
5442 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
5443 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
5444 NewClassTy = NewPT->getPointeeType();
5445 OldClassTy = OldPT->getPointeeType();
5446 }
5447 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
5448 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
5449 NewClassTy = NewRT->getPointeeType();
5450 OldClassTy = OldRT->getPointeeType();
5451 }
5452 }
Mike Stump1eb44332009-09-09 15:08:12 +00005453
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005454 // The return types aren't either both pointers or references to a class type.
5455 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005456 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005457 diag::err_different_return_type_for_overriding_virtual_function)
5458 << New->getDeclName() << NewTy << OldTy;
5459 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005460
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005461 return true;
5462 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005463
Douglas Gregora4923eb2009-11-16 21:35:15 +00005464 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005465 // Check if the new class derives from the old class.
5466 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5467 Diag(New->getLocation(),
5468 diag::err_covariant_return_not_derived)
5469 << New->getDeclName() << NewTy << OldTy;
5470 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5471 return true;
5472 }
Mike Stump1eb44332009-09-09 15:08:12 +00005473
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005474 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00005475 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005476 diag::err_covariant_return_inaccessible_base,
5477 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5478 // FIXME: Should this point to the return type?
5479 New->getLocation(), SourceRange(), New->getDeclName())) {
5480 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5481 return true;
5482 }
5483 }
Mike Stump1eb44332009-09-09 15:08:12 +00005484
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005485 // The qualifiers of the return types must be the same.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005486 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005487 Diag(New->getLocation(),
5488 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005489 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005490 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5491 return true;
5492 };
Mike Stump1eb44332009-09-09 15:08:12 +00005493
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005494
5495 // The new class type must have the same or less qualifiers as the old type.
5496 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5497 Diag(New->getLocation(),
5498 diag::err_covariant_return_type_class_type_more_qualified)
5499 << New->getDeclName() << NewTy << OldTy;
5500 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5501 return true;
5502 };
Mike Stump1eb44332009-09-09 15:08:12 +00005503
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005504 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005505}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005506
Sean Huntbbd37c62009-11-21 08:43:09 +00005507bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5508 const CXXMethodDecl *Old)
5509{
5510 if (Old->hasAttr<FinalAttr>()) {
5511 Diag(New->getLocation(), diag::err_final_function_overridden)
5512 << New->getDeclName();
5513 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5514 return true;
5515 }
5516
5517 return false;
5518}
5519
Douglas Gregor4ba31362009-12-01 17:24:26 +00005520/// \brief Mark the given method pure.
5521///
5522/// \param Method the method to be marked pure.
5523///
5524/// \param InitRange the source range that covers the "0" initializer.
5525bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5526 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5527 Method->setPure();
5528
5529 // A class is abstract if at least one function is pure virtual.
5530 Method->getParent()->setAbstract(true);
5531 return false;
5532 }
5533
5534 if (!Method->isInvalidDecl())
5535 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5536 << Method->getDeclName() << InitRange;
5537 return true;
5538}
5539
John McCall731ad842009-12-19 09:28:58 +00005540/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5541/// an initializer for the out-of-line declaration 'Dcl'. The scope
5542/// is a fresh scope pushed for just this purpose.
5543///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005544/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5545/// static data member of class X, names should be looked up in the scope of
5546/// class X.
5547void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005548 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005549 Decl *D = Dcl.getAs<Decl>();
5550 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005551
John McCall731ad842009-12-19 09:28:58 +00005552 // We should only get called for declarations with scope specifiers, like:
5553 // int foo::bar;
5554 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005555 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005556}
5557
5558/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005559/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005560void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005561 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005562 Decl *D = Dcl.getAs<Decl>();
5563 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005564
John McCall731ad842009-12-19 09:28:58 +00005565 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005566 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005567}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005568
5569/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5570/// C++ if/switch/while/for statement.
5571/// e.g: "if (int x = f()) {...}"
5572Action::DeclResult
5573Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5574 // C++ 6.4p2:
5575 // The declarator shall not specify a function or an array.
5576 // The type-specifier-seq shall not contain typedef and shall not declare a
5577 // new class or enumeration.
5578 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5579 "Parser allowed 'typedef' as storage class of condition decl.");
5580
John McCalla93c9342009-12-07 02:54:59 +00005581 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005582 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005583 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005584
5585 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5586 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5587 // would be created and CXXConditionDeclExpr wants a VarDecl.
5588 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5589 << D.getSourceRange();
5590 return DeclResult();
5591 } else if (OwnedTag && OwnedTag->isDefinition()) {
5592 // The type-specifier-seq shall not declare a new class or enumeration.
5593 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5594 }
5595
5596 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5597 if (!Dcl)
5598 return DeclResult();
5599
5600 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5601 VD->setDeclaredInCondition(true);
5602 return Dcl;
5603}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005604
Anders Carlssond6a637f2009-12-07 08:24:59 +00005605void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5606 CXXMethodDecl *MD) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005607 // Ignore dependent types.
5608 if (MD->isDependentContext())
5609 return;
5610
5611 CXXRecordDecl *RD = MD->getParent();
Anders Carlssonf53df232009-12-07 04:35:11 +00005612
5613 // Ignore classes without a vtable.
5614 if (!RD->isDynamicClass())
5615 return;
5616
Anders Carlssond6a637f2009-12-07 08:24:59 +00005617 if (!MD->isOutOfLine()) {
5618 // The only inline functions we care about are constructors. We also defer
5619 // marking the virtual members as referenced until we've reached the end
5620 // of the translation unit. We do this because we need to know the key
5621 // function of the class in order to determine the key function.
5622 if (isa<CXXConstructorDecl>(MD))
5623 ClassesWithUnmarkedVirtualMembers.insert(std::make_pair(RD, Loc));
5624 return;
5625 }
5626
Anders Carlssonf53df232009-12-07 04:35:11 +00005627 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005628
5629 if (!KeyFunction) {
5630 // This record does not have a key function, so we assume that the vtable
5631 // will be emitted when it's used by the constructor.
5632 if (!isa<CXXConstructorDecl>(MD))
5633 return;
5634 } else if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl()) {
5635 // We don't have the right key function.
5636 return;
5637 }
5638
Anders Carlssond6a637f2009-12-07 08:24:59 +00005639 // Mark the members as referenced.
5640 MarkVirtualMembersReferenced(Loc, RD);
5641 ClassesWithUnmarkedVirtualMembers.erase(RD);
5642}
5643
5644bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5645 if (ClassesWithUnmarkedVirtualMembers.empty())
5646 return false;
5647
5648 for (std::map<CXXRecordDecl *, SourceLocation>::iterator i =
5649 ClassesWithUnmarkedVirtualMembers.begin(),
5650 e = ClassesWithUnmarkedVirtualMembers.end(); i != e; ++i) {
5651 CXXRecordDecl *RD = i->first;
5652
5653 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5654 if (KeyFunction) {
5655 // We know that the class has a key function. If the key function was
5656 // declared in this translation unit, then it the class decl would not
5657 // have been in the ClassesWithUnmarkedVirtualMembers map.
5658 continue;
5659 }
5660
5661 SourceLocation Loc = i->second;
5662 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005663 }
5664
Anders Carlssond6a637f2009-12-07 08:24:59 +00005665 ClassesWithUnmarkedVirtualMembers.clear();
5666 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005667}
Anders Carlssond6a637f2009-12-07 08:24:59 +00005668
5669void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5670 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5671 e = RD->method_end(); i != e; ++i) {
5672 CXXMethodDecl *MD = *i;
5673
5674 // C++ [basic.def.odr]p2:
5675 // [...] A virtual member function is used if it is not pure. [...]
5676 if (MD->isVirtual() && !MD->isPure())
5677 MarkDeclarationReferenced(Loc, MD);
5678 }
5679}
5680