blob: 90983040b5b4b7ab4c3144ac82a2ebd4c22480c8 [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"
Anders Carlsson8211eff2009-03-24 01:19:16 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregor02189362008-10-22 21:13:31 +000019#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000020#include "clang/AST/StmtVisitor.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000021#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000022#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Chris Lattner8123a952008-04-10 02:22:51 +000024#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000025#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000026#include <map>
Chris Lattner3d1cee32008-04-08 05:04:30 +000027
28using namespace clang;
29
Chris Lattner8123a952008-04-10 02:22:51 +000030//===----------------------------------------------------------------------===//
31// CheckDefaultArgumentVisitor
32//===----------------------------------------------------------------------===//
33
Chris Lattner9e979552008-04-12 23:52:44 +000034namespace {
35 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
36 /// the default argument of a parameter to determine whether it
37 /// contains any ill-formed subexpressions. For example, this will
38 /// diagnose the use of local variables or parameters within the
39 /// default argument expression.
40 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000041 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000042 Expr *DefaultArg;
43 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000044
Chris Lattner9e979552008-04-12 23:52:44 +000045 public:
46 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
47 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000048
Chris Lattner9e979552008-04-12 23:52:44 +000049 bool VisitExpr(Expr *Node);
50 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000051 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000052 };
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 /// VisitExpr - Visit all of the children of this expression.
55 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
56 bool IsInvalid = false;
Chris Lattnerb77792e2008-07-26 22:17:49 +000057 for (Stmt::child_iterator I = Node->child_begin(),
58 E = Node->child_end(); I != E; ++I)
59 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000060 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000061 }
62
Chris Lattner9e979552008-04-12 23:52:44 +000063 /// VisitDeclRefExpr - Visit a reference to a declaration, to
64 /// determine whether this declaration can be used in the default
65 /// argument expression.
66 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000067 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000068 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
69 // C++ [dcl.fct.default]p9
70 // Default arguments are evaluated each time the function is
71 // called. The order of evaluation of function arguments is
72 // unspecified. Consequently, parameters of a function shall not
73 // be used in default argument expressions, even if they are not
74 // evaluated. Parameters of a function declared before a default
75 // argument expression are in scope and can hide namespace and
76 // class member names.
77 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000078 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000079 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000080 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000081 // C++ [dcl.fct.default]p7
82 // Local variables shall not be used in default argument
83 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000084 if (VDecl->isBlockVarDecl())
85 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000086 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000087 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000088 }
Chris Lattner8123a952008-04-10 02:22:51 +000089
Douglas Gregor3996f232008-11-04 13:41:56 +000090 return false;
91 }
Chris Lattner9e979552008-04-12 23:52:44 +000092
Douglas Gregor796da182008-11-04 14:32:21 +000093 /// VisitCXXThisExpr - Visit a C++ "this" expression.
94 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
95 // C++ [dcl.fct.default]p8:
96 // The keyword this shall not be used in a default argument of a
97 // member function.
98 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000099 diag::err_param_default_argument_references_this)
100 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000101 }
Chris Lattner8123a952008-04-10 02:22:51 +0000102}
103
104/// ActOnParamDefaultArgument - Check whether the default argument
105/// provided for a function parameter is well-formed. If so, attach it
106/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000107void
108Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000109 ExprArg defarg) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000110 ParmVarDecl *Param = (ParmVarDecl *)param;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000111 ExprOwningPtr<Expr> DefaultArg(this, (Expr *)defarg.release());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000112 QualType ParamType = Param->getType();
113
114 // Default arguments are only permitted in C++
115 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000116 Diag(EqualLoc, diag::err_param_default_argument)
117 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000118 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000119 return;
120 }
121
122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Chris Lattner3d1cee32008-04-08 05:04:30 +0000128 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor61366e92008-12-24 00:01:03 +0000129 bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
130 EqualLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000131 Param->getDeclName(),
132 /*DirectInit=*/false);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000133 if (DefaultArgPtr != DefaultArg.get()) {
134 DefaultArg.take();
135 DefaultArg.reset(DefaultArgPtr);
136 }
Douglas Gregoreb704f22008-11-04 13:57:51 +0000137 if (DefaultInitFailed) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000138 return;
139 }
140
Chris Lattner8123a952008-04-10 02:22:51 +0000141 // Check that the default argument is well-formed
Chris Lattner9e979552008-04-12 23:52:44 +0000142 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000143 if (DefaultArgChecker.Visit(DefaultArg.get())) {
144 Param->setInvalidDecl();
Chris Lattner8123a952008-04-10 02:22:51 +0000145 return;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000146 }
Chris Lattner8123a952008-04-10 02:22:51 +0000147
Chris Lattner3d1cee32008-04-08 05:04:30 +0000148 // Okay: add the default argument to the parameter
149 Param->setDefaultArg(DefaultArg.take());
150}
151
Douglas Gregor61366e92008-12-24 00:01:03 +0000152/// ActOnParamUnparsedDefaultArgument - We've seen a default
153/// argument for a function parameter, but we can't parse it yet
154/// because we're inside a class definition. Note that this default
155/// argument will be parsed later.
156void Sema::ActOnParamUnparsedDefaultArgument(DeclTy *param,
157 SourceLocation EqualLoc) {
158 ParmVarDecl *Param = (ParmVarDecl*)param;
159 if (Param)
160 Param->setUnparsedDefaultArg();
161}
162
Douglas Gregor72b505b2008-12-16 21:30:33 +0000163/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
164/// the default argument for the parameter param failed.
165void Sema::ActOnParamDefaultArgumentError(DeclTy *param) {
166 ((ParmVarDecl*)param)->setInvalidDecl();
167}
168
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000169/// CheckExtraCXXDefaultArguments - Check for any extra default
170/// arguments in the declarator, which is not a function declaration
171/// or definition and therefore is not permitted to have default
172/// arguments. This routine should be invoked for every declarator
173/// that is not a function declaration or definition.
174void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
175 // C++ [dcl.fct.default]p3
176 // A default argument expression shall be specified only in the
177 // parameter-declaration-clause of a function declaration or in a
178 // template-parameter (14.1). It shall not be specified for a
179 // parameter pack. If it is specified in a
180 // parameter-declaration-clause, it shall not occur within a
181 // declarator or abstract-declarator of a parameter-declaration.
182 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
183 DeclaratorChunk &chunk = D.getTypeObject(i);
184 if (chunk.Kind == DeclaratorChunk::Function) {
185 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
186 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
Douglas Gregor61366e92008-12-24 00:01:03 +0000187 if (Param->hasUnparsedDefaultArg()) {
188 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000189 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
190 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
191 delete Toks;
192 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000193 } else if (Param->getDefaultArg()) {
194 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
195 << Param->getDefaultArg()->getSourceRange();
196 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000197 }
198 }
199 }
200 }
201}
202
Chris Lattner3d1cee32008-04-08 05:04:30 +0000203// MergeCXXFunctionDecl - Merge two declarations of the same C++
204// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000205// type. Subroutine of MergeFunctionDecl. Returns true if there was an
206// error, false otherwise.
207bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
208 bool Invalid = false;
209
Chris Lattner3d1cee32008-04-08 05:04:30 +0000210 // C++ [dcl.fct.default]p4:
211 //
212 // For non-template functions, default arguments can be added in
213 // later declarations of a function in the same
214 // scope. Declarations in different scopes have completely
215 // distinct sets of default arguments. That is, declarations in
216 // inner scopes do not acquire default arguments from
217 // declarations in outer scopes, and vice versa. In a given
218 // function declaration, all parameters subsequent to a
219 // parameter with a default argument shall have default
220 // arguments supplied in this or previous declarations. A
221 // default argument shall not be redefined by a later
222 // declaration (not even to the same value).
223 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
224 ParmVarDecl *OldParam = Old->getParamDecl(p);
225 ParmVarDecl *NewParam = New->getParamDecl(p);
226
227 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
228 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000229 diag::err_param_default_argument_redefinition)
230 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000231 Diag(OldParam->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000232 Invalid = true;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000233 } else if (OldParam->getDefaultArg()) {
234 // Merge the old default argument into the new parameter
235 NewParam->setDefaultArg(OldParam->getDefaultArg());
236 }
237 }
238
Douglas Gregorcda9c672009-02-16 17:45:42 +0000239 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000240}
241
242/// CheckCXXDefaultArguments - Verify that the default arguments for a
243/// function declaration are well-formed according to C++
244/// [dcl.fct.default].
245void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
246 unsigned NumParams = FD->getNumParams();
247 unsigned p;
248
249 // Find first parameter with a default argument
250 for (p = 0; p < NumParams; ++p) {
251 ParmVarDecl *Param = FD->getParamDecl(p);
252 if (Param->getDefaultArg())
253 break;
254 }
255
256 // C++ [dcl.fct.default]p4:
257 // In a given function declaration, all parameters
258 // subsequent to a parameter with a default argument shall
259 // have default arguments supplied in this or previous
260 // declarations. A default argument shall not be redefined
261 // by a later declaration (not even to the same value).
262 unsigned LastMissingDefaultArg = 0;
263 for(; p < NumParams; ++p) {
264 ParmVarDecl *Param = FD->getParamDecl(p);
265 if (!Param->getDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000266 if (Param->isInvalidDecl())
267 /* We already complained about this parameter. */;
268 else if (Param->getIdentifier())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000269 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000270 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000271 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000272 else
273 Diag(Param->getLocation(),
274 diag::err_param_default_argument_missing);
275
276 LastMissingDefaultArg = p;
277 }
278 }
279
280 if (LastMissingDefaultArg > 0) {
281 // Some default arguments were missing. Clear out all of the
282 // default arguments up to (and including) the last missing
283 // default argument, so that we leave the function parameters
284 // in a semantically valid state.
285 for (p = 0; p <= LastMissingDefaultArg; ++p) {
286 ParmVarDecl *Param = FD->getParamDecl(p);
287 if (Param->getDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000288 if (!Param->hasUnparsedDefaultArg())
289 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000290 Param->setDefaultArg(0);
291 }
292 }
293 }
294}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000295
Douglas Gregorb48fe382008-10-31 09:07:45 +0000296/// isCurrentClassName - Determine whether the identifier II is the
297/// name of the class type currently being defined. In the case of
298/// nested classes, this will only return true if II is the name of
299/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000300bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
301 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000302 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000303 if (SS && SS->isSet() && !SS->isInvalid()) {
304 DeclContext *DC = computeDeclContext(*SS);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000305 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
306 } else
307 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
308
309 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000310 return &II == CurDecl->getIdentifier();
311 else
312 return false;
313}
314
Douglas Gregor2943aed2009-03-03 04:44:36 +0000315/// \brief Check the validity of a C++ base class specifier.
316///
317/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
318/// and returns NULL otherwise.
319CXXBaseSpecifier *
320Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
321 SourceRange SpecifierRange,
322 bool Virtual, AccessSpecifier Access,
323 QualType BaseType,
324 SourceLocation BaseLoc) {
325 // C++ [class.union]p1:
326 // A union shall not have base classes.
327 if (Class->isUnion()) {
328 Diag(Class->getLocation(), diag::err_base_clause_on_union)
329 << SpecifierRange;
330 return 0;
331 }
332
333 if (BaseType->isDependentType())
334 return new CXXBaseSpecifier(SpecifierRange, Virtual,
335 Class->getTagKind() == RecordDecl::TK_class,
336 Access, BaseType);
337
338 // Base specifiers must be record types.
339 if (!BaseType->isRecordType()) {
340 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
341 return 0;
342 }
343
344 // C++ [class.union]p1:
345 // A union shall not be used as a base class.
346 if (BaseType->isUnionType()) {
347 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
348 return 0;
349 }
350
351 // C++ [class.derived]p2:
352 // The class-name in a base-specifier shall not be an incompletely
353 // defined class.
Douglas Gregor86447ec2009-03-09 16:13:40 +0000354 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
Douglas Gregor26dce442009-03-10 00:06:19 +0000355 SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000356 return 0;
357
358 // If the base class is polymorphic, the new one is, too.
359 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
360 assert(BaseDecl && "Record type has no declaration");
361 BaseDecl = BaseDecl->getDefinition(Context);
362 assert(BaseDecl && "Base type is not incomplete, but has no definition");
363 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
364 Class->setPolymorphic(true);
365
366 // C++ [dcl.init.aggr]p1:
367 // An aggregate is [...] a class with [...] no base classes [...].
368 Class->setAggregate(false);
369 Class->setPOD(false);
370
371 // Create the base specifier.
372 // FIXME: Allocate via ASTContext?
373 return new CXXBaseSpecifier(SpecifierRange, Virtual,
374 Class->getTagKind() == RecordDecl::TK_class,
375 Access, BaseType);
376}
377
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000378/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
379/// one entry in the base class list of a class specifier, for
380/// example:
381/// class foo : public bar, virtual private baz {
382/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000383Sema::BaseResult
384Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
385 bool Virtual, AccessSpecifier Access,
386 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000387 AdjustDeclIfTemplate(classdecl);
388 CXXRecordDecl *Class = cast<CXXRecordDecl>((Decl*)classdecl);
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000389 QualType BaseType = QualType::getFromOpaquePtr(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000390 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
391 Virtual, Access,
392 BaseType, BaseLoc))
393 return BaseSpec;
394
395 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000396}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000397
Douglas Gregor2943aed2009-03-03 04:44:36 +0000398/// \brief Performs the actual work of attaching the given base class
399/// specifiers to a C++ class.
400bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
401 unsigned NumBases) {
402 if (NumBases == 0)
403 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000404
405 // Used to keep track of which base types we have already seen, so
406 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000407 // that the key is always the unqualified canonical type of the base
408 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000409 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
410
411 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000412 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000413 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000414 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000415 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000416 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor57c856b2008-10-23 18:13:27 +0000417 NewBaseType = NewBaseType.getUnqualifiedType();
418
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000419 if (KnownBaseTypes[NewBaseType]) {
420 // C++ [class.mi]p3:
421 // A class shall not be specified as a direct base class of a
422 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000423 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000424 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000425 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000426 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000427
428 // Delete the duplicate base class specifier; we're going to
429 // overwrite its pointer later.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000430 delete Bases[idx];
431
432 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000433 } else {
434 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000435 KnownBaseTypes[NewBaseType] = Bases[idx];
436 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000437 }
438 }
439
440 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000441 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000442
443 // Delete the remaining (good) base class specifiers, since their
444 // data has been copied into the CXXRecordDecl.
445 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2943aed2009-03-03 04:44:36 +0000446 delete Bases[idx];
447
448 return Invalid;
449}
450
451/// ActOnBaseSpecifiers - Attach the given base specifiers to the
452/// class, after checking whether there are any duplicate base
453/// classes.
454void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
455 unsigned NumBases) {
456 if (!ClassDecl || !Bases || !NumBases)
457 return;
458
459 AdjustDeclIfTemplate(ClassDecl);
460 AttachBaseSpecifiers(cast<CXXRecordDecl>((Decl*)ClassDecl),
461 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000462}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000463
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000464//===----------------------------------------------------------------------===//
465// C++ class member Handling
466//===----------------------------------------------------------------------===//
467
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000468/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
469/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
470/// bitfield width if there is one and 'InitExpr' specifies the initializer if
471/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
472/// declarators on it.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000473Sema::DeclTy *
474Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
475 ExprTy *BW, ExprTy *InitExpr,
476 DeclTy *LastInGroup) {
477 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000478 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000479 Expr *BitWidth = static_cast<Expr*>(BW);
480 Expr *Init = static_cast<Expr*>(InitExpr);
481 SourceLocation Loc = D.getIdentifierLoc();
482
Sebastian Redl669d5d72008-11-14 23:42:31 +0000483 bool isFunc = D.isFunctionDeclarator();
484
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000485 // C++ 9.2p6: A member shall not be declared to have automatic storage
486 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000487 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
488 // data members and cannot be applied to names declared const or static,
489 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000490 switch (DS.getStorageClassSpec()) {
491 case DeclSpec::SCS_unspecified:
492 case DeclSpec::SCS_typedef:
493 case DeclSpec::SCS_static:
494 // FALL THROUGH.
495 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000496 case DeclSpec::SCS_mutable:
497 if (isFunc) {
498 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000499 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000500 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000501 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
502
Sebastian Redla11f42f2008-11-17 23:24:37 +0000503 // FIXME: It would be nicer if the keyword was ignored only for this
504 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000505 D.getMutableDeclSpec().ClearStorageClassSpecs();
506 } else {
507 QualType T = GetTypeForDeclarator(D, S);
508 diag::kind err = static_cast<diag::kind>(0);
509 if (T->isReferenceType())
510 err = diag::err_mutable_reference;
511 else if (T.isConstQualified())
512 err = diag::err_mutable_const;
513 if (err != 0) {
514 if (DS.getStorageClassSpecLoc().isValid())
515 Diag(DS.getStorageClassSpecLoc(), err);
516 else
517 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000518 // FIXME: It would be nicer if the keyword was ignored only for this
519 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000520 D.getMutableDeclSpec().ClearStorageClassSpecs();
521 }
522 }
523 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000524 default:
525 if (DS.getStorageClassSpecLoc().isValid())
526 Diag(DS.getStorageClassSpecLoc(),
527 diag::err_storageclass_invalid_for_member);
528 else
529 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
530 D.getMutableDeclSpec().ClearStorageClassSpecs();
531 }
532
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000533 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000534 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000535 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000536 // Check also for this case:
537 //
538 // typedef int f();
539 // f a;
540 //
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000541 QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep());
542 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000543 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000544
Sebastian Redl669d5d72008-11-14 23:42:31 +0000545 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
546 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000547 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000548
549 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000550 if (isInstField) {
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000551 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
552 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000553 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000554 } else {
Daniel Dunbar914701e2008-08-05 16:28:08 +0000555 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Chris Lattner6f8ce142009-03-05 23:03:49 +0000556 if (!Member) {
557 if (BitWidth) DeleteExpr(BitWidth);
558 return LastInGroup;
559 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000560
561 // Non-instance-fields can't have a bitfield.
562 if (BitWidth) {
563 if (Member->isInvalidDecl()) {
564 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000565 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000566 // C++ 9.6p3: A bit-field shall not be a static member.
567 // "static member 'A' cannot be a bit-field"
568 Diag(Loc, diag::err_static_not_bitfield)
569 << Name << BitWidth->getSourceRange();
570 } else if (isa<TypedefDecl>(Member)) {
571 // "typedef member 'x' cannot be a bit-field"
572 Diag(Loc, diag::err_typedef_not_bitfield)
573 << Name << BitWidth->getSourceRange();
574 } else {
575 // A function typedef ("typedef int f(); f a;").
576 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
577 Diag(Loc, diag::err_not_integral_type_bitfield)
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000578 << Name << cast<ValueDecl>(Member)->getType()
579 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000580 }
581
582 DeleteExpr(BitWidth);
583 BitWidth = 0;
584 Member->setInvalidDecl();
585 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000586
587 Member->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000588 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000589
Douglas Gregor10bd3682008-11-17 22:58:34 +0000590 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000591
Douglas Gregor021c3b32009-03-11 23:00:04 +0000592 if (Init)
593 AddInitializerToDecl(Member, ExprArg(*this, Init), false);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000594
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000595 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000596 FieldCollector->Add(cast<FieldDecl>(Member));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000597 return LastInGroup;
598 }
599 return Member;
600}
601
Douglas Gregor7ad83902008-11-05 04:29:56 +0000602/// ActOnMemInitializer - Handle a C++ member initializer.
603Sema::MemInitResult
604Sema::ActOnMemInitializer(DeclTy *ConstructorD,
605 Scope *S,
606 IdentifierInfo *MemberOrBase,
607 SourceLocation IdLoc,
608 SourceLocation LParenLoc,
609 ExprTy **Args, unsigned NumArgs,
610 SourceLocation *CommaLocs,
611 SourceLocation RParenLoc) {
612 CXXConstructorDecl *Constructor
613 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
614 if (!Constructor) {
615 // The user wrote a constructor initializer on a function that is
616 // not a C++ constructor. Ignore the error for now, because we may
617 // have more member initializers coming; we'll diagnose it just
618 // once in ActOnMemInitializers.
619 return true;
620 }
621
622 CXXRecordDecl *ClassDecl = Constructor->getParent();
623
624 // C++ [class.base.init]p2:
625 // Names in a mem-initializer-id are looked up in the scope of the
626 // constructor’s class and, if not found in that scope, are looked
627 // up in the scope containing the constructor’s
628 // definition. [Note: if the constructor’s class contains a member
629 // with the same name as a direct or virtual base class of the
630 // class, a mem-initializer-id naming the member or base class and
631 // composed of a single identifier refers to the class member. A
632 // mem-initializer-id for the hidden base class may be specified
633 // using a qualified name. ]
634 // Look for a member, first.
Douglas Gregor44b43212008-12-11 16:49:14 +0000635 FieldDecl *Member = 0;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000636 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
Douglas Gregor44b43212008-12-11 16:49:14 +0000637 if (Result.first != Result.second)
638 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000639
640 // FIXME: Handle members of an anonymous union.
641
642 if (Member) {
643 // FIXME: Perform direct initialization of the member.
644 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
645 }
646
647 // It didn't name a member, so see if it names a class.
Douglas Gregorb696ea32009-02-04 17:00:24 +0000648 TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, 0/*SS*/);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000649 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000650 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
651 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000652
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000653 QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000654 if (!BaseType->isRecordType())
Chris Lattner3c73c412008-11-19 08:23:25 +0000655 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattner08631c52008-11-23 21:45:46 +0000656 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000657
658 // C++ [class.base.init]p2:
659 // [...] Unless the mem-initializer-id names a nonstatic data
660 // member of the constructor’s class or a direct or virtual base
661 // of that class, the mem-initializer is ill-formed. A
662 // mem-initializer-list can initialize a base class using any
663 // name that denotes that base class type.
664
665 // First, check for a direct base class.
666 const CXXBaseSpecifier *DirectBaseSpec = 0;
667 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
668 Base != ClassDecl->bases_end(); ++Base) {
669 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
670 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
671 // We found a direct base of this type. That's what we're
672 // initializing.
673 DirectBaseSpec = &*Base;
674 break;
675 }
676 }
677
678 // Check for a virtual base class.
679 // FIXME: We might be able to short-circuit this if we know in
680 // advance that there are no virtual bases.
681 const CXXBaseSpecifier *VirtualBaseSpec = 0;
682 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
683 // We haven't found a base yet; search the class hierarchy for a
684 // virtual base class.
685 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
686 /*DetectVirtual=*/false);
687 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
688 for (BasePaths::paths_iterator Path = Paths.begin();
689 Path != Paths.end(); ++Path) {
690 if (Path->back().Base->isVirtual()) {
691 VirtualBaseSpec = Path->back().Base;
692 break;
693 }
694 }
695 }
696 }
697
698 // C++ [base.class.init]p2:
699 // If a mem-initializer-id is ambiguous because it designates both
700 // a direct non-virtual base class and an inherited virtual base
701 // class, the mem-initializer is ill-formed.
702 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner3c73c412008-11-19 08:23:25 +0000703 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
704 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000705
706 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
707}
708
Anders Carlssona7b35212009-03-25 02:58:17 +0000709void Sema::ActOnMemInitializers(DeclTy *ConstructorDecl,
710 SourceLocation ColonLoc,
711 MemInitTy **MemInits, unsigned NumMemInits) {
712 CXXConstructorDecl *Constructor =
713 dyn_cast<CXXConstructorDecl>((Decl *)ConstructorDecl);
714
715 if (!Constructor) {
716 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
717 return;
718 }
719}
720
Anders Carlsson67e4dd22009-03-22 01:52:17 +0000721namespace {
722 /// PureVirtualMethodCollector - traverses a class and its superclasses
723 /// and determines if it has any pure virtual methods.
724 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
725 ASTContext &Context;
726
Sebastian Redldfe292d2009-03-22 21:28:55 +0000727 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +0000728 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +0000729
730 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +0000731 MethodList Methods;
732
733 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
734
735 public:
736 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
737 : Context(Ctx) {
738
739 MethodList List;
740 Collect(RD, List);
741
742 // Copy the temporary list to methods, and make sure to ignore any
743 // null entries.
744 for (size_t i = 0, e = List.size(); i != e; ++i) {
745 if (List[i])
746 Methods.push_back(List[i]);
747 }
748 }
749
Anders Carlsson4681ebd2009-03-22 20:18:17 +0000750 bool empty() const { return Methods.empty(); }
751
752 MethodList::const_iterator methods_begin() { return Methods.begin(); }
753 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +0000754 };
755
756 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
757 MethodList& Methods) {
758 // First, collect the pure virtual methods for the base classes.
759 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
760 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
761 if (const RecordType *RT = Base->getType()->getAsRecordType()) {
762 const CXXRecordDecl *BaseDecl
763 = cast<CXXRecordDecl>(RT->getDecl());
764 if (BaseDecl && BaseDecl->isAbstract())
765 Collect(BaseDecl, Methods);
766 }
767 }
768
769 // Next, zero out any pure virtual methods that this class overrides.
770 for (size_t i = 0, e = Methods.size(); i != e; ++i) {
771 const CXXMethodDecl *VMD = dyn_cast_or_null<CXXMethodDecl>(Methods[i]);
772 if (!VMD)
773 continue;
774
775 DeclContext::lookup_const_iterator I, E;
776 for (llvm::tie(I, E) = RD->lookup(VMD->getDeclName()); I != E; ++I) {
777 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*I)) {
778 if (Context.getCanonicalType(MD->getType()) ==
779 Context.getCanonicalType(VMD->getType())) {
780 // We did find a matching method, which means that this is not a
781 // pure virtual method in the current class. Zero it out.
782 Methods[i] = 0;
783 }
784 }
785 }
786 }
787
788 // Finally, add pure virtual methods from this class.
789 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
790 i != e; ++i) {
791 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
792 if (MD->isPure())
793 Methods.push_back(MD);
794 }
795 }
796 }
797}
Douglas Gregor7ad83902008-11-05 04:29:56 +0000798
Anders Carlsson4681ebd2009-03-22 20:18:17 +0000799bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +0000800 unsigned DiagID, AbstractDiagSelID SelID,
801 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +0000802
803 if (!getLangOptions().CPlusPlus)
804 return false;
Anders Carlsson11f21a02009-03-23 19:10:31 +0000805
806 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssone65a3c82009-03-24 17:23:42 +0000807 return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
808 CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +0000809
810 if (const PointerType *PT = T->getAsPointerType()) {
811 // Find the innermost pointer type.
812 while (const PointerType *T = PT->getPointeeType()->getAsPointerType())
813 PT = T;
Anders Carlsson4681ebd2009-03-22 20:18:17 +0000814
Anders Carlsson5eff73c2009-03-24 01:46:45 +0000815 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssone65a3c82009-03-24 17:23:42 +0000816 return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
817 CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +0000818 }
819
Anders Carlsson4681ebd2009-03-22 20:18:17 +0000820 const RecordType *RT = T->getAsRecordType();
821 if (!RT)
822 return false;
823
824 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
825 if (!RD)
826 return false;
827
Anders Carlssone65a3c82009-03-24 17:23:42 +0000828 if (CurrentRD && CurrentRD != RD)
829 return false;
830
Anders Carlsson4681ebd2009-03-22 20:18:17 +0000831 if (!RD->isAbstract())
832 return false;
833
Anders Carlssonb9bbe492009-03-23 17:49:10 +0000834 Diag(Loc, DiagID) << RD->getDeclName() << SelID;
Anders Carlsson4681ebd2009-03-22 20:18:17 +0000835
836 // Check if we've already emitted the list of pure virtual functions for this
837 // class.
838 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
839 return true;
840
841 PureVirtualMethodCollector Collector(Context, RD);
842
843 for (PureVirtualMethodCollector::MethodList::const_iterator I =
844 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
845 const CXXMethodDecl *MD = *I;
846
847 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
848 MD->getDeclName();
849 }
850
851 if (!PureVirtualClassDiagSet)
852 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
853 PureVirtualClassDiagSet->insert(RD);
854
855 return true;
856}
857
Anders Carlsson8211eff2009-03-24 01:19:16 +0000858namespace {
859 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
860 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
861 Sema &SemaRef;
862 CXXRecordDecl *AbstractClass;
863
Anders Carlssone65a3c82009-03-24 17:23:42 +0000864 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +0000865 bool Invalid = false;
866
Anders Carlssone65a3c82009-03-24 17:23:42 +0000867 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
868 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +0000869 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +0000870
Anders Carlsson8211eff2009-03-24 01:19:16 +0000871 return Invalid;
872 }
Anders Carlssone65a3c82009-03-24 17:23:42 +0000873
874 public:
875 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
876 : SemaRef(SemaRef), AbstractClass(ac) {
877 Visit(SemaRef.Context.getTranslationUnitDecl());
878 }
Anders Carlsson8211eff2009-03-24 01:19:16 +0000879
Anders Carlssone65a3c82009-03-24 17:23:42 +0000880 bool VisitFunctionDecl(const FunctionDecl *FD) {
881 if (FD->isThisDeclarationADefinition()) {
882 // No need to do the check if we're in a definition, because it requires
883 // that the return/param types are complete.
884 // because that requires
885 return VisitDeclContext(FD);
886 }
887
888 // Check the return type.
889 QualType RTy = FD->getType()->getAsFunctionType()->getResultType();
890 bool Invalid =
891 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
892 diag::err_abstract_type_in_decl,
893 Sema::AbstractReturnType,
894 AbstractClass);
895
896 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
897 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +0000898 const ParmVarDecl *VD = *I;
899 Invalid |=
900 SemaRef.RequireNonAbstractType(VD->getLocation(),
901 VD->getOriginalType(),
902 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +0000903 Sema::AbstractParamType,
904 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +0000905 }
906
907 return Invalid;
908 }
Anders Carlssone65a3c82009-03-24 17:23:42 +0000909
910 bool VisitDecl(const Decl* D) {
911 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
912 return VisitDeclContext(DC);
913
914 return false;
915 }
Anders Carlsson8211eff2009-03-24 01:19:16 +0000916 };
917}
918
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000919void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
920 DeclTy *TagDecl,
921 SourceLocation LBrac,
922 SourceLocation RBrac) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000923 TemplateDecl *Template = AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000924 ActOnFields(S, RLoc, TagDecl,
925 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +0000926 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000927
Anders Carlsson67e4dd22009-03-22 01:52:17 +0000928 CXXRecordDecl *RD = cast<CXXRecordDecl>((Decl*)TagDecl);
929 if (!RD->isAbstract()) {
930 // Collect all the pure virtual methods and see if this is an abstract
931 // class after all.
932 PureVirtualMethodCollector Collector(Context, RD);
933 if (!Collector.empty())
934 RD->setAbstract(true);
935 }
936
Anders Carlssone65a3c82009-03-24 17:23:42 +0000937 if (RD->isAbstract())
938 AbstractClassUsageDiagnoser(*this, RD);
Anders Carlsson8211eff2009-03-24 01:19:16 +0000939
Douglas Gregor2943aed2009-03-03 04:44:36 +0000940 if (!Template)
Anders Carlsson67e4dd22009-03-22 01:52:17 +0000941 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000942}
943
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000944/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
945/// special functions, such as the default constructor, copy
946/// constructor, or destructor, to the given C++ class (C++
947/// [special]p1). This routine can only be executed just before the
948/// definition of the class is complete.
949void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000950 QualType ClassType = Context.getTypeDeclType(ClassDecl);
951 ClassType = Context.getCanonicalType(ClassType);
952
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000953 if (!ClassDecl->hasUserDeclaredConstructor()) {
954 // C++ [class.ctor]p5:
955 // A default constructor for a class X is a constructor of class X
956 // that can be called without an argument. If there is no
957 // user-declared constructor for class X, a default constructor is
958 // implicitly declared. An implicitly-declared default constructor
959 // is an inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000960 DeclarationName Name
961 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000962 CXXConstructorDecl *DefaultCon =
963 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000964 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000965 Context.getFunctionType(Context.VoidTy,
966 0, 0, false, 0),
967 /*isExplicit=*/false,
968 /*isInline=*/true,
969 /*isImplicitlyDeclared=*/true);
970 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000971 DefaultCon->setImplicit();
Douglas Gregor482b77d2009-01-12 23:27:07 +0000972 ClassDecl->addDecl(DefaultCon);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000973
974 // Notify the class that we've added a constructor.
975 ClassDecl->addedConstructor(Context, DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000976 }
977
978 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
979 // C++ [class.copy]p4:
980 // If the class definition does not explicitly declare a copy
981 // constructor, one is declared implicitly.
982
983 // C++ [class.copy]p5:
984 // The implicitly-declared copy constructor for a class X will
985 // have the form
986 //
987 // X::X(const X&)
988 //
989 // if
990 bool HasConstCopyConstructor = true;
991
992 // -- each direct or virtual base class B of X has a copy
993 // constructor whose first parameter is of type const B& or
994 // const volatile B&, and
995 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
996 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
997 const CXXRecordDecl *BaseClassDecl
998 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
999 HasConstCopyConstructor
1000 = BaseClassDecl->hasConstCopyConstructor(Context);
1001 }
1002
1003 // -- for all the nonstatic data members of X that are of a
1004 // class type M (or array thereof), each such class type
1005 // has a copy constructor whose first parameter is of type
1006 // const M& or const volatile M&.
1007 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1008 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
1009 QualType FieldType = (*Field)->getType();
1010 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1011 FieldType = Array->getElementType();
1012 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
1013 const CXXRecordDecl *FieldClassDecl
1014 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1015 HasConstCopyConstructor
1016 = FieldClassDecl->hasConstCopyConstructor(Context);
1017 }
1018 }
1019
Sebastian Redl64b45f72009-01-05 20:52:13 +00001020 // Otherwise, the implicitly declared copy constructor will have
1021 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001022 //
1023 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00001024 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001025 if (HasConstCopyConstructor)
1026 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001027 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001028
Sebastian Redl64b45f72009-01-05 20:52:13 +00001029 // An implicitly-declared copy constructor is an inline public
1030 // member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001031 DeclarationName Name
1032 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001033 CXXConstructorDecl *CopyConstructor
1034 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001035 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001036 Context.getFunctionType(Context.VoidTy,
1037 &ArgType, 1,
1038 false, 0),
1039 /*isExplicit=*/false,
1040 /*isInline=*/true,
1041 /*isImplicitlyDeclared=*/true);
1042 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001043 CopyConstructor->setImplicit();
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001044
1045 // Add the parameter to the constructor.
1046 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1047 ClassDecl->getLocation(),
1048 /*IdentifierInfo=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001049 ArgType, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00001050 CopyConstructor->setParams(Context, &FromParam, 1);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001051
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001052 ClassDecl->addedConstructor(Context, CopyConstructor);
Douglas Gregor482b77d2009-01-12 23:27:07 +00001053 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001054 }
1055
Sebastian Redl64b45f72009-01-05 20:52:13 +00001056 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1057 // Note: The following rules are largely analoguous to the copy
1058 // constructor rules. Note that virtual bases are not taken into account
1059 // for determining the argument type of the operator. Note also that
1060 // operators taking an object instead of a reference are allowed.
1061 //
1062 // C++ [class.copy]p10:
1063 // If the class definition does not explicitly declare a copy
1064 // assignment operator, one is declared implicitly.
1065 // The implicitly-defined copy assignment operator for a class X
1066 // will have the form
1067 //
1068 // X& X::operator=(const X&)
1069 //
1070 // if
1071 bool HasConstCopyAssignment = true;
1072
1073 // -- each direct base class B of X has a copy assignment operator
1074 // whose parameter is of type const B&, const volatile B& or B,
1075 // and
1076 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1077 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1078 const CXXRecordDecl *BaseClassDecl
1079 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
1080 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
1081 }
1082
1083 // -- for all the nonstatic data members of X that are of a class
1084 // type M (or array thereof), each such class type has a copy
1085 // assignment operator whose parameter is of type const M&,
1086 // const volatile M& or M.
1087 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1088 HasConstCopyAssignment && Field != ClassDecl->field_end(); ++Field) {
1089 QualType FieldType = (*Field)->getType();
1090 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1091 FieldType = Array->getElementType();
1092 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
1093 const CXXRecordDecl *FieldClassDecl
1094 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1095 HasConstCopyAssignment
1096 = FieldClassDecl->hasConstCopyAssignment(Context);
1097 }
1098 }
1099
1100 // Otherwise, the implicitly declared copy assignment operator will
1101 // have the form
1102 //
1103 // X& X::operator=(X&)
1104 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001105 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001106 if (HasConstCopyAssignment)
1107 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001108 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001109
1110 // An implicitly-declared copy assignment operator is an inline public
1111 // member of its class.
1112 DeclarationName Name =
1113 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1114 CXXMethodDecl *CopyAssignment =
1115 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1116 Context.getFunctionType(RetType, &ArgType, 1,
1117 false, 0),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001118 /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001119 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001120 CopyAssignment->setImplicit();
Sebastian Redl64b45f72009-01-05 20:52:13 +00001121
1122 // Add the parameter to the operator.
1123 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1124 ClassDecl->getLocation(),
1125 /*IdentifierInfo=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001126 ArgType, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00001127 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001128
1129 // Don't call addedAssignmentOperator. There is no way to distinguish an
1130 // implicit from an explicit assignment operator.
Douglas Gregor482b77d2009-01-12 23:27:07 +00001131 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001132 }
1133
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001134 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001135 // C++ [class.dtor]p2:
1136 // If a class has no user-declared destructor, a destructor is
1137 // declared implicitly. An implicitly-declared destructor is an
1138 // inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001139 DeclarationName Name
1140 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001141 CXXDestructorDecl *Destructor
1142 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001143 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00001144 Context.getFunctionType(Context.VoidTy,
1145 0, 0, false, 0),
1146 /*isInline=*/true,
1147 /*isImplicitlyDeclared=*/true);
1148 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001149 Destructor->setImplicit();
Douglas Gregor482b77d2009-01-12 23:27:07 +00001150 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001151 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001152}
1153
Douglas Gregor72b505b2008-12-16 21:30:33 +00001154/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1155/// parsing a top-level (non-nested) C++ class, and we are now
1156/// parsing those parts of the given Method declaration that could
1157/// not be parsed earlier (C++ [class.mem]p2), such as default
1158/// arguments. This action should enter the scope of the given
1159/// Method declaration as if we had just parsed the qualified method
1160/// name. However, it should not bring the parameters into scope;
1161/// that will be performed by ActOnDelayedCXXMethodParameter.
Douglas Gregorab452ba2009-03-26 23:50:42 +00001162void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00001163 CXXScopeSpec SS;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001164 FunctionDecl *Method = (FunctionDecl*)MethodD;
1165 QualType ClassTy
1166 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1167 SS.setScopeRep(
1168 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001169 ActOnCXXEnterDeclaratorScope(S, SS);
1170}
1171
1172/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1173/// C++ method declaration. We're (re-)introducing the given
1174/// function parameter into scope for use in parsing later parts of
1175/// the method declaration. For example, we could see an
1176/// ActOnParamDefaultArgument event for this parameter.
1177void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
1178 ParmVarDecl *Param = (ParmVarDecl*)ParamD;
Douglas Gregor61366e92008-12-24 00:01:03 +00001179
1180 // If this parameter has an unparsed default argument, clear it out
1181 // to make way for the parsed default argument.
1182 if (Param->hasUnparsedDefaultArg())
1183 Param->setDefaultArg(0);
1184
Douglas Gregor72b505b2008-12-16 21:30:33 +00001185 S->AddDecl(Param);
1186 if (Param->getDeclName())
1187 IdResolver.AddDecl(Param);
1188}
1189
1190/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1191/// processing the delayed method declaration for Method. The method
1192/// declaration is now considered finished. There may be a separate
1193/// ActOnStartOfFunctionDef action later (not necessarily
1194/// immediately!) for this method, if it was also defined inside the
1195/// class body.
1196void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
1197 FunctionDecl *Method = (FunctionDecl*)MethodD;
1198 CXXScopeSpec SS;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001199 QualType ClassTy
1200 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1201 SS.setScopeRep(
1202 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001203 ActOnCXXExitDeclaratorScope(S, SS);
1204
1205 // Now that we have our default arguments, check the constructor
1206 // again. It could produce additional diagnostics or affect whether
1207 // the class has implicitly-declared destructors, among other
1208 // things.
1209 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
1210 if (CheckConstructor(Constructor))
1211 Constructor->setInvalidDecl();
1212 }
1213
1214 // Check the default arguments, which we may have added.
1215 if (!Method->isInvalidDecl())
1216 CheckCXXDefaultArguments(Method);
1217}
1218
Douglas Gregor42a552f2008-11-05 20:51:48 +00001219/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00001220/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00001221/// R. If there are any errors in the declarator, this routine will
1222/// emit diagnostics and return true. Otherwise, it will return
1223/// false. Either way, the type @p R will be updated to reflect a
1224/// well-formed type for the constructor.
1225bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
1226 FunctionDecl::StorageClass& SC) {
1227 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1228 bool isInvalid = false;
1229
1230 // C++ [class.ctor]p3:
1231 // A constructor shall not be virtual (10.3) or static (9.4). A
1232 // constructor can be invoked for a const, volatile or const
1233 // volatile object. A constructor shall not be declared const,
1234 // volatile, or const volatile (9.3.2).
1235 if (isVirtual) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001236 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1237 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1238 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001239 isInvalid = true;
1240 }
1241 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001242 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1243 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1244 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001245 isInvalid = true;
1246 SC = FunctionDecl::None;
1247 }
1248 if (D.getDeclSpec().hasTypeSpecifier()) {
1249 // Constructors don't have return types, but the parser will
1250 // happily parse something like:
1251 //
1252 // class X {
1253 // float X(float);
1254 // };
1255 //
1256 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001257 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
1258 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1259 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001260 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001261 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001262 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1263 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001264 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1265 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001266 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001267 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1268 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001269 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001270 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1271 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001272 }
1273
1274 // Rebuild the function type "R" without any type qualifiers (in
1275 // case any of the errors above fired) and with "void" as the
1276 // return type, since constructors don't have return types. We
1277 // *always* have to do this, because GetTypeForDeclarator will
1278 // put in a result type of "int" when none was specified.
Douglas Gregor72564e72009-02-26 23:50:07 +00001279 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001280 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1281 Proto->getNumArgs(),
1282 Proto->isVariadic(),
1283 0);
1284
1285 return isInvalid;
1286}
1287
Douglas Gregor72b505b2008-12-16 21:30:33 +00001288/// CheckConstructor - Checks a fully-formed constructor for
1289/// well-formedness, issuing any diagnostics required. Returns true if
1290/// the constructor declarator is invalid.
1291bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Douglas Gregor33297562009-03-27 04:38:56 +00001292 CXXRecordDecl *ClassDecl
1293 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
1294 if (!ClassDecl)
Douglas Gregor72b505b2008-12-16 21:30:33 +00001295 return true;
1296
Douglas Gregor33297562009-03-27 04:38:56 +00001297 bool Invalid = Constructor->isInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00001298
1299 // C++ [class.copy]p3:
1300 // A declaration of a constructor for a class X is ill-formed if
1301 // its first parameter is of type (optionally cv-qualified) X and
1302 // either there are no other parameters or else all other
1303 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00001304 if (!Constructor->isInvalidDecl() &&
1305 ((Constructor->getNumParams() == 1) ||
1306 (Constructor->getNumParams() > 1 &&
1307 Constructor->getParamDecl(1)->getDefaultArg() != 0))) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00001308 QualType ParamType = Constructor->getParamDecl(0)->getType();
1309 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1310 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1311 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1312 << SourceRange(Constructor->getParamDecl(0)->getLocation());
1313 Invalid = true;
1314 }
1315 }
1316
1317 // Notify the class that we've added a constructor.
1318 ClassDecl->addedConstructor(Context, Constructor);
1319
1320 return Invalid;
1321}
1322
Douglas Gregor42a552f2008-11-05 20:51:48 +00001323/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1324/// the well-formednes of the destructor declarator @p D with type @p
1325/// R. If there are any errors in the declarator, this routine will
1326/// emit diagnostics and return true. Otherwise, it will return
1327/// false. Either way, the type @p R will be updated to reflect a
1328/// well-formed type for the destructor.
1329bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1330 FunctionDecl::StorageClass& SC) {
1331 bool isInvalid = false;
1332
1333 // C++ [class.dtor]p1:
1334 // [...] A typedef-name that names a class is a class-name
1335 // (7.1.3); however, a typedef-name that names a class shall not
1336 // be used as the identifier in the declarator for a destructor
1337 // declaration.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001338 QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1339 if (DeclaratorType->getAsTypedefType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001340 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001341 << DeclaratorType;
Douglas Gregor55c60952008-11-10 14:41:22 +00001342 isInvalid = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001343 }
1344
1345 // C++ [class.dtor]p2:
1346 // A destructor is used to destroy objects of its class type. A
1347 // destructor takes no parameters, and no return type can be
1348 // specified for it (not even void). The address of a destructor
1349 // shall not be taken. A destructor shall not be static. A
1350 // destructor can be invoked for a const, volatile or const
1351 // volatile object. A destructor shall not be declared const,
1352 // volatile or const volatile (9.3.2).
1353 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001354 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1355 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1356 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001357 isInvalid = true;
1358 SC = FunctionDecl::None;
1359 }
1360 if (D.getDeclSpec().hasTypeSpecifier()) {
1361 // Destructors don't have return types, but the parser will
1362 // happily parse something like:
1363 //
1364 // class X {
1365 // float ~X();
1366 // };
1367 //
1368 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001369 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1370 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1371 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001372 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001373 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001374 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1375 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001376 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1377 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001378 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001379 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1380 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001381 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001382 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1383 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001384 }
1385
1386 // Make sure we don't have any parameters.
Douglas Gregor72564e72009-02-26 23:50:07 +00001387 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001388 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1389
1390 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00001391 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001392 }
1393
1394 // Make sure the destructor isn't variadic.
Douglas Gregor72564e72009-02-26 23:50:07 +00001395 if (R->getAsFunctionProtoType()->isVariadic())
Douglas Gregor42a552f2008-11-05 20:51:48 +00001396 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1397
1398 // Rebuild the function type "R" without any type qualifiers or
1399 // parameters (in case any of the errors above fired) and with
1400 // "void" as the return type, since destructors don't have return
1401 // types. We *always* have to do this, because GetTypeForDeclarator
1402 // will put in a result type of "int" when none was specified.
1403 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1404
1405 return isInvalid;
1406}
1407
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001408/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1409/// well-formednes of the conversion function declarator @p D with
1410/// type @p R. If there are any errors in the declarator, this routine
1411/// will emit diagnostics and return true. Otherwise, it will return
1412/// false. Either way, the type @p R will be updated to reflect a
1413/// well-formed type for the conversion operator.
1414bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1415 FunctionDecl::StorageClass& SC) {
1416 bool isInvalid = false;
1417
1418 // C++ [class.conv.fct]p1:
1419 // Neither parameter types nor return type can be specified. The
1420 // type of a conversion function (8.3.5) is “function taking no
1421 // parameter returning conversion-type-id.”
1422 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001423 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1424 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1425 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001426 isInvalid = true;
1427 SC = FunctionDecl::None;
1428 }
1429 if (D.getDeclSpec().hasTypeSpecifier()) {
1430 // Conversion functions don't have return types, but the parser will
1431 // happily parse something like:
1432 //
1433 // class X {
1434 // float operator bool();
1435 // };
1436 //
1437 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001438 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1439 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1440 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001441 }
1442
1443 // Make sure we don't have any parameters.
Douglas Gregor72564e72009-02-26 23:50:07 +00001444 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001445 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1446
1447 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00001448 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001449 }
1450
1451 // Make sure the conversion function isn't variadic.
Douglas Gregor72564e72009-02-26 23:50:07 +00001452 if (R->getAsFunctionProtoType()->isVariadic())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001453 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1454
1455 // C++ [class.conv.fct]p4:
1456 // The conversion-type-id shall not represent a function type nor
1457 // an array type.
1458 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1459 if (ConvType->isArrayType()) {
1460 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1461 ConvType = Context.getPointerType(ConvType);
1462 } else if (ConvType->isFunctionType()) {
1463 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1464 ConvType = Context.getPointerType(ConvType);
1465 }
1466
1467 // Rebuild the function type "R" without any parameters (in case any
1468 // of the errors above fired) and with the conversion type as the
1469 // return type.
1470 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor72564e72009-02-26 23:50:07 +00001471 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001472
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001473 // C++0x explicit conversion operators.
1474 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1475 Diag(D.getDeclSpec().getExplicitSpecLoc(),
1476 diag::warn_explicit_conversion_functions)
1477 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1478
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001479 return isInvalid;
1480}
1481
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001482/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1483/// the declaration of the given C++ conversion function. This routine
1484/// is responsible for recording the conversion function in the C++
1485/// class, if possible.
1486Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1487 assert(Conversion && "Expected to receive a conversion function declaration");
1488
Douglas Gregor9d350972008-12-12 08:25:50 +00001489 // Set the lexical context of this conversion function
1490 Conversion->setLexicalDeclContext(CurContext);
1491
1492 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001493
1494 // Make sure we aren't redeclaring the conversion function.
1495 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001496
1497 // C++ [class.conv.fct]p1:
1498 // [...] A conversion function is never used to convert a
1499 // (possibly cv-qualified) object to the (possibly cv-qualified)
1500 // same object type (or a reference to it), to a (possibly
1501 // cv-qualified) base class of that type (or a reference to it),
1502 // or to (possibly cv-qualified) void.
1503 // FIXME: Suppress this warning if the conversion function ends up
1504 // being a virtual function that overrides a virtual function in a
1505 // base class.
1506 QualType ClassType
1507 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1508 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1509 ConvType = ConvTypeRef->getPointeeType();
1510 if (ConvType->isRecordType()) {
1511 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1512 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00001513 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001514 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001515 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00001516 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001517 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001518 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00001519 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001520 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001521 }
1522
Douglas Gregor70316a02008-12-26 15:00:45 +00001523 if (Conversion->getPreviousDeclaration()) {
1524 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1525 for (OverloadedFunctionDecl::function_iterator
1526 Conv = Conversions->function_begin(),
1527 ConvEnd = Conversions->function_end();
1528 Conv != ConvEnd; ++Conv) {
1529 if (*Conv == Conversion->getPreviousDeclaration()) {
1530 *Conv = Conversion;
1531 return (DeclTy *)Conversion;
1532 }
1533 }
1534 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1535 } else
1536 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001537
1538 return (DeclTy *)Conversion;
1539}
1540
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001541//===----------------------------------------------------------------------===//
1542// Namespace Handling
1543//===----------------------------------------------------------------------===//
1544
1545/// ActOnStartNamespaceDef - This is called at the start of a namespace
1546/// definition.
1547Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1548 SourceLocation IdentLoc,
1549 IdentifierInfo *II,
1550 SourceLocation LBrace) {
1551 NamespaceDecl *Namespc =
1552 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1553 Namespc->setLBracLoc(LBrace);
1554
1555 Scope *DeclRegionScope = NamespcScope->getParent();
1556
1557 if (II) {
1558 // C++ [namespace.def]p2:
1559 // The identifier in an original-namespace-definition shall not have been
1560 // previously defined in the declarative region in which the
1561 // original-namespace-definition appears. The identifier in an
1562 // original-namespace-definition is the name of the namespace. Subsequently
1563 // in that declarative region, it is treated as an original-namespace-name.
1564
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001565 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1566 true);
Douglas Gregor44b43212008-12-11 16:49:14 +00001567
1568 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1569 // This is an extended namespace definition.
1570 // Attach this namespace decl to the chain of extended namespace
1571 // definitions.
1572 OrigNS->setNextNamespace(Namespc);
1573 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001574
Douglas Gregor44b43212008-12-11 16:49:14 +00001575 // Remove the previous declaration from the scope.
1576 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00001577 IdResolver.RemoveDecl(OrigNS);
1578 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001579 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001580 } else if (PrevDecl) {
1581 // This is an invalid name redefinition.
1582 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1583 << Namespc->getDeclName();
1584 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1585 Namespc->setInvalidDecl();
1586 // Continue on to push Namespc as current DeclContext and return it.
1587 }
1588
1589 PushOnScopeChains(Namespc, DeclRegionScope);
1590 } else {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001591 // FIXME: Handle anonymous namespaces
1592 }
1593
1594 // Although we could have an invalid decl (i.e. the namespace name is a
1595 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor44b43212008-12-11 16:49:14 +00001596 // FIXME: We should be able to push Namespc here, so that the
1597 // each DeclContext for the namespace has the declarations
1598 // that showed up in that particular namespace definition.
1599 PushDeclContext(NamespcScope, Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001600 return Namespc;
1601}
1602
1603/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1604/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1605void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1606 Decl *Dcl = static_cast<Decl *>(D);
1607 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1608 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1609 Namespc->setRBracLoc(RBrace);
1610 PopDeclContext();
1611}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001612
Douglas Gregorf780abc2008-12-30 03:27:21 +00001613Sema::DeclTy *Sema::ActOnUsingDirective(Scope *S,
1614 SourceLocation UsingLoc,
1615 SourceLocation NamespcLoc,
1616 const CXXScopeSpec &SS,
1617 SourceLocation IdentLoc,
1618 IdentifierInfo *NamespcName,
1619 AttributeList *AttrList) {
1620 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1621 assert(NamespcName && "Invalid NamespcName.");
1622 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001623 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00001624
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001625 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00001626
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001627 // Lookup namespace name.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001628 LookupResult R = LookupParsedName(S, &SS, NamespcName,
1629 LookupNamespaceName, false);
1630 if (R.isAmbiguous()) {
1631 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
1632 return 0;
1633 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001634 if (NamedDecl *NS = R) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00001635 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001636 // C++ [namespace.udir]p1:
1637 // A using-directive specifies that the names in the nominated
1638 // namespace can be used in the scope in which the
1639 // using-directive appears after the using-directive. During
1640 // unqualified name lookup (3.4.1), the names appear as if they
1641 // were declared in the nearest enclosing namespace which
1642 // contains both the using-directive and the nominated
1643 // namespace. [Note: in this context, “contains” means “contains
1644 // directly or indirectly”. ]
1645
1646 // Find enclosing context containing both using-directive and
1647 // nominated namespace.
1648 DeclContext *CommonAncestor = cast<DeclContext>(NS);
1649 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1650 CommonAncestor = CommonAncestor->getParent();
1651
1652 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc,
1653 NamespcLoc, IdentLoc,
1654 cast<NamespaceDecl>(NS),
1655 CommonAncestor);
1656 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00001657 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00001658 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00001659 }
1660
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001661 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00001662 delete AttrList;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001663 return UDir;
1664}
1665
1666void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1667 // If scope has associated entity, then using directive is at namespace
1668 // or translation unit scope. We add UsingDirectiveDecls, into
1669 // it's lookup structure.
1670 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
1671 Ctx->addDecl(UDir);
1672 else
1673 // Otherwise it is block-sope. using-directives will affect lookup
1674 // only to the end of scope.
1675 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00001676}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001677
1678/// AddCXXDirectInitializerToDecl - This action is called immediately after
1679/// ActOnDeclarator, when a C++ direct initializer is present.
1680/// e.g: "int x(1);"
1681void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00001682 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001683 SourceLocation *CommaLocs,
1684 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00001685 unsigned NumExprs = Exprs.size();
1686 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001687 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001688
1689 // If there is no declaration, there was an error parsing it. Just ignore
1690 // the initializer.
1691 if (RealDecl == 0) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001692 return;
1693 }
1694
1695 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1696 if (!VDecl) {
1697 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1698 RealDecl->setInvalidDecl();
1699 return;
1700 }
1701
Douglas Gregor615c5d42009-03-24 16:43:20 +00001702 // FIXME: Need to handle dependent types and expressions here.
1703
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001704 // We will treat direct-initialization as a copy-initialization:
1705 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001706 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1707 //
1708 // Clients that want to distinguish between the two forms, can check for
1709 // direct initializer using VarDecl::hasCXXDirectInitializer().
1710 // A major benefit is that clients that don't particularly care about which
1711 // exactly form was it (like the CodeGen) can handle both cases without
1712 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001713
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001714 // C++ 8.5p11:
1715 // The form of initialization (using parentheses or '=') is generally
1716 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001717 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001718 QualType DeclInitType = VDecl->getType();
1719 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1720 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001721
Douglas Gregor615c5d42009-03-24 16:43:20 +00001722 // FIXME: This isn't the right place to complete the type.
1723 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
1724 diag::err_typecheck_decl_incomplete_type)) {
1725 VDecl->setInvalidDecl();
1726 return;
1727 }
1728
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001729 if (VDecl->getType()->isRecordType()) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001730 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00001731 = PerformInitializationByConstructor(DeclInitType,
1732 (Expr **)Exprs.get(), NumExprs,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001733 VDecl->getLocation(),
1734 SourceRange(VDecl->getLocation(),
1735 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001736 VDecl->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001737 IK_Direct);
Sebastian Redlf53597f2009-03-15 17:47:39 +00001738 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00001739 RealDecl->setInvalidDecl();
Sebastian Redlf53597f2009-03-15 17:47:39 +00001740 else
1741 Exprs.release();
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001742
1743 // Let clients know that initialization was done with a direct
1744 // initializer.
1745 VDecl->setCXXDirectInitializer(true);
1746
1747 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1748 // the initializer.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001749 return;
1750 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001751
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001752 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001753 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1754 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001755 RealDecl->setInvalidDecl();
1756 return;
1757 }
1758
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001759 // Let clients know that initialization was done with a direct initializer.
1760 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001761
1762 assert(NumExprs == 1 && "Expected 1 expression");
1763 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00001764 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
1765 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001766}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001767
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001768/// PerformInitializationByConstructor - Perform initialization by
1769/// constructor (C++ [dcl.init]p14), which may occur as part of
1770/// direct-initialization or copy-initialization. We are initializing
1771/// an object of type @p ClassType with the given arguments @p
1772/// Args. @p Loc is the location in the source code where the
1773/// initializer occurs (e.g., a declaration, member initializer,
1774/// functional cast, etc.) while @p Range covers the whole
1775/// initialization. @p InitEntity is the entity being initialized,
1776/// which may by the name of a declaration or a type. @p Kind is the
1777/// kind of initialization we're performing, which affects whether
1778/// explicit constructors will be considered. When successful, returns
Douglas Gregor18fe5682008-11-03 20:45:27 +00001779/// the constructor that will be used to perform the initialization;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001780/// when the initialization fails, emits a diagnostic and returns
1781/// null.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001782CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001783Sema::PerformInitializationByConstructor(QualType ClassType,
1784 Expr **Args, unsigned NumArgs,
1785 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001786 DeclarationName InitEntity,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001787 InitializationKind Kind) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001788 const RecordType *ClassRec = ClassType->getAsRecordType();
1789 assert(ClassRec && "Can only initialize a class type here");
1790
1791 // C++ [dcl.init]p14:
1792 //
1793 // If the initialization is direct-initialization, or if it is
1794 // copy-initialization where the cv-unqualified version of the
1795 // source type is the same class as, or a derived class of, the
1796 // class of the destination, constructors are considered. The
1797 // applicable constructors are enumerated (13.3.1.3), and the
1798 // best one is chosen through overload resolution (13.3). The
1799 // constructor so selected is called to initialize the object,
1800 // with the initializer expression(s) as its argument(s). If no
1801 // constructor applies, or the overload resolution is ambiguous,
1802 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001803 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1804 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001805
1806 // Add constructors to the overload set.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001807 DeclarationName ConstructorName
1808 = Context.DeclarationNames.getCXXConstructorName(
1809 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001810 DeclContext::lookup_const_iterator Con, ConEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00001811 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001812 Con != ConEnd; ++Con) {
1813 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001814 if ((Kind == IK_Direct) ||
1815 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1816 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1817 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1818 }
1819
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001820 // FIXME: When we decide not to synthesize the implicitly-declared
1821 // constructors, we'll need to make them appear here.
1822
Douglas Gregor18fe5682008-11-03 20:45:27 +00001823 OverloadCandidateSet::iterator Best;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001824 switch (BestViableFunction(CandidateSet, Best)) {
1825 case OR_Success:
1826 // We found a constructor. Return it.
1827 return cast<CXXConstructorDecl>(Best->Function);
1828
1829 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00001830 if (InitEntity)
1831 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00001832 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00001833 else
1834 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00001835 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00001836 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001837 return 0;
1838
1839 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00001840 if (InitEntity)
1841 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
1842 else
1843 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001844 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1845 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001846
1847 case OR_Deleted:
1848 if (InitEntity)
1849 Diag(Loc, diag::err_ovl_deleted_init)
1850 << Best->Function->isDeleted()
1851 << InitEntity << Range;
1852 else
1853 Diag(Loc, diag::err_ovl_deleted_init)
1854 << Best->Function->isDeleted()
1855 << InitEntity << Range;
1856 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1857 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001858 }
1859
1860 return 0;
1861}
1862
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001863/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1864/// determine whether they are reference-related,
1865/// reference-compatible, reference-compatible with added
1866/// qualification, or incompatible, for use in C++ initialization by
1867/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1868/// type, and the first type (T1) is the pointee type of the reference
1869/// type being initialized.
1870Sema::ReferenceCompareResult
Douglas Gregor15da57e2008-10-29 02:00:59 +00001871Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1872 bool& DerivedToBase) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001873 assert(!T1->isReferenceType() &&
1874 "T1 must be the pointee type of the reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001875 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1876
1877 T1 = Context.getCanonicalType(T1);
1878 T2 = Context.getCanonicalType(T2);
1879 QualType UnqualT1 = T1.getUnqualifiedType();
1880 QualType UnqualT2 = T2.getUnqualifiedType();
1881
1882 // C++ [dcl.init.ref]p4:
1883 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1884 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1885 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001886 if (UnqualT1 == UnqualT2)
1887 DerivedToBase = false;
1888 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1889 DerivedToBase = true;
1890 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001891 return Ref_Incompatible;
1892
1893 // At this point, we know that T1 and T2 are reference-related (at
1894 // least).
1895
1896 // C++ [dcl.init.ref]p4:
1897 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1898 // reference-related to T2 and cv1 is the same cv-qualification
1899 // as, or greater cv-qualification than, cv2. For purposes of
1900 // overload resolution, cases for which cv1 is greater
1901 // cv-qualification than cv2 are identified as
1902 // reference-compatible with added qualification (see 13.3.3.2).
1903 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1904 return Ref_Compatible;
1905 else if (T1.isMoreQualifiedThan(T2))
1906 return Ref_Compatible_With_Added_Qualification;
1907 else
1908 return Ref_Related;
1909}
1910
1911/// CheckReferenceInit - Check the initialization of a reference
1912/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1913/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00001914/// list), and DeclType is the type of the declaration. When ICS is
1915/// non-null, this routine will compute the implicit conversion
1916/// sequence according to C++ [over.ics.ref] and will not produce any
1917/// diagnostics; when ICS is null, it will emit diagnostics when any
1918/// errors are found. Either way, a return value of true indicates
1919/// that there was a failure, a return value of false indicates that
1920/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001921///
1922/// When @p SuppressUserConversions, user-defined conversions are
1923/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001924/// When @p AllowExplicit, we also permit explicit user-defined
1925/// conversion functions.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001926bool
1927Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001928 ImplicitConversionSequence *ICS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001929 bool SuppressUserConversions,
1930 bool AllowExplicit) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001931 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1932
1933 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1934 QualType T2 = Init->getType();
1935
Douglas Gregor904eed32008-11-10 20:40:00 +00001936 // If the initializer is the address of an overloaded function, try
1937 // to resolve the overloaded function. If all goes well, T2 is the
1938 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00001939 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001940 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1941 ICS != 0);
1942 if (Fn) {
1943 // Since we're performing this reference-initialization for
1944 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001945 if (!ICS) {
1946 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
1947 return true;
1948
Douglas Gregor904eed32008-11-10 20:40:00 +00001949 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001950 }
Douglas Gregor904eed32008-11-10 20:40:00 +00001951
1952 T2 = Fn->getType();
1953 }
1954 }
1955
Douglas Gregor15da57e2008-10-29 02:00:59 +00001956 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001957 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00001958 bool DerivedToBase = false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001959 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001960 ReferenceCompareResult RefRelationship
1961 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1962
1963 // Most paths end in a failed conversion.
1964 if (ICS)
1965 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001966
1967 // C++ [dcl.init.ref]p5:
1968 // A reference to type “cv1 T1” is initialized by an expression
1969 // of type “cv2 T2” as follows:
1970
1971 // -- If the initializer expression
1972
1973 bool BindsDirectly = false;
1974 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1975 // reference-compatible with “cv2 T2,” or
Douglas Gregor15da57e2008-10-29 02:00:59 +00001976 //
1977 // Note that the bit-field check is skipped if we are just computing
1978 // the implicit conversion sequence (C++ [over.best.ics]p2).
1979 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1980 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001981 BindsDirectly = true;
1982
Anders Carlsson14734f72009-03-28 04:17:27 +00001983 // Rvalue references cannot bind to lvalues (N2812).
1984 if (isRValRef) {
1985 if (!ICS)
1986 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
1987 << Init->getSourceRange();
1988 return true;
1989 }
1990
Douglas Gregor15da57e2008-10-29 02:00:59 +00001991 if (ICS) {
1992 // C++ [over.ics.ref]p1:
1993 // When a parameter of reference type binds directly (8.5.3)
1994 // to an argument expression, the implicit conversion sequence
1995 // is the identity conversion, unless the argument expression
1996 // has a type that is a derived class of the parameter type,
1997 // in which case the implicit conversion sequence is a
1998 // derived-to-base Conversion (13.3.3.1).
1999 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2000 ICS->Standard.First = ICK_Identity;
2001 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2002 ICS->Standard.Third = ICK_Identity;
2003 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2004 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002005 ICS->Standard.ReferenceBinding = true;
2006 ICS->Standard.DirectBinding = true;
Douglas Gregor15da57e2008-10-29 02:00:59 +00002007
2008 // Nothing more to do: the inaccessibility/ambiguity check for
2009 // derived-to-base conversions is suppressed when we're
2010 // computing the implicit conversion sequence (C++
2011 // [over.best.ics]p2).
2012 return false;
2013 } else {
2014 // Perform the conversion.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002015 // FIXME: Binding to a subobject of the lvalue is going to require
2016 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002017 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002018 }
2019 }
2020
2021 // -- has a class type (i.e., T2 is a class type) and can be
2022 // implicitly converted to an lvalue of type “cv3 T3,”
2023 // where “cv1 T1” is reference-compatible with “cv3 T3”
2024 // 92) (this conversion is selected by enumerating the
2025 // applicable conversion functions (13.3.1.6) and choosing
2026 // the best one through overload resolution (13.3)),
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002027 if (!isRValRef && !SuppressUserConversions && T2->isRecordType()) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002028 // FIXME: Look for conversions in base classes!
2029 CXXRecordDecl *T2RecordDecl
2030 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002031
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002032 OverloadCandidateSet CandidateSet;
2033 OverloadedFunctionDecl *Conversions
2034 = T2RecordDecl->getConversionFunctions();
2035 for (OverloadedFunctionDecl::function_iterator Func
2036 = Conversions->function_begin();
2037 Func != Conversions->function_end(); ++Func) {
2038 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Sebastian Redldfe292d2009-03-22 21:28:55 +00002039
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002040 // If the conversion function doesn't return a reference type,
2041 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002042 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002043 (AllowExplicit || !Conv->isExplicit()))
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002044 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
2045 }
2046
2047 OverloadCandidateSet::iterator Best;
2048 switch (BestViableFunction(CandidateSet, Best)) {
2049 case OR_Success:
2050 // This is a direct binding.
2051 BindsDirectly = true;
2052
2053 if (ICS) {
2054 // C++ [over.ics.ref]p1:
2055 //
2056 // [...] If the parameter binds directly to the result of
2057 // applying a conversion function to the argument
2058 // expression, the implicit conversion sequence is a
2059 // user-defined conversion sequence (13.3.3.1.2), with the
2060 // second standard conversion sequence either an identity
2061 // conversion or, if the conversion function returns an
2062 // entity of a type that is a derived class of the parameter
2063 // type, a derived-to-base Conversion.
2064 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
2065 ICS->UserDefined.Before = Best->Conversions[0].Standard;
2066 ICS->UserDefined.After = Best->FinalConversion;
2067 ICS->UserDefined.ConversionFunction = Best->Function;
2068 assert(ICS->UserDefined.After.ReferenceBinding &&
2069 ICS->UserDefined.After.DirectBinding &&
2070 "Expected a direct reference binding!");
2071 return false;
2072 } else {
2073 // Perform the conversion.
2074 // FIXME: Binding to a subobject of the lvalue is going to require
2075 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002076 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002077 }
2078 break;
2079
2080 case OR_Ambiguous:
2081 assert(false && "Ambiguous reference binding conversions not implemented.");
2082 return true;
2083
2084 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002085 case OR_Deleted:
2086 // There was no suitable conversion, or we found a deleted
2087 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002088 break;
2089 }
2090 }
2091
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002092 if (BindsDirectly) {
2093 // C++ [dcl.init.ref]p4:
2094 // [...] In all cases where the reference-related or
2095 // reference-compatible relationship of two types is used to
2096 // establish the validity of a reference binding, and T1 is a
2097 // base class of T2, a program that necessitates such a binding
2098 // is ill-formed if T1 is an inaccessible (clause 11) or
2099 // ambiguous (10.2) base class of T2.
2100 //
2101 // Note that we only check this condition when we're allowed to
2102 // complain about errors, because we should not be checking for
2103 // ambiguity (or inaccessibility) unless the reference binding
2104 // actually happens.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002105 if (DerivedToBase)
2106 return CheckDerivedToBaseConversion(T2, T1,
2107 Init->getSourceRange().getBegin(),
2108 Init->getSourceRange());
2109 else
2110 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002111 }
2112
2113 // -- Otherwise, the reference shall be to a non-volatile const
Anders Carlsson14734f72009-03-28 04:17:27 +00002114 // type (i.e., cv1 shall be const), or shall be an rvalue reference.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002115 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00002116 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002117 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002118 diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00002119 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2120 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002121 return true;
2122 }
2123
2124 // -- If the initializer expression is an rvalue, with T2 a
2125 // class type, and “cv1 T1” is reference-compatible with
2126 // “cv2 T2,” the reference is bound in one of the
2127 // following ways (the choice is implementation-defined):
2128 //
2129 // -- The reference is bound to the object represented by
2130 // the rvalue (see 3.10) or to a sub-object within that
2131 // object.
2132 //
2133 // -- A temporary of type “cv1 T2” [sic] is created, and
2134 // a constructor is called to copy the entire rvalue
2135 // object into the temporary. The reference is bound to
2136 // the temporary or to a sub-object within the
2137 // temporary.
2138 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002139 // The constructor that would be used to make the copy
2140 // shall be callable whether or not the copy is actually
2141 // done.
2142 //
Anders Carlsson14734f72009-03-28 04:17:27 +00002143 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002144 // freedom, so we will always take the first option and never build
2145 // a temporary in this case. FIXME: We will, however, have to check
2146 // for the presence of a copy constructor in C++98/03 mode.
2147 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00002148 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
2149 if (ICS) {
2150 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2151 ICS->Standard.First = ICK_Identity;
2152 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2153 ICS->Standard.Third = ICK_Identity;
2154 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2155 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002156 ICS->Standard.ReferenceBinding = true;
Anders Carlsson14734f72009-03-28 04:17:27 +00002157 ICS->Standard.DirectBinding = false;
Douglas Gregor15da57e2008-10-29 02:00:59 +00002158 } else {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002159 // FIXME: Binding to a subobject of the rvalue is going to require
2160 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002161 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002162 }
2163 return false;
2164 }
2165
2166 // -- Otherwise, a temporary of type “cv1 T1” is created and
2167 // initialized from the initializer expression using the
2168 // rules for a non-reference copy initialization (8.5). The
2169 // reference is then bound to the temporary. If T1 is
2170 // reference-related to T2, cv1 must be the same
2171 // cv-qualification as, or greater cv-qualification than,
2172 // cv2; otherwise, the program is ill-formed.
2173 if (RefRelationship == Ref_Related) {
2174 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2175 // we would be reference-compatible or reference-compatible with
2176 // added qualification. But that wasn't the case, so the reference
2177 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002178 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002179 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002180 diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00002181 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2182 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002183 return true;
2184 }
2185
Douglas Gregor734d9862009-01-30 23:27:23 +00002186 // If at least one of the types is a class type, the types are not
2187 // related, and we aren't allowed any user conversions, the
2188 // reference binding fails. This case is important for breaking
2189 // recursion, since TryImplicitConversion below will attempt to
2190 // create a temporary through the use of a copy constructor.
2191 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
2192 (T1->isRecordType() || T2->isRecordType())) {
2193 if (!ICS)
2194 Diag(Init->getSourceRange().getBegin(),
2195 diag::err_typecheck_convert_incompatible)
2196 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
2197 return true;
2198 }
2199
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002200 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002201 if (ICS) {
Anders Carlsson14734f72009-03-28 04:17:27 +00002202 /// C++ [over.ics.ref]p2:
2203 ///
2204 /// When a parameter of reference type is not bound directly to
2205 /// an argument expression, the conversion sequence is the one
2206 /// required to convert the argument expression to the
2207 /// underlying type of the reference according to
2208 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
2209 /// to copy-initializing a temporary of the underlying type with
2210 /// the argument expression. Any difference in top-level
2211 /// cv-qualification is subsumed by the initialization itself
2212 /// and does not constitute a conversion.
Douglas Gregor225c41e2008-11-03 19:09:14 +00002213 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor15da57e2008-10-29 02:00:59 +00002214 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
2215 } else {
Douglas Gregor45920e82008-12-19 17:40:08 +00002216 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor15da57e2008-10-29 02:00:59 +00002217 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002218}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002219
2220/// CheckOverloadedOperatorDeclaration - Check whether the declaration
2221/// of this overloaded operator is well-formed. If so, returns false;
2222/// otherwise, emits appropriate diagnostics and returns true.
2223bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002224 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002225 "Expected an overloaded operator declaration");
2226
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002227 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
2228
2229 // C++ [over.oper]p5:
2230 // The allocation and deallocation functions, operator new,
2231 // operator new[], operator delete and operator delete[], are
2232 // described completely in 3.7.3. The attributes and restrictions
2233 // found in the rest of this subclause do not apply to them unless
2234 // explicitly stated in 3.7.3.
2235 // FIXME: Write a separate routine for checking this. For now, just
2236 // allow it.
2237 if (Op == OO_New || Op == OO_Array_New ||
2238 Op == OO_Delete || Op == OO_Array_Delete)
2239 return false;
2240
2241 // C++ [over.oper]p6:
2242 // An operator function shall either be a non-static member
2243 // function or be a non-member function and have at least one
2244 // parameter whose type is a class, a reference to a class, an
2245 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002246 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
2247 if (MethodDecl->isStatic())
2248 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002249 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002250 } else {
2251 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002252 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2253 ParamEnd = FnDecl->param_end();
2254 Param != ParamEnd; ++Param) {
2255 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002256 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
2257 ClassOrEnumParam = true;
2258 break;
2259 }
2260 }
2261
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002262 if (!ClassOrEnumParam)
2263 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002264 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002265 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002266 }
2267
2268 // C++ [over.oper]p8:
2269 // An operator function cannot have default arguments (8.3.6),
2270 // except where explicitly stated below.
2271 //
2272 // Only the function-call operator allows default arguments
2273 // (C++ [over.call]p1).
2274 if (Op != OO_Call) {
2275 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2276 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00002277 if ((*Param)->hasUnparsedDefaultArg())
2278 return Diag((*Param)->getLocation(),
2279 diag::err_operator_overload_default_arg)
2280 << FnDecl->getDeclName();
2281 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002282 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002283 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002284 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002285 }
2286 }
2287
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002288 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2289 { false, false, false }
2290#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2291 , { Unary, Binary, MemberOnly }
2292#include "clang/Basic/OperatorKinds.def"
2293 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002294
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002295 bool CanBeUnaryOperator = OperatorUses[Op][0];
2296 bool CanBeBinaryOperator = OperatorUses[Op][1];
2297 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002298
2299 // C++ [over.oper]p8:
2300 // [...] Operator functions cannot have more or fewer parameters
2301 // than the number required for the corresponding operator, as
2302 // described in the rest of this subclause.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002303 unsigned NumParams = FnDecl->getNumParams()
2304 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002305 if (Op != OO_Call &&
2306 ((NumParams == 1 && !CanBeUnaryOperator) ||
2307 (NumParams == 2 && !CanBeBinaryOperator) ||
2308 (NumParams < 1) || (NumParams > 2))) {
2309 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00002310 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002311 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00002312 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002313 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00002314 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002315 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00002316 assert(CanBeBinaryOperator &&
2317 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00002318 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002319 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002320
Chris Lattner416e46f2008-11-21 07:57:12 +00002321 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002322 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002323 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002324
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002325 // Overloaded operators other than operator() cannot be variadic.
2326 if (Op != OO_Call &&
Douglas Gregor72564e72009-02-26 23:50:07 +00002327 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002328 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002329 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002330 }
2331
2332 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002333 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2334 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002335 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002336 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002337 }
2338
2339 // C++ [over.inc]p1:
2340 // The user-defined function called operator++ implements the
2341 // prefix and postfix ++ operator. If this function is a member
2342 // function with no parameters, or a non-member function with one
2343 // parameter of class or enumeration type, it defines the prefix
2344 // increment operator ++ for objects of that type. If the function
2345 // is a member function with one parameter (which shall be of type
2346 // int) or a non-member function with two parameters (the second
2347 // of which shall be of type int), it defines the postfix
2348 // increment operator ++ for objects of that type.
2349 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2350 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2351 bool ParamIsInt = false;
2352 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2353 ParamIsInt = BT->getKind() == BuiltinType::Int;
2354
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00002355 if (!ParamIsInt)
2356 return Diag(LastParam->getLocation(),
2357 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00002358 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002359 }
2360
Sebastian Redl64b45f72009-01-05 20:52:13 +00002361 // Notify the class if it got an assignment operator.
2362 if (Op == OO_Equal) {
2363 // Would have returned earlier otherwise.
2364 assert(isa<CXXMethodDecl>(FnDecl) &&
2365 "Overloaded = not member, but not filtered.");
2366 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2367 Method->getParent()->addedAssignmentOperator(Context, Method);
2368 }
2369
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002370 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002371}
Chris Lattner5a003a42008-12-17 07:09:26 +00002372
Douglas Gregor074149e2009-01-05 19:45:36 +00002373/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2374/// linkage specification, including the language and (if present)
2375/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2376/// the location of the language string literal, which is provided
2377/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2378/// the '{' brace. Otherwise, this linkage specification does not
2379/// have any braces.
2380Sema::DeclTy *Sema::ActOnStartLinkageSpecification(Scope *S,
2381 SourceLocation ExternLoc,
2382 SourceLocation LangLoc,
2383 const char *Lang,
2384 unsigned StrSize,
2385 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00002386 LinkageSpecDecl::LanguageIDs Language;
2387 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2388 Language = LinkageSpecDecl::lang_c;
2389 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2390 Language = LinkageSpecDecl::lang_cxx;
2391 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00002392 Diag(LangLoc, diag::err_bad_language);
Chris Lattnercc98eac2008-12-17 07:13:27 +00002393 return 0;
2394 }
2395
2396 // FIXME: Add all the various semantics of linkage specifications
2397
Douglas Gregor074149e2009-01-05 19:45:36 +00002398 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2399 LangLoc, Language,
2400 LBraceLoc.isValid());
Douglas Gregor482b77d2009-01-12 23:27:07 +00002401 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00002402 PushDeclContext(S, D);
2403 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00002404}
2405
Douglas Gregor074149e2009-01-05 19:45:36 +00002406/// ActOnFinishLinkageSpecification - Completely the definition of
2407/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2408/// valid, it's the position of the closing '}' brace in a linkage
2409/// specification that uses braces.
2410Sema::DeclTy *Sema::ActOnFinishLinkageSpecification(Scope *S,
2411 DeclTy *LinkageSpec,
2412 SourceLocation RBraceLoc) {
2413 if (LinkageSpec)
2414 PopDeclContext();
2415 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00002416}
2417
Sebastian Redl4b07b292008-12-22 19:15:10 +00002418/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2419/// handler.
2420Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D)
2421{
2422 QualType ExDeclType = GetTypeForDeclarator(D, S);
2423 SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin();
2424
2425 bool Invalid = false;
2426
2427 // Arrays and functions decay.
2428 if (ExDeclType->isArrayType())
2429 ExDeclType = Context.getArrayDecayedType(ExDeclType);
2430 else if (ExDeclType->isFunctionType())
2431 ExDeclType = Context.getPointerType(ExDeclType);
2432
2433 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2434 // The exception-declaration shall not denote a pointer or reference to an
2435 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002436 // N2844 forbids rvalue references.
2437 if(ExDeclType->isRValueReferenceType()) {
2438 Diag(Begin, diag::err_catch_rvalue_ref) << D.getSourceRange();
2439 Invalid = true;
2440 }
Sebastian Redl4b07b292008-12-22 19:15:10 +00002441 QualType BaseType = ExDeclType;
2442 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002443 unsigned DK = diag::err_catch_incomplete;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002444 if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2445 BaseType = Ptr->getPointeeType();
2446 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002447 DK = diag::err_catch_incomplete_ptr;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002448 } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002449 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00002450 BaseType = Ref->getPointeeType();
2451 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002452 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002453 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002454 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor86447ec2009-03-09 16:13:40 +00002455 RequireCompleteType(Begin, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00002456 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002457
Sebastian Redl8351da02008-12-22 21:35:02 +00002458 // FIXME: Need to test for ability to copy-construct and destroy the
2459 // exception variable.
2460 // FIXME: Need to check for abstract classes.
2461
Sebastian Redl4b07b292008-12-22 19:15:10 +00002462 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002463 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002464 // The scope should be freshly made just for us. There is just no way
2465 // it contains any previous declaration.
2466 assert(!S->isDeclScope(PrevDecl));
2467 if (PrevDecl->isTemplateParameter()) {
2468 // Maybe we will complain about the shadowed template parameter.
2469 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2470
2471 }
2472 }
2473
2474 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002475 II, ExDeclType, VarDecl::None, Begin);
Sebastian Redl4b07b292008-12-22 19:15:10 +00002476 if (D.getInvalidType() || Invalid)
2477 ExDecl->setInvalidDecl();
2478
2479 if (D.getCXXScopeSpec().isSet()) {
2480 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2481 << D.getCXXScopeSpec().getRange();
2482 ExDecl->setInvalidDecl();
2483 }
2484
2485 // Add the exception declaration into this scope.
2486 S->AddDecl(ExDecl);
2487 if (II)
2488 IdResolver.AddDecl(ExDecl);
2489
2490 ProcessDeclAttributes(ExDecl, D);
2491 return ExDecl;
2492}
Anders Carlssonfb311762009-03-14 00:25:26 +00002493
2494Sema::DeclTy *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
2495 ExprArg assertexpr,
Anders Carlsson94b15fb2009-03-15 18:44:04 +00002496 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00002497 Expr *AssertExpr = (Expr *)assertexpr.get();
2498 StringLiteral *AssertMessage =
2499 cast<StringLiteral>((Expr *)assertmessageexpr.get());
2500
Anders Carlssonc3082412009-03-14 00:33:21 +00002501 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
2502 llvm::APSInt Value(32);
2503 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
2504 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
2505 AssertExpr->getSourceRange();
2506 return 0;
2507 }
Anders Carlssonfb311762009-03-14 00:25:26 +00002508
Anders Carlssonc3082412009-03-14 00:33:21 +00002509 if (Value == 0) {
2510 std::string str(AssertMessage->getStrData(),
2511 AssertMessage->getByteLength());
Anders Carlsson94b15fb2009-03-15 18:44:04 +00002512 Diag(AssertLoc, diag::err_static_assert_failed)
2513 << str << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00002514 }
2515 }
2516
Anders Carlsson77d81422009-03-15 17:35:16 +00002517 assertexpr.release();
2518 assertmessageexpr.release();
Anders Carlssonfb311762009-03-14 00:25:26 +00002519 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
2520 AssertExpr, AssertMessage);
Anders Carlssonfb311762009-03-14 00:25:26 +00002521
2522 CurContext->addDecl(Decl);
2523 return Decl;
2524}
Sebastian Redl50de12f2009-03-24 22:27:57 +00002525
2526void Sema::SetDeclDeleted(DeclTy *dcl, SourceLocation DelLoc) {
2527 Decl *Dcl = static_cast<Decl*>(dcl);
2528 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
2529 if (!Fn) {
2530 Diag(DelLoc, diag::err_deleted_non_function);
2531 return;
2532 }
2533 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
2534 Diag(DelLoc, diag::err_deleted_decl_not_first);
2535 Diag(Prev->getLocation(), diag::note_previous_declaration);
2536 // If the declaration wasn't the first, we delete the function anyway for
2537 // recovery.
2538 }
2539 Fn->setDeleted();
2540}