blob: b95ebf0bad8387a1a0d7dcff6d64141001208abc [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"
Chris Lattner97316c02008-04-10 02:22:51 +000023#include "llvm/Support/Compiler.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000024#include <algorithm> // for std::equal
Douglas Gregorabed2172008-10-22 17:49:05 +000025#include <map>
Chris Lattnerac7b83a2008-04-08 05:04:30 +000026
27using namespace clang;
28
Chris Lattner97316c02008-04-10 02:22:51 +000029//===----------------------------------------------------------------------===//
30// CheckDefaultArgumentVisitor
31//===----------------------------------------------------------------------===//
32
Chris Lattnerb1856db2008-04-12 23:52:44 +000033namespace {
34 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
35 /// the default argument of a parameter to determine whether it
36 /// contains any ill-formed subexpressions. For example, this will
37 /// diagnose the use of local variables or parameters within the
38 /// default argument expression.
39 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000040 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb1856db2008-04-12 23:52:44 +000041 Expr *DefaultArg;
42 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000043
Chris Lattnerb1856db2008-04-12 23:52:44 +000044 public:
45 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
46 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000047
Chris Lattnerb1856db2008-04-12 23:52:44 +000048 bool VisitExpr(Expr *Node);
49 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregora5b022a2008-11-04 14:32:21 +000050 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb1856db2008-04-12 23:52:44 +000051 };
Chris Lattner97316c02008-04-10 02:22:51 +000052
Chris Lattnerb1856db2008-04-12 23:52:44 +000053 /// VisitExpr - Visit all of the children of this expression.
54 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
55 bool IsInvalid = false;
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000056 for (Stmt::child_iterator I = Node->child_begin(),
57 E = Node->child_end(); I != E; ++I)
58 IsInvalid |= Visit(*I);
Chris Lattnerb1856db2008-04-12 23:52:44 +000059 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000060 }
61
Chris Lattnerb1856db2008-04-12 23:52:44 +000062 /// VisitDeclRefExpr - Visit a reference to a declaration, to
63 /// determine whether this declaration can be used in the default
64 /// argument expression.
65 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregord2baafd2008-10-21 16:13:35 +000066 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb1856db2008-04-12 23:52:44 +000067 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
68 // C++ [dcl.fct.default]p9
69 // Default arguments are evaluated each time the function is
70 // called. The order of evaluation of function arguments is
71 // unspecified. Consequently, parameters of a function shall not
72 // be used in default argument expressions, even if they are not
73 // evaluated. Parameters of a function declared before a default
74 // argument expression are in scope and can hide namespace and
75 // class member names.
76 return S->Diag(DRE->getSourceRange().getBegin(),
77 diag::err_param_default_argument_references_param,
78 Param->getName(), DefaultArg->getSourceRange());
Steve Naroff72a6ebc2008-04-15 22:42:06 +000079 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000080 // C++ [dcl.fct.default]p7
81 // Local variables shall not be used in default argument
82 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000083 if (VDecl->isBlockVarDecl())
84 return S->Diag(DRE->getSourceRange().getBegin(),
85 diag::err_param_default_argument_references_local,
86 VDecl->getName(), DefaultArg->getSourceRange());
Chris Lattnerb1856db2008-04-12 23:52:44 +000087 }
Chris Lattner97316c02008-04-10 02:22:51 +000088
Douglas Gregor3c246952008-11-04 13:41:56 +000089 return false;
90 }
Chris Lattnerb1856db2008-04-12 23:52:44 +000091
Douglas Gregora5b022a2008-11-04 14:32:21 +000092 /// VisitCXXThisExpr - Visit a C++ "this" expression.
93 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
94 // C++ [dcl.fct.default]p8:
95 // The keyword this shall not be used in a default argument of a
96 // member function.
97 return S->Diag(ThisE->getSourceRange().getBegin(),
98 diag::err_param_default_argument_references_this,
99 ThisE->getSourceRange());
Chris Lattnerb1856db2008-04-12 23:52:44 +0000100 }
Chris Lattner97316c02008-04-10 02:22:51 +0000101}
102
103/// ActOnParamDefaultArgument - Check whether the default argument
104/// provided for a function parameter is well-formed. If so, attach it
105/// to the parameter declaration.
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000106void
107Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
108 ExprTy *defarg) {
109 ParmVarDecl *Param = (ParmVarDecl *)param;
110 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
111 QualType ParamType = Param->getType();
112
113 // Default arguments are only permitted in C++
114 if (!getLangOptions().CPlusPlus) {
115 Diag(EqualLoc, diag::err_param_default_argument,
116 DefaultArg->getSourceRange());
117 return;
118 }
119
120 // C++ [dcl.fct.default]p5
121 // A default argument expression is implicitly converted (clause
122 // 4) to the parameter type. The default argument expression has
123 // the same semantic constraints as the initializer expression in
124 // a declaration of a variable of the parameter type, using the
125 // copy-initialization semantics (8.5).
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000126 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor58c428c2008-11-04 13:57:51 +0000127 bool DefaultInitFailed = PerformCopyInitialization(DefaultArgPtr, ParamType,
128 "in default argument");
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000129 if (DefaultArgPtr != DefaultArg.get()) {
130 DefaultArg.take();
131 DefaultArg.reset(DefaultArgPtr);
132 }
Douglas Gregor58c428c2008-11-04 13:57:51 +0000133 if (DefaultInitFailed) {
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000134 return;
135 }
136
Chris Lattner97316c02008-04-10 02:22:51 +0000137 // Check that the default argument is well-formed
Chris Lattnerb1856db2008-04-12 23:52:44 +0000138 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Chris Lattner97316c02008-04-10 02:22:51 +0000139 if (DefaultArgChecker.Visit(DefaultArg.get()))
140 return;
141
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(DefaultArg.take());
144}
145
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000146/// CheckExtraCXXDefaultArguments - Check for any extra default
147/// arguments in the declarator, which is not a function declaration
148/// or definition and therefore is not permitted to have default
149/// arguments. This routine should be invoked for every declarator
150/// that is not a function declaration or definition.
151void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
152 // C++ [dcl.fct.default]p3
153 // A default argument expression shall be specified only in the
154 // parameter-declaration-clause of a function declaration or in a
155 // template-parameter (14.1). It shall not be specified for a
156 // parameter pack. If it is specified in a
157 // parameter-declaration-clause, it shall not occur within a
158 // declarator or abstract-declarator of a parameter-declaration.
159 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
160 DeclaratorChunk &chunk = D.getTypeObject(i);
161 if (chunk.Kind == DeclaratorChunk::Function) {
162 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
163 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
164 if (Param->getDefaultArg()) {
165 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc,
166 Param->getDefaultArg()->getSourceRange());
167 Param->setDefaultArg(0);
168 }
169 }
170 }
171 }
172}
173
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000174// MergeCXXFunctionDecl - Merge two declarations of the same C++
175// function, once we already know that they have the same
176// type. Subroutine of MergeFunctionDecl.
177FunctionDecl *
178Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
179 // C++ [dcl.fct.default]p4:
180 //
181 // For non-template functions, default arguments can be added in
182 // later declarations of a function in the same
183 // scope. Declarations in different scopes have completely
184 // distinct sets of default arguments. That is, declarations in
185 // inner scopes do not acquire default arguments from
186 // declarations in outer scopes, and vice versa. In a given
187 // function declaration, all parameters subsequent to a
188 // parameter with a default argument shall have default
189 // arguments supplied in this or previous declarations. A
190 // default argument shall not be redefined by a later
191 // declaration (not even to the same value).
192 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
193 ParmVarDecl *OldParam = Old->getParamDecl(p);
194 ParmVarDecl *NewParam = New->getParamDecl(p);
195
196 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
197 Diag(NewParam->getLocation(),
198 diag::err_param_default_argument_redefinition,
199 NewParam->getDefaultArg()->getSourceRange());
200 Diag(OldParam->getLocation(), diag::err_previous_definition);
201 } else if (OldParam->getDefaultArg()) {
202 // Merge the old default argument into the new parameter
203 NewParam->setDefaultArg(OldParam->getDefaultArg());
204 }
205 }
206
207 return New;
208}
209
210/// CheckCXXDefaultArguments - Verify that the default arguments for a
211/// function declaration are well-formed according to C++
212/// [dcl.fct.default].
213void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
214 unsigned NumParams = FD->getNumParams();
215 unsigned p;
216
217 // Find first parameter with a default argument
218 for (p = 0; p < NumParams; ++p) {
219 ParmVarDecl *Param = FD->getParamDecl(p);
220 if (Param->getDefaultArg())
221 break;
222 }
223
224 // C++ [dcl.fct.default]p4:
225 // In a given function declaration, all parameters
226 // subsequent to a parameter with a default argument shall
227 // have default arguments supplied in this or previous
228 // declarations. A default argument shall not be redefined
229 // by a later declaration (not even to the same value).
230 unsigned LastMissingDefaultArg = 0;
231 for(; p < NumParams; ++p) {
232 ParmVarDecl *Param = FD->getParamDecl(p);
233 if (!Param->getDefaultArg()) {
234 if (Param->getIdentifier())
235 Diag(Param->getLocation(),
236 diag::err_param_default_argument_missing_name,
237 Param->getIdentifier()->getName());
238 else
239 Diag(Param->getLocation(),
240 diag::err_param_default_argument_missing);
241
242 LastMissingDefaultArg = p;
243 }
244 }
245
246 if (LastMissingDefaultArg > 0) {
247 // Some default arguments were missing. Clear out all of the
248 // default arguments up to (and including) the last missing
249 // default argument, so that we leave the function parameters
250 // in a semantically valid state.
251 for (p = 0; p <= LastMissingDefaultArg; ++p) {
252 ParmVarDecl *Param = FD->getParamDecl(p);
253 if (Param->getDefaultArg()) {
254 delete Param->getDefaultArg();
255 Param->setDefaultArg(0);
256 }
257 }
258 }
259}
Douglas Gregorec93f442008-04-13 21:30:24 +0000260
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000261/// isCurrentClassName - Determine whether the identifier II is the
262/// name of the class type currently being defined. In the case of
263/// nested classes, this will only return true if II is the name of
264/// the innermost class.
265bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *) {
266 if (CXXRecordDecl *CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext))
267 return &II == CurDecl->getIdentifier();
268 else
269 return false;
270}
271
Douglas Gregorec93f442008-04-13 21:30:24 +0000272/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
273/// one entry in the base class list of a class specifier, for
274/// example:
275/// class foo : public bar, virtual private baz {
276/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorabed2172008-10-22 17:49:05 +0000277Sema::BaseResult
278Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
279 bool Virtual, AccessSpecifier Access,
280 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000281 RecordDecl *Decl = (RecordDecl*)classdecl;
282 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
283
284 // Base specifiers must be record types.
285 if (!BaseType->isRecordType()) {
286 Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000287 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000288 }
289
290 // C++ [class.union]p1:
291 // A union shall not be used as a base class.
292 if (BaseType->isUnionType()) {
293 Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000294 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000295 }
296
297 // C++ [class.union]p1:
298 // A union shall not have base classes.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000299 if (Decl->isUnion()) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000300 Diag(Decl->getLocation(), diag::err_base_clause_on_union,
301 SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000302 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000303 }
304
305 // C++ [class.derived]p2:
306 // The class-name in a base-specifier shall not be an incompletely
307 // defined class.
308 if (BaseType->isIncompleteType()) {
309 Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000310 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000311 }
312
Douglas Gregorabed2172008-10-22 17:49:05 +0000313 // Create the base specifier.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000314 return new CXXBaseSpecifier(SpecifierRange, Virtual,
315 BaseType->isClassType(), Access, BaseType);
Douglas Gregorabed2172008-10-22 17:49:05 +0000316}
Douglas Gregorec93f442008-04-13 21:30:24 +0000317
Douglas Gregorabed2172008-10-22 17:49:05 +0000318/// ActOnBaseSpecifiers - Attach the given base specifiers to the
319/// class, after checking whether there are any duplicate base
320/// classes.
321void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
322 unsigned NumBases) {
323 if (NumBases == 0)
324 return;
325
326 // Used to keep track of which base types we have already seen, so
327 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000328 // that the key is always the unqualified canonical type of the base
329 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000330 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
331
332 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000333 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
334 unsigned NumGoodBases = 0;
335 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000336 QualType NewBaseType
Douglas Gregor4fd85902008-10-23 18:13:27 +0000337 = Context.getCanonicalType(BaseSpecs[idx]->getType());
338 NewBaseType = NewBaseType.getUnqualifiedType();
339
Douglas Gregorabed2172008-10-22 17:49:05 +0000340 if (KnownBaseTypes[NewBaseType]) {
341 // C++ [class.mi]p3:
342 // A class shall not be specified as a direct base class of a
343 // derived class more than once.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000344 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Douglas Gregorabed2172008-10-22 17:49:05 +0000345 diag::err_duplicate_base_class,
346 KnownBaseTypes[NewBaseType]->getType().getAsString(),
Douglas Gregor4fd85902008-10-23 18:13:27 +0000347 BaseSpecs[idx]->getSourceRange());
348
349 // Delete the duplicate base class specifier; we're going to
350 // overwrite its pointer later.
351 delete BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000352 } else {
353 // Okay, add this new base class.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000354 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
355 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000356 }
357 }
358
359 // Attach the remaining base class specifiers to the derived class.
360 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000361 Decl->setBases(BaseSpecs, NumGoodBases);
362
363 // Delete the remaining (good) base class specifiers, since their
364 // data has been copied into the CXXRecordDecl.
365 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
366 delete BaseSpecs[idx];
Douglas Gregorec93f442008-04-13 21:30:24 +0000367}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000368
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000369//===----------------------------------------------------------------------===//
370// C++ class member Handling
371//===----------------------------------------------------------------------===//
372
373/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
374/// definition, when on C++.
375void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000376 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
377 PushDeclContext(Dcl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000378 FieldCollector->StartClass();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000379
380 if (Dcl->getIdentifier()) {
381 // C++ [class]p2:
382 // [...] The class-name is also inserted into the scope of the
383 // class itself; this is known as the injected-class-name. For
384 // purposes of access checking, the injected-class-name is treated
385 // as if it were a public member name.
386 TypedefDecl *InjectedClassName
387 = TypedefDecl::Create(Context, Dcl, LBrace, Dcl->getIdentifier(),
388 Context.getTypeDeclType(Dcl), /*PrevDecl=*/0);
389 PushOnScopeChains(InjectedClassName, S);
390 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000391}
392
393/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
394/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
395/// bitfield width if there is one and 'InitExpr' specifies the initializer if
396/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
397/// declarators on it.
398///
399/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
400/// an instance field is declared, a new CXXFieldDecl is created but the method
401/// does *not* return it; it returns LastInGroup instead. The other C++ members
402/// (which are all ScopedDecls) are returned after appending them to
403/// LastInGroup.
404Sema::DeclTy *
405Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
406 ExprTy *BW, ExprTy *InitExpr,
407 DeclTy *LastInGroup) {
408 const DeclSpec &DS = D.getDeclSpec();
409 IdentifierInfo *II = D.getIdentifier();
410 Expr *BitWidth = static_cast<Expr*>(BW);
411 Expr *Init = static_cast<Expr*>(InitExpr);
412 SourceLocation Loc = D.getIdentifierLoc();
413
414 // C++ 9.2p6: A member shall not be declared to have automatic storage
415 // duration (auto, register) or with the extern storage-class-specifier.
416 switch (DS.getStorageClassSpec()) {
417 case DeclSpec::SCS_unspecified:
418 case DeclSpec::SCS_typedef:
419 case DeclSpec::SCS_static:
420 // FALL THROUGH.
421 break;
422 default:
423 if (DS.getStorageClassSpecLoc().isValid())
424 Diag(DS.getStorageClassSpecLoc(),
425 diag::err_storageclass_invalid_for_member);
426 else
427 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
428 D.getMutableDeclSpec().ClearStorageClassSpecs();
429 }
430
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000431 bool isFunc = D.isFunctionDeclarator();
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000432 if (!isFunc &&
433 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
434 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000435 // Check also for this case:
436 //
437 // typedef int f();
438 // f a;
439 //
440 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
441 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
442 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000443
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000444 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000445 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000446
447 Decl *Member;
448 bool InvalidDecl = false;
449
450 if (isInstField)
451 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
452 else
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000453 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000454
455 if (!Member) return LastInGroup;
456
Sanjiv Guptafa451432008-10-31 09:52:39 +0000457 assert((II || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000458
459 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
460 // specific methods. Use a wrapper class that can be used with all C++ class
461 // member decls.
462 CXXClassMemberWrapper(Member).setAccess(AS);
463
464 if (BitWidth) {
465 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
466 // constant-expression be a value equal to zero.
467 // FIXME: Check this.
468
469 if (D.isFunctionDeclarator()) {
470 // FIXME: Emit diagnostic about only constructors taking base initializers
471 // or something similar, when constructor support is in place.
472 Diag(Loc, diag::err_not_bitfield_type,
473 II->getName(), BitWidth->getSourceRange());
474 InvalidDecl = true;
475
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000476 } else if (isInstField) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000477 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000478 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000479 Diag(Loc, diag::err_not_integral_type_bitfield,
480 II->getName(), BitWidth->getSourceRange());
481 InvalidDecl = true;
482 }
483
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000484 } else if (isa<FunctionDecl>(Member)) {
485 // A function typedef ("typedef int f(); f a;").
486 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
487 Diag(Loc, diag::err_not_integral_type_bitfield,
488 II->getName(), BitWidth->getSourceRange());
489 InvalidDecl = true;
490
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000491 } else if (isa<TypedefDecl>(Member)) {
492 // "cannot declare 'A' to be a bit-field type"
493 Diag(Loc, diag::err_not_bitfield_type, II->getName(),
494 BitWidth->getSourceRange());
495 InvalidDecl = true;
496
497 } else {
498 assert(isa<CXXClassVarDecl>(Member) &&
499 "Didn't we cover all member kinds?");
500 // C++ 9.6p3: A bit-field shall not be a static member.
501 // "static member 'A' cannot be a bit-field"
502 Diag(Loc, diag::err_static_not_bitfield, II->getName(),
503 BitWidth->getSourceRange());
504 InvalidDecl = true;
505 }
506 }
507
508 if (Init) {
509 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
510 // if it declares a static member of const integral or const enumeration
511 // type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000512 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
513 // ...static member of...
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000514 CVD->setInit(Init);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000515 // ...const integral or const enumeration type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000516 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
517 CVD->getType()->isIntegralType()) {
518 // constant-initializer
519 if (CheckForConstantInitializer(Init, CVD->getType()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000520 InvalidDecl = true;
521
522 } else {
523 // not const integral.
524 Diag(Loc, diag::err_member_initialization,
525 II->getName(), Init->getSourceRange());
526 InvalidDecl = true;
527 }
528
529 } else {
530 // not static member.
531 Diag(Loc, diag::err_member_initialization,
532 II->getName(), Init->getSourceRange());
533 InvalidDecl = true;
534 }
535 }
536
537 if (InvalidDecl)
538 Member->setInvalidDecl();
539
540 if (isInstField) {
541 FieldCollector->Add(cast<CXXFieldDecl>(Member));
542 return LastInGroup;
543 }
544 return Member;
545}
546
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000547/// ActOnMemInitializer - Handle a C++ member initializer.
548Sema::MemInitResult
549Sema::ActOnMemInitializer(DeclTy *ConstructorD,
550 Scope *S,
551 IdentifierInfo *MemberOrBase,
552 SourceLocation IdLoc,
553 SourceLocation LParenLoc,
554 ExprTy **Args, unsigned NumArgs,
555 SourceLocation *CommaLocs,
556 SourceLocation RParenLoc) {
557 CXXConstructorDecl *Constructor
558 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
559 if (!Constructor) {
560 // The user wrote a constructor initializer on a function that is
561 // not a C++ constructor. Ignore the error for now, because we may
562 // have more member initializers coming; we'll diagnose it just
563 // once in ActOnMemInitializers.
564 return true;
565 }
566
567 CXXRecordDecl *ClassDecl = Constructor->getParent();
568
569 // C++ [class.base.init]p2:
570 // Names in a mem-initializer-id are looked up in the scope of the
571 // constructor’s class and, if not found in that scope, are looked
572 // up in the scope containing the constructor’s
573 // definition. [Note: if the constructor’s class contains a member
574 // with the same name as a direct or virtual base class of the
575 // class, a mem-initializer-id naming the member or base class and
576 // composed of a single identifier refers to the class member. A
577 // mem-initializer-id for the hidden base class may be specified
578 // using a qualified name. ]
579 // Look for a member, first.
580 CXXFieldDecl *Member = ClassDecl->getMember(MemberOrBase);
581
582 // FIXME: Handle members of an anonymous union.
583
584 if (Member) {
585 // FIXME: Perform direct initialization of the member.
586 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
587 }
588
589 // It didn't name a member, so see if it names a class.
590 TypeTy *BaseTy = isTypeName(*MemberOrBase, S);
591 if (!BaseTy)
592 return Diag(IdLoc, diag::err_mem_init_not_member_or_class,
593 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
594
595 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
596 if (!BaseType->isRecordType())
597 return Diag(IdLoc, diag::err_base_init_does_not_name_class,
598 BaseType.getAsString(), SourceRange(IdLoc, RParenLoc));
599
600 // C++ [class.base.init]p2:
601 // [...] Unless the mem-initializer-id names a nonstatic data
602 // member of the constructor’s class or a direct or virtual base
603 // of that class, the mem-initializer is ill-formed. A
604 // mem-initializer-list can initialize a base class using any
605 // name that denotes that base class type.
606
607 // First, check for a direct base class.
608 const CXXBaseSpecifier *DirectBaseSpec = 0;
609 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
610 Base != ClassDecl->bases_end(); ++Base) {
611 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
612 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
613 // We found a direct base of this type. That's what we're
614 // initializing.
615 DirectBaseSpec = &*Base;
616 break;
617 }
618 }
619
620 // Check for a virtual base class.
621 // FIXME: We might be able to short-circuit this if we know in
622 // advance that there are no virtual bases.
623 const CXXBaseSpecifier *VirtualBaseSpec = 0;
624 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
625 // We haven't found a base yet; search the class hierarchy for a
626 // virtual base class.
627 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
628 /*DetectVirtual=*/false);
629 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
630 for (BasePaths::paths_iterator Path = Paths.begin();
631 Path != Paths.end(); ++Path) {
632 if (Path->back().Base->isVirtual()) {
633 VirtualBaseSpec = Path->back().Base;
634 break;
635 }
636 }
637 }
638 }
639
640 // C++ [base.class.init]p2:
641 // If a mem-initializer-id is ambiguous because it designates both
642 // a direct non-virtual base class and an inherited virtual base
643 // class, the mem-initializer is ill-formed.
644 if (DirectBaseSpec && VirtualBaseSpec)
645 return Diag(IdLoc, diag::err_base_init_direct_and_virtual,
646 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
647
648 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
649}
650
651
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000652void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
653 DeclTy *TagDecl,
654 SourceLocation LBrac,
655 SourceLocation RBrac) {
656 ActOnFields(S, RLoc, TagDecl,
657 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +0000658 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000659}
660
Douglas Gregore640ab62008-11-03 17:51:48 +0000661/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
662/// special functions, such as the default constructor, copy
663/// constructor, or destructor, to the given C++ class (C++
664/// [special]p1). This routine can only be executed just before the
665/// definition of the class is complete.
666void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
667 if (!ClassDecl->hasUserDeclaredConstructor()) {
668 // C++ [class.ctor]p5:
669 // A default constructor for a class X is a constructor of class X
670 // that can be called without an argument. If there is no
671 // user-declared constructor for class X, a default constructor is
672 // implicitly declared. An implicitly-declared default constructor
673 // is an inline public member of its class.
674 CXXConstructorDecl *DefaultCon =
675 CXXConstructorDecl::Create(Context, ClassDecl,
676 ClassDecl->getLocation(),
677 ClassDecl->getIdentifier(),
678 Context.getFunctionType(Context.VoidTy,
679 0, 0, false, 0),
680 /*isExplicit=*/false,
681 /*isInline=*/true,
682 /*isImplicitlyDeclared=*/true);
683 DefaultCon->setAccess(AS_public);
684 ClassDecl->addConstructor(Context, DefaultCon);
685 }
686
687 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
688 // C++ [class.copy]p4:
689 // If the class definition does not explicitly declare a copy
690 // constructor, one is declared implicitly.
691
692 // C++ [class.copy]p5:
693 // The implicitly-declared copy constructor for a class X will
694 // have the form
695 //
696 // X::X(const X&)
697 //
698 // if
699 bool HasConstCopyConstructor = true;
700
701 // -- each direct or virtual base class B of X has a copy
702 // constructor whose first parameter is of type const B& or
703 // const volatile B&, and
704 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
705 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
706 const CXXRecordDecl *BaseClassDecl
707 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
708 HasConstCopyConstructor
709 = BaseClassDecl->hasConstCopyConstructor(Context);
710 }
711
712 // -- for all the nonstatic data members of X that are of a
713 // class type M (or array thereof), each such class type
714 // has a copy constructor whose first parameter is of type
715 // const M& or const volatile M&.
716 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
717 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
718 QualType FieldType = (*Field)->getType();
719 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
720 FieldType = Array->getElementType();
721 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
722 const CXXRecordDecl *FieldClassDecl
723 = cast<CXXRecordDecl>(FieldClassType->getDecl());
724 HasConstCopyConstructor
725 = FieldClassDecl->hasConstCopyConstructor(Context);
726 }
727 }
728
729 // Otherwise, the implicitly declared copy constructor will have
730 // the form
731 //
732 // X::X(X&)
733 QualType ArgType = Context.getTypeDeclType(ClassDecl);
734 if (HasConstCopyConstructor)
735 ArgType = ArgType.withConst();
736 ArgType = Context.getReferenceType(ArgType);
737
738 // An implicitly-declared copy constructor is an inline public
739 // member of its class.
740 CXXConstructorDecl *CopyConstructor
741 = CXXConstructorDecl::Create(Context, ClassDecl,
742 ClassDecl->getLocation(),
743 ClassDecl->getIdentifier(),
744 Context.getFunctionType(Context.VoidTy,
745 &ArgType, 1,
746 false, 0),
747 /*isExplicit=*/false,
748 /*isInline=*/true,
749 /*isImplicitlyDeclared=*/true);
750 CopyConstructor->setAccess(AS_public);
751
752 // Add the parameter to the constructor.
753 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
754 ClassDecl->getLocation(),
755 /*IdentifierInfo=*/0,
756 ArgType, VarDecl::None, 0, 0);
757 CopyConstructor->setParams(&FromParam, 1);
758
759 ClassDecl->addConstructor(Context, CopyConstructor);
760 }
761
762 // FIXME: Implicit destructor
763 // FIXME: Implicit copy assignment operator
764}
765
Argiris Kirtzidis448b4e42008-08-09 00:39:29 +0000766void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000767 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000768 FieldCollector->FinishClass();
Douglas Gregore640ab62008-11-03 17:51:48 +0000769 AddImplicitlyDeclaredMembersToClass(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000770 PopDeclContext();
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000771
772 // Everything, including inline method definitions, have been parsed.
773 // Let the consumer know of the new TagDecl definition.
774 Consumer.HandleTagDeclDefinition(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000775}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000776
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000777/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete
778/// the declaration of the given C++ constructor ConDecl that was
779/// built from declarator D. This routine is responsible for checking
780/// that the newly-created constructor declaration is well-formed and
781/// for recording it in the C++ class. Example:
782///
783/// @code
784/// class X {
785/// X(); // X::X() will be the ConDecl.
786/// };
787/// @endcode
788Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) {
789 assert(ConDecl && "Expected to receive a constructor declaration");
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000790
791 // Check default arguments on the constructor
792 CheckCXXDefaultArguments(ConDecl);
793
Douglas Gregorccabf082008-10-31 20:25:05 +0000794 CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
795 if (!ClassDecl) {
796 ConDecl->setInvalidDecl();
797 return ConDecl;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000798 }
799
Douglas Gregorccabf082008-10-31 20:25:05 +0000800 // Make sure this constructor is an overload of the existing
801 // constructors.
802 OverloadedFunctionDecl::function_iterator MatchedDecl;
803 if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) {
804 Diag(ConDecl->getLocation(),
805 diag::err_constructor_redeclared,
806 SourceRange(ConDecl->getLocation()));
807 Diag((*MatchedDecl)->getLocation(),
808 diag::err_previous_declaration,
809 SourceRange((*MatchedDecl)->getLocation()));
810 ConDecl->setInvalidDecl();
811 return ConDecl;
812 }
813
814
815 // C++ [class.copy]p3:
816 // A declaration of a constructor for a class X is ill-formed if
817 // its first parameter is of type (optionally cv-qualified) X and
818 // either there are no other parameters or else all other
819 // parameters have default arguments.
820 if ((ConDecl->getNumParams() == 1) ||
821 (ConDecl->getNumParams() > 1 &&
822 ConDecl->getParamDecl(1)->getDefaultArg() != 0)) {
823 QualType ParamType = ConDecl->getParamDecl(0)->getType();
824 QualType ClassTy = Context.getTagDeclType(
825 const_cast<CXXRecordDecl*>(ConDecl->getParent()));
826 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
827 Diag(ConDecl->getLocation(),
828 diag::err_constructor_byvalue_arg,
829 SourceRange(ConDecl->getParamDecl(0)->getLocation()));
830 ConDecl->setInvalidDecl();
831 return 0;
832 }
833 }
834
835 // Add this constructor to the set of constructors of the current
836 // class.
837 ClassDecl->addConstructor(Context, ConDecl);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000838 return (DeclTy *)ConDecl;
839}
840
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000841//===----------------------------------------------------------------------===//
842// Namespace Handling
843//===----------------------------------------------------------------------===//
844
845/// ActOnStartNamespaceDef - This is called at the start of a namespace
846/// definition.
847Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
848 SourceLocation IdentLoc,
849 IdentifierInfo *II,
850 SourceLocation LBrace) {
851 NamespaceDecl *Namespc =
852 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
853 Namespc->setLBracLoc(LBrace);
854
855 Scope *DeclRegionScope = NamespcScope->getParent();
856
857 if (II) {
858 // C++ [namespace.def]p2:
859 // The identifier in an original-namespace-definition shall not have been
860 // previously defined in the declarative region in which the
861 // original-namespace-definition appears. The identifier in an
862 // original-namespace-definition is the name of the namespace. Subsequently
863 // in that declarative region, it is treated as an original-namespace-name.
864
865 Decl *PrevDecl =
Argiris Kirtzidisda64ff42008-10-14 18:28:48 +0000866 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000867 /*enableLazyBuiltinCreation=*/false);
868
Argiris Kirtzidisad9de132008-09-10 02:11:07 +0000869 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000870 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
871 // This is an extended namespace definition.
872 // Attach this namespace decl to the chain of extended namespace
873 // definitions.
874 NamespaceDecl *NextNS = OrigNS;
875 while (NextNS->getNextNamespace())
876 NextNS = NextNS->getNextNamespace();
877
878 NextNS->setNextNamespace(Namespc);
879 Namespc->setOriginalNamespace(OrigNS);
880
881 // We won't add this decl to the current scope. We want the namespace
882 // name to return the original namespace decl during a name lookup.
883 } else {
884 // This is an invalid name redefinition.
885 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
886 Namespc->getName());
887 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
888 Namespc->setInvalidDecl();
889 // Continue on to push Namespc as current DeclContext and return it.
890 }
891 } else {
892 // This namespace name is declared for the first time.
893 PushOnScopeChains(Namespc, DeclRegionScope);
894 }
895 }
896 else {
897 // FIXME: Handle anonymous namespaces
898 }
899
900 // Although we could have an invalid decl (i.e. the namespace name is a
901 // redefinition), push it as current DeclContext and try to continue parsing.
902 PushDeclContext(Namespc->getOriginalNamespace());
903 return Namespc;
904}
905
906/// ActOnFinishNamespaceDef - This callback is called after a namespace is
907/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
908void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
909 Decl *Dcl = static_cast<Decl *>(D);
910 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
911 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
912 Namespc->setRBracLoc(RBrace);
913 PopDeclContext();
914}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000915
916
917/// AddCXXDirectInitializerToDecl - This action is called immediately after
918/// ActOnDeclarator, when a C++ direct initializer is present.
919/// e.g: "int x(1);"
920void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
921 ExprTy **ExprTys, unsigned NumExprs,
922 SourceLocation *CommaLocs,
923 SourceLocation RParenLoc) {
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000924 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +0000925 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000926
927 // If there is no declaration, there was an error parsing it. Just ignore
928 // the initializer.
929 if (RealDecl == 0) {
Ted Kremenek85b4c492008-10-06 20:35:04 +0000930 for (unsigned i = 0; i != NumExprs; ++i)
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000931 delete static_cast<Expr *>(ExprTys[i]);
932 return;
933 }
934
935 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
936 if (!VDecl) {
937 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
938 RealDecl->setInvalidDecl();
939 return;
940 }
941
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +0000942 // We will treat direct-initialization as a copy-initialization:
943 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000944 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
945 //
946 // Clients that want to distinguish between the two forms, can check for
947 // direct initializer using VarDecl::hasCXXDirectInitializer().
948 // A major benefit is that clients that don't particularly care about which
949 // exactly form was it (like the CodeGen) can handle both cases without
950 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000951
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000952 // C++ 8.5p11:
953 // The form of initialization (using parentheses or '=') is generally
954 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000955 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +0000956 QualType DeclInitType = VDecl->getType();
957 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
958 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000959
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000960 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +0000961 CXXConstructorDecl *Constructor
Douglas Gregor6428e762008-11-05 15:29:30 +0000962 = PerformInitializationByConstructor(DeclInitType,
963 (Expr **)ExprTys, NumExprs,
964 VDecl->getLocation(),
965 SourceRange(VDecl->getLocation(),
966 RParenLoc),
967 VDecl->getName(),
968 IK_Direct);
Douglas Gregor5870a952008-11-03 20:45:27 +0000969 if (!Constructor) {
970 RealDecl->setInvalidDecl();
971 }
Douglas Gregor6428e762008-11-05 15:29:30 +0000972
973 // Let clients know that initialization was done with a direct
974 // initializer.
975 VDecl->setCXXDirectInitializer(true);
976
977 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
978 // the initializer.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000979 return;
980 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000981
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +0000982 if (NumExprs > 1) {
983 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
984 SourceRange(VDecl->getLocation(), RParenLoc));
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000985 RealDecl->setInvalidDecl();
986 return;
987 }
988
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000989 // Let clients know that initialization was done with a direct initializer.
990 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +0000991
992 assert(NumExprs == 1 && "Expected 1 expression");
993 // Set the init expression, handles conversions.
994 AddInitializerToDecl(Dcl, ExprTys[0]);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000995}
Douglas Gregor81c29152008-10-29 00:13:59 +0000996
Douglas Gregor6428e762008-11-05 15:29:30 +0000997/// PerformInitializationByConstructor - Perform initialization by
998/// constructor (C++ [dcl.init]p14), which may occur as part of
999/// direct-initialization or copy-initialization. We are initializing
1000/// an object of type @p ClassType with the given arguments @p
1001/// Args. @p Loc is the location in the source code where the
1002/// initializer occurs (e.g., a declaration, member initializer,
1003/// functional cast, etc.) while @p Range covers the whole
1004/// initialization. @p InitEntity is the entity being initialized,
1005/// which may by the name of a declaration or a type. @p Kind is the
1006/// kind of initialization we're performing, which affects whether
1007/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00001008/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00001009/// when the initialization fails, emits a diagnostic and returns
1010/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00001011CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00001012Sema::PerformInitializationByConstructor(QualType ClassType,
1013 Expr **Args, unsigned NumArgs,
1014 SourceLocation Loc, SourceRange Range,
1015 std::string InitEntity,
1016 InitializationKind Kind) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001017 const RecordType *ClassRec = ClassType->getAsRecordType();
1018 assert(ClassRec && "Can only initialize a class type here");
1019
1020 // C++ [dcl.init]p14:
1021 //
1022 // If the initialization is direct-initialization, or if it is
1023 // copy-initialization where the cv-unqualified version of the
1024 // source type is the same class as, or a derived class of, the
1025 // class of the destination, constructors are considered. The
1026 // applicable constructors are enumerated (13.3.1.3), and the
1027 // best one is chosen through overload resolution (13.3). The
1028 // constructor so selected is called to initialize the object,
1029 // with the initializer expression(s) as its argument(s). If no
1030 // constructor applies, or the overload resolution is ambiguous,
1031 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00001032 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1033 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00001034
1035 // Add constructors to the overload set.
1036 OverloadedFunctionDecl *Constructors
1037 = const_cast<OverloadedFunctionDecl *>(ClassDecl->getConstructors());
1038 for (OverloadedFunctionDecl::function_iterator Con
1039 = Constructors->function_begin();
1040 Con != Constructors->function_end(); ++Con) {
1041 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1042 if ((Kind == IK_Direct) ||
1043 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1044 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1045 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1046 }
1047
Douglas Gregor5870a952008-11-03 20:45:27 +00001048 OverloadCandidateSet::iterator Best;
Douglas Gregor5870a952008-11-03 20:45:27 +00001049 switch (BestViableFunction(CandidateSet, Best)) {
1050 case OR_Success:
1051 // We found a constructor. Return it.
1052 return cast<CXXConstructorDecl>(Best->Function);
1053
1054 case OR_No_Viable_Function:
1055 if (CandidateSet.empty())
1056 Diag(Loc, diag::err_ovl_no_viable_function_in_init,
1057 InitEntity, Range);
1058 else {
1059 Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands,
1060 InitEntity, Range);
1061 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1062 }
1063 return 0;
1064
1065 case OR_Ambiguous:
1066 Diag(Loc, diag::err_ovl_ambiguous_init,
1067 InitEntity, Range);
1068 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1069 return 0;
1070 }
1071
1072 return 0;
1073}
1074
Douglas Gregor81c29152008-10-29 00:13:59 +00001075/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1076/// determine whether they are reference-related,
1077/// reference-compatible, reference-compatible with added
1078/// qualification, or incompatible, for use in C++ initialization by
1079/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1080/// type, and the first type (T1) is the pointee type of the reference
1081/// type being initialized.
1082Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001083Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1084 bool& DerivedToBase) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001085 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1086 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1087
1088 T1 = Context.getCanonicalType(T1);
1089 T2 = Context.getCanonicalType(T2);
1090 QualType UnqualT1 = T1.getUnqualifiedType();
1091 QualType UnqualT2 = T2.getUnqualifiedType();
1092
1093 // C++ [dcl.init.ref]p4:
1094 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1095 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1096 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001097 if (UnqualT1 == UnqualT2)
1098 DerivedToBase = false;
1099 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1100 DerivedToBase = true;
1101 else
Douglas Gregor81c29152008-10-29 00:13:59 +00001102 return Ref_Incompatible;
1103
1104 // At this point, we know that T1 and T2 are reference-related (at
1105 // least).
1106
1107 // C++ [dcl.init.ref]p4:
1108 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1109 // reference-related to T2 and cv1 is the same cv-qualification
1110 // as, or greater cv-qualification than, cv2. For purposes of
1111 // overload resolution, cases for which cv1 is greater
1112 // cv-qualification than cv2 are identified as
1113 // reference-compatible with added qualification (see 13.3.3.2).
1114 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1115 return Ref_Compatible;
1116 else if (T1.isMoreQualifiedThan(T2))
1117 return Ref_Compatible_With_Added_Qualification;
1118 else
1119 return Ref_Related;
1120}
1121
1122/// CheckReferenceInit - Check the initialization of a reference
1123/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1124/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00001125/// list), and DeclType is the type of the declaration. When ICS is
1126/// non-null, this routine will compute the implicit conversion
1127/// sequence according to C++ [over.ics.ref] and will not produce any
1128/// diagnostics; when ICS is null, it will emit diagnostics when any
1129/// errors are found. Either way, a return value of true indicates
1130/// that there was a failure, a return value of false indicates that
1131/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001132///
1133/// When @p SuppressUserConversions, user-defined conversions are
1134/// suppressed.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001135bool
1136Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001137 ImplicitConversionSequence *ICS,
1138 bool SuppressUserConversions) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001139 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1140
1141 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1142 QualType T2 = Init->getType();
1143
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001144 // Compute some basic properties of the types and the initializer.
1145 bool DerivedToBase = false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001146 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001147 ReferenceCompareResult RefRelationship
1148 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1149
1150 // Most paths end in a failed conversion.
1151 if (ICS)
1152 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00001153
1154 // C++ [dcl.init.ref]p5:
1155 // A reference to type “cv1 T1” is initialized by an expression
1156 // of type “cv2 T2” as follows:
1157
1158 // -- If the initializer expression
1159
1160 bool BindsDirectly = false;
1161 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1162 // reference-compatible with “cv2 T2,” or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001163 //
1164 // Note that the bit-field check is skipped if we are just computing
1165 // the implicit conversion sequence (C++ [over.best.ics]p2).
1166 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1167 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001168 BindsDirectly = true;
1169
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001170 if (ICS) {
1171 // C++ [over.ics.ref]p1:
1172 // When a parameter of reference type binds directly (8.5.3)
1173 // to an argument expression, the implicit conversion sequence
1174 // is the identity conversion, unless the argument expression
1175 // has a type that is a derived class of the parameter type,
1176 // in which case the implicit conversion sequence is a
1177 // derived-to-base Conversion (13.3.3.1).
1178 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1179 ICS->Standard.First = ICK_Identity;
1180 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1181 ICS->Standard.Third = ICK_Identity;
1182 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1183 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001184 ICS->Standard.ReferenceBinding = true;
1185 ICS->Standard.DirectBinding = true;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001186
1187 // Nothing more to do: the inaccessibility/ambiguity check for
1188 // derived-to-base conversions is suppressed when we're
1189 // computing the implicit conversion sequence (C++
1190 // [over.best.ics]p2).
1191 return false;
1192 } else {
1193 // Perform the conversion.
Douglas Gregor81c29152008-10-29 00:13:59 +00001194 // FIXME: Binding to a subobject of the lvalue is going to require
1195 // more AST annotation than this.
1196 ImpCastExprToType(Init, T1);
1197 }
1198 }
1199
1200 // -- has a class type (i.e., T2 is a class type) and can be
1201 // implicitly converted to an lvalue of type “cv3 T3,”
1202 // where “cv1 T1” is reference-compatible with “cv3 T3”
1203 // 92) (this conversion is selected by enumerating the
1204 // applicable conversion functions (13.3.1.6) and choosing
1205 // the best one through overload resolution (13.3)),
1206 // FIXME: Implement this second bullet, once we have conversion
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001207 // functions. Also remember C++ [over.ics.ref]p1, second part.
Douglas Gregor81c29152008-10-29 00:13:59 +00001208
1209 if (BindsDirectly) {
1210 // C++ [dcl.init.ref]p4:
1211 // [...] In all cases where the reference-related or
1212 // reference-compatible relationship of two types is used to
1213 // establish the validity of a reference binding, and T1 is a
1214 // base class of T2, a program that necessitates such a binding
1215 // is ill-formed if T1 is an inaccessible (clause 11) or
1216 // ambiguous (10.2) base class of T2.
1217 //
1218 // Note that we only check this condition when we're allowed to
1219 // complain about errors, because we should not be checking for
1220 // ambiguity (or inaccessibility) unless the reference binding
1221 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001222 if (DerivedToBase)
1223 return CheckDerivedToBaseConversion(T2, T1,
1224 Init->getSourceRange().getBegin(),
1225 Init->getSourceRange());
1226 else
1227 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001228 }
1229
1230 // -- Otherwise, the reference shall be to a non-volatile const
1231 // type (i.e., cv1 shall be const).
1232 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001233 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001234 Diag(Init->getSourceRange().getBegin(),
1235 diag::err_not_reference_to_const_init,
1236 T1.getAsString(),
1237 InitLvalue != Expr::LV_Valid? "temporary" : "value",
1238 T2.getAsString(), Init->getSourceRange());
1239 return true;
1240 }
1241
1242 // -- If the initializer expression is an rvalue, with T2 a
1243 // class type, and “cv1 T1” is reference-compatible with
1244 // “cv2 T2,” the reference is bound in one of the
1245 // following ways (the choice is implementation-defined):
1246 //
1247 // -- The reference is bound to the object represented by
1248 // the rvalue (see 3.10) or to a sub-object within that
1249 // object.
1250 //
1251 // -- A temporary of type “cv1 T2” [sic] is created, and
1252 // a constructor is called to copy the entire rvalue
1253 // object into the temporary. The reference is bound to
1254 // the temporary or to a sub-object within the
1255 // temporary.
1256 //
1257 //
1258 // The constructor that would be used to make the copy
1259 // shall be callable whether or not the copy is actually
1260 // done.
1261 //
1262 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1263 // freedom, so we will always take the first option and never build
1264 // a temporary in this case. FIXME: We will, however, have to check
1265 // for the presence of a copy constructor in C++98/03 mode.
1266 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001267 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1268 if (ICS) {
1269 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1270 ICS->Standard.First = ICK_Identity;
1271 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1272 ICS->Standard.Third = ICK_Identity;
1273 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1274 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001275 ICS->Standard.ReferenceBinding = true;
1276 ICS->Standard.DirectBinding = false;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001277 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001278 // FIXME: Binding to a subobject of the rvalue is going to require
1279 // more AST annotation than this.
1280 ImpCastExprToType(Init, T1);
1281 }
1282 return false;
1283 }
1284
1285 // -- Otherwise, a temporary of type “cv1 T1” is created and
1286 // initialized from the initializer expression using the
1287 // rules for a non-reference copy initialization (8.5). The
1288 // reference is then bound to the temporary. If T1 is
1289 // reference-related to T2, cv1 must be the same
1290 // cv-qualification as, or greater cv-qualification than,
1291 // cv2; otherwise, the program is ill-formed.
1292 if (RefRelationship == Ref_Related) {
1293 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1294 // we would be reference-compatible or reference-compatible with
1295 // added qualification. But that wasn't the case, so the reference
1296 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001297 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001298 Diag(Init->getSourceRange().getBegin(),
1299 diag::err_reference_init_drops_quals,
1300 T1.getAsString(),
1301 InitLvalue != Expr::LV_Valid? "temporary" : "value",
1302 T2.getAsString(), Init->getSourceRange());
1303 return true;
1304 }
1305
1306 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001307 if (ICS) {
1308 /// C++ [over.ics.ref]p2:
1309 ///
1310 /// When a parameter of reference type is not bound directly to
1311 /// an argument expression, the conversion sequence is the one
1312 /// required to convert the argument expression to the
1313 /// underlying type of the reference according to
1314 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1315 /// to copy-initializing a temporary of the underlying type with
1316 /// the argument expression. Any difference in top-level
1317 /// cv-qualification is subsumed by the initialization itself
1318 /// and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001319 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001320 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1321 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001322 return PerformImplicitConversion(Init, T1);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001323 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001324}