blob: b3e0ca8b85216d54a55f2ed21f1ece4bc904e6fe [file] [log] [blame]
Chris Lattnerac7b83a2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregora65e8dd2008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregorec93f442008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor05904022008-10-22 21:13:31 +000018#include "clang/AST/TypeOrdering.h"
Chris Lattner97316c02008-04-10 02:22:51 +000019#include "clang/AST/StmtVisitor.h"
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +000020#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000021#include "clang/Basic/Diagnostic.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000022#include "clang/Parse/DeclSpec.h"
Douglas Gregor682a8cf2008-11-17 16:14:12 +000023#include "llvm/ADT/StringExtras.h"
Chris Lattner97316c02008-04-10 02:22:51 +000024#include "llvm/Support/Compiler.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000025#include <algorithm> // for std::equal
Douglas Gregorabed2172008-10-22 17:49:05 +000026#include <map>
Chris Lattnerac7b83a2008-04-08 05:04:30 +000027
28using namespace clang;
29
Chris Lattner97316c02008-04-10 02:22:51 +000030//===----------------------------------------------------------------------===//
31// CheckDefaultArgumentVisitor
32//===----------------------------------------------------------------------===//
33
Chris Lattnerb1856db2008-04-12 23:52:44 +000034namespace {
35 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
36 /// the default argument of a parameter to determine whether it
37 /// contains any ill-formed subexpressions. For example, this will
38 /// diagnose the use of local variables or parameters within the
39 /// default argument expression.
40 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000041 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb1856db2008-04-12 23:52:44 +000042 Expr *DefaultArg;
43 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000044
Chris Lattnerb1856db2008-04-12 23:52:44 +000045 public:
46 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
47 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000048
Chris Lattnerb1856db2008-04-12 23:52:44 +000049 bool VisitExpr(Expr *Node);
50 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregora5b022a2008-11-04 14:32:21 +000051 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb1856db2008-04-12 23:52:44 +000052 };
Chris Lattner97316c02008-04-10 02:22:51 +000053
Chris Lattnerb1856db2008-04-12 23:52:44 +000054 /// VisitExpr - Visit all of the children of this expression.
55 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
56 bool IsInvalid = false;
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000057 for (Stmt::child_iterator I = Node->child_begin(),
58 E = Node->child_end(); I != E; ++I)
59 IsInvalid |= Visit(*I);
Chris Lattnerb1856db2008-04-12 23:52:44 +000060 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000061 }
62
Chris Lattnerb1856db2008-04-12 23:52:44 +000063 /// VisitDeclRefExpr - Visit a reference to a declaration, to
64 /// determine whether this declaration can be used in the default
65 /// argument expression.
66 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregord2baafd2008-10-21 16:13:35 +000067 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb1856db2008-04-12 23:52:44 +000068 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
69 // C++ [dcl.fct.default]p9
70 // Default arguments are evaluated each time the function is
71 // called. The order of evaluation of function arguments is
72 // unspecified. Consequently, parameters of a function shall not
73 // be used in default argument expressions, even if they are not
74 // evaluated. Parameters of a function declared before a default
75 // argument expression are in scope and can hide namespace and
76 // class member names.
77 return S->Diag(DRE->getSourceRange().getBegin(),
78 diag::err_param_default_argument_references_param,
79 Param->getName(), DefaultArg->getSourceRange());
Steve Naroff72a6ebc2008-04-15 22:42:06 +000080 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000081 // C++ [dcl.fct.default]p7
82 // Local variables shall not be used in default argument
83 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000084 if (VDecl->isBlockVarDecl())
85 return S->Diag(DRE->getSourceRange().getBegin(),
86 diag::err_param_default_argument_references_local,
87 VDecl->getName(), DefaultArg->getSourceRange());
Chris Lattnerb1856db2008-04-12 23:52:44 +000088 }
Chris Lattner97316c02008-04-10 02:22:51 +000089
Douglas Gregor3c246952008-11-04 13:41:56 +000090 return false;
91 }
Chris Lattnerb1856db2008-04-12 23:52:44 +000092
Douglas Gregora5b022a2008-11-04 14:32:21 +000093 /// VisitCXXThisExpr - Visit a C++ "this" expression.
94 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
95 // C++ [dcl.fct.default]p8:
96 // The keyword this shall not be used in a default argument of a
97 // member function.
98 return S->Diag(ThisE->getSourceRange().getBegin(),
99 diag::err_param_default_argument_references_this,
100 ThisE->getSourceRange());
Chris Lattnerb1856db2008-04-12 23:52:44 +0000101 }
Chris Lattner97316c02008-04-10 02:22:51 +0000102}
103
104/// ActOnParamDefaultArgument - Check whether the default argument
105/// provided for a function parameter is well-formed. If so, attach it
106/// to the parameter declaration.
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000107void
108Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
109 ExprTy *defarg) {
110 ParmVarDecl *Param = (ParmVarDecl *)param;
111 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
112 QualType ParamType = Param->getType();
113
114 // Default arguments are only permitted in C++
115 if (!getLangOptions().CPlusPlus) {
116 Diag(EqualLoc, diag::err_param_default_argument,
117 DefaultArg->getSourceRange());
118 return;
119 }
120
121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000127 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor58c428c2008-11-04 13:57:51 +0000128 bool DefaultInitFailed = PerformCopyInitialization(DefaultArgPtr, ParamType,
129 "in default argument");
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000130 if (DefaultArgPtr != DefaultArg.get()) {
131 DefaultArg.take();
132 DefaultArg.reset(DefaultArgPtr);
133 }
Douglas Gregor58c428c2008-11-04 13:57:51 +0000134 if (DefaultInitFailed) {
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000135 return;
136 }
137
Chris Lattner97316c02008-04-10 02:22:51 +0000138 // Check that the default argument is well-formed
Chris Lattnerb1856db2008-04-12 23:52:44 +0000139 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Chris Lattner97316c02008-04-10 02:22:51 +0000140 if (DefaultArgChecker.Visit(DefaultArg.get()))
141 return;
142
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000143 // Okay: add the default argument to the parameter
144 Param->setDefaultArg(DefaultArg.take());
145}
146
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000147/// CheckExtraCXXDefaultArguments - Check for any extra default
148/// arguments in the declarator, which is not a function declaration
149/// or definition and therefore is not permitted to have default
150/// arguments. This routine should be invoked for every declarator
151/// that is not a function declaration or definition.
152void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
153 // C++ [dcl.fct.default]p3
154 // A default argument expression shall be specified only in the
155 // parameter-declaration-clause of a function declaration or in a
156 // template-parameter (14.1). It shall not be specified for a
157 // parameter pack. If it is specified in a
158 // parameter-declaration-clause, it shall not occur within a
159 // declarator or abstract-declarator of a parameter-declaration.
160 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
161 DeclaratorChunk &chunk = D.getTypeObject(i);
162 if (chunk.Kind == DeclaratorChunk::Function) {
163 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
164 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
165 if (Param->getDefaultArg()) {
166 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc,
167 Param->getDefaultArg()->getSourceRange());
168 Param->setDefaultArg(0);
169 }
170 }
171 }
172 }
173}
174
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000175// MergeCXXFunctionDecl - Merge two declarations of the same C++
176// function, once we already know that they have the same
177// type. Subroutine of MergeFunctionDecl.
178FunctionDecl *
179Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
180 // C++ [dcl.fct.default]p4:
181 //
182 // For non-template functions, default arguments can be added in
183 // later declarations of a function in the same
184 // scope. Declarations in different scopes have completely
185 // distinct sets of default arguments. That is, declarations in
186 // inner scopes do not acquire default arguments from
187 // declarations in outer scopes, and vice versa. In a given
188 // function declaration, all parameters subsequent to a
189 // parameter with a default argument shall have default
190 // arguments supplied in this or previous declarations. A
191 // default argument shall not be redefined by a later
192 // declaration (not even to the same value).
193 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
194 ParmVarDecl *OldParam = Old->getParamDecl(p);
195 ParmVarDecl *NewParam = New->getParamDecl(p);
196
197 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
198 Diag(NewParam->getLocation(),
199 diag::err_param_default_argument_redefinition,
200 NewParam->getDefaultArg()->getSourceRange());
201 Diag(OldParam->getLocation(), diag::err_previous_definition);
202 } else if (OldParam->getDefaultArg()) {
203 // Merge the old default argument into the new parameter
204 NewParam->setDefaultArg(OldParam->getDefaultArg());
205 }
206 }
207
208 return New;
209}
210
211/// CheckCXXDefaultArguments - Verify that the default arguments for a
212/// function declaration are well-formed according to C++
213/// [dcl.fct.default].
214void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
215 unsigned NumParams = FD->getNumParams();
216 unsigned p;
217
218 // Find first parameter with a default argument
219 for (p = 0; p < NumParams; ++p) {
220 ParmVarDecl *Param = FD->getParamDecl(p);
221 if (Param->getDefaultArg())
222 break;
223 }
224
225 // C++ [dcl.fct.default]p4:
226 // In a given function declaration, all parameters
227 // subsequent to a parameter with a default argument shall
228 // have default arguments supplied in this or previous
229 // declarations. A default argument shall not be redefined
230 // by a later declaration (not even to the same value).
231 unsigned LastMissingDefaultArg = 0;
232 for(; p < NumParams; ++p) {
233 ParmVarDecl *Param = FD->getParamDecl(p);
234 if (!Param->getDefaultArg()) {
235 if (Param->getIdentifier())
236 Diag(Param->getLocation(),
237 diag::err_param_default_argument_missing_name,
238 Param->getIdentifier()->getName());
239 else
240 Diag(Param->getLocation(),
241 diag::err_param_default_argument_missing);
242
243 LastMissingDefaultArg = p;
244 }
245 }
246
247 if (LastMissingDefaultArg > 0) {
248 // Some default arguments were missing. Clear out all of the
249 // default arguments up to (and including) the last missing
250 // default argument, so that we leave the function parameters
251 // in a semantically valid state.
252 for (p = 0; p <= LastMissingDefaultArg; ++p) {
253 ParmVarDecl *Param = FD->getParamDecl(p);
254 if (Param->getDefaultArg()) {
255 delete Param->getDefaultArg();
256 Param->setDefaultArg(0);
257 }
258 }
259 }
260}
Douglas Gregorec93f442008-04-13 21:30:24 +0000261
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000262/// isCurrentClassName - Determine whether the identifier II is the
263/// name of the class type currently being defined. In the case of
264/// nested classes, this will only return true if II is the name of
265/// the innermost class.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000266bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
267 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000268 CXXRecordDecl *CurDecl;
269 if (SS) {
270 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
271 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
272 } else
273 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
274
275 if (CurDecl)
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000276 return &II == CurDecl->getIdentifier();
277 else
278 return false;
279}
280
Douglas Gregorec93f442008-04-13 21:30:24 +0000281/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
282/// one entry in the base class list of a class specifier, for
283/// example:
284/// class foo : public bar, virtual private baz {
285/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorabed2172008-10-22 17:49:05 +0000286Sema::BaseResult
287Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
288 bool Virtual, AccessSpecifier Access,
289 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000290 RecordDecl *Decl = (RecordDecl*)classdecl;
291 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
292
293 // Base specifiers must be record types.
294 if (!BaseType->isRecordType()) {
295 Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000296 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000297 }
298
299 // C++ [class.union]p1:
300 // A union shall not be used as a base class.
301 if (BaseType->isUnionType()) {
302 Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000303 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000304 }
305
306 // C++ [class.union]p1:
307 // A union shall not have base classes.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000308 if (Decl->isUnion()) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000309 Diag(Decl->getLocation(), diag::err_base_clause_on_union,
310 SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000311 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000312 }
313
314 // C++ [class.derived]p2:
315 // The class-name in a base-specifier shall not be an incompletely
316 // defined class.
317 if (BaseType->isIncompleteType()) {
318 Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000319 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000320 }
321
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000322 // If the base class is polymorphic, the new one is, too.
323 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
324 assert(BaseDecl && "Record type has no declaration");
325 BaseDecl = BaseDecl->getDefinition(Context);
326 assert(BaseDecl && "Base type is not incomplete, but has no definition");
327 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic()) {
328 cast<CXXRecordDecl>(Decl)->setPolymorphic(true);
329 }
330
Douglas Gregorabed2172008-10-22 17:49:05 +0000331 // Create the base specifier.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000332 return new CXXBaseSpecifier(SpecifierRange, Virtual,
333 BaseType->isClassType(), Access, BaseType);
Douglas Gregorabed2172008-10-22 17:49:05 +0000334}
Douglas Gregorec93f442008-04-13 21:30:24 +0000335
Douglas Gregorabed2172008-10-22 17:49:05 +0000336/// ActOnBaseSpecifiers - Attach the given base specifiers to the
337/// class, after checking whether there are any duplicate base
338/// classes.
339void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
340 unsigned NumBases) {
341 if (NumBases == 0)
342 return;
343
344 // Used to keep track of which base types we have already seen, so
345 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000346 // that the key is always the unqualified canonical type of the base
347 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000348 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
349
350 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000351 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
352 unsigned NumGoodBases = 0;
353 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000354 QualType NewBaseType
Douglas Gregor4fd85902008-10-23 18:13:27 +0000355 = Context.getCanonicalType(BaseSpecs[idx]->getType());
356 NewBaseType = NewBaseType.getUnqualifiedType();
357
Douglas Gregorabed2172008-10-22 17:49:05 +0000358 if (KnownBaseTypes[NewBaseType]) {
359 // C++ [class.mi]p3:
360 // A class shall not be specified as a direct base class of a
361 // derived class more than once.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000362 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Douglas Gregorabed2172008-10-22 17:49:05 +0000363 diag::err_duplicate_base_class,
364 KnownBaseTypes[NewBaseType]->getType().getAsString(),
Douglas Gregor4fd85902008-10-23 18:13:27 +0000365 BaseSpecs[idx]->getSourceRange());
366
367 // Delete the duplicate base class specifier; we're going to
368 // overwrite its pointer later.
369 delete BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000370 } else {
371 // Okay, add this new base class.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000372 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
373 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000374 }
375 }
376
377 // Attach the remaining base class specifiers to the derived class.
378 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000379 Decl->setBases(BaseSpecs, NumGoodBases);
380
381 // Delete the remaining (good) base class specifiers, since their
382 // data has been copied into the CXXRecordDecl.
383 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
384 delete BaseSpecs[idx];
Douglas Gregorec93f442008-04-13 21:30:24 +0000385}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000386
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000387//===----------------------------------------------------------------------===//
388// C++ class member Handling
389//===----------------------------------------------------------------------===//
390
391/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
392/// definition, when on C++.
393void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000394 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
395 PushDeclContext(Dcl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000396 FieldCollector->StartClass();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000397
398 if (Dcl->getIdentifier()) {
399 // C++ [class]p2:
400 // [...] The class-name is also inserted into the scope of the
401 // class itself; this is known as the injected-class-name. For
402 // purposes of access checking, the injected-class-name is treated
403 // as if it were a public member name.
Douglas Gregorbd19fdb2008-11-10 14:41:22 +0000404 PushOnScopeChains(Dcl, S);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000405 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000406}
407
408/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
409/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
410/// bitfield width if there is one and 'InitExpr' specifies the initializer if
411/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
412/// declarators on it.
413///
414/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
415/// an instance field is declared, a new CXXFieldDecl is created but the method
416/// does *not* return it; it returns LastInGroup instead. The other C++ members
417/// (which are all ScopedDecls) are returned after appending them to
418/// LastInGroup.
419Sema::DeclTy *
420Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
421 ExprTy *BW, ExprTy *InitExpr,
422 DeclTy *LastInGroup) {
423 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor6704b312008-11-17 22:58:34 +0000424 DeclarationName Name = GetNameForDeclarator(D);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000425 Expr *BitWidth = static_cast<Expr*>(BW);
426 Expr *Init = static_cast<Expr*>(InitExpr);
427 SourceLocation Loc = D.getIdentifierLoc();
428
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000429 bool isFunc = D.isFunctionDeclarator();
430
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000431 // C++ 9.2p6: A member shall not be declared to have automatic storage
432 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000433 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
434 // data members and cannot be applied to names declared const or static,
435 // and cannot be applied to reference members.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000436 switch (DS.getStorageClassSpec()) {
437 case DeclSpec::SCS_unspecified:
438 case DeclSpec::SCS_typedef:
439 case DeclSpec::SCS_static:
440 // FALL THROUGH.
441 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000442 case DeclSpec::SCS_mutable:
443 if (isFunc) {
444 if (DS.getStorageClassSpecLoc().isValid())
445 Diag(DS.getStorageClassSpecLoc(),
446 diag::err_mutable_function);
447 else
448 Diag(DS.getThreadSpecLoc(),
449 diag::err_mutable_function);
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000450 // FIXME: It would be nicer if the keyword was ignored only for this
451 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000452 D.getMutableDeclSpec().ClearStorageClassSpecs();
453 } else {
454 QualType T = GetTypeForDeclarator(D, S);
455 diag::kind err = static_cast<diag::kind>(0);
456 if (T->isReferenceType())
457 err = diag::err_mutable_reference;
458 else if (T.isConstQualified())
459 err = diag::err_mutable_const;
460 if (err != 0) {
461 if (DS.getStorageClassSpecLoc().isValid())
462 Diag(DS.getStorageClassSpecLoc(), err);
463 else
464 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000465 // FIXME: It would be nicer if the keyword was ignored only for this
466 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000467 D.getMutableDeclSpec().ClearStorageClassSpecs();
468 }
469 }
470 break;
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000471 default:
472 if (DS.getStorageClassSpecLoc().isValid())
473 Diag(DS.getStorageClassSpecLoc(),
474 diag::err_storageclass_invalid_for_member);
475 else
476 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
477 D.getMutableDeclSpec().ClearStorageClassSpecs();
478 }
479
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000480 if (!isFunc &&
481 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
482 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000483 // Check also for this case:
484 //
485 // typedef int f();
486 // f a;
487 //
488 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
489 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
490 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000491
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000492 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
493 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000494 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000495
496 Decl *Member;
497 bool InvalidDecl = false;
498
499 if (isInstField)
500 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
501 else
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000502 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000503
504 if (!Member) return LastInGroup;
505
Douglas Gregor6704b312008-11-17 22:58:34 +0000506 assert((Name || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000507
508 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
509 // specific methods. Use a wrapper class that can be used with all C++ class
510 // member decls.
511 CXXClassMemberWrapper(Member).setAccess(AS);
512
Douglas Gregor15e04622008-11-05 16:20:31 +0000513 // C++ [dcl.init.aggr]p1:
514 // An aggregate is an array or a class (clause 9) with [...] no
515 // private or protected non-static data members (clause 11).
516 if (isInstField && (AS == AS_private || AS == AS_protected))
517 cast<CXXRecordDecl>(CurContext)->setAggregate(false);
518
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000519 if (DS.isVirtualSpecified()) {
520 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
521 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
522 InvalidDecl = true;
523 } else {
524 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
525 CurClass->setAggregate(false);
526 CurClass->setPolymorphic(true);
527 }
528 }
Douglas Gregor15e04622008-11-05 16:20:31 +0000529
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000530 if (BitWidth) {
531 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
532 // constant-expression be a value equal to zero.
533 // FIXME: Check this.
534
535 if (D.isFunctionDeclarator()) {
536 // FIXME: Emit diagnostic about only constructors taking base initializers
537 // or something similar, when constructor support is in place.
538 Diag(Loc, diag::err_not_bitfield_type,
Douglas Gregor6704b312008-11-17 22:58:34 +0000539 Name.getAsString(), BitWidth->getSourceRange());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000540 InvalidDecl = true;
541
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000542 } else if (isInstField) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000543 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000544 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000545 Diag(Loc, diag::err_not_integral_type_bitfield,
Douglas Gregor6704b312008-11-17 22:58:34 +0000546 Name.getAsString(), BitWidth->getSourceRange());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000547 InvalidDecl = true;
548 }
549
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000550 } else if (isa<FunctionDecl>(Member)) {
551 // A function typedef ("typedef int f(); f a;").
552 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
553 Diag(Loc, diag::err_not_integral_type_bitfield,
Douglas Gregor6704b312008-11-17 22:58:34 +0000554 Name.getAsString(), BitWidth->getSourceRange());
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000555 InvalidDecl = true;
556
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000557 } else if (isa<TypedefDecl>(Member)) {
558 // "cannot declare 'A' to be a bit-field type"
Douglas Gregor6704b312008-11-17 22:58:34 +0000559 Diag(Loc, diag::err_not_bitfield_type, Name.getAsString(),
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000560 BitWidth->getSourceRange());
561 InvalidDecl = true;
562
563 } else {
564 assert(isa<CXXClassVarDecl>(Member) &&
565 "Didn't we cover all member kinds?");
566 // C++ 9.6p3: A bit-field shall not be a static member.
567 // "static member 'A' cannot be a bit-field"
Douglas Gregor6704b312008-11-17 22:58:34 +0000568 Diag(Loc, diag::err_static_not_bitfield, Name.getAsString(),
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000569 BitWidth->getSourceRange());
570 InvalidDecl = true;
571 }
572 }
573
574 if (Init) {
575 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
576 // if it declares a static member of const integral or const enumeration
577 // type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000578 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
579 // ...static member of...
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000580 CVD->setInit(Init);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000581 // ...const integral or const enumeration type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000582 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
583 CVD->getType()->isIntegralType()) {
584 // constant-initializer
585 if (CheckForConstantInitializer(Init, CVD->getType()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000586 InvalidDecl = true;
587
588 } else {
589 // not const integral.
590 Diag(Loc, diag::err_member_initialization,
Douglas Gregor6704b312008-11-17 22:58:34 +0000591 Name.getAsString(), Init->getSourceRange());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000592 InvalidDecl = true;
593 }
594
595 } else {
596 // not static member.
597 Diag(Loc, diag::err_member_initialization,
Douglas Gregor6704b312008-11-17 22:58:34 +0000598 Name.getAsString(), Init->getSourceRange());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000599 InvalidDecl = true;
600 }
601 }
602
603 if (InvalidDecl)
604 Member->setInvalidDecl();
605
606 if (isInstField) {
607 FieldCollector->Add(cast<CXXFieldDecl>(Member));
608 return LastInGroup;
609 }
610 return Member;
611}
612
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000613/// ActOnMemInitializer - Handle a C++ member initializer.
614Sema::MemInitResult
615Sema::ActOnMemInitializer(DeclTy *ConstructorD,
616 Scope *S,
617 IdentifierInfo *MemberOrBase,
618 SourceLocation IdLoc,
619 SourceLocation LParenLoc,
620 ExprTy **Args, unsigned NumArgs,
621 SourceLocation *CommaLocs,
622 SourceLocation RParenLoc) {
623 CXXConstructorDecl *Constructor
624 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
625 if (!Constructor) {
626 // The user wrote a constructor initializer on a function that is
627 // not a C++ constructor. Ignore the error for now, because we may
628 // have more member initializers coming; we'll diagnose it just
629 // once in ActOnMemInitializers.
630 return true;
631 }
632
633 CXXRecordDecl *ClassDecl = Constructor->getParent();
634
635 // C++ [class.base.init]p2:
636 // Names in a mem-initializer-id are looked up in the scope of the
637 // constructor’s class and, if not found in that scope, are looked
638 // up in the scope containing the constructor’s
639 // definition. [Note: if the constructor’s class contains a member
640 // with the same name as a direct or virtual base class of the
641 // class, a mem-initializer-id naming the member or base class and
642 // composed of a single identifier refers to the class member. A
643 // mem-initializer-id for the hidden base class may be specified
644 // using a qualified name. ]
645 // Look for a member, first.
646 CXXFieldDecl *Member = ClassDecl->getMember(MemberOrBase);
647
648 // FIXME: Handle members of an anonymous union.
649
650 if (Member) {
651 // FIXME: Perform direct initialization of the member.
652 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
653 }
654
655 // It didn't name a member, so see if it names a class.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000656 TypeTy *BaseTy = isTypeName(*MemberOrBase, S, 0/*SS*/);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000657 if (!BaseTy)
658 return Diag(IdLoc, diag::err_mem_init_not_member_or_class,
659 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
660
661 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
662 if (!BaseType->isRecordType())
663 return Diag(IdLoc, diag::err_base_init_does_not_name_class,
664 BaseType.getAsString(), SourceRange(IdLoc, RParenLoc));
665
666 // C++ [class.base.init]p2:
667 // [...] Unless the mem-initializer-id names a nonstatic data
668 // member of the constructor’s class or a direct or virtual base
669 // of that class, the mem-initializer is ill-formed. A
670 // mem-initializer-list can initialize a base class using any
671 // name that denotes that base class type.
672
673 // First, check for a direct base class.
674 const CXXBaseSpecifier *DirectBaseSpec = 0;
675 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
676 Base != ClassDecl->bases_end(); ++Base) {
677 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
678 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
679 // We found a direct base of this type. That's what we're
680 // initializing.
681 DirectBaseSpec = &*Base;
682 break;
683 }
684 }
685
686 // Check for a virtual base class.
687 // FIXME: We might be able to short-circuit this if we know in
688 // advance that there are no virtual bases.
689 const CXXBaseSpecifier *VirtualBaseSpec = 0;
690 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
691 // We haven't found a base yet; search the class hierarchy for a
692 // virtual base class.
693 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
694 /*DetectVirtual=*/false);
695 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
696 for (BasePaths::paths_iterator Path = Paths.begin();
697 Path != Paths.end(); ++Path) {
698 if (Path->back().Base->isVirtual()) {
699 VirtualBaseSpec = Path->back().Base;
700 break;
701 }
702 }
703 }
704 }
705
706 // C++ [base.class.init]p2:
707 // If a mem-initializer-id is ambiguous because it designates both
708 // a direct non-virtual base class and an inherited virtual base
709 // class, the mem-initializer is ill-formed.
710 if (DirectBaseSpec && VirtualBaseSpec)
711 return Diag(IdLoc, diag::err_base_init_direct_and_virtual,
712 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
713
714 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
715}
716
717
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000718void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
719 DeclTy *TagDecl,
720 SourceLocation LBrac,
721 SourceLocation RBrac) {
722 ActOnFields(S, RLoc, TagDecl,
723 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +0000724 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000725}
726
Douglas Gregore640ab62008-11-03 17:51:48 +0000727/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
728/// special functions, such as the default constructor, copy
729/// constructor, or destructor, to the given C++ class (C++
730/// [special]p1). This routine can only be executed just before the
731/// definition of the class is complete.
732void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000733 QualType ClassType = Context.getTypeDeclType(ClassDecl);
734 ClassType = Context.getCanonicalType(ClassType);
735
Douglas Gregore640ab62008-11-03 17:51:48 +0000736 if (!ClassDecl->hasUserDeclaredConstructor()) {
737 // C++ [class.ctor]p5:
738 // A default constructor for a class X is a constructor of class X
739 // that can be called without an argument. If there is no
740 // user-declared constructor for class X, a default constructor is
741 // implicitly declared. An implicitly-declared default constructor
742 // is an inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000743 DeclarationName Name
744 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000745 CXXConstructorDecl *DefaultCon =
746 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000747 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000748 Context.getFunctionType(Context.VoidTy,
749 0, 0, false, 0),
750 /*isExplicit=*/false,
751 /*isInline=*/true,
752 /*isImplicitlyDeclared=*/true);
753 DefaultCon->setAccess(AS_public);
754 ClassDecl->addConstructor(Context, DefaultCon);
755 }
756
757 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
758 // C++ [class.copy]p4:
759 // If the class definition does not explicitly declare a copy
760 // constructor, one is declared implicitly.
761
762 // C++ [class.copy]p5:
763 // The implicitly-declared copy constructor for a class X will
764 // have the form
765 //
766 // X::X(const X&)
767 //
768 // if
769 bool HasConstCopyConstructor = true;
770
771 // -- each direct or virtual base class B of X has a copy
772 // constructor whose first parameter is of type const B& or
773 // const volatile B&, and
774 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
775 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
776 const CXXRecordDecl *BaseClassDecl
777 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
778 HasConstCopyConstructor
779 = BaseClassDecl->hasConstCopyConstructor(Context);
780 }
781
782 // -- for all the nonstatic data members of X that are of a
783 // class type M (or array thereof), each such class type
784 // has a copy constructor whose first parameter is of type
785 // const M& or const volatile M&.
786 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
787 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
788 QualType FieldType = (*Field)->getType();
789 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
790 FieldType = Array->getElementType();
791 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
792 const CXXRecordDecl *FieldClassDecl
793 = cast<CXXRecordDecl>(FieldClassType->getDecl());
794 HasConstCopyConstructor
795 = FieldClassDecl->hasConstCopyConstructor(Context);
796 }
797 }
798
799 // Otherwise, the implicitly declared copy constructor will have
800 // the form
801 //
802 // X::X(X&)
803 QualType ArgType = Context.getTypeDeclType(ClassDecl);
804 if (HasConstCopyConstructor)
805 ArgType = ArgType.withConst();
806 ArgType = Context.getReferenceType(ArgType);
807
808 // An implicitly-declared copy constructor is an inline public
809 // member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000810 DeclarationName Name
811 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000812 CXXConstructorDecl *CopyConstructor
813 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000814 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000815 Context.getFunctionType(Context.VoidTy,
816 &ArgType, 1,
817 false, 0),
818 /*isExplicit=*/false,
819 /*isInline=*/true,
820 /*isImplicitlyDeclared=*/true);
821 CopyConstructor->setAccess(AS_public);
822
823 // Add the parameter to the constructor.
824 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
825 ClassDecl->getLocation(),
826 /*IdentifierInfo=*/0,
827 ArgType, VarDecl::None, 0, 0);
828 CopyConstructor->setParams(&FromParam, 1);
829
830 ClassDecl->addConstructor(Context, CopyConstructor);
831 }
832
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000833 if (!ClassDecl->getDestructor()) {
834 // C++ [class.dtor]p2:
835 // If a class has no user-declared destructor, a destructor is
836 // declared implicitly. An implicitly-declared destructor is an
837 // inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000838 DeclarationName Name
839 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000840 CXXDestructorDecl *Destructor
841 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000842 ClassDecl->getLocation(), Name,
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000843 Context.getFunctionType(Context.VoidTy,
844 0, 0, false, 0),
845 /*isInline=*/true,
846 /*isImplicitlyDeclared=*/true);
847 Destructor->setAccess(AS_public);
848 ClassDecl->setDestructor(Destructor);
849 }
850
Douglas Gregore640ab62008-11-03 17:51:48 +0000851 // FIXME: Implicit copy assignment operator
852}
853
Argiris Kirtzidis448b4e42008-08-09 00:39:29 +0000854void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000855 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000856 FieldCollector->FinishClass();
Douglas Gregore640ab62008-11-03 17:51:48 +0000857 AddImplicitlyDeclaredMembersToClass(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000858 PopDeclContext();
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000859
860 // Everything, including inline method definitions, have been parsed.
861 // Let the consumer know of the new TagDecl definition.
862 Consumer.HandleTagDeclDefinition(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000863}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000864
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000865/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
866/// the well-formednes of the constructor declarator @p D with type @p
867/// R. If there are any errors in the declarator, this routine will
868/// emit diagnostics and return true. Otherwise, it will return
869/// false. Either way, the type @p R will be updated to reflect a
870/// well-formed type for the constructor.
871bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
872 FunctionDecl::StorageClass& SC) {
873 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
874 bool isInvalid = false;
875
876 // C++ [class.ctor]p3:
877 // A constructor shall not be virtual (10.3) or static (9.4). A
878 // constructor can be invoked for a const, volatile or const
879 // volatile object. A constructor shall not be declared const,
880 // volatile, or const volatile (9.3.2).
881 if (isVirtual) {
882 Diag(D.getIdentifierLoc(),
883 diag::err_constructor_cannot_be,
884 "virtual",
885 SourceRange(D.getDeclSpec().getVirtualSpecLoc()),
886 SourceRange(D.getIdentifierLoc()));
887 isInvalid = true;
888 }
889 if (SC == FunctionDecl::Static) {
890 Diag(D.getIdentifierLoc(),
891 diag::err_constructor_cannot_be,
892 "static",
893 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
894 SourceRange(D.getIdentifierLoc()));
895 isInvalid = true;
896 SC = FunctionDecl::None;
897 }
898 if (D.getDeclSpec().hasTypeSpecifier()) {
899 // Constructors don't have return types, but the parser will
900 // happily parse something like:
901 //
902 // class X {
903 // float X(float);
904 // };
905 //
906 // The return type will be eliminated later.
907 Diag(D.getIdentifierLoc(),
908 diag::err_constructor_return_type,
909 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
910 SourceRange(D.getIdentifierLoc()));
911 }
912 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
913 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
914 if (FTI.TypeQuals & QualType::Const)
915 Diag(D.getIdentifierLoc(),
916 diag::err_invalid_qualified_constructor,
917 "const",
918 SourceRange(D.getIdentifierLoc()));
919 if (FTI.TypeQuals & QualType::Volatile)
920 Diag(D.getIdentifierLoc(),
921 diag::err_invalid_qualified_constructor,
922 "volatile",
923 SourceRange(D.getIdentifierLoc()));
924 if (FTI.TypeQuals & QualType::Restrict)
925 Diag(D.getIdentifierLoc(),
926 diag::err_invalid_qualified_constructor,
927 "restrict",
928 SourceRange(D.getIdentifierLoc()));
929 }
930
931 // Rebuild the function type "R" without any type qualifiers (in
932 // case any of the errors above fired) and with "void" as the
933 // return type, since constructors don't have return types. We
934 // *always* have to do this, because GetTypeForDeclarator will
935 // put in a result type of "int" when none was specified.
936 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto();
937 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
938 Proto->getNumArgs(),
939 Proto->isVariadic(),
940 0);
941
942 return isInvalid;
943}
944
945/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
946/// the well-formednes of the destructor declarator @p D with type @p
947/// R. If there are any errors in the declarator, this routine will
948/// emit diagnostics and return true. Otherwise, it will return
949/// false. Either way, the type @p R will be updated to reflect a
950/// well-formed type for the destructor.
951bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
952 FunctionDecl::StorageClass& SC) {
953 bool isInvalid = false;
954
955 // C++ [class.dtor]p1:
956 // [...] A typedef-name that names a class is a class-name
957 // (7.1.3); however, a typedef-name that names a class shall not
958 // be used as the identifier in the declarator for a destructor
959 // declaration.
960 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType();
961 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) {
Douglas Gregorbd19fdb2008-11-10 14:41:22 +0000962 Diag(D.getIdentifierLoc(),
963 diag::err_destructor_typedef_name,
964 TypedefD->getName());
965 isInvalid = true;
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000966 }
967
968 // C++ [class.dtor]p2:
969 // A destructor is used to destroy objects of its class type. A
970 // destructor takes no parameters, and no return type can be
971 // specified for it (not even void). The address of a destructor
972 // shall not be taken. A destructor shall not be static. A
973 // destructor can be invoked for a const, volatile or const
974 // volatile object. A destructor shall not be declared const,
975 // volatile or const volatile (9.3.2).
976 if (SC == FunctionDecl::Static) {
977 Diag(D.getIdentifierLoc(),
978 diag::err_destructor_cannot_be,
979 "static",
980 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
981 SourceRange(D.getIdentifierLoc()));
982 isInvalid = true;
983 SC = FunctionDecl::None;
984 }
985 if (D.getDeclSpec().hasTypeSpecifier()) {
986 // Destructors don't have return types, but the parser will
987 // happily parse something like:
988 //
989 // class X {
990 // float ~X();
991 // };
992 //
993 // The return type will be eliminated later.
994 Diag(D.getIdentifierLoc(),
995 diag::err_destructor_return_type,
996 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
997 SourceRange(D.getIdentifierLoc()));
998 }
999 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
1000 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1001 if (FTI.TypeQuals & QualType::Const)
1002 Diag(D.getIdentifierLoc(),
1003 diag::err_invalid_qualified_destructor,
1004 "const",
1005 SourceRange(D.getIdentifierLoc()));
1006 if (FTI.TypeQuals & QualType::Volatile)
1007 Diag(D.getIdentifierLoc(),
1008 diag::err_invalid_qualified_destructor,
1009 "volatile",
1010 SourceRange(D.getIdentifierLoc()));
1011 if (FTI.TypeQuals & QualType::Restrict)
1012 Diag(D.getIdentifierLoc(),
1013 diag::err_invalid_qualified_destructor,
1014 "restrict",
1015 SourceRange(D.getIdentifierLoc()));
1016 }
1017
1018 // Make sure we don't have any parameters.
1019 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1020 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1021
1022 // Delete the parameters.
1023 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1024 if (FTI.NumArgs) {
1025 delete [] FTI.ArgInfo;
1026 FTI.NumArgs = 0;
1027 FTI.ArgInfo = 0;
1028 }
1029 }
1030
1031 // Make sure the destructor isn't variadic.
1032 if (R->getAsFunctionTypeProto()->isVariadic())
1033 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1034
1035 // Rebuild the function type "R" without any type qualifiers or
1036 // parameters (in case any of the errors above fired) and with
1037 // "void" as the return type, since destructors don't have return
1038 // types. We *always* have to do this, because GetTypeForDeclarator
1039 // will put in a result type of "int" when none was specified.
1040 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1041
1042 return isInvalid;
1043}
1044
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001045/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1046/// well-formednes of the conversion function declarator @p D with
1047/// type @p R. If there are any errors in the declarator, this routine
1048/// will emit diagnostics and return true. Otherwise, it will return
1049/// false. Either way, the type @p R will be updated to reflect a
1050/// well-formed type for the conversion operator.
1051bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1052 FunctionDecl::StorageClass& SC) {
1053 bool isInvalid = false;
1054
1055 // C++ [class.conv.fct]p1:
1056 // Neither parameter types nor return type can be specified. The
1057 // type of a conversion function (8.3.5) is “function taking no
1058 // parameter returning conversion-type-id.”
1059 if (SC == FunctionDecl::Static) {
1060 Diag(D.getIdentifierLoc(),
1061 diag::err_conv_function_not_member,
1062 "static",
1063 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
1064 SourceRange(D.getIdentifierLoc()));
1065 isInvalid = true;
1066 SC = FunctionDecl::None;
1067 }
1068 if (D.getDeclSpec().hasTypeSpecifier()) {
1069 // Conversion functions don't have return types, but the parser will
1070 // happily parse something like:
1071 //
1072 // class X {
1073 // float operator bool();
1074 // };
1075 //
1076 // The return type will be changed later anyway.
1077 Diag(D.getIdentifierLoc(),
1078 diag::err_conv_function_return_type,
1079 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
1080 SourceRange(D.getIdentifierLoc()));
1081 }
1082
1083 // Make sure we don't have any parameters.
1084 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1085 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1086
1087 // Delete the parameters.
1088 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1089 if (FTI.NumArgs) {
1090 delete [] FTI.ArgInfo;
1091 FTI.NumArgs = 0;
1092 FTI.ArgInfo = 0;
1093 }
1094 }
1095
1096 // Make sure the conversion function isn't variadic.
1097 if (R->getAsFunctionTypeProto()->isVariadic())
1098 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1099
1100 // C++ [class.conv.fct]p4:
1101 // The conversion-type-id shall not represent a function type nor
1102 // an array type.
1103 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1104 if (ConvType->isArrayType()) {
1105 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1106 ConvType = Context.getPointerType(ConvType);
1107 } else if (ConvType->isFunctionType()) {
1108 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1109 ConvType = Context.getPointerType(ConvType);
1110 }
1111
1112 // Rebuild the function type "R" without any parameters (in case any
1113 // of the errors above fired) and with the conversion type as the
1114 // return type.
1115 R = Context.getFunctionType(ConvType, 0, 0, false,
1116 R->getAsFunctionTypeProto()->getTypeQuals());
1117
1118 return isInvalid;
1119}
1120
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001121/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete
1122/// the declaration of the given C++ constructor ConDecl that was
1123/// built from declarator D. This routine is responsible for checking
1124/// that the newly-created constructor declaration is well-formed and
1125/// for recording it in the C++ class. Example:
1126///
1127/// @code
1128/// class X {
1129/// X(); // X::X() will be the ConDecl.
1130/// };
1131/// @endcode
1132Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) {
1133 assert(ConDecl && "Expected to receive a constructor declaration");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001134
1135 // Check default arguments on the constructor
1136 CheckCXXDefaultArguments(ConDecl);
1137
Douglas Gregorccabf082008-10-31 20:25:05 +00001138 CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1139 if (!ClassDecl) {
1140 ConDecl->setInvalidDecl();
1141 return ConDecl;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001142 }
1143
Douglas Gregorccabf082008-10-31 20:25:05 +00001144 // Make sure this constructor is an overload of the existing
1145 // constructors.
1146 OverloadedFunctionDecl::function_iterator MatchedDecl;
1147 if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) {
1148 Diag(ConDecl->getLocation(),
1149 diag::err_constructor_redeclared,
1150 SourceRange(ConDecl->getLocation()));
1151 Diag((*MatchedDecl)->getLocation(),
1152 diag::err_previous_declaration,
1153 SourceRange((*MatchedDecl)->getLocation()));
1154 ConDecl->setInvalidDecl();
1155 return ConDecl;
1156 }
1157
1158
1159 // C++ [class.copy]p3:
1160 // A declaration of a constructor for a class X is ill-formed if
1161 // its first parameter is of type (optionally cv-qualified) X and
1162 // either there are no other parameters or else all other
1163 // parameters have default arguments.
1164 if ((ConDecl->getNumParams() == 1) ||
1165 (ConDecl->getNumParams() > 1 &&
1166 ConDecl->getParamDecl(1)->getDefaultArg() != 0)) {
1167 QualType ParamType = ConDecl->getParamDecl(0)->getType();
1168 QualType ClassTy = Context.getTagDeclType(
1169 const_cast<CXXRecordDecl*>(ConDecl->getParent()));
1170 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1171 Diag(ConDecl->getLocation(),
1172 diag::err_constructor_byvalue_arg,
1173 SourceRange(ConDecl->getParamDecl(0)->getLocation()));
1174 ConDecl->setInvalidDecl();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001175 return ConDecl;
Douglas Gregorccabf082008-10-31 20:25:05 +00001176 }
1177 }
1178
1179 // Add this constructor to the set of constructors of the current
1180 // class.
1181 ClassDecl->addConstructor(Context, ConDecl);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001182 return (DeclTy *)ConDecl;
1183}
1184
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001185/// ActOnDestructorDeclarator - Called by ActOnDeclarator to complete
1186/// the declaration of the given C++ @p Destructor. This routine is
1187/// responsible for recording the destructor in the C++ class, if
1188/// possible.
1189Sema::DeclTy *Sema::ActOnDestructorDeclarator(CXXDestructorDecl *Destructor) {
1190 assert(Destructor && "Expected to receive a destructor declaration");
1191
1192 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext);
1193
1194 // Make sure we aren't redeclaring the destructor.
1195 if (CXXDestructorDecl *PrevDestructor = ClassDecl->getDestructor()) {
1196 Diag(Destructor->getLocation(), diag::err_destructor_redeclared);
1197 Diag(PrevDestructor->getLocation(),
1198 PrevDestructor->isThisDeclarationADefinition()?
1199 diag::err_previous_definition
1200 : diag::err_previous_declaration);
1201 Destructor->setInvalidDecl();
1202 return Destructor;
1203 }
1204
1205 ClassDecl->setDestructor(Destructor);
1206 return (DeclTy *)Destructor;
1207}
1208
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001209/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1210/// the declaration of the given C++ conversion function. This routine
1211/// is responsible for recording the conversion function in the C++
1212/// class, if possible.
1213Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1214 assert(Conversion && "Expected to receive a conversion function declaration");
1215
1216 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext);
1217
1218 // Make sure we aren't redeclaring the conversion function.
1219 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
1220 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1221 for (OverloadedFunctionDecl::function_iterator Func
1222 = Conversions->function_begin();
1223 Func != Conversions->function_end(); ++Func) {
1224 CXXConversionDecl *OtherConv = cast<CXXConversionDecl>(*Func);
1225 if (ConvType == Context.getCanonicalType(OtherConv->getConversionType())) {
1226 Diag(Conversion->getLocation(), diag::err_conv_function_redeclared);
1227 Diag(OtherConv->getLocation(),
1228 OtherConv->isThisDeclarationADefinition()?
1229 diag::err_previous_definition
1230 : diag::err_previous_declaration);
1231 Conversion->setInvalidDecl();
1232 return (DeclTy *)Conversion;
1233 }
1234 }
1235
1236 // C++ [class.conv.fct]p1:
1237 // [...] A conversion function is never used to convert a
1238 // (possibly cv-qualified) object to the (possibly cv-qualified)
1239 // same object type (or a reference to it), to a (possibly
1240 // cv-qualified) base class of that type (or a reference to it),
1241 // or to (possibly cv-qualified) void.
1242 // FIXME: Suppress this warning if the conversion function ends up
1243 // being a virtual function that overrides a virtual function in a
1244 // base class.
1245 QualType ClassType
1246 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1247 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1248 ConvType = ConvTypeRef->getPointeeType();
1249 if (ConvType->isRecordType()) {
1250 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1251 if (ConvType == ClassType)
1252 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used,
1253 ClassType.getAsString());
1254 else if (IsDerivedFrom(ClassType, ConvType))
1255 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used,
1256 ClassType.getAsString(),
1257 ConvType.getAsString());
1258 } else if (ConvType->isVoidType()) {
1259 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used,
1260 ClassType.getAsString(), ConvType.getAsString());
1261 }
1262
1263 ClassDecl->addConversionFunction(Context, Conversion);
1264
1265 return (DeclTy *)Conversion;
1266}
1267
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001268//===----------------------------------------------------------------------===//
1269// Namespace Handling
1270//===----------------------------------------------------------------------===//
1271
1272/// ActOnStartNamespaceDef - This is called at the start of a namespace
1273/// definition.
1274Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1275 SourceLocation IdentLoc,
1276 IdentifierInfo *II,
1277 SourceLocation LBrace) {
1278 NamespaceDecl *Namespc =
1279 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1280 Namespc->setLBracLoc(LBrace);
1281
1282 Scope *DeclRegionScope = NamespcScope->getParent();
1283
1284 if (II) {
1285 // C++ [namespace.def]p2:
1286 // The identifier in an original-namespace-definition shall not have been
1287 // previously defined in the declarative region in which the
1288 // original-namespace-definition appears. The identifier in an
1289 // original-namespace-definition is the name of the namespace. Subsequently
1290 // in that declarative region, it is treated as an original-namespace-name.
1291
1292 Decl *PrevDecl =
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001293 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 0,
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001294 /*enableLazyBuiltinCreation=*/false);
1295
Argiris Kirtzidisad9de132008-09-10 02:11:07 +00001296 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001297 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
1298 // This is an extended namespace definition.
1299 // Attach this namespace decl to the chain of extended namespace
1300 // definitions.
1301 NamespaceDecl *NextNS = OrigNS;
1302 while (NextNS->getNextNamespace())
1303 NextNS = NextNS->getNextNamespace();
1304
1305 NextNS->setNextNamespace(Namespc);
1306 Namespc->setOriginalNamespace(OrigNS);
1307
1308 // We won't add this decl to the current scope. We want the namespace
1309 // name to return the original namespace decl during a name lookup.
1310 } else {
1311 // This is an invalid name redefinition.
1312 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
1313 Namespc->getName());
1314 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1315 Namespc->setInvalidDecl();
1316 // Continue on to push Namespc as current DeclContext and return it.
1317 }
1318 } else {
1319 // This namespace name is declared for the first time.
1320 PushOnScopeChains(Namespc, DeclRegionScope);
1321 }
1322 }
1323 else {
1324 // FIXME: Handle anonymous namespaces
1325 }
1326
1327 // Although we could have an invalid decl (i.e. the namespace name is a
1328 // redefinition), push it as current DeclContext and try to continue parsing.
1329 PushDeclContext(Namespc->getOriginalNamespace());
1330 return Namespc;
1331}
1332
1333/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1334/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1335void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1336 Decl *Dcl = static_cast<Decl *>(D);
1337 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1338 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1339 Namespc->setRBracLoc(RBrace);
1340 PopDeclContext();
1341}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001342
1343
1344/// AddCXXDirectInitializerToDecl - This action is called immediately after
1345/// ActOnDeclarator, when a C++ direct initializer is present.
1346/// e.g: "int x(1);"
1347void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1348 ExprTy **ExprTys, unsigned NumExprs,
1349 SourceLocation *CommaLocs,
1350 SourceLocation RParenLoc) {
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001351 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001352 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001353
1354 // If there is no declaration, there was an error parsing it. Just ignore
1355 // the initializer.
1356 if (RealDecl == 0) {
Ted Kremenek85b4c492008-10-06 20:35:04 +00001357 for (unsigned i = 0; i != NumExprs; ++i)
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001358 delete static_cast<Expr *>(ExprTys[i]);
1359 return;
1360 }
1361
1362 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1363 if (!VDecl) {
1364 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1365 RealDecl->setInvalidDecl();
1366 return;
1367 }
1368
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001369 // We will treat direct-initialization as a copy-initialization:
1370 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001371 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1372 //
1373 // Clients that want to distinguish between the two forms, can check for
1374 // direct initializer using VarDecl::hasCXXDirectInitializer().
1375 // A major benefit is that clients that don't particularly care about which
1376 // exactly form was it (like the CodeGen) can handle both cases without
1377 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001378
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001379 // C++ 8.5p11:
1380 // The form of initialization (using parentheses or '=') is generally
1381 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001382 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +00001383 QualType DeclInitType = VDecl->getType();
1384 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1385 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001386
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001387 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001388 CXXConstructorDecl *Constructor
Douglas Gregor6428e762008-11-05 15:29:30 +00001389 = PerformInitializationByConstructor(DeclInitType,
1390 (Expr **)ExprTys, NumExprs,
1391 VDecl->getLocation(),
1392 SourceRange(VDecl->getLocation(),
1393 RParenLoc),
1394 VDecl->getName(),
1395 IK_Direct);
Douglas Gregor5870a952008-11-03 20:45:27 +00001396 if (!Constructor) {
1397 RealDecl->setInvalidDecl();
1398 }
Douglas Gregor6428e762008-11-05 15:29:30 +00001399
1400 // Let clients know that initialization was done with a direct
1401 // initializer.
1402 VDecl->setCXXDirectInitializer(true);
1403
1404 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1405 // the initializer.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001406 return;
1407 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001408
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001409 if (NumExprs > 1) {
1410 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
1411 SourceRange(VDecl->getLocation(), RParenLoc));
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001412 RealDecl->setInvalidDecl();
1413 return;
1414 }
1415
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001416 // Let clients know that initialization was done with a direct initializer.
1417 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001418
1419 assert(NumExprs == 1 && "Expected 1 expression");
1420 // Set the init expression, handles conversions.
1421 AddInitializerToDecl(Dcl, ExprTys[0]);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001422}
Douglas Gregor81c29152008-10-29 00:13:59 +00001423
Douglas Gregor6428e762008-11-05 15:29:30 +00001424/// PerformInitializationByConstructor - Perform initialization by
1425/// constructor (C++ [dcl.init]p14), which may occur as part of
1426/// direct-initialization or copy-initialization. We are initializing
1427/// an object of type @p ClassType with the given arguments @p
1428/// Args. @p Loc is the location in the source code where the
1429/// initializer occurs (e.g., a declaration, member initializer,
1430/// functional cast, etc.) while @p Range covers the whole
1431/// initialization. @p InitEntity is the entity being initialized,
1432/// which may by the name of a declaration or a type. @p Kind is the
1433/// kind of initialization we're performing, which affects whether
1434/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00001435/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00001436/// when the initialization fails, emits a diagnostic and returns
1437/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00001438CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00001439Sema::PerformInitializationByConstructor(QualType ClassType,
1440 Expr **Args, unsigned NumArgs,
1441 SourceLocation Loc, SourceRange Range,
1442 std::string InitEntity,
1443 InitializationKind Kind) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001444 const RecordType *ClassRec = ClassType->getAsRecordType();
1445 assert(ClassRec && "Can only initialize a class type here");
1446
1447 // C++ [dcl.init]p14:
1448 //
1449 // If the initialization is direct-initialization, or if it is
1450 // copy-initialization where the cv-unqualified version of the
1451 // source type is the same class as, or a derived class of, the
1452 // class of the destination, constructors are considered. The
1453 // applicable constructors are enumerated (13.3.1.3), and the
1454 // best one is chosen through overload resolution (13.3). The
1455 // constructor so selected is called to initialize the object,
1456 // with the initializer expression(s) as its argument(s). If no
1457 // constructor applies, or the overload resolution is ambiguous,
1458 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00001459 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1460 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00001461
1462 // Add constructors to the overload set.
1463 OverloadedFunctionDecl *Constructors
1464 = const_cast<OverloadedFunctionDecl *>(ClassDecl->getConstructors());
1465 for (OverloadedFunctionDecl::function_iterator Con
1466 = Constructors->function_begin();
1467 Con != Constructors->function_end(); ++Con) {
1468 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1469 if ((Kind == IK_Direct) ||
1470 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1471 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1472 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1473 }
1474
Douglas Gregor5870a952008-11-03 20:45:27 +00001475 OverloadCandidateSet::iterator Best;
Douglas Gregor5870a952008-11-03 20:45:27 +00001476 switch (BestViableFunction(CandidateSet, Best)) {
1477 case OR_Success:
1478 // We found a constructor. Return it.
1479 return cast<CXXConstructorDecl>(Best->Function);
1480
1481 case OR_No_Viable_Function:
1482 if (CandidateSet.empty())
1483 Diag(Loc, diag::err_ovl_no_viable_function_in_init,
1484 InitEntity, Range);
1485 else {
1486 Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands,
1487 InitEntity, Range);
1488 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1489 }
1490 return 0;
1491
1492 case OR_Ambiguous:
1493 Diag(Loc, diag::err_ovl_ambiguous_init,
1494 InitEntity, Range);
1495 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1496 return 0;
1497 }
1498
1499 return 0;
1500}
1501
Douglas Gregor81c29152008-10-29 00:13:59 +00001502/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1503/// determine whether they are reference-related,
1504/// reference-compatible, reference-compatible with added
1505/// qualification, or incompatible, for use in C++ initialization by
1506/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1507/// type, and the first type (T1) is the pointee type of the reference
1508/// type being initialized.
1509Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001510Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1511 bool& DerivedToBase) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001512 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1513 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1514
1515 T1 = Context.getCanonicalType(T1);
1516 T2 = Context.getCanonicalType(T2);
1517 QualType UnqualT1 = T1.getUnqualifiedType();
1518 QualType UnqualT2 = T2.getUnqualifiedType();
1519
1520 // C++ [dcl.init.ref]p4:
1521 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1522 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1523 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001524 if (UnqualT1 == UnqualT2)
1525 DerivedToBase = false;
1526 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1527 DerivedToBase = true;
1528 else
Douglas Gregor81c29152008-10-29 00:13:59 +00001529 return Ref_Incompatible;
1530
1531 // At this point, we know that T1 and T2 are reference-related (at
1532 // least).
1533
1534 // C++ [dcl.init.ref]p4:
1535 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1536 // reference-related to T2 and cv1 is the same cv-qualification
1537 // as, or greater cv-qualification than, cv2. For purposes of
1538 // overload resolution, cases for which cv1 is greater
1539 // cv-qualification than cv2 are identified as
1540 // reference-compatible with added qualification (see 13.3.3.2).
1541 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1542 return Ref_Compatible;
1543 else if (T1.isMoreQualifiedThan(T2))
1544 return Ref_Compatible_With_Added_Qualification;
1545 else
1546 return Ref_Related;
1547}
1548
1549/// CheckReferenceInit - Check the initialization of a reference
1550/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1551/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00001552/// list), and DeclType is the type of the declaration. When ICS is
1553/// non-null, this routine will compute the implicit conversion
1554/// sequence according to C++ [over.ics.ref] and will not produce any
1555/// diagnostics; when ICS is null, it will emit diagnostics when any
1556/// errors are found. Either way, a return value of true indicates
1557/// that there was a failure, a return value of false indicates that
1558/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001559///
1560/// When @p SuppressUserConversions, user-defined conversions are
1561/// suppressed.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001562bool
1563Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001564 ImplicitConversionSequence *ICS,
1565 bool SuppressUserConversions) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001566 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1567
1568 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1569 QualType T2 = Init->getType();
1570
Douglas Gregor45014fd2008-11-10 20:40:00 +00001571 // If the initializer is the address of an overloaded function, try
1572 // to resolve the overloaded function. If all goes well, T2 is the
1573 // type of the resulting function.
1574 if (T2->isOverloadType()) {
1575 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1576 ICS != 0);
1577 if (Fn) {
1578 // Since we're performing this reference-initialization for
1579 // real, update the initializer with the resulting function.
1580 if (!ICS)
1581 FixOverloadedFunctionReference(Init, Fn);
1582
1583 T2 = Fn->getType();
1584 }
1585 }
1586
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001587 // Compute some basic properties of the types and the initializer.
1588 bool DerivedToBase = false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001589 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001590 ReferenceCompareResult RefRelationship
1591 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1592
1593 // Most paths end in a failed conversion.
1594 if (ICS)
1595 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00001596
1597 // C++ [dcl.init.ref]p5:
1598 // A reference to type “cv1 T1” is initialized by an expression
1599 // of type “cv2 T2” as follows:
1600
1601 // -- If the initializer expression
1602
1603 bool BindsDirectly = false;
1604 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1605 // reference-compatible with “cv2 T2,” or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001606 //
1607 // Note that the bit-field check is skipped if we are just computing
1608 // the implicit conversion sequence (C++ [over.best.ics]p2).
1609 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1610 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001611 BindsDirectly = true;
1612
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001613 if (ICS) {
1614 // C++ [over.ics.ref]p1:
1615 // When a parameter of reference type binds directly (8.5.3)
1616 // to an argument expression, the implicit conversion sequence
1617 // is the identity conversion, unless the argument expression
1618 // has a type that is a derived class of the parameter type,
1619 // in which case the implicit conversion sequence is a
1620 // derived-to-base Conversion (13.3.3.1).
1621 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1622 ICS->Standard.First = ICK_Identity;
1623 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1624 ICS->Standard.Third = ICK_Identity;
1625 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1626 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001627 ICS->Standard.ReferenceBinding = true;
1628 ICS->Standard.DirectBinding = true;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001629
1630 // Nothing more to do: the inaccessibility/ambiguity check for
1631 // derived-to-base conversions is suppressed when we're
1632 // computing the implicit conversion sequence (C++
1633 // [over.best.ics]p2).
1634 return false;
1635 } else {
1636 // Perform the conversion.
Douglas Gregor81c29152008-10-29 00:13:59 +00001637 // FIXME: Binding to a subobject of the lvalue is going to require
1638 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001639 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001640 }
1641 }
1642
1643 // -- has a class type (i.e., T2 is a class type) and can be
1644 // implicitly converted to an lvalue of type “cv3 T3,”
1645 // where “cv1 T1” is reference-compatible with “cv3 T3”
1646 // 92) (this conversion is selected by enumerating the
1647 // applicable conversion functions (13.3.1.6) and choosing
1648 // the best one through overload resolution (13.3)),
Douglas Gregore6985fe2008-11-10 16:14:15 +00001649 if (!SuppressUserConversions && T2->isRecordType()) {
1650 // FIXME: Look for conversions in base classes!
1651 CXXRecordDecl *T2RecordDecl
1652 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor81c29152008-10-29 00:13:59 +00001653
Douglas Gregore6985fe2008-11-10 16:14:15 +00001654 OverloadCandidateSet CandidateSet;
1655 OverloadedFunctionDecl *Conversions
1656 = T2RecordDecl->getConversionFunctions();
1657 for (OverloadedFunctionDecl::function_iterator Func
1658 = Conversions->function_begin();
1659 Func != Conversions->function_end(); ++Func) {
1660 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1661
1662 // If the conversion function doesn't return a reference type,
1663 // it can't be considered for this conversion.
1664 // FIXME: This will change when we support rvalue references.
1665 if (Conv->getConversionType()->isReferenceType())
1666 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1667 }
1668
1669 OverloadCandidateSet::iterator Best;
1670 switch (BestViableFunction(CandidateSet, Best)) {
1671 case OR_Success:
1672 // This is a direct binding.
1673 BindsDirectly = true;
1674
1675 if (ICS) {
1676 // C++ [over.ics.ref]p1:
1677 //
1678 // [...] If the parameter binds directly to the result of
1679 // applying a conversion function to the argument
1680 // expression, the implicit conversion sequence is a
1681 // user-defined conversion sequence (13.3.3.1.2), with the
1682 // second standard conversion sequence either an identity
1683 // conversion or, if the conversion function returns an
1684 // entity of a type that is a derived class of the parameter
1685 // type, a derived-to-base Conversion.
1686 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1687 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1688 ICS->UserDefined.After = Best->FinalConversion;
1689 ICS->UserDefined.ConversionFunction = Best->Function;
1690 assert(ICS->UserDefined.After.ReferenceBinding &&
1691 ICS->UserDefined.After.DirectBinding &&
1692 "Expected a direct reference binding!");
1693 return false;
1694 } else {
1695 // Perform the conversion.
1696 // FIXME: Binding to a subobject of the lvalue is going to require
1697 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001698 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregore6985fe2008-11-10 16:14:15 +00001699 }
1700 break;
1701
1702 case OR_Ambiguous:
1703 assert(false && "Ambiguous reference binding conversions not implemented.");
1704 return true;
1705
1706 case OR_No_Viable_Function:
1707 // There was no suitable conversion; continue with other checks.
1708 break;
1709 }
1710 }
1711
Douglas Gregor81c29152008-10-29 00:13:59 +00001712 if (BindsDirectly) {
1713 // C++ [dcl.init.ref]p4:
1714 // [...] In all cases where the reference-related or
1715 // reference-compatible relationship of two types is used to
1716 // establish the validity of a reference binding, and T1 is a
1717 // base class of T2, a program that necessitates such a binding
1718 // is ill-formed if T1 is an inaccessible (clause 11) or
1719 // ambiguous (10.2) base class of T2.
1720 //
1721 // Note that we only check this condition when we're allowed to
1722 // complain about errors, because we should not be checking for
1723 // ambiguity (or inaccessibility) unless the reference binding
1724 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001725 if (DerivedToBase)
1726 return CheckDerivedToBaseConversion(T2, T1,
1727 Init->getSourceRange().getBegin(),
1728 Init->getSourceRange());
1729 else
1730 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001731 }
1732
1733 // -- Otherwise, the reference shall be to a non-volatile const
1734 // type (i.e., cv1 shall be const).
1735 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001736 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001737 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00001738 diag::err_not_reference_to_const_init)
1739 << T1.getAsString()
1740 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1741 << T2.getAsString() << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001742 return true;
1743 }
1744
1745 // -- If the initializer expression is an rvalue, with T2 a
1746 // class type, and “cv1 T1” is reference-compatible with
1747 // “cv2 T2,” the reference is bound in one of the
1748 // following ways (the choice is implementation-defined):
1749 //
1750 // -- The reference is bound to the object represented by
1751 // the rvalue (see 3.10) or to a sub-object within that
1752 // object.
1753 //
1754 // -- A temporary of type “cv1 T2” [sic] is created, and
1755 // a constructor is called to copy the entire rvalue
1756 // object into the temporary. The reference is bound to
1757 // the temporary or to a sub-object within the
1758 // temporary.
1759 //
1760 //
1761 // The constructor that would be used to make the copy
1762 // shall be callable whether or not the copy is actually
1763 // done.
1764 //
1765 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1766 // freedom, so we will always take the first option and never build
1767 // a temporary in this case. FIXME: We will, however, have to check
1768 // for the presence of a copy constructor in C++98/03 mode.
1769 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001770 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1771 if (ICS) {
1772 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1773 ICS->Standard.First = ICK_Identity;
1774 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1775 ICS->Standard.Third = ICK_Identity;
1776 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1777 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001778 ICS->Standard.ReferenceBinding = true;
1779 ICS->Standard.DirectBinding = false;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001780 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001781 // FIXME: Binding to a subobject of the rvalue is going to require
1782 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001783 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001784 }
1785 return false;
1786 }
1787
1788 // -- Otherwise, a temporary of type “cv1 T1” is created and
1789 // initialized from the initializer expression using the
1790 // rules for a non-reference copy initialization (8.5). The
1791 // reference is then bound to the temporary. If T1 is
1792 // reference-related to T2, cv1 must be the same
1793 // cv-qualification as, or greater cv-qualification than,
1794 // cv2; otherwise, the program is ill-formed.
1795 if (RefRelationship == Ref_Related) {
1796 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1797 // we would be reference-compatible or reference-compatible with
1798 // added qualification. But that wasn't the case, so the reference
1799 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001800 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001801 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00001802 diag::err_reference_init_drops_quals)
1803 << T1.getAsString()
1804 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1805 << T2.getAsString() << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001806 return true;
1807 }
1808
1809 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001810 if (ICS) {
1811 /// C++ [over.ics.ref]p2:
1812 ///
1813 /// When a parameter of reference type is not bound directly to
1814 /// an argument expression, the conversion sequence is the one
1815 /// required to convert the argument expression to the
1816 /// underlying type of the reference according to
1817 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1818 /// to copy-initializing a temporary of the underlying type with
1819 /// the argument expression. Any difference in top-level
1820 /// cv-qualification is subsumed by the initialization itself
1821 /// and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001822 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001823 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1824 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001825 return PerformImplicitConversion(Init, T1);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001826 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001827}
Douglas Gregore60e5d32008-11-06 22:13:31 +00001828
1829/// CheckOverloadedOperatorDeclaration - Check whether the declaration
1830/// of this overloaded operator is well-formed. If so, returns false;
1831/// otherwise, emits appropriate diagnostics and returns true.
1832bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001833 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregore60e5d32008-11-06 22:13:31 +00001834 "Expected an overloaded operator declaration");
1835
Douglas Gregore60e5d32008-11-06 22:13:31 +00001836 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
1837
1838 // C++ [over.oper]p5:
1839 // The allocation and deallocation functions, operator new,
1840 // operator new[], operator delete and operator delete[], are
1841 // described completely in 3.7.3. The attributes and restrictions
1842 // found in the rest of this subclause do not apply to them unless
1843 // explicitly stated in 3.7.3.
1844 // FIXME: Write a separate routine for checking this. For now, just
1845 // allow it.
1846 if (Op == OO_New || Op == OO_Array_New ||
1847 Op == OO_Delete || Op == OO_Array_Delete)
1848 return false;
1849
1850 // C++ [over.oper]p6:
1851 // An operator function shall either be a non-static member
1852 // function or be a non-member function and have at least one
1853 // parameter whose type is a class, a reference to a class, an
1854 // enumeration, or a reference to an enumeration.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001855 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
1856 if (MethodDecl->isStatic())
1857 return Diag(FnDecl->getLocation(),
1858 diag::err_operator_overload_static,
1859 FnDecl->getName());
Douglas Gregore60e5d32008-11-06 22:13:31 +00001860 } else {
1861 bool ClassOrEnumParam = false;
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001862 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
1863 ParamEnd = FnDecl->param_end();
1864 Param != ParamEnd; ++Param) {
1865 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregore60e5d32008-11-06 22:13:31 +00001866 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
1867 ClassOrEnumParam = true;
1868 break;
1869 }
1870 }
1871
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001872 if (!ClassOrEnumParam)
1873 return Diag(FnDecl->getLocation(),
1874 diag::err_operator_overload_needs_class_or_enum,
1875 FnDecl->getName());
Douglas Gregore60e5d32008-11-06 22:13:31 +00001876 }
1877
1878 // C++ [over.oper]p8:
1879 // An operator function cannot have default arguments (8.3.6),
1880 // except where explicitly stated below.
1881 //
1882 // Only the function-call operator allows default arguments
1883 // (C++ [over.call]p1).
1884 if (Op != OO_Call) {
1885 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
1886 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001887 if (Expr *DefArg = (*Param)->getDefaultArg())
1888 return Diag((*Param)->getLocation(),
1889 diag::err_operator_overload_default_arg,
1890 FnDecl->getName(), DefArg->getSourceRange());
Douglas Gregore60e5d32008-11-06 22:13:31 +00001891 }
1892 }
1893
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001894 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
1895 { false, false, false }
1896#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1897 , { Unary, Binary, MemberOnly }
1898#include "clang/Basic/OperatorKinds.def"
1899 };
Douglas Gregore60e5d32008-11-06 22:13:31 +00001900
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001901 bool CanBeUnaryOperator = OperatorUses[Op][0];
1902 bool CanBeBinaryOperator = OperatorUses[Op][1];
1903 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregore60e5d32008-11-06 22:13:31 +00001904
1905 // C++ [over.oper]p8:
1906 // [...] Operator functions cannot have more or fewer parameters
1907 // than the number required for the corresponding operator, as
1908 // described in the rest of this subclause.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001909 unsigned NumParams = FnDecl->getNumParams()
1910 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregore60e5d32008-11-06 22:13:31 +00001911 if (Op != OO_Call &&
1912 ((NumParams == 1 && !CanBeUnaryOperator) ||
1913 (NumParams == 2 && !CanBeBinaryOperator) ||
1914 (NumParams < 1) || (NumParams > 2))) {
1915 // We have the wrong number of parameters.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001916 std::string NumParamsStr = llvm::utostr(NumParams);
Douglas Gregore60e5d32008-11-06 22:13:31 +00001917
1918 diag::kind DK;
1919
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001920 if (CanBeUnaryOperator && CanBeBinaryOperator) {
1921 if (NumParams == 1)
1922 DK = diag::err_operator_overload_must_be_unary_or_binary;
1923 else
1924 DK = diag::err_operator_overload_must_be_unary_or_binary;
1925 } else if (CanBeUnaryOperator) {
1926 if (NumParams == 1)
1927 DK = diag::err_operator_overload_must_be_unary;
1928 else
1929 DK = diag::err_operator_overload_must_be_unary_plural;
1930 } else if (CanBeBinaryOperator) {
1931 if (NumParams == 1)
1932 DK = diag::err_operator_overload_must_be_binary;
1933 else
1934 DK = diag::err_operator_overload_must_be_binary_plural;
1935 } else {
Douglas Gregore60e5d32008-11-06 22:13:31 +00001936 assert(false && "All non-call overloaded operators are unary or binary!");
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001937 }
Douglas Gregore60e5d32008-11-06 22:13:31 +00001938
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001939 return Diag(FnDecl->getLocation(), DK,
1940 FnDecl->getName(), NumParamsStr);
Douglas Gregore60e5d32008-11-06 22:13:31 +00001941 }
1942
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001943 // Overloaded operators other than operator() cannot be variadic.
1944 if (Op != OO_Call &&
1945 FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) {
1946 return Diag(FnDecl->getLocation(),
1947 diag::err_operator_overload_variadic,
1948 FnDecl->getName());
Douglas Gregore60e5d32008-11-06 22:13:31 +00001949 }
1950
1951 // Some operators must be non-static member functions.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001952 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
1953 return Diag(FnDecl->getLocation(),
1954 diag::err_operator_overload_must_be_member,
1955 FnDecl->getName());
Douglas Gregore60e5d32008-11-06 22:13:31 +00001956 }
1957
1958 // C++ [over.inc]p1:
1959 // The user-defined function called operator++ implements the
1960 // prefix and postfix ++ operator. If this function is a member
1961 // function with no parameters, or a non-member function with one
1962 // parameter of class or enumeration type, it defines the prefix
1963 // increment operator ++ for objects of that type. If the function
1964 // is a member function with one parameter (which shall be of type
1965 // int) or a non-member function with two parameters (the second
1966 // of which shall be of type int), it defines the postfix
1967 // increment operator ++ for objects of that type.
1968 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
1969 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
1970 bool ParamIsInt = false;
1971 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
1972 ParamIsInt = BT->getKind() == BuiltinType::Int;
1973
1974 if (!ParamIsInt) {
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001975 diag::kind DK;
Douglas Gregoraa368a22008-11-17 15:03:30 +00001976 if (Op == OO_PlusPlus)
1977 DK = diag::err_operator_overload_post_inc_must_be_int;
1978 else
1979 DK = diag::err_operator_overload_post_dec_must_be_int;
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001980 return Diag(LastParam->getLocation(), DK,
1981 Context.getCanonicalType(LastParam->getType()).getAsString());
Douglas Gregore60e5d32008-11-06 22:13:31 +00001982 }
1983 }
1984
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001985 return false;
Douglas Gregore60e5d32008-11-06 22:13:31 +00001986}