blob: bdc2fafce847e8c78d70a3dabc92d8c7251a1e58 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor7ad83902008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor02189362008-10-22 21:13:31 +000018#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000019#include "clang/AST/StmtVisitor.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000020#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000021#include "clang/Basic/Diagnostic.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000022#include "clang/Parse/DeclSpec.h"
Chris Lattner8123a952008-04-10 02:22:51 +000023#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000025#include <map>
Chris Lattner3d1cee32008-04-08 05:04:30 +000026
27using namespace clang;
28
Chris Lattner8123a952008-04-10 02:22:51 +000029//===----------------------------------------------------------------------===//
30// CheckDefaultArgumentVisitor
31//===----------------------------------------------------------------------===//
32
Chris Lattner9e979552008-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 Lattnerb77792e2008-07-26 22:17:49 +000040 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000041 Expr *DefaultArg;
42 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000043
Chris Lattner9e979552008-04-12 23:52:44 +000044 public:
45 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
46 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000047
Chris Lattner9e979552008-04-12 23:52:44 +000048 bool VisitExpr(Expr *Node);
49 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000050 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000051 };
Chris Lattner8123a952008-04-10 02:22:51 +000052
Chris Lattner9e979552008-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 Lattnerb77792e2008-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 Lattner9e979552008-04-12 23:52:44 +000059 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000060 }
61
Chris Lattner9e979552008-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 Gregor8e9bebd2008-10-21 16:13:35 +000066 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-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 Naroff248a7532008-04-15 22:42:06 +000079 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000080 // C++ [dcl.fct.default]p7
81 // Local variables shall not be used in default argument
82 // expressions.
Steve Naroff248a7532008-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 Lattner9e979552008-04-12 23:52:44 +000087 }
Chris Lattner8123a952008-04-10 02:22:51 +000088
Douglas Gregor3996f232008-11-04 13:41:56 +000089 return false;
90 }
Chris Lattner9e979552008-04-12 23:52:44 +000091
Douglas Gregor796da182008-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 Lattner9e979552008-04-12 23:52:44 +0000100 }
Chris Lattner8123a952008-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 Lattner3d1cee32008-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 Lattner3d1cee32008-04-08 05:04:30 +0000126 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregoreb704f22008-11-04 13:57:51 +0000127 bool DefaultInitFailed = PerformCopyInitialization(DefaultArgPtr, ParamType,
128 "in default argument");
Chris Lattner3d1cee32008-04-08 05:04:30 +0000129 if (DefaultArgPtr != DefaultArg.get()) {
130 DefaultArg.take();
131 DefaultArg.reset(DefaultArgPtr);
132 }
Douglas Gregoreb704f22008-11-04 13:57:51 +0000133 if (DefaultInitFailed) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000134 return;
135 }
136
Chris Lattner8123a952008-04-10 02:22:51 +0000137 // Check that the default argument is well-formed
Chris Lattner9e979552008-04-12 23:52:44 +0000138 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Chris Lattner8123a952008-04-10 02:22:51 +0000139 if (DefaultArgChecker.Visit(DefaultArg.get()))
140 return;
141
Chris Lattner3d1cee32008-04-08 05:04:30 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(DefaultArg.take());
144}
145
Douglas Gregor6d6eb572008-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 Lattner3d1cee32008-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 Gregore37ac4f2008-04-13 21:30:24 +0000260
Douglas Gregorb48fe382008-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 Gregore37ac4f2008-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 Gregorf8268ae2008-10-22 17:49:05 +0000277Sema::BaseResult
278Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
279 bool Virtual, AccessSpecifier Access,
280 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregore37ac4f2008-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 Gregorf8268ae2008-10-22 17:49:05 +0000287 return true;
Douglas Gregore37ac4f2008-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 Gregorf8268ae2008-10-22 17:49:05 +0000294 return true;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000295 }
296
297 // C++ [class.union]p1:
298 // A union shall not have base classes.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000299 if (Decl->isUnion()) {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000300 Diag(Decl->getLocation(), diag::err_base_clause_on_union,
301 SpecifierRange);
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000302 return true;
Douglas Gregore37ac4f2008-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 Gregorf8268ae2008-10-22 17:49:05 +0000310 return true;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000311 }
312
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000313 // If the base class is polymorphic, the new one is, too.
314 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
315 assert(BaseDecl && "Record type has no declaration");
316 BaseDecl = BaseDecl->getDefinition(Context);
317 assert(BaseDecl && "Base type is not incomplete, but has no definition");
318 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic()) {
319 cast<CXXRecordDecl>(Decl)->setPolymorphic(true);
320 }
321
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000322 // Create the base specifier.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000323 return new CXXBaseSpecifier(SpecifierRange, Virtual,
324 BaseType->isClassType(), Access, BaseType);
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000325}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000326
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000327/// ActOnBaseSpecifiers - Attach the given base specifiers to the
328/// class, after checking whether there are any duplicate base
329/// classes.
330void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
331 unsigned NumBases) {
332 if (NumBases == 0)
333 return;
334
335 // Used to keep track of which base types we have already seen, so
336 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000337 // that the key is always the unqualified canonical type of the base
338 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000339 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
340
341 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000342 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
343 unsigned NumGoodBases = 0;
344 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000345 QualType NewBaseType
Douglas Gregor57c856b2008-10-23 18:13:27 +0000346 = Context.getCanonicalType(BaseSpecs[idx]->getType());
347 NewBaseType = NewBaseType.getUnqualifiedType();
348
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000349 if (KnownBaseTypes[NewBaseType]) {
350 // C++ [class.mi]p3:
351 // A class shall not be specified as a direct base class of a
352 // derived class more than once.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000353 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000354 diag::err_duplicate_base_class,
355 KnownBaseTypes[NewBaseType]->getType().getAsString(),
Douglas Gregor57c856b2008-10-23 18:13:27 +0000356 BaseSpecs[idx]->getSourceRange());
357
358 // Delete the duplicate base class specifier; we're going to
359 // overwrite its pointer later.
360 delete BaseSpecs[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000361 } else {
362 // Okay, add this new base class.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000363 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
364 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000365 }
366 }
367
368 // Attach the remaining base class specifiers to the derived class.
369 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000370 Decl->setBases(BaseSpecs, NumGoodBases);
371
372 // Delete the remaining (good) base class specifiers, since their
373 // data has been copied into the CXXRecordDecl.
374 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
375 delete BaseSpecs[idx];
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000376}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000377
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000378//===----------------------------------------------------------------------===//
379// C++ class member Handling
380//===----------------------------------------------------------------------===//
381
382/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
383/// definition, when on C++.
384void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
Douglas Gregorb48fe382008-10-31 09:07:45 +0000385 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
386 PushDeclContext(Dcl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000387 FieldCollector->StartClass();
Douglas Gregorb48fe382008-10-31 09:07:45 +0000388
389 if (Dcl->getIdentifier()) {
390 // C++ [class]p2:
391 // [...] The class-name is also inserted into the scope of the
392 // class itself; this is known as the injected-class-name. For
393 // purposes of access checking, the injected-class-name is treated
394 // as if it were a public member name.
Douglas Gregor42a552f2008-11-05 20:51:48 +0000395 // FIXME: this should probably have its own kind of type node.
Douglas Gregorb48fe382008-10-31 09:07:45 +0000396 TypedefDecl *InjectedClassName
397 = TypedefDecl::Create(Context, Dcl, LBrace, Dcl->getIdentifier(),
398 Context.getTypeDeclType(Dcl), /*PrevDecl=*/0);
399 PushOnScopeChains(InjectedClassName, S);
400 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000401}
402
403/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
404/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
405/// bitfield width if there is one and 'InitExpr' specifies the initializer if
406/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
407/// declarators on it.
408///
409/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
410/// an instance field is declared, a new CXXFieldDecl is created but the method
411/// does *not* return it; it returns LastInGroup instead. The other C++ members
412/// (which are all ScopedDecls) are returned after appending them to
413/// LastInGroup.
414Sema::DeclTy *
415Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
416 ExprTy *BW, ExprTy *InitExpr,
417 DeclTy *LastInGroup) {
418 const DeclSpec &DS = D.getDeclSpec();
419 IdentifierInfo *II = D.getIdentifier();
420 Expr *BitWidth = static_cast<Expr*>(BW);
421 Expr *Init = static_cast<Expr*>(InitExpr);
422 SourceLocation Loc = D.getIdentifierLoc();
423
424 // C++ 9.2p6: A member shall not be declared to have automatic storage
425 // duration (auto, register) or with the extern storage-class-specifier.
426 switch (DS.getStorageClassSpec()) {
427 case DeclSpec::SCS_unspecified:
428 case DeclSpec::SCS_typedef:
429 case DeclSpec::SCS_static:
430 // FALL THROUGH.
431 break;
432 default:
433 if (DS.getStorageClassSpecLoc().isValid())
434 Diag(DS.getStorageClassSpecLoc(),
435 diag::err_storageclass_invalid_for_member);
436 else
437 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
438 D.getMutableDeclSpec().ClearStorageClassSpecs();
439 }
440
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000441 bool isFunc = D.isFunctionDeclarator();
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000442 if (!isFunc &&
443 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
444 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000445 // Check also for this case:
446 //
447 // typedef int f();
448 // f a;
449 //
450 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
451 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
452 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000453
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000454 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000455 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000456
457 Decl *Member;
458 bool InvalidDecl = false;
459
460 if (isInstField)
461 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
462 else
Daniel Dunbar914701e2008-08-05 16:28:08 +0000463 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000464
465 if (!Member) return LastInGroup;
466
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +0000467 assert((II || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000468
469 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
470 // specific methods. Use a wrapper class that can be used with all C++ class
471 // member decls.
472 CXXClassMemberWrapper(Member).setAccess(AS);
473
Douglas Gregor64bffa92008-11-05 16:20:31 +0000474 // C++ [dcl.init.aggr]p1:
475 // An aggregate is an array or a class (clause 9) with [...] no
476 // private or protected non-static data members (clause 11).
477 if (isInstField && (AS == AS_private || AS == AS_protected))
478 cast<CXXRecordDecl>(CurContext)->setAggregate(false);
479
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000480 if (DS.isVirtualSpecified()) {
481 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
482 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
483 InvalidDecl = true;
484 } else {
485 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
486 CurClass->setAggregate(false);
487 CurClass->setPolymorphic(true);
488 }
489 }
Douglas Gregor64bffa92008-11-05 16:20:31 +0000490
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000491 if (BitWidth) {
492 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
493 // constant-expression be a value equal to zero.
494 // FIXME: Check this.
495
496 if (D.isFunctionDeclarator()) {
497 // FIXME: Emit diagnostic about only constructors taking base initializers
498 // or something similar, when constructor support is in place.
499 Diag(Loc, diag::err_not_bitfield_type,
500 II->getName(), BitWidth->getSourceRange());
501 InvalidDecl = true;
502
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000503 } else if (isInstField) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000504 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000505 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000506 Diag(Loc, diag::err_not_integral_type_bitfield,
507 II->getName(), BitWidth->getSourceRange());
508 InvalidDecl = true;
509 }
510
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000511 } else if (isa<FunctionDecl>(Member)) {
512 // A function typedef ("typedef int f(); f a;").
513 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
514 Diag(Loc, diag::err_not_integral_type_bitfield,
515 II->getName(), BitWidth->getSourceRange());
516 InvalidDecl = true;
517
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000518 } else if (isa<TypedefDecl>(Member)) {
519 // "cannot declare 'A' to be a bit-field type"
520 Diag(Loc, diag::err_not_bitfield_type, II->getName(),
521 BitWidth->getSourceRange());
522 InvalidDecl = true;
523
524 } else {
525 assert(isa<CXXClassVarDecl>(Member) &&
526 "Didn't we cover all member kinds?");
527 // C++ 9.6p3: A bit-field shall not be a static member.
528 // "static member 'A' cannot be a bit-field"
529 Diag(Loc, diag::err_static_not_bitfield, II->getName(),
530 BitWidth->getSourceRange());
531 InvalidDecl = true;
532 }
533 }
534
535 if (Init) {
536 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
537 // if it declares a static member of const integral or const enumeration
538 // type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000539 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
540 // ...static member of...
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000541 CVD->setInit(Init);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000542 // ...const integral or const enumeration type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000543 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
544 CVD->getType()->isIntegralType()) {
545 // constant-initializer
546 if (CheckForConstantInitializer(Init, CVD->getType()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000547 InvalidDecl = true;
548
549 } else {
550 // not const integral.
551 Diag(Loc, diag::err_member_initialization,
552 II->getName(), Init->getSourceRange());
553 InvalidDecl = true;
554 }
555
556 } else {
557 // not static member.
558 Diag(Loc, diag::err_member_initialization,
559 II->getName(), Init->getSourceRange());
560 InvalidDecl = true;
561 }
562 }
563
564 if (InvalidDecl)
565 Member->setInvalidDecl();
566
567 if (isInstField) {
568 FieldCollector->Add(cast<CXXFieldDecl>(Member));
569 return LastInGroup;
570 }
571 return Member;
572}
573
Douglas Gregor7ad83902008-11-05 04:29:56 +0000574/// ActOnMemInitializer - Handle a C++ member initializer.
575Sema::MemInitResult
576Sema::ActOnMemInitializer(DeclTy *ConstructorD,
577 Scope *S,
578 IdentifierInfo *MemberOrBase,
579 SourceLocation IdLoc,
580 SourceLocation LParenLoc,
581 ExprTy **Args, unsigned NumArgs,
582 SourceLocation *CommaLocs,
583 SourceLocation RParenLoc) {
584 CXXConstructorDecl *Constructor
585 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
586 if (!Constructor) {
587 // The user wrote a constructor initializer on a function that is
588 // not a C++ constructor. Ignore the error for now, because we may
589 // have more member initializers coming; we'll diagnose it just
590 // once in ActOnMemInitializers.
591 return true;
592 }
593
594 CXXRecordDecl *ClassDecl = Constructor->getParent();
595
596 // C++ [class.base.init]p2:
597 // Names in a mem-initializer-id are looked up in the scope of the
598 // constructor’s class and, if not found in that scope, are looked
599 // up in the scope containing the constructor’s
600 // definition. [Note: if the constructor’s class contains a member
601 // with the same name as a direct or virtual base class of the
602 // class, a mem-initializer-id naming the member or base class and
603 // composed of a single identifier refers to the class member. A
604 // mem-initializer-id for the hidden base class may be specified
605 // using a qualified name. ]
606 // Look for a member, first.
607 CXXFieldDecl *Member = ClassDecl->getMember(MemberOrBase);
608
609 // FIXME: Handle members of an anonymous union.
610
611 if (Member) {
612 // FIXME: Perform direct initialization of the member.
613 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
614 }
615
616 // It didn't name a member, so see if it names a class.
617 TypeTy *BaseTy = isTypeName(*MemberOrBase, S);
618 if (!BaseTy)
619 return Diag(IdLoc, diag::err_mem_init_not_member_or_class,
620 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
621
622 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
623 if (!BaseType->isRecordType())
624 return Diag(IdLoc, diag::err_base_init_does_not_name_class,
625 BaseType.getAsString(), SourceRange(IdLoc, RParenLoc));
626
627 // C++ [class.base.init]p2:
628 // [...] Unless the mem-initializer-id names a nonstatic data
629 // member of the constructor’s class or a direct or virtual base
630 // of that class, the mem-initializer is ill-formed. A
631 // mem-initializer-list can initialize a base class using any
632 // name that denotes that base class type.
633
634 // First, check for a direct base class.
635 const CXXBaseSpecifier *DirectBaseSpec = 0;
636 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
637 Base != ClassDecl->bases_end(); ++Base) {
638 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
639 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
640 // We found a direct base of this type. That's what we're
641 // initializing.
642 DirectBaseSpec = &*Base;
643 break;
644 }
645 }
646
647 // Check for a virtual base class.
648 // FIXME: We might be able to short-circuit this if we know in
649 // advance that there are no virtual bases.
650 const CXXBaseSpecifier *VirtualBaseSpec = 0;
651 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
652 // We haven't found a base yet; search the class hierarchy for a
653 // virtual base class.
654 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
655 /*DetectVirtual=*/false);
656 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
657 for (BasePaths::paths_iterator Path = Paths.begin();
658 Path != Paths.end(); ++Path) {
659 if (Path->back().Base->isVirtual()) {
660 VirtualBaseSpec = Path->back().Base;
661 break;
662 }
663 }
664 }
665 }
666
667 // C++ [base.class.init]p2:
668 // If a mem-initializer-id is ambiguous because it designates both
669 // a direct non-virtual base class and an inherited virtual base
670 // class, the mem-initializer is ill-formed.
671 if (DirectBaseSpec && VirtualBaseSpec)
672 return Diag(IdLoc, diag::err_base_init_direct_and_virtual,
673 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
674
675 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
676}
677
678
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000679void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
680 DeclTy *TagDecl,
681 SourceLocation LBrac,
682 SourceLocation RBrac) {
683 ActOnFields(S, RLoc, TagDecl,
684 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +0000685 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000686}
687
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000688/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
689/// special functions, such as the default constructor, copy
690/// constructor, or destructor, to the given C++ class (C++
691/// [special]p1). This routine can only be executed just before the
692/// definition of the class is complete.
693void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
694 if (!ClassDecl->hasUserDeclaredConstructor()) {
695 // C++ [class.ctor]p5:
696 // A default constructor for a class X is a constructor of class X
697 // that can be called without an argument. If there is no
698 // user-declared constructor for class X, a default constructor is
699 // implicitly declared. An implicitly-declared default constructor
700 // is an inline public member of its class.
701 CXXConstructorDecl *DefaultCon =
702 CXXConstructorDecl::Create(Context, ClassDecl,
703 ClassDecl->getLocation(),
704 ClassDecl->getIdentifier(),
705 Context.getFunctionType(Context.VoidTy,
706 0, 0, false, 0),
707 /*isExplicit=*/false,
708 /*isInline=*/true,
709 /*isImplicitlyDeclared=*/true);
710 DefaultCon->setAccess(AS_public);
711 ClassDecl->addConstructor(Context, DefaultCon);
712 }
713
714 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
715 // C++ [class.copy]p4:
716 // If the class definition does not explicitly declare a copy
717 // constructor, one is declared implicitly.
718
719 // C++ [class.copy]p5:
720 // The implicitly-declared copy constructor for a class X will
721 // have the form
722 //
723 // X::X(const X&)
724 //
725 // if
726 bool HasConstCopyConstructor = true;
727
728 // -- each direct or virtual base class B of X has a copy
729 // constructor whose first parameter is of type const B& or
730 // const volatile B&, and
731 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
732 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
733 const CXXRecordDecl *BaseClassDecl
734 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
735 HasConstCopyConstructor
736 = BaseClassDecl->hasConstCopyConstructor(Context);
737 }
738
739 // -- for all the nonstatic data members of X that are of a
740 // class type M (or array thereof), each such class type
741 // has a copy constructor whose first parameter is of type
742 // const M& or const volatile M&.
743 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
744 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
745 QualType FieldType = (*Field)->getType();
746 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
747 FieldType = Array->getElementType();
748 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
749 const CXXRecordDecl *FieldClassDecl
750 = cast<CXXRecordDecl>(FieldClassType->getDecl());
751 HasConstCopyConstructor
752 = FieldClassDecl->hasConstCopyConstructor(Context);
753 }
754 }
755
756 // Otherwise, the implicitly declared copy constructor will have
757 // the form
758 //
759 // X::X(X&)
760 QualType ArgType = Context.getTypeDeclType(ClassDecl);
761 if (HasConstCopyConstructor)
762 ArgType = ArgType.withConst();
763 ArgType = Context.getReferenceType(ArgType);
764
765 // An implicitly-declared copy constructor is an inline public
766 // member of its class.
767 CXXConstructorDecl *CopyConstructor
768 = CXXConstructorDecl::Create(Context, ClassDecl,
769 ClassDecl->getLocation(),
770 ClassDecl->getIdentifier(),
771 Context.getFunctionType(Context.VoidTy,
772 &ArgType, 1,
773 false, 0),
774 /*isExplicit=*/false,
775 /*isInline=*/true,
776 /*isImplicitlyDeclared=*/true);
777 CopyConstructor->setAccess(AS_public);
778
779 // Add the parameter to the constructor.
780 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
781 ClassDecl->getLocation(),
782 /*IdentifierInfo=*/0,
783 ArgType, VarDecl::None, 0, 0);
784 CopyConstructor->setParams(&FromParam, 1);
785
786 ClassDecl->addConstructor(Context, CopyConstructor);
787 }
788
Douglas Gregor42a552f2008-11-05 20:51:48 +0000789 if (!ClassDecl->getDestructor()) {
790 // C++ [class.dtor]p2:
791 // If a class has no user-declared destructor, a destructor is
792 // declared implicitly. An implicitly-declared destructor is an
793 // inline public member of its class.
794 std::string DestructorName = "~";
795 DestructorName += ClassDecl->getName();
796 CXXDestructorDecl *Destructor
797 = CXXDestructorDecl::Create(Context, ClassDecl,
798 ClassDecl->getLocation(),
799 &PP.getIdentifierTable().get(DestructorName),
800 Context.getFunctionType(Context.VoidTy,
801 0, 0, false, 0),
802 /*isInline=*/true,
803 /*isImplicitlyDeclared=*/true);
804 Destructor->setAccess(AS_public);
805 ClassDecl->setDestructor(Destructor);
806 }
807
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000808 // FIXME: Implicit copy assignment operator
809}
810
Argyrios Kyrtzidis5b7f0c82008-08-09 00:39:29 +0000811void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +0000812 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000813 FieldCollector->FinishClass();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000814 AddImplicitlyDeclaredMembersToClass(Rec);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000815 PopDeclContext();
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +0000816
817 // Everything, including inline method definitions, have been parsed.
818 // Let the consumer know of the new TagDecl definition.
819 Consumer.HandleTagDeclDefinition(Rec);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000820}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000821
Douglas Gregor42a552f2008-11-05 20:51:48 +0000822/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
823/// the well-formednes of the constructor declarator @p D with type @p
824/// R. If there are any errors in the declarator, this routine will
825/// emit diagnostics and return true. Otherwise, it will return
826/// false. Either way, the type @p R will be updated to reflect a
827/// well-formed type for the constructor.
828bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
829 FunctionDecl::StorageClass& SC) {
830 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
831 bool isInvalid = false;
832
833 // C++ [class.ctor]p3:
834 // A constructor shall not be virtual (10.3) or static (9.4). A
835 // constructor can be invoked for a const, volatile or const
836 // volatile object. A constructor shall not be declared const,
837 // volatile, or const volatile (9.3.2).
838 if (isVirtual) {
839 Diag(D.getIdentifierLoc(),
840 diag::err_constructor_cannot_be,
841 "virtual",
842 SourceRange(D.getDeclSpec().getVirtualSpecLoc()),
843 SourceRange(D.getIdentifierLoc()));
844 isInvalid = true;
845 }
846 if (SC == FunctionDecl::Static) {
847 Diag(D.getIdentifierLoc(),
848 diag::err_constructor_cannot_be,
849 "static",
850 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
851 SourceRange(D.getIdentifierLoc()));
852 isInvalid = true;
853 SC = FunctionDecl::None;
854 }
855 if (D.getDeclSpec().hasTypeSpecifier()) {
856 // Constructors don't have return types, but the parser will
857 // happily parse something like:
858 //
859 // class X {
860 // float X(float);
861 // };
862 //
863 // The return type will be eliminated later.
864 Diag(D.getIdentifierLoc(),
865 diag::err_constructor_return_type,
866 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
867 SourceRange(D.getIdentifierLoc()));
868 }
869 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
870 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
871 if (FTI.TypeQuals & QualType::Const)
872 Diag(D.getIdentifierLoc(),
873 diag::err_invalid_qualified_constructor,
874 "const",
875 SourceRange(D.getIdentifierLoc()));
876 if (FTI.TypeQuals & QualType::Volatile)
877 Diag(D.getIdentifierLoc(),
878 diag::err_invalid_qualified_constructor,
879 "volatile",
880 SourceRange(D.getIdentifierLoc()));
881 if (FTI.TypeQuals & QualType::Restrict)
882 Diag(D.getIdentifierLoc(),
883 diag::err_invalid_qualified_constructor,
884 "restrict",
885 SourceRange(D.getIdentifierLoc()));
886 }
887
888 // Rebuild the function type "R" without any type qualifiers (in
889 // case any of the errors above fired) and with "void" as the
890 // return type, since constructors don't have return types. We
891 // *always* have to do this, because GetTypeForDeclarator will
892 // put in a result type of "int" when none was specified.
893 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto();
894 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
895 Proto->getNumArgs(),
896 Proto->isVariadic(),
897 0);
898
899 return isInvalid;
900}
901
902/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
903/// the well-formednes of the destructor declarator @p D with type @p
904/// R. If there are any errors in the declarator, this routine will
905/// emit diagnostics and return true. Otherwise, it will return
906/// false. Either way, the type @p R will be updated to reflect a
907/// well-formed type for the destructor.
908bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
909 FunctionDecl::StorageClass& SC) {
910 bool isInvalid = false;
911
912 // C++ [class.dtor]p1:
913 // [...] A typedef-name that names a class is a class-name
914 // (7.1.3); however, a typedef-name that names a class shall not
915 // be used as the identifier in the declarator for a destructor
916 // declaration.
917 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType();
918 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) {
919 if (TypedefD->getIdentifier() !=
920 cast<CXXRecordDecl>(CurContext)->getIdentifier()) {
921 // FIXME: This would be easier if we could just look at whether
922 // we found the injected-class-name.
923 Diag(D.getIdentifierLoc(),
924 diag::err_destructor_typedef_name,
925 TypedefD->getName());
926 isInvalid = true;
927 }
928 }
929
930 // C++ [class.dtor]p2:
931 // A destructor is used to destroy objects of its class type. A
932 // destructor takes no parameters, and no return type can be
933 // specified for it (not even void). The address of a destructor
934 // shall not be taken. A destructor shall not be static. A
935 // destructor can be invoked for a const, volatile or const
936 // volatile object. A destructor shall not be declared const,
937 // volatile or const volatile (9.3.2).
938 if (SC == FunctionDecl::Static) {
939 Diag(D.getIdentifierLoc(),
940 diag::err_destructor_cannot_be,
941 "static",
942 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
943 SourceRange(D.getIdentifierLoc()));
944 isInvalid = true;
945 SC = FunctionDecl::None;
946 }
947 if (D.getDeclSpec().hasTypeSpecifier()) {
948 // Destructors don't have return types, but the parser will
949 // happily parse something like:
950 //
951 // class X {
952 // float ~X();
953 // };
954 //
955 // The return type will be eliminated later.
956 Diag(D.getIdentifierLoc(),
957 diag::err_destructor_return_type,
958 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
959 SourceRange(D.getIdentifierLoc()));
960 }
961 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
962 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
963 if (FTI.TypeQuals & QualType::Const)
964 Diag(D.getIdentifierLoc(),
965 diag::err_invalid_qualified_destructor,
966 "const",
967 SourceRange(D.getIdentifierLoc()));
968 if (FTI.TypeQuals & QualType::Volatile)
969 Diag(D.getIdentifierLoc(),
970 diag::err_invalid_qualified_destructor,
971 "volatile",
972 SourceRange(D.getIdentifierLoc()));
973 if (FTI.TypeQuals & QualType::Restrict)
974 Diag(D.getIdentifierLoc(),
975 diag::err_invalid_qualified_destructor,
976 "restrict",
977 SourceRange(D.getIdentifierLoc()));
978 }
979
980 // Make sure we don't have any parameters.
981 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
982 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
983
984 // Delete the parameters.
985 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
986 if (FTI.NumArgs) {
987 delete [] FTI.ArgInfo;
988 FTI.NumArgs = 0;
989 FTI.ArgInfo = 0;
990 }
991 }
992
993 // Make sure the destructor isn't variadic.
994 if (R->getAsFunctionTypeProto()->isVariadic())
995 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
996
997 // Rebuild the function type "R" without any type qualifiers or
998 // parameters (in case any of the errors above fired) and with
999 // "void" as the return type, since destructors don't have return
1000 // types. We *always* have to do this, because GetTypeForDeclarator
1001 // will put in a result type of "int" when none was specified.
1002 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1003
1004 return isInvalid;
1005}
1006
Douglas Gregorb48fe382008-10-31 09:07:45 +00001007/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete
1008/// the declaration of the given C++ constructor ConDecl that was
1009/// built from declarator D. This routine is responsible for checking
1010/// that the newly-created constructor declaration is well-formed and
1011/// for recording it in the C++ class. Example:
1012///
1013/// @code
1014/// class X {
1015/// X(); // X::X() will be the ConDecl.
1016/// };
1017/// @endcode
1018Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) {
1019 assert(ConDecl && "Expected to receive a constructor declaration");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001020
1021 // Check default arguments on the constructor
1022 CheckCXXDefaultArguments(ConDecl);
1023
Douglas Gregor030ff0c2008-10-31 20:25:05 +00001024 CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1025 if (!ClassDecl) {
1026 ConDecl->setInvalidDecl();
1027 return ConDecl;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001028 }
1029
Douglas Gregor030ff0c2008-10-31 20:25:05 +00001030 // Make sure this constructor is an overload of the existing
1031 // constructors.
1032 OverloadedFunctionDecl::function_iterator MatchedDecl;
1033 if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) {
1034 Diag(ConDecl->getLocation(),
1035 diag::err_constructor_redeclared,
1036 SourceRange(ConDecl->getLocation()));
1037 Diag((*MatchedDecl)->getLocation(),
1038 diag::err_previous_declaration,
1039 SourceRange((*MatchedDecl)->getLocation()));
1040 ConDecl->setInvalidDecl();
1041 return ConDecl;
1042 }
1043
1044
1045 // C++ [class.copy]p3:
1046 // A declaration of a constructor for a class X is ill-formed if
1047 // its first parameter is of type (optionally cv-qualified) X and
1048 // either there are no other parameters or else all other
1049 // parameters have default arguments.
1050 if ((ConDecl->getNumParams() == 1) ||
1051 (ConDecl->getNumParams() > 1 &&
1052 ConDecl->getParamDecl(1)->getDefaultArg() != 0)) {
1053 QualType ParamType = ConDecl->getParamDecl(0)->getType();
1054 QualType ClassTy = Context.getTagDeclType(
1055 const_cast<CXXRecordDecl*>(ConDecl->getParent()));
1056 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1057 Diag(ConDecl->getLocation(),
1058 diag::err_constructor_byvalue_arg,
1059 SourceRange(ConDecl->getParamDecl(0)->getLocation()));
1060 ConDecl->setInvalidDecl();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001061 return ConDecl;
Douglas Gregor030ff0c2008-10-31 20:25:05 +00001062 }
1063 }
1064
1065 // Add this constructor to the set of constructors of the current
1066 // class.
1067 ClassDecl->addConstructor(Context, ConDecl);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001068 return (DeclTy *)ConDecl;
1069}
1070
Douglas Gregor42a552f2008-11-05 20:51:48 +00001071/// ActOnDestructorDeclarator - Called by ActOnDeclarator to complete
1072/// the declaration of the given C++ @p Destructor. This routine is
1073/// responsible for recording the destructor in the C++ class, if
1074/// possible.
1075Sema::DeclTy *Sema::ActOnDestructorDeclarator(CXXDestructorDecl *Destructor) {
1076 assert(Destructor && "Expected to receive a destructor declaration");
1077
1078 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext);
1079
1080 // Make sure we aren't redeclaring the destructor.
1081 if (CXXDestructorDecl *PrevDestructor = ClassDecl->getDestructor()) {
1082 Diag(Destructor->getLocation(), diag::err_destructor_redeclared);
1083 Diag(PrevDestructor->getLocation(),
1084 PrevDestructor->isThisDeclarationADefinition()?
1085 diag::err_previous_definition
1086 : diag::err_previous_declaration);
1087 Destructor->setInvalidDecl();
1088 return Destructor;
1089 }
1090
1091 ClassDecl->setDestructor(Destructor);
1092 return (DeclTy *)Destructor;
1093}
1094
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001095//===----------------------------------------------------------------------===//
1096// Namespace Handling
1097//===----------------------------------------------------------------------===//
1098
1099/// ActOnStartNamespaceDef - This is called at the start of a namespace
1100/// definition.
1101Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1102 SourceLocation IdentLoc,
1103 IdentifierInfo *II,
1104 SourceLocation LBrace) {
1105 NamespaceDecl *Namespc =
1106 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1107 Namespc->setLBracLoc(LBrace);
1108
1109 Scope *DeclRegionScope = NamespcScope->getParent();
1110
1111 if (II) {
1112 // C++ [namespace.def]p2:
1113 // The identifier in an original-namespace-definition shall not have been
1114 // previously defined in the declarative region in which the
1115 // original-namespace-definition appears. The identifier in an
1116 // original-namespace-definition is the name of the namespace. Subsequently
1117 // in that declarative region, it is treated as an original-namespace-name.
1118
1119 Decl *PrevDecl =
Argyrios Kyrtzidis154d8e22008-10-14 18:28:48 +00001120 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001121 /*enableLazyBuiltinCreation=*/false);
1122
Argyrios Kyrtzidis2fac6262008-09-10 02:11:07 +00001123 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001124 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
1125 // This is an extended namespace definition.
1126 // Attach this namespace decl to the chain of extended namespace
1127 // definitions.
1128 NamespaceDecl *NextNS = OrigNS;
1129 while (NextNS->getNextNamespace())
1130 NextNS = NextNS->getNextNamespace();
1131
1132 NextNS->setNextNamespace(Namespc);
1133 Namespc->setOriginalNamespace(OrigNS);
1134
1135 // We won't add this decl to the current scope. We want the namespace
1136 // name to return the original namespace decl during a name lookup.
1137 } else {
1138 // This is an invalid name redefinition.
1139 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
1140 Namespc->getName());
1141 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1142 Namespc->setInvalidDecl();
1143 // Continue on to push Namespc as current DeclContext and return it.
1144 }
1145 } else {
1146 // This namespace name is declared for the first time.
1147 PushOnScopeChains(Namespc, DeclRegionScope);
1148 }
1149 }
1150 else {
1151 // FIXME: Handle anonymous namespaces
1152 }
1153
1154 // Although we could have an invalid decl (i.e. the namespace name is a
1155 // redefinition), push it as current DeclContext and try to continue parsing.
1156 PushDeclContext(Namespc->getOriginalNamespace());
1157 return Namespc;
1158}
1159
1160/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1161/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1162void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1163 Decl *Dcl = static_cast<Decl *>(D);
1164 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1165 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1166 Namespc->setRBracLoc(RBrace);
1167 PopDeclContext();
1168}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001169
1170
1171/// AddCXXDirectInitializerToDecl - This action is called immediately after
1172/// ActOnDeclarator, when a C++ direct initializer is present.
1173/// e.g: "int x(1);"
1174void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1175 ExprTy **ExprTys, unsigned NumExprs,
1176 SourceLocation *CommaLocs,
1177 SourceLocation RParenLoc) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001178 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001179 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001180
1181 // If there is no declaration, there was an error parsing it. Just ignore
1182 // the initializer.
1183 if (RealDecl == 0) {
Ted Kremenek15f61392008-10-06 20:35:04 +00001184 for (unsigned i = 0; i != NumExprs; ++i)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001185 delete static_cast<Expr *>(ExprTys[i]);
1186 return;
1187 }
1188
1189 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1190 if (!VDecl) {
1191 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1192 RealDecl->setInvalidDecl();
1193 return;
1194 }
1195
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001196 // We will treat direct-initialization as a copy-initialization:
1197 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001198 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1199 //
1200 // Clients that want to distinguish between the two forms, can check for
1201 // direct initializer using VarDecl::hasCXXDirectInitializer().
1202 // A major benefit is that clients that don't particularly care about which
1203 // exactly form was it (like the CodeGen) can handle both cases without
1204 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001205
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001206 // C++ 8.5p11:
1207 // The form of initialization (using parentheses or '=') is generally
1208 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001209 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001210 QualType DeclInitType = VDecl->getType();
1211 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1212 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001213
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001214 if (VDecl->getType()->isRecordType()) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001215 CXXConstructorDecl *Constructor
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001216 = PerformInitializationByConstructor(DeclInitType,
1217 (Expr **)ExprTys, NumExprs,
1218 VDecl->getLocation(),
1219 SourceRange(VDecl->getLocation(),
1220 RParenLoc),
1221 VDecl->getName(),
1222 IK_Direct);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001223 if (!Constructor) {
1224 RealDecl->setInvalidDecl();
1225 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001226
1227 // Let clients know that initialization was done with a direct
1228 // initializer.
1229 VDecl->setCXXDirectInitializer(true);
1230
1231 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1232 // the initializer.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001233 return;
1234 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001235
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001236 if (NumExprs > 1) {
1237 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
1238 SourceRange(VDecl->getLocation(), RParenLoc));
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001239 RealDecl->setInvalidDecl();
1240 return;
1241 }
1242
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001243 // Let clients know that initialization was done with a direct initializer.
1244 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001245
1246 assert(NumExprs == 1 && "Expected 1 expression");
1247 // Set the init expression, handles conversions.
1248 AddInitializerToDecl(Dcl, ExprTys[0]);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001249}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001250
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001251/// PerformInitializationByConstructor - Perform initialization by
1252/// constructor (C++ [dcl.init]p14), which may occur as part of
1253/// direct-initialization or copy-initialization. We are initializing
1254/// an object of type @p ClassType with the given arguments @p
1255/// Args. @p Loc is the location in the source code where the
1256/// initializer occurs (e.g., a declaration, member initializer,
1257/// functional cast, etc.) while @p Range covers the whole
1258/// initialization. @p InitEntity is the entity being initialized,
1259/// which may by the name of a declaration or a type. @p Kind is the
1260/// kind of initialization we're performing, which affects whether
1261/// explicit constructors will be considered. When successful, returns
Douglas Gregor18fe5682008-11-03 20:45:27 +00001262/// the constructor that will be used to perform the initialization;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001263/// when the initialization fails, emits a diagnostic and returns
1264/// null.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001265CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001266Sema::PerformInitializationByConstructor(QualType ClassType,
1267 Expr **Args, unsigned NumArgs,
1268 SourceLocation Loc, SourceRange Range,
1269 std::string InitEntity,
1270 InitializationKind Kind) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001271 const RecordType *ClassRec = ClassType->getAsRecordType();
1272 assert(ClassRec && "Can only initialize a class type here");
1273
1274 // C++ [dcl.init]p14:
1275 //
1276 // If the initialization is direct-initialization, or if it is
1277 // copy-initialization where the cv-unqualified version of the
1278 // source type is the same class as, or a derived class of, the
1279 // class of the destination, constructors are considered. The
1280 // applicable constructors are enumerated (13.3.1.3), and the
1281 // best one is chosen through overload resolution (13.3). The
1282 // constructor so selected is called to initialize the object,
1283 // with the initializer expression(s) as its argument(s). If no
1284 // constructor applies, or the overload resolution is ambiguous,
1285 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001286 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1287 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001288
1289 // Add constructors to the overload set.
1290 OverloadedFunctionDecl *Constructors
1291 = const_cast<OverloadedFunctionDecl *>(ClassDecl->getConstructors());
1292 for (OverloadedFunctionDecl::function_iterator Con
1293 = Constructors->function_begin();
1294 Con != Constructors->function_end(); ++Con) {
1295 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1296 if ((Kind == IK_Direct) ||
1297 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1298 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1299 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1300 }
1301
Douglas Gregor18fe5682008-11-03 20:45:27 +00001302 OverloadCandidateSet::iterator Best;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001303 switch (BestViableFunction(CandidateSet, Best)) {
1304 case OR_Success:
1305 // We found a constructor. Return it.
1306 return cast<CXXConstructorDecl>(Best->Function);
1307
1308 case OR_No_Viable_Function:
1309 if (CandidateSet.empty())
1310 Diag(Loc, diag::err_ovl_no_viable_function_in_init,
1311 InitEntity, Range);
1312 else {
1313 Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands,
1314 InitEntity, Range);
1315 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1316 }
1317 return 0;
1318
1319 case OR_Ambiguous:
1320 Diag(Loc, diag::err_ovl_ambiguous_init,
1321 InitEntity, Range);
1322 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1323 return 0;
1324 }
1325
1326 return 0;
1327}
1328
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001329/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1330/// determine whether they are reference-related,
1331/// reference-compatible, reference-compatible with added
1332/// qualification, or incompatible, for use in C++ initialization by
1333/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1334/// type, and the first type (T1) is the pointee type of the reference
1335/// type being initialized.
1336Sema::ReferenceCompareResult
Douglas Gregor15da57e2008-10-29 02:00:59 +00001337Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1338 bool& DerivedToBase) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001339 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1340 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1341
1342 T1 = Context.getCanonicalType(T1);
1343 T2 = Context.getCanonicalType(T2);
1344 QualType UnqualT1 = T1.getUnqualifiedType();
1345 QualType UnqualT2 = T2.getUnqualifiedType();
1346
1347 // C++ [dcl.init.ref]p4:
1348 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1349 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1350 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001351 if (UnqualT1 == UnqualT2)
1352 DerivedToBase = false;
1353 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1354 DerivedToBase = true;
1355 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001356 return Ref_Incompatible;
1357
1358 // At this point, we know that T1 and T2 are reference-related (at
1359 // least).
1360
1361 // C++ [dcl.init.ref]p4:
1362 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1363 // reference-related to T2 and cv1 is the same cv-qualification
1364 // as, or greater cv-qualification than, cv2. For purposes of
1365 // overload resolution, cases for which cv1 is greater
1366 // cv-qualification than cv2 are identified as
1367 // reference-compatible with added qualification (see 13.3.3.2).
1368 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1369 return Ref_Compatible;
1370 else if (T1.isMoreQualifiedThan(T2))
1371 return Ref_Compatible_With_Added_Qualification;
1372 else
1373 return Ref_Related;
1374}
1375
1376/// CheckReferenceInit - Check the initialization of a reference
1377/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1378/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00001379/// list), and DeclType is the type of the declaration. When ICS is
1380/// non-null, this routine will compute the implicit conversion
1381/// sequence according to C++ [over.ics.ref] and will not produce any
1382/// diagnostics; when ICS is null, it will emit diagnostics when any
1383/// errors are found. Either way, a return value of true indicates
1384/// that there was a failure, a return value of false indicates that
1385/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001386///
1387/// When @p SuppressUserConversions, user-defined conversions are
1388/// suppressed.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001389bool
1390Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001391 ImplicitConversionSequence *ICS,
1392 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001393 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1394
1395 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1396 QualType T2 = Init->getType();
1397
Douglas Gregor15da57e2008-10-29 02:00:59 +00001398 // Compute some basic properties of the types and the initializer.
1399 bool DerivedToBase = false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001400 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001401 ReferenceCompareResult RefRelationship
1402 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1403
1404 // Most paths end in a failed conversion.
1405 if (ICS)
1406 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001407
1408 // C++ [dcl.init.ref]p5:
1409 // A reference to type “cv1 T1” is initialized by an expression
1410 // of type “cv2 T2” as follows:
1411
1412 // -- If the initializer expression
1413
1414 bool BindsDirectly = false;
1415 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1416 // reference-compatible with “cv2 T2,” or
Douglas Gregor15da57e2008-10-29 02:00:59 +00001417 //
1418 // Note that the bit-field check is skipped if we are just computing
1419 // the implicit conversion sequence (C++ [over.best.ics]p2).
1420 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1421 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001422 BindsDirectly = true;
1423
Douglas Gregor15da57e2008-10-29 02:00:59 +00001424 if (ICS) {
1425 // C++ [over.ics.ref]p1:
1426 // When a parameter of reference type binds directly (8.5.3)
1427 // to an argument expression, the implicit conversion sequence
1428 // is the identity conversion, unless the argument expression
1429 // has a type that is a derived class of the parameter type,
1430 // in which case the implicit conversion sequence is a
1431 // derived-to-base Conversion (13.3.3.1).
1432 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1433 ICS->Standard.First = ICK_Identity;
1434 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1435 ICS->Standard.Third = ICK_Identity;
1436 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1437 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001438 ICS->Standard.ReferenceBinding = true;
1439 ICS->Standard.DirectBinding = true;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001440
1441 // Nothing more to do: the inaccessibility/ambiguity check for
1442 // derived-to-base conversions is suppressed when we're
1443 // computing the implicit conversion sequence (C++
1444 // [over.best.ics]p2).
1445 return false;
1446 } else {
1447 // Perform the conversion.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001448 // FIXME: Binding to a subobject of the lvalue is going to require
1449 // more AST annotation than this.
1450 ImpCastExprToType(Init, T1);
1451 }
1452 }
1453
1454 // -- has a class type (i.e., T2 is a class type) and can be
1455 // implicitly converted to an lvalue of type “cv3 T3,”
1456 // where “cv1 T1” is reference-compatible with “cv3 T3”
1457 // 92) (this conversion is selected by enumerating the
1458 // applicable conversion functions (13.3.1.6) and choosing
1459 // the best one through overload resolution (13.3)),
1460 // FIXME: Implement this second bullet, once we have conversion
Douglas Gregor15da57e2008-10-29 02:00:59 +00001461 // functions. Also remember C++ [over.ics.ref]p1, second part.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001462
1463 if (BindsDirectly) {
1464 // C++ [dcl.init.ref]p4:
1465 // [...] In all cases where the reference-related or
1466 // reference-compatible relationship of two types is used to
1467 // establish the validity of a reference binding, and T1 is a
1468 // base class of T2, a program that necessitates such a binding
1469 // is ill-formed if T1 is an inaccessible (clause 11) or
1470 // ambiguous (10.2) base class of T2.
1471 //
1472 // Note that we only check this condition when we're allowed to
1473 // complain about errors, because we should not be checking for
1474 // ambiguity (or inaccessibility) unless the reference binding
1475 // actually happens.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001476 if (DerivedToBase)
1477 return CheckDerivedToBaseConversion(T2, T1,
1478 Init->getSourceRange().getBegin(),
1479 Init->getSourceRange());
1480 else
1481 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001482 }
1483
1484 // -- Otherwise, the reference shall be to a non-volatile const
1485 // type (i.e., cv1 shall be const).
1486 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00001487 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001488 Diag(Init->getSourceRange().getBegin(),
1489 diag::err_not_reference_to_const_init,
1490 T1.getAsString(),
1491 InitLvalue != Expr::LV_Valid? "temporary" : "value",
1492 T2.getAsString(), Init->getSourceRange());
1493 return true;
1494 }
1495
1496 // -- If the initializer expression is an rvalue, with T2 a
1497 // class type, and “cv1 T1” is reference-compatible with
1498 // “cv2 T2,” the reference is bound in one of the
1499 // following ways (the choice is implementation-defined):
1500 //
1501 // -- The reference is bound to the object represented by
1502 // the rvalue (see 3.10) or to a sub-object within that
1503 // object.
1504 //
1505 // -- A temporary of type “cv1 T2” [sic] is created, and
1506 // a constructor is called to copy the entire rvalue
1507 // object into the temporary. The reference is bound to
1508 // the temporary or to a sub-object within the
1509 // temporary.
1510 //
1511 //
1512 // The constructor that would be used to make the copy
1513 // shall be callable whether or not the copy is actually
1514 // done.
1515 //
1516 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1517 // freedom, so we will always take the first option and never build
1518 // a temporary in this case. FIXME: We will, however, have to check
1519 // for the presence of a copy constructor in C++98/03 mode.
1520 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00001521 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1522 if (ICS) {
1523 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1524 ICS->Standard.First = ICK_Identity;
1525 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1526 ICS->Standard.Third = ICK_Identity;
1527 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1528 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001529 ICS->Standard.ReferenceBinding = true;
1530 ICS->Standard.DirectBinding = false;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001531 } else {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001532 // FIXME: Binding to a subobject of the rvalue is going to require
1533 // more AST annotation than this.
1534 ImpCastExprToType(Init, T1);
1535 }
1536 return false;
1537 }
1538
1539 // -- Otherwise, a temporary of type “cv1 T1” is created and
1540 // initialized from the initializer expression using the
1541 // rules for a non-reference copy initialization (8.5). The
1542 // reference is then bound to the temporary. If T1 is
1543 // reference-related to T2, cv1 must be the same
1544 // cv-qualification as, or greater cv-qualification than,
1545 // cv2; otherwise, the program is ill-formed.
1546 if (RefRelationship == Ref_Related) {
1547 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1548 // we would be reference-compatible or reference-compatible with
1549 // added qualification. But that wasn't the case, so the reference
1550 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001551 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001552 Diag(Init->getSourceRange().getBegin(),
1553 diag::err_reference_init_drops_quals,
1554 T1.getAsString(),
1555 InitLvalue != Expr::LV_Valid? "temporary" : "value",
1556 T2.getAsString(), Init->getSourceRange());
1557 return true;
1558 }
1559
1560 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001561 if (ICS) {
1562 /// C++ [over.ics.ref]p2:
1563 ///
1564 /// When a parameter of reference type is not bound directly to
1565 /// an argument expression, the conversion sequence is the one
1566 /// required to convert the argument expression to the
1567 /// underlying type of the reference according to
1568 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1569 /// to copy-initializing a temporary of the underlying type with
1570 /// the argument expression. Any difference in top-level
1571 /// cv-qualification is subsumed by the initialization itself
1572 /// and does not constitute a conversion.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001573 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001574 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1575 } else {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001576 return PerformImplicitConversion(Init, T1);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001577 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001578}