blob: 2253f093df099c5212e6b8d2fe9669cef30f76ae [file] [log] [blame]
Chris Lattner697e5d62006-11-09 06:32:27 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner697e5d62006-11-09 06:32:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnere168f762006-11-10 05:29:30 +000014#include "Sema.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Anders Carlsson7a241ba2008-07-03 04:20:39 +000017#include "clang/AST/APValue.h"
Chris Lattner622c1932008-02-06 00:51:33 +000018#include "clang/AST/ASTConsumer.h"
Chris Lattner5c5fbcc2006-12-03 08:41:30 +000019#include "clang/AST/ASTContext.h"
Mike Stump33979f72009-07-22 23:56:57 +000020#include "clang/Analysis/CFG.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000021#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Chris Lattner2c6fcf52008-06-26 18:38:35 +000024#include "clang/AST/ExprCXX.h"
Sebastian Redla7b98a72009-04-26 20:35:05 +000025#include "clang/AST/StmtCXX.h"
Mike Stump671cc002009-07-23 00:20:25 +000026#include "clang/AST/StmtObjC.h"
Chris Lattner591a6752006-11-19 23:16:18 +000027#include "clang/Parse/DeclSpec.h"
Douglas Gregor15e56022009-10-13 23:27:22 +000028#include "clang/Parse/ParseDiagnostic.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000029#include "clang/Parse/Template.h"
Anders Carlssond624e162009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Steve Naroffe101f952008-01-30 23:46:05 +000031#include "clang/Basic/SourceManager.h"
Anders Carlssond624e162009-08-26 23:45:07 +000032#include "clang/Basic/TargetInfo.h"
Steve Naroffe101f952008-01-30 23:46:05 +000033// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner622c1932008-02-06 00:51:33 +000034#include "clang/Lex/Preprocessor.h"
Mike Stump11289f42009-09-09 15:08:12 +000035#include "clang/Lex/HeaderSearch.h"
Daniel Dunbara2f7c952009-07-23 05:01:54 +000036#include "llvm/ADT/BitVector.h"
Douglas Gregor7a4fad12008-12-11 20:41:00 +000037#include "llvm/ADT/STLExtras.h"
John McCall0e21fcc2009-12-24 09:58:38 +000038#include "llvm/ADT/Triple.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000039#include <algorithm>
Douglas Gregor56fbc372009-09-28 21:14:19 +000040#include <cstring>
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000041#include <functional>
Mike Stump33979f72009-07-22 23:56:57 +000042#include <queue>
Chris Lattner697e5d62006-11-09 06:32:27 +000043using namespace clang;
44
Chris Lattner03b53942009-03-05 01:25:28 +000045/// getDeclName - Return a pretty name for the specified decl if possible, or
Mike Stump11289f42009-09-09 15:08:12 +000046/// an empty string if not. This is used for pretty crash reporting.
Chris Lattner83f095c2009-03-28 19:18:32 +000047std::string Sema::getDeclName(DeclPtrTy d) {
48 Decl *D = d.getAs<Decl>();
Chris Lattner03b53942009-03-05 01:25:28 +000049 if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
50 return DN->getQualifiedNameAsString();
51 return "";
52}
53
Chris Lattner5bbb3c82009-03-29 16:50:03 +000054Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
55 return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
56}
57
Douglas Gregorec6e1892009-02-04 19:16:12 +000058/// \brief If the identifier refers to a type name within this scope,
59/// return the declaration of that type.
60///
61/// This routine performs ordinary name lookup of the identifier II
62/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor9817f4a2009-02-09 15:09:02 +000063/// determine whether the name refers to a type. If so, returns an
64/// opaque pointer (actually a QualType) corresponding to that
65/// type. Otherwise, returns NULL.
Douglas Gregorec6e1892009-02-04 19:16:12 +000066///
67/// If name lookup results in an ambiguity, this routine will complain
68/// and then return NULL.
Douglas Gregor9817f4a2009-02-09 15:09:02 +000069Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
Douglas Gregor5e0962f2009-08-26 18:27:52 +000070 Scope *S, const CXXScopeSpec *SS,
Douglas Gregora25d65d2009-11-20 22:03:38 +000071 bool isClassName,
72 TypeTy *ObjectTypePtr) {
73 // Determine where we will perform name lookup.
74 DeclContext *LookupCtx = 0;
75 if (ObjectTypePtr) {
76 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
77 if (ObjectType->isRecordType())
78 LookupCtx = computeDeclContext(ObjectType);
79 } else if (SS && SS->isSet()) {
80 LookupCtx = computeDeclContext(*SS, false);
81
82 if (!LookupCtx) {
83 if (isDependentScopeSpecifier(*SS)) {
84 // C++ [temp.res]p3:
85 // A qualified-id that refers to a type and in which the
86 // nested-name-specifier depends on a template-parameter (14.6.2)
87 // shall be prefixed by the keyword typename to indicate that the
88 // qualified-id denotes a type, forming an
89 // elaborated-type-specifier (7.1.5.3).
90 //
91 // We therefore do not perform any name lookup if the result would
92 // refer to a member of an unknown specialization.
93 if (!isClassName)
94 return 0;
95
96 // We know from the grammar that this name refers to a type, so build a
97 // TypenameType node to describe the type.
98 // FIXME: Record somewhere that this TypenameType node has no "typename"
99 // keyword associated with it.
100 return CheckTypenameType((NestedNameSpecifier *)SS->getScopeRep(),
101 II, SS->getRange()).getAsOpaquePtr();
102 }
103
Douglas Gregor5e0962f2009-08-26 18:27:52 +0000104 return 0;
Douglas Gregora25d65d2009-11-20 22:03:38 +0000105 }
106
107 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
108 return 0;
Douglas Gregor5e0962f2009-08-26 18:27:52 +0000109 }
Eli Friedman9025ec22009-12-21 01:42:38 +0000110
111 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
112 // lookup for class-names.
113 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
114 LookupOrdinaryName;
115 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000116 if (LookupCtx) {
117 // Perform "qualified" name lookup into the declaration context we
118 // computed, which is either the type of the base of a member access
119 // expression or the declaration context associated with a prior
120 // nested-name-specifier.
121 LookupQualifiedName(Result, LookupCtx);
Douglas Gregorc9f9b862009-05-11 19:58:34 +0000122
Douglas Gregora25d65d2009-11-20 22:03:38 +0000123 if (ObjectTypePtr && Result.empty()) {
124 // C++ [basic.lookup.classref]p3:
125 // If the unqualified-id is ~type-name, the type-name is looked up
126 // in the context of the entire postfix-expression. If the type T of
127 // the object expression is of a class type C, the type-name is also
128 // looked up in the scope of class C. At least one of the lookups shall
129 // find a name that refers to (possibly cv-qualified) T.
130 LookupName(Result, S);
131 }
132 } else {
133 // Perform unqualified name lookup.
134 LookupName(Result, S);
135 }
136
Chris Lattnera3778332009-02-16 22:07:16 +0000137 NamedDecl *IIDecl = 0;
John McCall27b18f82009-11-17 02:14:36 +0000138 switch (Result.getResultKind()) {
Chris Lattnera3778332009-02-16 22:07:16 +0000139 case LookupResult::NotFound:
140 case LookupResult::FoundOverloaded:
John McCalle61f2ba2009-11-18 02:36:19 +0000141 case LookupResult::FoundUnresolvedValue:
Chris Lattnera3778332009-02-16 22:07:16 +0000142 return 0;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000143
Chris Lattnere40853a2009-10-25 22:09:09 +0000144 case LookupResult::Ambiguous:
John McCall6538c932009-10-10 05:48:19 +0000145 // Recover from type-hiding ambiguities by hiding the type. We'll
146 // do the lookup again when looking for an object, and we can
147 // diagnose the error then. If we don't do this, then the error
148 // about hiding the type will be immediately followed by an error
149 // that only makes sense if the identifier was treated like a type.
John McCall27b18f82009-11-17 02:14:36 +0000150 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
151 Result.suppressDiagnostics();
John McCall6538c932009-10-10 05:48:19 +0000152 return 0;
John McCall27b18f82009-11-17 02:14:36 +0000153 }
John McCall6538c932009-10-10 05:48:19 +0000154
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000155 // Look to see if we have a type anywhere in the list of results.
156 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
157 Res != ResEnd; ++Res) {
158 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump11289f42009-09-09 15:08:12 +0000159 if (!IIDecl ||
160 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor712a3512009-04-13 15:14:38 +0000161 IIDecl->getLocation().getRawEncoding())
162 IIDecl = *Res;
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000163 }
164 }
165
166 if (!IIDecl) {
167 // None of the entities we found is a type, so there is no way
168 // to even assume that the result is a type. In this case, don't
169 // complain about the ambiguity. The parser will either try to
170 // perform this lookup again (e.g., as an object name), which
171 // will produce the ambiguity, or will complain that it expected
172 // a type name.
John McCall27b18f82009-11-17 02:14:36 +0000173 Result.suppressDiagnostics();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000174 return 0;
175 }
176
177 // We found a type within the ambiguous lookup; diagnose the
178 // ambiguity and then return that type. This might be the right
179 // answer, or it might not be, but it suppresses any attempt to
180 // perform the name lookup again.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000181 break;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000182
Chris Lattnera3778332009-02-16 22:07:16 +0000183 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +0000184 IIDecl = Result.getFoundDecl();
Chris Lattnera3778332009-02-16 22:07:16 +0000185 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000186 }
187
Chris Lattner17e15f12009-10-25 17:16:46 +0000188 assert(IIDecl && "Didn't find decl");
John McCall28a6aea2009-11-04 02:18:39 +0000189
Chris Lattner17e15f12009-10-25 17:16:46 +0000190 QualType T;
191 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall28a6aea2009-11-04 02:18:39 +0000192 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCall27b18f82009-11-17 02:14:36 +0000193
Chris Lattner17e15f12009-10-25 17:16:46 +0000194 // C++ [temp.local]p2:
195 // Within the scope of a class template specialization or
196 // partial specialization, when the injected-class-name is
197 // not followed by a <, it is equivalent to the
198 // injected-class-name followed by the template-argument s
199 // of the class template specialization or partial
200 // specialization enclosed in <>.
201 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD))
202 if (RD->isInjectedClassName())
203 if (ClassTemplateDecl *Template = RD->getDescribedClassTemplate())
204 T = Template->getInjectedClassNameType(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000205
Chris Lattner17e15f12009-10-25 17:16:46 +0000206 if (T.isNull())
207 T = Context.getTypeDeclType(TD);
208
Douglas Gregore177b722009-03-19 00:39:20 +0000209 if (SS)
210 T = getQualifiedNameType(*SS, T);
Chris Lattner17e15f12009-10-25 17:16:46 +0000211
212 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Chris Lattner17e15f12009-10-25 17:16:46 +0000213 T = Context.getObjCInterfaceType(IDecl);
John McCalle61f2ba2009-11-18 02:36:19 +0000214 } else if (UnresolvedUsingTypenameDecl *UUDecl =
215 dyn_cast<UnresolvedUsingTypenameDecl>(IIDecl)) {
216 // FIXME: preserve source structure information.
217 T = Context.getTypenameType(UUDecl->getTargetNestedNameSpecifier(), &II);
John McCall27b18f82009-11-17 02:14:36 +0000218 } else {
219 // If it's not plausibly a type, suppress diagnostics.
220 Result.suppressDiagnostics();
Chris Lattner17e15f12009-10-25 17:16:46 +0000221 return 0;
John McCall27b18f82009-11-17 02:14:36 +0000222 }
Douglas Gregor52537682009-03-19 00:18:19 +0000223
Chris Lattner17e15f12009-10-25 17:16:46 +0000224 return T.getAsOpaquePtr();
Chris Lattnere168f762006-11-10 05:29:30 +0000225}
226
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000227/// isTagName() - This method is called *for error recovery purposes only*
228/// to determine if the specified name is a valid tag name ("struct foo"). If
229/// so, this returns the TST for the tag corresponding to it (TST_enum,
230/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
231/// where the user forgot to specify the tag.
232DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
233 // Do a tag name lookup in this scope.
John McCall27b18f82009-11-17 02:14:36 +0000234 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
235 LookupName(R, S, false);
236 R.suppressDiagnostics();
237 if (R.getResultKind() == LookupResult::Found)
John McCall67c00872009-12-02 08:25:40 +0000238 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000239 switch (TD->getTagKind()) {
240 case TagDecl::TK_struct: return DeclSpec::TST_struct;
241 case TagDecl::TK_union: return DeclSpec::TST_union;
242 case TagDecl::TK_class: return DeclSpec::TST_class;
243 case TagDecl::TK_enum: return DeclSpec::TST_enum;
244 }
245 }
Mike Stump11289f42009-09-09 15:08:12 +0000246
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000247 return DeclSpec::TST_unspecified;
248}
249
Douglas Gregor15e56022009-10-13 23:27:22 +0000250bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
251 SourceLocation IILoc,
252 Scope *S,
253 const CXXScopeSpec *SS,
254 TypeTy *&SuggestedType) {
255 // We don't have anything to suggest (yet).
256 SuggestedType = 0;
257
Douglas Gregor2d435302009-12-30 17:04:44 +0000258 // There may have been a typo in the name of the type. Look up typo
259 // results, in case we have something that we can suggest.
260 LookupResult Lookup(*this, &II, IILoc, LookupOrdinaryName,
261 NotForRedeclaration);
262
263 // FIXME: It would be nice if we could correct for typos in built-in
264 // names, such as "itn" for "int".
265
266 if (CorrectTypo(Lookup, S, SS) && Lookup.isSingleResult()) {
267 NamedDecl *Result = Lookup.getAsSingle<NamedDecl>();
268 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
269 !Result->isInvalidDecl()) {
270 // We found a similarly-named type or interface; suggest that.
271 if (!SS || !SS->isSet())
272 Diag(IILoc, diag::err_unknown_typename_suggest)
273 << &II << Lookup.getLookupName()
274 << CodeModificationHint::CreateReplacement(SourceRange(IILoc),
275 Result->getNameAsString());
276 else if (DeclContext *DC = computeDeclContext(*SS, false))
277 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
278 << &II << DC << Lookup.getLookupName() << SS->getRange()
279 << CodeModificationHint::CreateReplacement(SourceRange(IILoc),
280 Result->getNameAsString());
281 else
282 llvm_unreachable("could not have corrected a typo here");
283
284 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS);
285 return true;
286 }
287 }
288
Douglas Gregor15e56022009-10-13 23:27:22 +0000289 // FIXME: Should we move the logic that tries to recover from a missing tag
290 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
291
Douglas Gregor2d435302009-12-30 17:04:44 +0000292 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Douglas Gregor15e56022009-10-13 23:27:22 +0000293 Diag(IILoc, diag::err_unknown_typename) << &II;
294 else if (DeclContext *DC = computeDeclContext(*SS, false))
295 Diag(IILoc, diag::err_typename_nested_not_found)
296 << &II << DC << SS->getRange();
297 else if (isDependentScopeSpecifier(*SS)) {
298 Diag(SS->getRange().getBegin(), diag::err_typename_missing)
Daniel Dunbar07d07852009-10-18 21:17:35 +0000299 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000300 << SourceRange(SS->getRange().getBegin(), IILoc)
301 << CodeModificationHint::CreateInsertion(SS->getRange().getBegin(),
302 "typename ");
303 SuggestedType = ActOnTypenameType(SourceLocation(), *SS, II, IILoc).get();
304 } else {
305 assert(SS && SS->isInvalid() &&
306 "Invalid scope specifier has already been diagnosed");
307 }
308
309 return true;
310}
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000311
John McCall5ed6e8f2009-08-18 00:00:49 +0000312// Determines the context to return to after temporarily entering a
313// context. This depends in an unnecessarily complicated way on the
314// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000315DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000316
John McCall5ed6e8f2009-08-18 00:00:49 +0000317 // Functions defined inline within classes aren't parsed until we've
318 // finished parsing the top-level class, so the top-level class is
319 // the context we'll need to return to.
320 if (isa<FunctionDecl>(DC)) {
321 DC = DC->getLexicalParent();
322
323 // A function not defined within a class will always return to its
324 // lexical context.
325 if (!isa<CXXRecordDecl>(DC))
326 return DC;
327
328 // A C++ inline method/friend is parsed *after* the topmost class
329 // it was declared in is fully parsed ("complete"); the topmost
330 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000331 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000332 DC = RD;
333
334 // Return the declaration context of the topmost class the inline method is
335 // declared in.
336 return DC;
337 }
338
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000339 if (isa<ObjCMethodDecl>(DC))
340 return Context.getTranslationUnitDecl();
341
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000342 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000343}
344
Douglas Gregor91f84212008-12-11 16:49:14 +0000345void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000346 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000347 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000348 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000349 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000350}
351
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000352void Sema::PopDeclContext() {
353 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000354
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000355 CurContext = getContainingDC(CurContext);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000356}
357
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000358/// EnterDeclaratorContext - Used when we must lookup names in the context
359/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000360///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000361void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000362 // C++0x [basic.lookup.unqual]p13:
363 // A name used in the definition of a static data member of class
364 // X (after the qualified-id of the static member) is looked up as
365 // if the name was used in a member function of X.
366 // C++0x [basic.lookup.unqual]p14:
367 // If a variable member of a namespace is defined outside of the
368 // scope of its namespace then any name used in the definition of
369 // the variable member (after the declarator-id) is looked up as
370 // if the definition of the variable member occurred in its
371 // namespace.
372 // Both of these imply that we should push a scope whose context
373 // is the semantic context of the declaration. We can't use
374 // PushDeclContext here because that context is not necessarily
375 // lexically contained in the current context. Fortunately,
376 // the containing scope should have the appropriate information.
377
378 assert(!S->getEntity() && "scope already has entity");
379
380#ifndef NDEBUG
381 Scope *Ancestor = S->getParent();
382 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
383 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
384#endif
385
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000386 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000387 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000388}
389
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000390void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000391 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000392
John McCall6df5fef2009-12-19 10:49:29 +0000393 // Switch back to the lexical context. The safety of this is
394 // enforced by an assert in EnterDeclaratorContext.
395 Scope *Ancestor = S->getParent();
396 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
397 CurContext = (DeclContext*) Ancestor->getEntity();
398
399 // We don't need to do anything with the scope, which is going to
400 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000401}
402
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000403/// \brief Determine whether we allow overloading of the function
404/// PrevDecl with another declaration.
405///
406/// This routine determines whether overloading is possible, not
407/// whether some new function is actually an overload. It will return
408/// true in C++ (where we can always provide overloads) or, as an
409/// extension, in C when the previous function is already an
410/// overloaded function declaration or has the "overloadable"
411/// attribute.
John McCall1f82f242009-11-18 22:49:29 +0000412static bool AllowOverloadingOfFunction(LookupResult &Previous,
413 ASTContext &Context) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000414 if (Context.getLangOptions().CPlusPlus)
415 return true;
416
John McCall1f82f242009-11-18 22:49:29 +0000417 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000418 return true;
419
John McCall1f82f242009-11-18 22:49:29 +0000420 return (Previous.getResultKind() == LookupResult::Found
421 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000422}
423
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000424/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +0000425void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +0000426 // Move up the scope chain until we find the nearest enclosing
427 // non-transparent context. The declaration will be introduced into this
428 // scope.
Mike Stump11289f42009-09-09 15:08:12 +0000429 while (S->getEntity() &&
Douglas Gregor07665a62009-01-05 19:45:36 +0000430 ((DeclContext *)S->getEntity())->isTransparentContext())
431 S = S->getParent();
432
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000433 // Add scoped declarations into their context, so that they can be
434 // found later. Declarations without a context won't be inserted
435 // into any context.
John McCall759e32b2009-08-31 22:39:49 +0000436 if (AddToContext)
437 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000438
Douglas Gregor5ad7c542009-09-28 18:41:37 +0000439 // Out-of-line function and variable definitions should not be pushed into
440 // scope.
441 if ((isa<FunctionTemplateDecl>(D) &&
442 cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->isOutOfLine()) ||
Eli Friedman73168192009-12-08 05:40:03 +0000443 (isa<FunctionDecl>(D) &&
444 (cast<FunctionDecl>(D)->isFunctionTemplateSpecialization() ||
445 cast<FunctionDecl>(D)->isOutOfLine())) ||
Douglas Gregor5ad7c542009-09-28 18:41:37 +0000446 (isa<VarDecl>(D) && cast<VarDecl>(D)->isOutOfLine()))
447 return;
448
John McCall9f3059a2009-10-09 21:13:30 +0000449 // If this replaces anything in the current scope,
450 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
451 IEnd = IdResolver.end();
452 for (; I != IEnd; ++I) {
453 if (S->isDeclScope(DeclPtrTy::make(*I)) && D->declarationReplaces(*I)) {
454 S->RemoveDecl(DeclPtrTy::make(*I));
455 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000456
John McCall9f3059a2009-10-09 21:13:30 +0000457 // Should only need to replace one decl.
458 break;
Douglas Gregor38feed82009-04-24 02:57:34 +0000459 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000460 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000461
John McCall9f3059a2009-10-09 21:13:30 +0000462 S->AddDecl(DeclPtrTy::make(D));
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000463 IdResolver.AddDecl(D);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000464}
465
Douglas Gregor505ad492009-09-28 00:47:05 +0000466bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) {
Douglas Gregor505ad492009-09-28 00:47:05 +0000467 return IdResolver.isDeclInScope(D, Ctx, Context, S);
468}
469
John McCall1f82f242009-11-18 22:49:29 +0000470static bool isOutOfScopePreviousDeclaration(NamedDecl *,
471 DeclContext*,
472 ASTContext&);
473
474/// Filters out lookup results that don't fall within the given scope
475/// as determined by isDeclInScope.
476static void FilterLookupForScope(Sema &SemaRef, LookupResult &R,
477 DeclContext *Ctx, Scope *S,
478 bool ConsiderLinkage) {
479 LookupResult::Filter F = R.makeFilter();
480 while (F.hasNext()) {
481 NamedDecl *D = F.next();
482
483 if (SemaRef.isDeclInScope(D, Ctx, S))
484 continue;
485
486 if (ConsiderLinkage &&
487 isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context))
488 continue;
489
490 F.erase();
491 }
492
493 F.done();
494}
495
496static bool isUsingDecl(NamedDecl *D) {
497 return isa<UsingShadowDecl>(D) ||
498 isa<UnresolvedUsingTypenameDecl>(D) ||
499 isa<UnresolvedUsingValueDecl>(D);
500}
501
502/// Removes using shadow declarations from the lookup results.
503static void RemoveUsingDecls(LookupResult &R) {
504 LookupResult::Filter F = R.makeFilter();
505 while (F.hasNext())
506 if (isUsingDecl(F.next()))
507 F.erase();
508
509 F.done();
510}
511
Anders Carlsson2889e0e2009-11-07 07:18:14 +0000512static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +0000513 if (D->isUsed() || D->hasAttr<UnusedAttr>())
514 return false;
515
516 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
517 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
518 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
519 if (!RD->hasTrivialConstructor())
520 return false;
521 if (!RD->hasTrivialDestructor())
522 return false;
523 }
524 }
525 }
526
527 return (isa<VarDecl>(D) && !isa<ParmVarDecl>(D) &&
528 !isa<ImplicitParamDecl>(D) &&
Anders Carlsson2889e0e2009-11-07 07:18:14 +0000529 D->getDeclContext()->isFunctionOrMethod());
530}
531
Steve Naroffc62adb62007-10-09 22:01:59 +0000532void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000533 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000534 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +0000535 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000536
Chris Lattner302b4be2006-11-19 02:31:38 +0000537 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
538 I != E; ++I) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000539 Decl *TmpD = (*I).getAs<Decl>();
Steve Naroff9324db12007-09-13 18:10:37 +0000540 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +0000541
Douglas Gregor91f84212008-12-11 16:49:14 +0000542 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
543 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +0000544
Douglas Gregor91f84212008-12-11 16:49:14 +0000545 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +0000546
Douglas Gregor3beaf9b2009-10-08 21:35:42 +0000547 // Diagnose unused variables in this scope.
Anders Carlsson2889e0e2009-11-07 07:18:14 +0000548 if (ShouldDiagnoseUnusedDecl(D))
549 Diag(D->getLocation(), diag::warn_unused_variable) << D->getDeclName();
Douglas Gregor3beaf9b2009-10-08 21:35:42 +0000550
Douglas Gregor91f84212008-12-11 16:49:14 +0000551 // Remove this name from our lexical scope.
552 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +0000553 }
554}
555
Steve Naroff257520b2008-04-01 23:04:06 +0000556/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
557/// return 0 if one not found.
Steve Naroff257520b2008-04-01 23:04:06 +0000558ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff77892752008-04-02 18:30:49 +0000559 // The third "scope" argument is 0 since we aren't enabling lazy built-in
560 // creation from this context.
John McCall9f3059a2009-10-09 21:13:30 +0000561 NamedDecl *IDecl = LookupSingleName(TUScope, Id, LookupOrdinaryName);
Mike Stump11289f42009-09-09 15:08:12 +0000562
Steve Naroff2fc93f52008-04-02 14:35:35 +0000563 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +0000564}
565
Douglas Gregor45a33ec2009-01-12 18:45:55 +0000566/// getNonFieldDeclScope - Retrieves the innermost scope, starting
567/// from S, where a non-field would be declared. This routine copes
568/// with the difference between C and C++ scoping rules in structs and
569/// unions. For example, the following code is well-formed in C but
570/// ill-formed in C++:
571/// @code
572/// struct S6 {
573/// enum { BAR } e;
574/// };
Mike Stump11289f42009-09-09 15:08:12 +0000575///
Douglas Gregor45a33ec2009-01-12 18:45:55 +0000576/// void test_S6() {
577/// struct S6 a;
578/// a.e = BAR;
579/// }
580/// @endcode
581/// For the declaration of BAR, this routine will return a different
582/// scope. The scope S will be the scope of the unnamed enumeration
583/// within S6. In C++, this routine will return the scope associated
584/// with S6, because the enumeration's scope is a transparent
585/// context but structures can contain non-field names. In C, this
586/// routine will return the translation unit scope, since the
587/// enumeration's scope is a transparent context and structures cannot
588/// contain non-field names.
589Scope *Sema::getNonFieldDeclScope(Scope *S) {
590 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump11289f42009-09-09 15:08:12 +0000591 (S->getEntity() &&
Douglas Gregor45a33ec2009-01-12 18:45:55 +0000592 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
593 (S->isClassScope() && !getLangOptions().CPlusPlus))
594 S = S->getParent();
595 return S;
596}
597
Chris Lattner4dd27102008-05-05 22:18:14 +0000598void Sema::InitBuiltinVaListType() {
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000599 if (!Context.getBuiltinVaListType().isNull())
600 return;
Mike Stump11289f42009-09-09 15:08:12 +0000601
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000602 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
John McCall9f3059a2009-10-09 21:13:30 +0000603 NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, LookupOrdinaryName);
Steve Naroffeee59eb2007-10-18 22:17:45 +0000604 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000605 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
606}
607
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000608/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
609/// file scope. lazily create a decl for it. ForRedeclaration is true
610/// if we're creating this built-in in anticipation of redeclaring the
611/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000612NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000613 Scope *S, bool ForRedeclaration,
614 SourceLocation Loc) {
Chris Lattner9561a0b2007-01-28 08:20:04 +0000615 Builtin::ID BID = (Builtin::ID)bid;
616
Chris Lattnerff2c1872008-09-28 05:54:29 +0000617 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000618 InitBuiltinVaListType();
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000619
Chris Lattnerecd79c62009-06-14 00:45:47 +0000620 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +0000621 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +0000622 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +0000623 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +0000624 // Okay
625 break;
626
Mike Stump93246cc2009-07-28 23:57:15 +0000627 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +0000628 if (ForRedeclaration)
629 Diag(Loc, diag::err_implicit_decl_requires_stdio)
630 << Context.BuiltinInfo.GetName(BID);
631 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +0000632
Mike Stump93246cc2009-07-28 23:57:15 +0000633 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +0000634 if (ForRedeclaration)
635 Diag(Loc, diag::err_implicit_decl_requires_setjmp)
636 << Context.BuiltinInfo.GetName(BID);
637 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +0000638 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000639
640 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
641 Diag(Loc, diag::ext_implicit_lib_function_decl)
642 << Context.BuiltinInfo.GetName(BID)
643 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +0000644 if (Context.BuiltinInfo.getHeaderName(BID) &&
Chris Lattneraf73cf62009-04-16 03:59:32 +0000645 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
646 != Diagnostic::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000647 Diag(Loc, diag::note_please_include_header)
648 << Context.BuiltinInfo.getHeaderName(BID)
649 << Context.BuiltinInfo.GetName(BID);
650 }
651
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +0000652 FunctionDecl *New = FunctionDecl::Create(Context,
653 Context.getTranslationUnitDecl(),
John McCallbcd03502009-12-07 02:54:59 +0000654 Loc, II, R, /*TInfo=*/0,
Douglas Gregor739ef0c2009-02-25 16:33:18 +0000655 FunctionDecl::Extern, false,
656 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000657 New->setImplicit();
658
Chris Lattner4dd27102008-05-05 22:18:14 +0000659 // Create Decl objects for each parameter, adding them to the
660 // FunctionDecl.
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000661 if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner4dd27102008-05-05 22:18:14 +0000662 llvm::SmallVector<ParmVarDecl*, 16> Params;
663 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
664 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +0000665 FT->getArgType(i), /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000666 VarDecl::None, 0));
Jay Foad7d0479f2009-05-21 09:52:38 +0000667 New->setParams(Context, Params.data(), Params.size());
Chris Lattner4dd27102008-05-05 22:18:14 +0000668 }
Mike Stump11289f42009-09-09 15:08:12 +0000669
670 AddKnownFunctionAttributes(New);
671
Chris Lattnerc5c95b52008-04-11 07:00:53 +0000672 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +0000673 // FIXME: This is hideous. We need to teach PushOnScopeChains to
674 // relate Scopes to DeclContexts, and probably eliminate CurContext
675 // entirely, but we're not there yet.
676 DeclContext *SavedContext = CurContext;
677 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000678 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +0000679 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +0000680 return New;
681}
682
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000683/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
684/// same name and scope as a previous declaration 'Old'. Figure out
685/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000686/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +0000687///
John McCall1f82f242009-11-18 22:49:29 +0000688void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) {
689 // If the new decl is known invalid already, don't bother doing any
690 // merging checks.
691 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +0000692
Steve Naroff44cfcb62008-09-09 14:32:20 +0000693 // Allow multiple definitions for ObjC built-in typedefs.
694 // FIXME: Verify the underlying types are equivalent!
695 if (getLangOptions().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +0000696 const IdentifierInfo *TypeID = New->getIdentifier();
697 switch (TypeID->getLength()) {
698 default: break;
Mike Stump11289f42009-09-09 15:08:12 +0000699 case 2:
Chris Lattner66e32812008-11-20 05:41:43 +0000700 if (!TypeID->isStr("id"))
701 break;
David Chisnall9f57c292009-08-17 16:35:33 +0000702 Context.ObjCIdRedefinitionType = New->getUnderlyingType();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000703 // Install the built-in type for 'id', ignoring the current definition.
704 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
705 return;
Chris Lattner66e32812008-11-20 05:41:43 +0000706 case 5:
707 if (!TypeID->isStr("Class"))
708 break;
David Chisnall9f57c292009-08-17 16:35:33 +0000709 Context.ObjCClassRedefinitionType = New->getUnderlyingType();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000710 // Install the built-in type for 'Class', ignoring the current definition.
711 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000712 return;
Chris Lattner66e32812008-11-20 05:41:43 +0000713 case 3:
714 if (!TypeID->isStr("SEL"))
715 break;
Fariborz Jahanian04b258c2009-11-25 23:07:42 +0000716 Context.ObjCSelRedefinitionType = New->getUnderlyingType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000717 // Install the built-in type for 'SEL', ignoring the current definition.
718 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000719 return;
Chris Lattner66e32812008-11-20 05:41:43 +0000720 case 8:
721 if (!TypeID->isStr("Protocol"))
722 break;
Steve Naroff44cfcb62008-09-09 14:32:20 +0000723 Context.setObjCProtoType(New->getUnderlyingType());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000724 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +0000725 }
726 // Fall through - the typedef name was not a builtin type.
727 }
John McCall1f82f242009-11-18 22:49:29 +0000728
Douglas Gregorfb034662009-01-28 17:15:10 +0000729 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +0000730 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
731 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +0000732 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000733 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +0000734
735 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000736 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +0000737 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +0000738
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000739 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +0000740 }
Douglas Gregorfb034662009-01-28 17:15:10 +0000741
John McCall1f82f242009-11-18 22:49:29 +0000742 // If the old declaration is invalid, just give up here.
743 if (Old->isInvalidDecl())
744 return New->setInvalidDecl();
745
Mike Stump11289f42009-09-09 15:08:12 +0000746 // Determine the "old" type we'll use for checking and diagnostics.
Douglas Gregorfb034662009-01-28 17:15:10 +0000747 QualType OldType;
748 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
749 OldType = OldTypedef->getUnderlyingType();
750 else
751 OldType = Context.getTypeDeclType(Old);
752
Chris Lattnerf9c49e52008-07-25 18:44:27 +0000753 // If the typedef types are not identical, reject them in all languages and
754 // with any extensions enabled.
Douglas Gregorfb034662009-01-28 17:15:10 +0000755
Mike Stump11289f42009-09-09 15:08:12 +0000756 if (OldType != New->getUnderlyingType() &&
757 Context.getCanonicalType(OldType) !=
Chris Lattnerf9c49e52008-07-25 18:44:27 +0000758 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +0000759 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregorfb034662009-01-28 17:15:10 +0000760 << New->getUnderlyingType() << OldType;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000761 if (Old->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +0000762 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000763 return New->setInvalidDecl();
Chris Lattnerf9c49e52008-07-25 18:44:27 +0000764 }
Mike Stump11289f42009-09-09 15:08:12 +0000765
John McCall91f1a022009-12-30 00:31:22 +0000766 // The types match. Link up the redeclaration chain if the old
767 // declaration was a typedef.
768 // FIXME: this is a potential source of wierdness if the type
769 // spellings don't match exactly.
770 if (isa<TypedefDecl>(Old))
771 New->setPreviousDeclaration(cast<TypedefDecl>(Old));
772
Steve Naroff7cae42b2009-07-10 23:34:53 +0000773 if (getLangOptions().Microsoft)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000774 return;
Eli Friedman61b529f2008-06-11 06:20:39 +0000775
Douglas Gregor5d58c3a2008-11-21 16:29:06 +0000776 // C++ [dcl.typedef]p2:
777 // In a given non-class scope, a typedef specifier can be used to
778 // redefine the name of any type declared in that scope to refer
779 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +0000780 if (getLangOptions().CPlusPlus) {
781 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000782 return;
Chris Lattner2581fc32009-04-17 22:04:20 +0000783 Diag(New->getLocation(), diag::err_redefinition)
784 << New->getDeclName();
785 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000786 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +0000787 }
Eli Friedman61b529f2008-06-11 06:20:39 +0000788
Chris Lattner2581fc32009-04-17 22:04:20 +0000789 // If we have a redefinition of a typedef in C, emit a warning. This warning
790 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +0000791 // -Wtypedef-redefinition. If either the original or the redefinition is
792 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner9a845892009-04-27 01:46:12 +0000793 if (PP.getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +0000794 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
795 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +0000796 return;
Mike Stump11289f42009-09-09 15:08:12 +0000797
Chris Lattner2581fc32009-04-17 22:04:20 +0000798 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
799 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +0000800 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000801 return;
Chris Lattner01564d92007-01-27 19:27:06 +0000802}
803
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000804/// DeclhasAttr - returns true if decl Declaration already has the target
805/// attribute.
Mike Stump11289f42009-09-09 15:08:12 +0000806static bool
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000807DeclHasAttr(const Decl *decl, const Attr *target) {
808 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
Chris Lattner84966392008-03-03 03:28:21 +0000809 if (attr->getKind() == target->getKind())
810 return true;
811
812 return false;
813}
814
815/// MergeAttributes - append attributes from the Old decl to the New one.
Chris Lattner9a2d50e72009-03-04 06:05:19 +0000816static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000817 for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
818 if (!DeclHasAttr(New, attr) && attr->isMerged()) {
Douglas Gregor76fe50c2009-04-28 06:37:30 +0000819 Attr *NewAttr = attr->clone(C);
820 NewAttr->setInherited(true);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000821 New->addAttr(NewAttr);
Chris Lattner84966392008-03-03 03:28:21 +0000822 }
823 }
824}
825
Douglas Gregora74a2972009-03-06 22:43:54 +0000826/// Used in MergeFunctionDecl to keep track of function parameters in
827/// C.
828struct GNUCompatibleParamWarning {
829 ParmVarDecl *OldParm;
830 ParmVarDecl *NewParm;
831 QualType PromotedType;
832};
833
Anders Carlsson1f78b2b2009-12-04 22:33:25 +0000834
835/// getSpecialMember - get the special member enum for a method.
836static Sema::CXXSpecialMember getSpecialMember(ASTContext &Ctx,
837 const CXXMethodDecl *MD) {
838 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
839 if (Ctor->isDefaultConstructor())
840 return Sema::CXXDefaultConstructor;
Douglas Gregor507eb872009-12-22 00:34:07 +0000841 if (Ctor->isCopyConstructor())
Anders Carlsson1f78b2b2009-12-04 22:33:25 +0000842 return Sema::CXXCopyConstructor;
843 }
844
845 if (isa<CXXDestructorDecl>(MD))
846 return Sema::CXXDestructor;
847
848 assert(MD->isCopyAssignment() && "Must have copy assignment operator");
849 return Sema::CXXCopyAssignment;
850}
851
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000852/// MergeFunctionDecl - We just parsed a function 'New' from
853/// declarator D which has the same name and scope as a previous
854/// declaration 'Old'. Figure out how to resolve this situation,
855/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000856///
857/// In C++, New and Old must be declarations that are not
858/// overloaded. Use IsOverload to determine whether New and Old are
859/// overloaded, and to select the Old declaration that New should be
860/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000861///
862/// Returns true if there was an error, false otherwise.
863bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000864 // Verify the old decl was also a function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000865 FunctionDecl *Old = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000866 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000867 = dyn_cast<FunctionTemplateDecl>(OldD))
868 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000869 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000870 Old = dyn_cast<FunctionDecl>(OldD);
Chris Lattnerc511efb2007-01-27 19:32:14 +0000871 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +0000872 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
873 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
874 Diag(Shadow->getTargetDecl()->getLocation(),
875 diag::note_using_decl_target);
876 Diag(Shadow->getUsingDecl()->getLocation(),
877 diag::note_using_decl) << 0;
878 return true;
879 }
880
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +0000881 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000882 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +0000883 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000884 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +0000885 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000886
887 // Determine whether the previous declaration was a definition,
888 // implicit declaration, or a declaration.
889 diag::kind PrevDiag;
890 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +0000891 PrevDiag = diag::note_previous_definition;
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000892 else if (Old->isImplicit())
893 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump11289f42009-09-09 15:08:12 +0000894 else
Chris Lattner0369c572008-11-23 23:12:31 +0000895 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +0000896
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000897 QualType OldQType = Context.getCanonicalType(Old->getType());
898 QualType NewQType = Context.getCanonicalType(New->getType());
Mike Stump11289f42009-09-09 15:08:12 +0000899
Douglas Gregore62c0a42009-02-24 01:23:02 +0000900 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
901 New->getStorageClass() == FunctionDecl::Static &&
902 Old->getStorageClass() != FunctionDecl::Static) {
903 Diag(New->getLocation(), diag::err_static_non_static)
904 << New;
905 Diag(Old->getLocation(), PrevDiag);
906 return true;
907 }
908
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000909 if (getLangOptions().CPlusPlus) {
910 // (C++98 13.1p2):
911 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +0000912 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000913 // cannot be overloaded.
Mike Stump11289f42009-09-09 15:08:12 +0000914 QualType OldReturnType
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000915 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +0000916 QualType NewReturnType
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000917 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
918 if (OldReturnType != NewReturnType) {
919 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000920 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000921 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000922 }
923
924 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
925 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +0000926 if (OldMethod && NewMethod) {
927 if (!NewMethod->getFriendObjectKind() &&
928 NewMethod->getLexicalDeclContext()->isRecord()) {
929 // -- Member function declarations with the same name and the
930 // same parameter types cannot be overloaded if any of them
931 // is a static member function declaration.
932 if (OldMethod->isStatic() || NewMethod->isStatic()) {
933 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
934 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
935 return true;
936 }
937
938 // C++ [class.mem]p1:
939 // [...] A member shall not be declared twice in the
940 // member-specification, except that a nested class or member
941 // class template can be declared and then later defined.
942 unsigned NewDiag;
943 if (isa<CXXConstructorDecl>(OldMethod))
944 NewDiag = diag::err_constructor_redeclared;
945 else if (isa<CXXDestructorDecl>(NewMethod))
946 NewDiag = diag::err_destructor_redeclared;
947 else if (isa<CXXConversionDecl>(NewMethod))
948 NewDiag = diag::err_conv_function_redeclared;
949 else
950 NewDiag = diag::err_member_redeclared;
951
952 Diag(New->getLocation(), NewDiag);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000953 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Anders Carlsson1f78b2b2009-12-04 22:33:25 +0000954 } else {
955 if (OldMethod->isImplicit()) {
956 Diag(NewMethod->getLocation(),
957 diag::err_definition_of_implicitly_declared_member)
958 << New << getSpecialMember(Context, OldMethod);
959
960 Diag(OldMethod->getLocation(),
961 diag::note_previous_implicit_declaration);
962 return true;
963 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000964 }
965 }
966
967 // (C++98 8.3.5p3):
968 // All declarations for a function shall agree exactly in both the
969 // return type and the parameter-type-list.
Nuno Lopes0e7860f2009-12-23 23:40:33 +0000970 // attributes should be ignored when comparing.
971 if (Context.getNoReturnType(OldQType, false) ==
972 Context.getNoReturnType(NewQType, false))
Douglas Gregore62c0a42009-02-24 01:23:02 +0000973 return MergeCompatibleFunctionDecls(New, Old);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000974
975 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +0000976 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000977
978 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +0000979 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000980 if (!getLangOptions().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +0000981 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +0000982 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
983 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000984 const FunctionProtoType *OldProto = 0;
985 if (isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +0000986 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +0000987 // The old declaration provided a function prototype, but the
988 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +0000989 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Douglas Gregorbcbf8632009-02-16 18:20:44 +0000990 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
991 OldProto->arg_type_end());
992 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jay Foad7d0479f2009-05-21 09:52:38 +0000993 ParamTypes.data(), ParamTypes.size(),
Douglas Gregorbcbf8632009-02-16 18:20:44 +0000994 OldProto->isVariadic(),
995 OldProto->getTypeQuals());
996 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +0000997 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +0000998
999 // Synthesize a parameter for each argument type.
1000 llvm::SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00001001 for (FunctionProtoType::arg_type_iterator
1002 ParamType = OldProto->arg_type_begin(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001003 ParamEnd = OldProto->arg_type_end();
1004 ParamType != ParamEnd; ++ParamType) {
1005 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
1006 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00001007 *ParamType, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001008 VarDecl::None, 0);
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001009 Param->setImplicit();
1010 Params.push_back(Param);
1011 }
1012
Jay Foad7d0479f2009-05-21 09:52:38 +00001013 New->setParams(Context, Params.data(), Params.size());
Mike Stump11289f42009-09-09 15:08:12 +00001014 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001015
Douglas Gregore62c0a42009-02-24 01:23:02 +00001016 return MergeCompatibleFunctionDecls(New, Old);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001017 }
Chris Lattner45d561a2007-11-06 06:07:26 +00001018
Douglas Gregora74a2972009-03-06 22:43:54 +00001019 // GNU C permits a K&R definition to follow a prototype declaration
1020 // if the declared types of the parameters in the K&R definition
1021 // match the types in the prototype declaration, even when the
1022 // promoted types of the parameters from the K&R definition differ
1023 // from the types in the prototype. GCC then keeps the types from
1024 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001025 //
1026 // If a variadic prototype is followed by a non-variadic K&R definition,
1027 // the K&R definition becomes variadic. This is sort of an edge case, but
1028 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1029 // C99 6.9.1p8.
Douglas Gregora74a2972009-03-06 22:43:54 +00001030 if (!getLangOptions().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001031 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00001032 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001033 Old->getNumParams() == New->getNumParams()) {
1034 llvm::SmallVector<QualType, 16> ArgTypes;
1035 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00001036 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00001037 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001038 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00001039 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001040
Douglas Gregora74a2972009-03-06 22:43:54 +00001041 // Determine whether this is the GNU C extension.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001042 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1043 NewProto->getResultType());
1044 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00001045 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001046 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00001047 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1048 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00001049 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregora74a2972009-03-06 22:43:54 +00001050 NewProto->getArgType(Idx))) {
1051 ArgTypes.push_back(NewParm->getType());
1052 } else if (Context.typesAreCompatible(OldParm->getType(),
1053 NewParm->getType())) {
Mike Stump11289f42009-09-09 15:08:12 +00001054 GNUCompatibleParamWarning Warn
Douglas Gregora74a2972009-03-06 22:43:54 +00001055 = { OldParm, NewParm, NewProto->getArgType(Idx) };
1056 Warnings.push_back(Warn);
1057 ArgTypes.push_back(NewParm->getType());
1058 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001059 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00001060 }
1061
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001062 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00001063 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1064 Diag(Warnings[Warn].NewParm->getLocation(),
1065 diag::ext_param_promoted_not_compatible_with_prototype)
1066 << Warnings[Warn].PromotedType
1067 << Warnings[Warn].OldParm->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001068 Diag(Warnings[Warn].OldParm->getLocation(),
Douglas Gregora74a2972009-03-06 22:43:54 +00001069 diag::note_previous_declaration);
1070 }
1071
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001072 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1073 ArgTypes.size(),
1074 OldProto->isVariadic(), 0));
Douglas Gregora74a2972009-03-06 22:43:54 +00001075 return MergeCompatibleFunctionDecls(New, Old);
1076 }
1077
1078 // Fall through to diagnose conflicting types.
1079 }
1080
Steve Naroff17832a42008-01-16 15:01:34 +00001081 // A function that has already been declared has been redeclared or defined
1082 // with a different type- show appropriate diagnostic
Douglas Gregor15fc9562009-09-12 00:22:50 +00001083 if (unsigned BuiltinID = Old->getBuiltinID()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001084 // The user has declared a builtin function with an incompatible
1085 // signature.
1086 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1087 // The function the user is redeclaring is a library-defined
1088 // function like 'malloc' or 'printf'. Warn about the
Douglas Gregor893c2c92009-03-23 17:47:24 +00001089 // redeclaration, then pretend that we don't know about this
1090 // library built-in.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001091 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1092 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1093 << Old << Old->getType();
Douglas Gregor893c2c92009-03-23 17:47:24 +00001094 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1095 Old->setInvalidDecl();
1096 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001097 }
Steve Naroff17832a42008-01-16 15:01:34 +00001098
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001099 PrevDiag = diag::note_previous_builtin_declaration;
1100 }
1101
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001102 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001103 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001104 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00001105}
1106
Douglas Gregore62c0a42009-02-24 01:23:02 +00001107/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00001108/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00001109///
1110/// This routine handles the merging of attributes and other
1111/// properties of function declarations form the old declaration to
1112/// the new declaration, once we know that New is in fact a
1113/// redeclaration of Old.
1114///
1115/// \returns false
1116bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1117 // Merge the attributes
Chris Lattner9a2d50e72009-03-04 06:05:19 +00001118 MergeAttributes(New, Old, Context);
Douglas Gregore62c0a42009-02-24 01:23:02 +00001119
1120 // Merge the storage class.
Douglas Gregor299d76e2009-09-13 07:46:26 +00001121 if (Old->getStorageClass() != FunctionDecl::Extern &&
1122 Old->getStorageClass() != FunctionDecl::None)
Douglas Gregor76fe50c2009-04-28 06:37:30 +00001123 New->setStorageClass(Old->getStorageClass());
Douglas Gregore62c0a42009-02-24 01:23:02 +00001124
Douglas Gregore62c0a42009-02-24 01:23:02 +00001125 // Merge "pure" flag.
1126 if (Old->isPure())
1127 New->setPure();
1128
1129 // Merge the "deleted" flag.
1130 if (Old->isDeleted())
1131 New->setDeleted();
Mike Stump11289f42009-09-09 15:08:12 +00001132
Douglas Gregore62c0a42009-02-24 01:23:02 +00001133 if (getLangOptions().CPlusPlus)
1134 return MergeCXXFunctionDecl(New, Old);
1135
1136 return false;
1137}
1138
Chris Lattner01564d92007-01-27 19:27:06 +00001139/// MergeVarDecl - We just parsed a variable 'New' which has the same name
1140/// and scope as a previous declaration 'Old'. Figure out how to resolve this
1141/// situation, merging decls or emitting diagnostics as appropriate.
1142///
Mike Stump11289f42009-09-09 15:08:12 +00001143/// Tentative definition rules (C99 6.9.2p2) are checked by
1144/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00001145/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00001146///
John McCall1f82f242009-11-18 22:49:29 +00001147void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
1148 // If the new decl is already invalid, don't do any other checking.
1149 if (New->isInvalidDecl())
1150 return;
Mike Stump11289f42009-09-09 15:08:12 +00001151
Chris Lattnerc511efb2007-01-27 19:32:14 +00001152 // Verify the old decl was also a variable.
John McCall1f82f242009-11-18 22:49:29 +00001153 VarDecl *Old = 0;
1154 if (!Previous.isSingleResult() ||
1155 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001156 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001157 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001158 Diag(Previous.getRepresentativeDecl()->getLocation(),
1159 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001160 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001161 }
Chris Lattner84966392008-03-03 03:28:21 +00001162
Chris Lattner9a2d50e72009-03-04 06:05:19 +00001163 MergeAttributes(New, Old, Context);
Chris Lattner84966392008-03-03 03:28:21 +00001164
Eli Friedman8b7c5262009-01-24 23:49:55 +00001165 // Merge the types
Eli Friedman168fe152009-05-16 13:54:38 +00001166 QualType MergedT;
1167 if (getLangOptions().CPlusPlus) {
1168 if (Context.hasSameType(New->getType(), Old->getType()))
1169 MergedT = New->getType();
Eli Friedmane919e382009-12-10 08:54:47 +00001170 // C++ [basic.link]p10:
1171 // [...] the types specified by all declarations referring to a given
1172 // object or function shall be identical, except that declarations for an
1173 // array object can specify array types that differ by the presence or
1174 // absence of a major array bound (8.3.4).
Mike Stump11289f42009-09-09 15:08:12 +00001175 else if (Old->getType()->isIncompleteArrayType() &&
Douglas Gregor7d983672009-09-09 06:04:29 +00001176 New->getType()->isArrayType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001177 CanQual<ArrayType> OldArray
Douglas Gregor7d983672009-09-09 06:04:29 +00001178 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
Mike Stump11289f42009-09-09 15:08:12 +00001179 CanQual<ArrayType> NewArray
Douglas Gregor7d983672009-09-09 06:04:29 +00001180 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1181 if (OldArray->getElementType() == NewArray->getElementType())
1182 MergedT = New->getType();
Eli Friedmane919e382009-12-10 08:54:47 +00001183 } else if (Old->getType()->isArrayType() &&
1184 New->getType()->isIncompleteArrayType()) {
1185 CanQual<ArrayType> OldArray
1186 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1187 CanQual<ArrayType> NewArray
1188 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1189 if (OldArray->getElementType() == NewArray->getElementType())
1190 MergedT = Old->getType();
Douglas Gregor7d983672009-09-09 06:04:29 +00001191 }
Eli Friedman168fe152009-05-16 13:54:38 +00001192 } else {
1193 MergedT = Context.mergeTypes(New->getType(), Old->getType());
1194 }
Eli Friedman8b7c5262009-01-24 23:49:55 +00001195 if (MergedT.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00001196 Diag(New->getLocation(), diag::err_redefinition_different_type)
Douglas Gregor020713e2009-01-09 19:42:16 +00001197 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001198 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001199 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00001200 }
Eli Friedman8b7c5262009-01-24 23:49:55 +00001201 New->setType(MergedT);
Douglas Gregor04e9a032009-03-11 23:52:16 +00001202
Steve Naroff1e787362008-01-30 00:44:01 +00001203 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
1204 if (New->getStorageClass() == VarDecl::Static &&
Daniel Dunbar0ca16602009-04-14 02:25:56 +00001205 (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001206 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001207 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001208 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00001209 }
Mike Stump11289f42009-09-09 15:08:12 +00001210 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00001211 // For an identifier declared with the storage-class specifier
1212 // extern in a scope in which a prior declaration of that
1213 // identifier is visible,23) if the prior declaration specifies
1214 // internal or external linkage, the linkage of the identifier at
1215 // the later declaration is the same as the linkage specified at
1216 // the prior declaration. If no prior declaration is visible, or
1217 // if the prior declaration specifies no linkage, then the
1218 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00001219 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00001220 /* Okay */;
1221 else if (New->getStorageClass() != VarDecl::Static &&
1222 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001223 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001224 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001225 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00001226 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00001227
Steve Naroffa5629372008-09-17 14:05:40 +00001228 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00001229
Daniel Dunbar0ca16602009-04-14 02:25:56 +00001230 // FIXME: The test for external storage here seems wrong? We still
1231 // need to check for mismatches.
1232 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00001233 // Don't complain about out-of-line definitions of static members.
1234 !(Old->getLexicalDeclContext()->isRecord() &&
1235 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00001236 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001237 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001238 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00001239 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00001240
Eli Friedmand5c0eed2009-04-19 20:27:55 +00001241 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1242 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1243 Diag(Old->getLocation(), diag::note_previous_definition);
1244 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1245 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1246 Diag(Old->getLocation(), diag::note_previous_definition);
1247 }
1248
Douglas Gregor0760fa12009-03-10 23:43:53 +00001249 // Keep a chain of previous declarations.
1250 New->setPreviousDeclaration(Old);
Chris Lattner01564d92007-01-27 19:27:06 +00001251}
1252
Mike Stump8e79f992009-07-24 02:49:01 +00001253/// CheckFallThrough - Check that we don't fall off the end of a
1254/// Statement that should return a value.
1255///
1256/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
Mike Stump989dc732009-10-27 02:07:23 +00001257/// MaybeFallThrough iff we might or might not fall off the end,
1258/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
1259/// return. We assume NeverFallThrough iff we never fall off the end of the
1260/// statement but we may return. We assume that functions not marked noreturn
1261/// will return.
Mike Stump33979f72009-07-22 23:56:57 +00001262Sema::ControlFlowKind Sema::CheckFallThrough(Stmt *Root) {
Ted Kremenek89e53fd2009-10-20 23:48:29 +00001263 // FIXME: Eventually share this CFG object when we have other warnings based
1264 // of the CFG. This can be done using AnalysisContext.
Mike Stump33979f72009-07-22 23:56:57 +00001265 llvm::OwningPtr<CFG> cfg (CFG::buildCFG(Root, &Context));
Mike Stump11289f42009-09-09 15:08:12 +00001266
Mike Stump33979f72009-07-22 23:56:57 +00001267 // FIXME: They should never return 0, fix that, delete this code.
1268 if (cfg == 0)
Mike Stumpab8b2e02009-10-27 01:59:05 +00001269 // FIXME: This should be NeverFallThrough
1270 return NeverFallThroughOrReturn;
Mike Stump96208892009-07-23 22:40:11 +00001271 // The CFG leaves in dead things, and we don't want to dead code paths to
1272 // confuse us, so we mark all live things first.
Mike Stump33979f72009-07-22 23:56:57 +00001273 std::queue<CFGBlock*> workq;
Daniel Dunbara2f7c952009-07-23 05:01:54 +00001274 llvm::BitVector live(cfg->getNumBlockIDs());
Mike Stump33979f72009-07-22 23:56:57 +00001275 // Prep work queue
1276 workq.push(&cfg->getEntry());
1277 // Solve
1278 while (!workq.empty()) {
1279 CFGBlock *item = workq.front();
1280 workq.pop();
Daniel Dunbara2f7c952009-07-23 05:01:54 +00001281 live.set(item->getBlockID());
Mike Stump96208892009-07-23 22:40:11 +00001282 for (CFGBlock::succ_iterator I=item->succ_begin(),
1283 E=item->succ_end();
1284 I != E;
1285 ++I) {
1286 if ((*I) && !live[(*I)->getBlockID()]) {
1287 live.set((*I)->getBlockID());
1288 workq.push(*I);
Mike Stump33979f72009-07-22 23:56:57 +00001289 }
1290 }
1291 }
1292
Mike Stump96208892009-07-23 22:40:11 +00001293 // Now we know what is live, we check the live precessors of the exit block
1294 // and look for fall through paths, being careful to ignore normal returns,
1295 // and exceptional paths.
Mike Stump33979f72009-07-22 23:56:57 +00001296 bool HasLiveReturn = false;
1297 bool HasFakeEdge = false;
1298 bool HasPlainEdge = false;
Ted Kremenekf3afe1e92009-10-27 01:07:53 +00001299 for (CFGBlock::pred_iterator I=cfg->getExit().pred_begin(),
Mike Stump96208892009-07-23 22:40:11 +00001300 E = cfg->getExit().pred_end();
1301 I != E;
1302 ++I) {
1303 CFGBlock& B = **I;
1304 if (!live[B.getBlockID()])
Mike Stump33979f72009-07-22 23:56:57 +00001305 continue;
Mike Stump96208892009-07-23 22:40:11 +00001306 if (B.size() == 0) {
Mike Stump33979f72009-07-22 23:56:57 +00001307 // A labeled empty statement, or the entry block...
1308 HasPlainEdge = true;
1309 continue;
1310 }
Mike Stump96208892009-07-23 22:40:11 +00001311 Stmt *S = B[B.size()-1];
Mike Stump33979f72009-07-22 23:56:57 +00001312 if (isa<ReturnStmt>(S)) {
1313 HasLiveReturn = true;
1314 continue;
1315 }
1316 if (isa<ObjCAtThrowStmt>(S)) {
1317 HasFakeEdge = true;
1318 continue;
1319 }
1320 if (isa<CXXThrowExpr>(S)) {
1321 HasFakeEdge = true;
1322 continue;
1323 }
1324 bool NoReturnEdge = false;
Mike Stump96208892009-07-23 22:40:11 +00001325 if (CallExpr *C = dyn_cast<CallExpr>(S)) {
1326 Expr *CEE = C->getCallee()->IgnoreParenCasts();
Mike Stump8c5d7992009-07-25 21:26:53 +00001327 if (CEE->getType().getNoReturnAttr()) {
1328 NoReturnEdge = true;
1329 HasFakeEdge = true;
1330 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
Mike Stumpfeb19452009-12-15 03:11:10 +00001331 ValueDecl *VD = DRE->getDecl();
1332 if (VD->hasAttr<NoReturnAttr>()) {
1333 NoReturnEdge = true;
1334 HasFakeEdge = true;
Mike Stump33979f72009-07-22 23:56:57 +00001335 }
1336 }
Mike Stump96208892009-07-23 22:40:11 +00001337 }
1338 // FIXME: Add noreturn message sends.
Mike Stump33979f72009-07-22 23:56:57 +00001339 if (NoReturnEdge == false)
1340 HasPlainEdge = true;
1341 }
Mike Stumpab8b2e02009-10-27 01:59:05 +00001342 if (!HasPlainEdge) {
1343 if (HasLiveReturn)
1344 return NeverFallThrough;
1345 return NeverFallThroughOrReturn;
1346 }
Mike Stump96208892009-07-23 22:40:11 +00001347 if (HasFakeEdge || HasLiveReturn)
1348 return MaybeFallThrough;
1349 // This says AlwaysFallThrough for calls to functions that are not marked
1350 // noreturn, that don't return. If people would like this warning to be more
1351 // accurate, such functions should be marked as noreturn.
1352 return AlwaysFallThrough;
Mike Stump33979f72009-07-22 23:56:57 +00001353}
1354
1355/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
Mike Stump8e79f992009-07-24 02:49:01 +00001356/// function that should return a value. Check that we don't fall off the end
Mike Stump3bf1ab42009-07-28 22:04:01 +00001357/// of a noreturn function. We assume that functions and blocks not marked
1358/// noreturn will return.
Mike Stump33979f72009-07-22 23:56:57 +00001359void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body) {
Mike Stump96208892009-07-23 22:40:11 +00001360 // FIXME: Would be nice if we had a better way to control cascading errors,
1361 // but for now, avoid them. The problem is that when Parse sees:
1362 // int foo() { return a; }
1363 // The return is eaten and the Sema code sees just:
1364 // int foo() { }
1365 // which this code would then warn about.
Mike Stump33979f72009-07-22 23:56:57 +00001366 if (getDiagnostics().hasErrorOccurred())
1367 return;
Chris Lattnerc77f9892009-10-25 22:43:07 +00001368
Mike Stump8e79f992009-07-24 02:49:01 +00001369 bool ReturnsVoid = false;
1370 bool HasNoReturn = false;
1371 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor78b691a2009-10-01 23:25:31 +00001372 // If the result type of the function is a dependent type, we don't know
1373 // whether it will be void or not, so don't
1374 if (FD->getResultType()->isDependentType())
1375 return;
Mike Stump8e79f992009-07-24 02:49:01 +00001376 if (FD->getResultType()->isVoidType())
1377 ReturnsVoid = true;
1378 if (FD->hasAttr<NoReturnAttr>())
1379 HasNoReturn = true;
1380 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
1381 if (MD->getResultType()->isVoidType())
1382 ReturnsVoid = true;
1383 if (MD->hasAttr<NoReturnAttr>())
1384 HasNoReturn = true;
1385 }
Mike Stump11289f42009-09-09 15:08:12 +00001386
Mike Stumpbce7a272009-07-28 23:11:12 +00001387 // Short circuit for compilation speed.
Mike Stump8e79f992009-07-24 02:49:01 +00001388 if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function)
1389 == Diagnostic::Ignored || ReturnsVoid)
1390 && (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr)
Mike Stumpbce7a272009-07-28 23:11:12 +00001391 == Diagnostic::Ignored || !HasNoReturn)
1392 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
1393 == Diagnostic::Ignored || !ReturnsVoid))
Mike Stump33979f72009-07-22 23:56:57 +00001394 return;
Douglas Gregor78b691a2009-10-01 23:25:31 +00001395 // FIXME: Function try block
Mike Stump33979f72009-07-22 23:56:57 +00001396 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
1397 switch (CheckFallThrough(Body)) {
1398 case MaybeFallThrough:
Mike Stump8e79f992009-07-24 02:49:01 +00001399 if (HasNoReturn)
1400 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
1401 else if (!ReturnsVoid)
1402 Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function);
Mike Stump33979f72009-07-22 23:56:57 +00001403 break;
1404 case AlwaysFallThrough:
Mike Stump8e79f992009-07-24 02:49:01 +00001405 if (HasNoReturn)
1406 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
1407 else if (!ReturnsVoid)
1408 Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function);
Mike Stump33979f72009-07-22 23:56:57 +00001409 break;
Mike Stumpab8b2e02009-10-27 01:59:05 +00001410 case NeverFallThroughOrReturn:
Chris Lattnerc77f9892009-10-25 22:43:07 +00001411 if (ReturnsVoid && !HasNoReturn)
Mike Stumpbce7a272009-07-28 23:11:12 +00001412 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function);
Mike Stump33979f72009-07-22 23:56:57 +00001413 break;
Mike Stumpab8b2e02009-10-27 01:59:05 +00001414 case NeverFallThrough:
1415 break;
Mike Stump33979f72009-07-22 23:56:57 +00001416 }
1417 }
1418}
1419
Mike Stump3bf1ab42009-07-28 22:04:01 +00001420/// CheckFallThroughForBlock - Check that we don't fall off the end of a block
1421/// that should return a value. Check that we don't fall off the end of a
1422/// noreturn block. We assume that functions and blocks not marked noreturn
1423/// will return.
1424void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body) {
1425 // FIXME: Would be nice if we had a better way to control cascading errors,
1426 // but for now, avoid them. The problem is that when Parse sees:
1427 // int foo() { return a; }
1428 // The return is eaten and the Sema code sees just:
1429 // int foo() { }
1430 // which this code would then warn about.
1431 if (getDiagnostics().hasErrorOccurred())
1432 return;
1433 bool ReturnsVoid = false;
1434 bool HasNoReturn = false;
Chris Lattnerc77f9892009-10-25 22:43:07 +00001435 if (const FunctionType *FT =BlockTy->getPointeeType()->getAs<FunctionType>()){
Mike Stump3bf1ab42009-07-28 22:04:01 +00001436 if (FT->getResultType()->isVoidType())
1437 ReturnsVoid = true;
1438 if (FT->getNoReturnAttr())
1439 HasNoReturn = true;
1440 }
Mike Stump11289f42009-09-09 15:08:12 +00001441
Mike Stumpbce7a272009-07-28 23:11:12 +00001442 // Short circuit for compilation speed.
1443 if (ReturnsVoid
1444 && !HasNoReturn
1445 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
1446 == Diagnostic::Ignored || !ReturnsVoid))
Mike Stump3bf1ab42009-07-28 22:04:01 +00001447 return;
1448 // FIXME: Funtion try block
1449 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
1450 switch (CheckFallThrough(Body)) {
1451 case MaybeFallThrough:
1452 if (HasNoReturn)
1453 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
1454 else if (!ReturnsVoid)
1455 Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block);
1456 break;
1457 case AlwaysFallThrough:
1458 if (HasNoReturn)
1459 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
1460 else if (!ReturnsVoid)
1461 Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block);
1462 break;
Mike Stumpab8b2e02009-10-27 01:59:05 +00001463 case NeverFallThroughOrReturn:
Mike Stumpbce7a272009-07-28 23:11:12 +00001464 if (ReturnsVoid)
1465 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block);
Mike Stump3bf1ab42009-07-28 22:04:01 +00001466 break;
Mike Stumpab8b2e02009-10-27 01:59:05 +00001467 case NeverFallThrough:
1468 break;
Mike Stump3bf1ab42009-07-28 22:04:01 +00001469 }
1470 }
1471}
1472
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001473/// CheckParmsForFunctionDef - Check that the parameters of the given
1474/// function are appropriate for the definition of a function. This
1475/// takes care of any checks that cannot be performed on the
1476/// declaration itself, e.g., that the types of each of the function
1477/// parameters are complete.
1478bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
1479 bool HasInvalidParm = false;
1480 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1481 ParmVarDecl *Param = FD->getParamDecl(p);
1482
1483 // C99 6.7.5.3p4: the parameters in a parameter type list in a
1484 // function declarator that is part of a function definition of
1485 // that function shall not have incomplete type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00001486 //
1487 // This is also C++ [dcl.fct]p6.
Douglas Gregordd430f72009-01-19 19:26:10 +00001488 if (!Param->isInvalidDecl() &&
Douglas Gregored0cfbd2009-03-09 16:13:40 +00001489 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregordd430f72009-01-19 19:26:10 +00001490 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001491 Param->setInvalidDecl();
1492 HasInvalidParm = true;
1493 }
Mike Stump11289f42009-09-09 15:08:12 +00001494
Chris Lattner3d722972008-12-17 07:32:46 +00001495 // C99 6.9.1p5: If the declarator includes a parameter type list, the
1496 // declaration of each parameter shall include an identifier.
Mike Stump11289f42009-09-09 15:08:12 +00001497 if (Param->getIdentifier() == 0 &&
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001498 !Param->isImplicit() &&
1499 !getLangOptions().CPlusPlus)
Chris Lattner3d722972008-12-17 07:32:46 +00001500 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001501 }
1502
1503 return HasInvalidParm;
1504}
1505
Chris Lattnerb6738ec2007-01-28 00:38:24 +00001506/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1507/// no declarator (e.g. "struct foo;") is parsed.
Chris Lattner83f095c2009-03-28 19:18:32 +00001508Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Eli Friedman32e6e8e2009-04-09 21:26:42 +00001509 // FIXME: Error on auto/register at file scope
1510 // FIXME: Error on inline/virtual/explicit
Eli Friedmand5c0eed2009-04-19 20:27:55 +00001511 // FIXME: Warn on useless __thread
Eli Friedman32e6e8e2009-04-09 21:26:42 +00001512 // FIXME: Warn on useless const/volatile
1513 // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1514 // FIXME: Warn on useless attributes
John McCallc3987482009-10-07 23:34:25 +00001515 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00001516 TagDecl *Tag = 0;
1517 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1518 DS.getTypeSpecType() == DeclSpec::TST_struct ||
1519 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001520 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallc3987482009-10-07 23:34:25 +00001521 TagD = static_cast<Decl *>(DS.getTypeRep());
1522
1523 if (!TagD) // We probably had an error
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001524 return DeclPtrTy();
1525
John McCall07e91c02009-08-06 02:15:43 +00001526 // Note that the above type specs guarantee that the
1527 // type rep is a Decl, whereas in many of the others
1528 // it's a Type.
John McCallc3987482009-10-07 23:34:25 +00001529 Tag = dyn_cast<TagDecl>(TagD);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001530 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00001531
Nuno Lopese9823fa2009-12-17 11:35:26 +00001532 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1533 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
1534 // or incomplete types shall not be restrict-qualified."
1535 if (TypeQuals & DeclSpec::TQ_restrict)
1536 Diag(DS.getRestrictSpecLoc(),
1537 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
1538 << DS.getSourceRange();
1539 }
1540
Douglas Gregor3dad8422009-09-26 06:47:28 +00001541 if (DS.isFriendSpecified()) {
John McCallc3987482009-10-07 23:34:25 +00001542 // If we're dealing with a class template decl, assume that the
1543 // template routines are handling it.
1544 if (TagD && isa<ClassTemplateDecl>(TagD))
Douglas Gregor3dad8422009-09-26 06:47:28 +00001545 return DeclPtrTy();
John McCallc3987482009-10-07 23:34:25 +00001546 return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
Douglas Gregor3dad8422009-09-26 06:47:28 +00001547 }
1548
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00001549 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
Chris Lattnerecf328e2009-10-25 22:21:57 +00001550 // If there are attributes in the DeclSpec, apply them to the record.
1551 if (const AttributeList *AL = DS.getAttributes())
1552 ProcessDeclAttributeList(S, Record, AL);
1553
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00001554 if (!Record->getDeclName() && Record->isDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00001555 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1556 if (getLangOptions().CPlusPlus ||
1557 Record->getDeclContext()->isRecord())
1558 return BuildAnonymousStructOrUnion(S, DS, Record);
1559
1560 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1561 << DS.getSourceRange();
1562 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00001563
1564 // Microsoft allows unnamed struct/union fields. Don't complain
1565 // about them.
1566 // FIXME: Should we support Microsoft's extensions in this area?
1567 if (Record->getDeclName() && getLangOptions().Microsoft)
Chris Lattner83f095c2009-03-28 19:18:32 +00001568 return DeclPtrTy::make(Tag);
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00001569 }
Douglas Gregor3dad8422009-09-26 06:47:28 +00001570
Mike Stump11289f42009-09-09 15:08:12 +00001571 if (!DS.isMissingDeclaratorOk() &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001572 DS.getTypeSpecType() != DeclSpec::TST_error) {
Douglas Gregor2d9dde0e2009-01-22 16:23:54 +00001573 // Warn about typedefs of enums without names, since this is an
1574 // extension in both Microsoft an GNU.
Douglas Gregor051d8fd2009-01-17 02:55:50 +00001575 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1576 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregor2d9dde0e2009-01-22 16:23:54 +00001577 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregor2b136fe2009-01-13 23:10:51 +00001578 << DS.getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00001579 return DeclPtrTy::make(Tag);
Douglas Gregor2b136fe2009-01-13 23:10:51 +00001580 }
1581
Sebastian Redla2b5e312008-12-28 15:28:59 +00001582 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1583 << DS.getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00001584 return DeclPtrTy();
Sebastian Redla2b5e312008-12-28 15:28:59 +00001585 }
Mike Stump11289f42009-09-09 15:08:12 +00001586
Chris Lattner83f095c2009-03-28 19:18:32 +00001587 return DeclPtrTy::make(Tag);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001588}
1589
John McCallea305ed2009-12-18 10:40:03 +00001590/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00001591/// check if there's an existing declaration that can't be overloaded.
1592///
1593/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00001594static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
1595 Scope *S,
1596 DeclarationName Name,
1597 SourceLocation NameLoc,
1598 unsigned diagnostic) {
1599 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
1600 Sema::ForRedeclaration);
1601 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00001602
John McCallea305ed2009-12-18 10:40:03 +00001603 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00001604 return false;
1605
1606 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00001607 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
John McCall1f82f242009-11-18 22:49:29 +00001608
John McCallea305ed2009-12-18 10:40:03 +00001609 SemaRef.Diag(NameLoc, diagnostic) << Name;
1610 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00001611
1612 return true;
1613}
1614
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001615/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1616/// anonymous struct or union AnonRecord into the owning context Owner
1617/// and scope S. This routine will be invoked just after we realize
1618/// that an unnamed union or struct is actually an anonymous union or
1619/// struct, e.g.,
1620///
1621/// @code
1622/// union {
1623/// int i;
1624/// float f;
1625/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1626/// // f into the surrounding scope.x
1627/// @endcode
1628///
1629/// This routine is recursive, injecting the names of nested anonymous
1630/// structs/unions into the owning context and scope as well.
1631bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
1632 RecordDecl *AnonRecord) {
John McCall1f82f242009-11-18 22:49:29 +00001633 unsigned diagKind
1634 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
1635 : diag::err_anonymous_struct_member_redecl;
1636
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001637 bool Invalid = false;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001638 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
1639 FEnd = AnonRecord->field_end();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001640 F != FEnd; ++F) {
1641 if ((*F)->getDeclName()) {
John McCallea305ed2009-12-18 10:40:03 +00001642 if (CheckAnonMemberRedeclaration(*this, S, (*F)->getDeclName(),
1643 (*F)->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001644 // C++ [class.union]p2:
1645 // The names of the members of an anonymous union shall be
1646 // distinct from the names of any other entity in the
1647 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001648 Invalid = true;
1649 } else {
1650 // C++ [class.union]p2:
1651 // For the purpose of name lookup, after the anonymous union
1652 // definition, the members of the anonymous union are
1653 // considered to have been defined in the scope in which the
1654 // anonymous union is declared.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001655 Owner->makeDeclVisibleInContext(*F);
Chris Lattner83f095c2009-03-28 19:18:32 +00001656 S->AddDecl(DeclPtrTy::make(*F));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001657 IdResolver.AddDecl(*F);
1658 }
1659 } else if (const RecordType *InnerRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001660 = (*F)->getType()->getAs<RecordType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001661 RecordDecl *InnerRecord = InnerRecordType->getDecl();
1662 if (InnerRecord->isAnonymousStructOrUnion())
Mike Stump11289f42009-09-09 15:08:12 +00001663 Invalid = Invalid ||
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001664 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
1665 }
1666 }
1667
1668 return Invalid;
1669}
1670
1671/// ActOnAnonymousStructOrUnion - Handle the declaration of an
1672/// anonymous structure or union. Anonymous unions are a C++ feature
1673/// (C++ [class.union]) and a GNU C extension; anonymous structures
Mike Stump11289f42009-09-09 15:08:12 +00001674/// are a GNU C and GNU C++ extension.
Chris Lattner83f095c2009-03-28 19:18:32 +00001675Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1676 RecordDecl *Record) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001677 DeclContext *Owner = Record->getDeclContext();
1678
1679 // Diagnose whether this anonymous struct/union is an extension.
1680 if (Record->isUnion() && !getLangOptions().CPlusPlus)
1681 Diag(Record->getLocation(), diag::ext_anonymous_union);
1682 else if (!Record->isUnion())
1683 Diag(Record->getLocation(), diag::ext_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00001684
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001685 // C and C++ require different kinds of checks for anonymous
1686 // structs/unions.
1687 bool Invalid = false;
1688 if (getLangOptions().CPlusPlus) {
1689 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00001690 unsigned DiagID;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001691 // C++ [class.union]p3:
1692 // Anonymous unions declared in a named namespace or in the
1693 // global namespace shall be declared static.
1694 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1695 (isa<TranslationUnitDecl>(Owner) ||
Mike Stump11289f42009-09-09 15:08:12 +00001696 (isa<NamespaceDecl>(Owner) &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001697 cast<NamespaceDecl>(Owner)->getDeclName()))) {
1698 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1699 Invalid = true;
1700
1701 // Recover by adding 'static'.
John McCall49bfce42009-08-03 20:12:06 +00001702 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1703 PrevSpec, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +00001704 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001705 // C++ [class.union]p3:
1706 // A storage class is not allowed in a declaration of an
1707 // anonymous union in a class scope.
1708 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1709 isa<RecordDecl>(Owner)) {
Mike Stump11289f42009-09-09 15:08:12 +00001710 Diag(DS.getStorageClassSpecLoc(),
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001711 diag::err_anonymous_union_with_storage_spec);
1712 Invalid = true;
1713
1714 // Recover by removing the storage specifier.
1715 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
John McCall49bfce42009-08-03 20:12:06 +00001716 PrevSpec, DiagID);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001717 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00001718
Mike Stump11289f42009-09-09 15:08:12 +00001719 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00001720 // The member-specification of an anonymous union shall only
1721 // define non-static data members. [Note: nested types and
1722 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001723 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1724 MemEnd = Record->decls_end();
Douglas Gregorf4d33272009-01-07 19:46:03 +00001725 Mem != MemEnd; ++Mem) {
1726 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1727 // C++ [class.union]p3:
1728 // An anonymous union shall not have private or protected
1729 // members (clause 11).
1730 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
1731 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1732 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1733 Invalid = true;
1734 }
1735 } else if ((*Mem)->isImplicit()) {
1736 // Any implicit members are fine.
Douglas Gregor8761da52009-02-03 00:34:39 +00001737 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1738 // This is a type that showed up in an
1739 // elaborated-type-specifier inside the anonymous struct or
1740 // union, but which actually declares a type outside of the
1741 // anonymous struct or union. It's okay.
Douglas Gregorf4d33272009-01-07 19:46:03 +00001742 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1743 if (!MemRecord->isAnonymousStructOrUnion() &&
1744 MemRecord->getDeclName()) {
1745 // This is a nested type declaration.
1746 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1747 << (int)Record->isUnion();
1748 Invalid = true;
1749 }
1750 } else {
1751 // We have something that isn't a non-static data
1752 // member. Complain about it.
1753 unsigned DK = diag::err_anonymous_record_bad_member;
1754 if (isa<TypeDecl>(*Mem))
1755 DK = diag::err_anonymous_record_with_type;
1756 else if (isa<FunctionDecl>(*Mem))
1757 DK = diag::err_anonymous_record_with_function;
1758 else if (isa<VarDecl>(*Mem))
1759 DK = diag::err_anonymous_record_with_static;
1760 Diag((*Mem)->getLocation(), DK)
1761 << (int)Record->isUnion();
1762 Invalid = true;
1763 }
1764 }
Mike Stump11289f42009-09-09 15:08:12 +00001765 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001766
1767 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00001768 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1769 << (int)getLangOptions().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001770 Invalid = true;
1771 }
1772
John McCallfa2d6922009-10-22 23:31:08 +00001773 // Mock up a declarator.
1774 Declarator Dc(DS, Declarator::TypeNameContext);
John McCallbcd03502009-12-07 02:54:59 +00001775 TypeSourceInfo *TInfo = 0;
1776 GetTypeForDeclarator(Dc, S, &TInfo);
1777 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00001778
Mike Stump11289f42009-09-09 15:08:12 +00001779 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001780 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001781 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1782 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001783 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001784 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00001785 TInfo,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001786 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregorf4d33272009-01-07 19:46:03 +00001787 Anon->setAccess(AS_public);
1788 if (getLangOptions().CPlusPlus)
1789 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001790 } else {
1791 VarDecl::StorageClass SC;
1792 switch (DS.getStorageClassSpec()) {
1793 default: assert(0 && "Unknown storage class!");
1794 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1795 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1796 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1797 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1798 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1799 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1800 case DeclSpec::SCS_mutable:
1801 // mutable can only appear on non-static class members, so it's always
1802 // an error here
1803 Diag(Record->getLocation(), diag::err_mutable_nonmember);
1804 Invalid = true;
1805 SC = VarDecl::None;
1806 break;
1807 }
1808
1809 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001810 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001811 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00001812 TInfo,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001813 SC);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001814 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00001815 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001816
1817 // Add the anonymous struct/union object to the current
1818 // context. We'll be referencing this object when we refer to one of
1819 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001820 Owner->addDecl(Anon);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001821
1822 // Inject the members of the anonymous struct/union into the owning
1823 // context and into the identifier resolver chain for name lookup
1824 // purposes.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00001825 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1826 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001827
1828 // Mark this as an anonymous struct/union type. Note that we do not
1829 // do this until after we have already checked and injected the
1830 // members of this anonymous struct/union type, because otherwise
1831 // the members could be injected twice: once by DeclContext when it
1832 // builds its lookup table, and once by
Mike Stump11289f42009-09-09 15:08:12 +00001833 // InjectAnonymousStructOrUnionMembers.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001834 Record->setAnonymousStructOrUnion(true);
1835
1836 if (Invalid)
1837 Anon->setInvalidDecl();
1838
Chris Lattner83f095c2009-03-28 19:18:32 +00001839 return DeclPtrTy::make(Anon);
Chris Lattnerb6738ec2007-01-28 00:38:24 +00001840}
1841
Steve Naroff2fea1392007-09-02 02:04:30 +00001842
Douglas Gregor92751d42008-11-17 22:58:34 +00001843/// GetNameForDeclarator - Determine the full declaration name for the
1844/// given Declarator.
1845DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00001846 return GetNameFromUnqualifiedId(D.getName());
1847}
1848
1849/// \brief Retrieves the canonicalized name from a parsed unqualified-id.
John McCall10eae182009-11-30 22:42:35 +00001850DeclarationName Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
Douglas Gregor7861a802009-11-03 01:35:08 +00001851 switch (Name.getKind()) {
Douglas Gregora121b752009-11-03 16:56:39 +00001852 case UnqualifiedId::IK_Identifier:
1853 return DeclarationName(Name.Identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00001854
Douglas Gregora121b752009-11-03 16:56:39 +00001855 case UnqualifiedId::IK_OperatorFunctionId:
1856 return Context.DeclarationNames.getCXXOperatorName(
Alexis Hunt8818b422009-11-29 03:04:53 +00001857 Name.OperatorFunctionId.Operator);
Alexis Hunt34458502009-11-28 04:44:28 +00001858
1859 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +00001860 return Context.DeclarationNames.getCXXLiteralOperatorName(
1861 Name.Identifier);
Alexis Hunt34458502009-11-28 04:44:28 +00001862
Douglas Gregora121b752009-11-03 16:56:39 +00001863 case UnqualifiedId::IK_ConversionFunctionId: {
1864 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId);
1865 if (Ty.isNull())
1866 return DeclarationName();
Douglas Gregord90fd522009-09-25 21:45:23 +00001867
Douglas Gregora121b752009-11-03 16:56:39 +00001868 return Context.DeclarationNames.getCXXConversionFunctionName(
Alexis Hunt8818b422009-11-29 03:04:53 +00001869 Context.getCanonicalType(Ty));
Douglas Gregora121b752009-11-03 16:56:39 +00001870 }
1871
1872 case UnqualifiedId::IK_ConstructorName: {
1873 QualType Ty = GetTypeFromParser(Name.ConstructorName);
1874 if (Ty.isNull())
1875 return DeclarationName();
1876
1877 return Context.DeclarationNames.getCXXConstructorName(
Alexis Hunt8818b422009-11-29 03:04:53 +00001878 Context.getCanonicalType(Ty));
Douglas Gregora121b752009-11-03 16:56:39 +00001879 }
1880
1881 case UnqualifiedId::IK_DestructorName: {
1882 QualType Ty = GetTypeFromParser(Name.DestructorName);
1883 if (Ty.isNull())
1884 return DeclarationName();
1885
1886 return Context.DeclarationNames.getCXXDestructorName(
1887 Context.getCanonicalType(Ty));
1888 }
1889
1890 case UnqualifiedId::IK_TemplateId: {
1891 TemplateName TName
John McCalld28ae272009-12-02 08:04:21 +00001892 = TemplateName::getFromVoidPointer(Name.TemplateId->Template);
1893 return Context.getNameForTemplate(TName);
Douglas Gregora121b752009-11-03 16:56:39 +00001894 }
Douglas Gregord90fd522009-09-25 21:45:23 +00001895 }
Douglas Gregora121b752009-11-03 16:56:39 +00001896
Douglas Gregor92751d42008-11-17 22:58:34 +00001897 assert(false && "Unknown name kind");
Douglas Gregora121b752009-11-03 16:56:39 +00001898 return DeclarationName();
Douglas Gregor92751d42008-11-17 22:58:34 +00001899}
1900
Douglas Gregor8af63e42009-02-06 17:46:57 +00001901/// isNearlyMatchingFunction - Determine whether the C++ functions
1902/// Declaration and Definition are "nearly" matching. This heuristic
1903/// is used to improve diagnostics in the case where an out-of-line
1904/// function definition doesn't match any declaration within
1905/// the class or namespace.
1906static bool isNearlyMatchingFunction(ASTContext &Context,
1907 FunctionDecl *Declaration,
1908 FunctionDecl *Definition) {
Douglas Gregorad590502008-12-15 23:53:10 +00001909 if (Declaration->param_size() != Definition->param_size())
1910 return false;
1911 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1912 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1913 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1914
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001915 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
1916 DefParamTy.getNonReferenceType()))
Douglas Gregorad590502008-12-15 23:53:10 +00001917 return false;
1918 }
1919
1920 return true;
1921}
1922
Mike Stump11289f42009-09-09 15:08:12 +00001923Sema::DeclPtrTy
1924Sema::HandleDeclarator(Scope *S, Declarator &D,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00001925 MultiTemplateParamsArg TemplateParamLists,
1926 bool IsFunctionDefinition) {
Douglas Gregor92751d42008-11-17 22:58:34 +00001927 DeclarationName Name = GetNameForDeclarator(D);
1928
Chris Lattner02c04392007-07-25 00:24:17 +00001929 // All of these full declarators require an identifier. If it doesn't have
1930 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00001931 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001932 if (!D.isInvalidType()) // Reject this if we think it is valid.
Chris Lattner8c5dd732008-11-11 06:13:16 +00001933 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00001934 diag::err_declarator_need_ident)
1935 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00001936 return DeclPtrTy();
Chris Lattner02c04392007-07-25 00:24:17 +00001937 }
Mike Stump11289f42009-09-09 15:08:12 +00001938
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001939 // The scope passed in may not be a decl scope. Zip up the scope tree until
1940 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00001941 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001942 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001943 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001944
Douglas Gregor15acfb92009-08-06 16:20:37 +00001945 // If this is an out-of-line definition of a member of a class template
1946 // or class template partial specialization, we may need to rebuild the
1947 // type specifier in the declarator. See RebuildTypeInCurrentInstantiation()
1948 // for more information.
1949 // FIXME: cope with decltype(expr) and typeof(expr) once the rebuilder can
1950 // handle expressions properly.
1951 DeclSpec &DS = const_cast<DeclSpec&>(D.getDeclSpec());
1952 if (D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid() &&
1953 isDependentScopeSpecifier(D.getCXXScopeSpec()) &&
1954 (DS.getTypeSpecType() == DeclSpec::TST_typename ||
1955 DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
1956 DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
1957 DS.getTypeSpecType() == DeclSpec::TST_decltype)) {
1958 if (DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(), true)) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001959 // FIXME: Preserve type source info.
1960 QualType T = GetTypeFromParser(DS.getTypeRep());
John McCall4d6d6132009-12-19 09:35:56 +00001961
1962 DeclContext *SavedContext = CurContext;
1963 CurContext = DC;
Douglas Gregor15acfb92009-08-06 16:20:37 +00001964 T = RebuildTypeInCurrentInstantiation(T, D.getIdentifierLoc(), Name);
John McCall4d6d6132009-12-19 09:35:56 +00001965 CurContext = SavedContext;
1966
Douglas Gregor15acfb92009-08-06 16:20:37 +00001967 if (T.isNull())
1968 return DeclPtrTy();
1969 DS.UpdateTypeRep(T.getAsOpaquePtr());
1970 }
1971 }
Mike Stump11289f42009-09-09 15:08:12 +00001972
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001973 DeclContext *DC;
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001974 NamedDecl *New;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001975
John McCallbcd03502009-12-07 02:54:59 +00001976 TypeSourceInfo *TInfo = 0;
1977 QualType R = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregoreddf4332009-02-24 20:03:32 +00001978
John McCall1f82f242009-11-18 22:49:29 +00001979 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
1980 ForRedeclaration);
1981
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001982 // See if this is a redefinition of a variable in the same scope.
Douglas Gregorc2fd6262009-03-06 19:06:37 +00001983 if (D.getCXXScopeSpec().isInvalid()) {
1984 DC = CurContext;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001985 D.setInvalidType();
Douglas Gregorc2fd6262009-03-06 19:06:37 +00001986 } else if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00001987 bool IsLinkageLookup = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001988
1989 // If the declaration we're planning to build will be a function
1990 // or object with linkage, then look for another declaration with
1991 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
1992 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1993 /* Do nothing*/;
1994 else if (R->isFunctionType()) {
Douglas Gregor20749772009-07-07 17:00:05 +00001995 if (CurContext->isFunctionOrMethod() ||
1996 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00001997 IsLinkageLookup = true;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001998 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
John McCall1f82f242009-11-18 22:49:29 +00001999 IsLinkageLookup = true;
Douglas Gregor20749772009-07-07 17:00:05 +00002000 else if (CurContext->getLookupContext()->isTranslationUnit() &&
2001 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00002002 IsLinkageLookup = true;
2003
2004 if (IsLinkageLookup)
2005 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00002006
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002007 DC = CurContext;
John McCall1f82f242009-11-18 22:49:29 +00002008 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002009 } else { // Something like "int foo::x;"
Douglas Gregord8d297c2009-07-21 23:53:31 +00002010 DC = computeDeclContext(D.getCXXScopeSpec(), true);
Mike Stump11289f42009-09-09 15:08:12 +00002011
Douglas Gregor053f6912009-08-26 00:04:55 +00002012 if (!DC) {
2013 // If we could not compute the declaration context, it's because the
2014 // declaration context is dependent but does not refer to a class,
2015 // class template, or class template partial specialization. Complain
2016 // and return early, to avoid the coming semantic disaster.
Mike Stump11289f42009-09-09 15:08:12 +00002017 Diag(D.getIdentifierLoc(),
Douglas Gregor053f6912009-08-26 00:04:55 +00002018 diag::err_template_qualified_declarator_no_match)
2019 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
2020 << D.getCXXScopeSpec().getRange();
2021 return DeclPtrTy();
2022 }
Mike Stump11289f42009-09-09 15:08:12 +00002023
Douglas Gregorcf915552009-10-13 16:30:37 +00002024 if (!DC->isDependentContext() &&
2025 RequireCompleteDeclContext(D.getCXXScopeSpec()))
2026 return DeclPtrTy();
2027
John McCall1f82f242009-11-18 22:49:29 +00002028 LookupQualifiedName(Previous, DC);
2029
2030 // Don't consider using declarations as previous declarations for
2031 // out-of-line members.
2032 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002033
2034 // C++ 7.3.1.2p2:
2035 // Members (including explicit specializations of templates) of a named
2036 // namespace can also be defined outside that namespace by explicit
2037 // qualification of the name being defined, provided that the entity being
2038 // defined was already declared in the namespace and the definition appears
2039 // after the point of declaration in a namespace that encloses the
2040 // declarations namespace.
2041 //
Douglas Gregorad590502008-12-15 23:53:10 +00002042 // Note that we only check the context at this point. We don't yet
2043 // have enough information to make sure that PrevDecl is actually
2044 // the declaration we want to match. For example, given:
2045 //
Douglas Gregor4287b372008-12-12 08:25:50 +00002046 // class X {
2047 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00002048 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00002049 // };
2050 //
Douglas Gregorad590502008-12-15 23:53:10 +00002051 // void X::f(int) { } // ill-formed
2052 //
2053 // In this case, PrevDecl will point to the overload set
2054 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00002055 // matches.
Douglas Gregor8af63e42009-02-06 17:46:57 +00002056
2057 // First check whether we named the global scope.
2058 if (isa<TranslationUnitDecl>(DC)) {
Mike Stump11289f42009-09-09 15:08:12 +00002059 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
Douglas Gregor8af63e42009-02-06 17:46:57 +00002060 << Name << D.getCXXScopeSpec().getRange();
Sebastian Redlafb8be72009-11-08 11:36:54 +00002061 } else {
2062 DeclContext *Cur = CurContext;
2063 while (isa<LinkageSpecDecl>(Cur))
2064 Cur = Cur->getParent();
2065 if (!Cur->Encloses(DC)) {
2066 // The qualifying scope doesn't enclose the original declaration.
2067 // Emit diagnostic based on current scope.
2068 SourceLocation L = D.getIdentifierLoc();
2069 SourceRange R = D.getCXXScopeSpec().getRange();
2070 if (isa<FunctionDecl>(Cur))
2071 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
2072 else
2073 Diag(L, diag::err_invalid_declarator_scope)
2074 << Name << cast<NamedDecl>(DC) << R;
2075 D.setInvalidType();
2076 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002077 }
2078 }
2079
John McCall1f82f242009-11-18 22:49:29 +00002080 if (Previous.isSingleResult() &&
2081 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00002082 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002083 if (!D.isInvalidType())
John McCall1f82f242009-11-18 22:49:29 +00002084 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
2085 Previous.getFoundDecl()))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002086 D.setInvalidType();
Mike Stump11289f42009-09-09 15:08:12 +00002087
Douglas Gregor5101c242008-12-05 18:15:24 +00002088 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00002089 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00002090 }
2091
Douglas Gregor83a586e2008-04-13 21:07:44 +00002092 // In C++, the previous declaration we find might be a tag type
2093 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00002094 // tag type. Note that this does does not apply if we're declaring a
2095 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00002096 if (Previous.isSingleTagDecl() &&
Douglas Gregorfb034662009-01-28 17:15:10 +00002097 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00002098 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00002099
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002100 bool Redeclaration = false;
Chris Lattner01a7c532007-01-25 23:09:03 +00002101 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002102 if (TemplateParamLists.size()) {
2103 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
2104 return DeclPtrTy();
2105 }
Mike Stump11289f42009-09-09 15:08:12 +00002106
John McCallbcd03502009-12-07 02:54:59 +00002107 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
Douglas Gregoreddf4332009-02-24 20:03:32 +00002108 } else if (R->isFunctionType()) {
John McCallbcd03502009-12-07 02:54:59 +00002109 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002110 move(TemplateParamLists),
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002111 IsFunctionDefinition, Redeclaration);
Chris Lattner01a7c532007-01-25 23:09:03 +00002112 } else {
John McCallbcd03502009-12-07 02:54:59 +00002113 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002114 move(TemplateParamLists),
2115 Redeclaration);
Chris Lattner01a7c532007-01-25 23:09:03 +00002116 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00002117
2118 if (New == 0)
Chris Lattner83f095c2009-03-28 19:18:32 +00002119 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00002120
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002121 // If this has an identifier and is not an invalid redeclaration or
2122 // function template specialization, add it to the scope stack.
Eli Friedman73168192009-12-08 05:40:03 +00002123 if (Name && !(Redeclaration && New->isInvalidDecl()))
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00002124 PushOnScopeChains(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00002125
Chris Lattner83f095c2009-03-28 19:18:32 +00002126 return DeclPtrTy::make(New);
Chris Lattnere168f762006-11-10 05:29:30 +00002127}
2128
Eli Friedmana3b1d032009-02-21 00:44:51 +00002129/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2130/// types into constant array types in certain situations which would otherwise
2131/// be errors (for GCC compatibility).
2132static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2133 ASTContext &Context,
2134 bool &SizeIsNegative) {
2135 // This method tries to turn a variable array into a constant
2136 // array even when the size isn't an ICE. This is necessary
2137 // for compatibility with code that depends on gcc's buggy
2138 // constant expression folding, like struct {char x[(int)(char*)2];}
2139 SizeIsNegative = false;
2140
John McCall8ccfcb52009-09-24 19:53:00 +00002141 QualifierCollector Qs;
2142 const Type *Ty = Qs.strip(T);
2143
2144 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00002145 QualType Pointee = PTy->getPointeeType();
2146 QualType FixedType =
2147 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
2148 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00002149 FixedType = Context.getPointerType(FixedType);
John McCall8ccfcb52009-09-24 19:53:00 +00002150 return Qs.apply(FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00002151 }
2152
2153 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00002154 if (!VLATy)
2155 return QualType();
2156 // FIXME: We should probably handle this case
2157 if (VLATy->getElementType()->isVariablyModifiedType())
2158 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00002159
Eli Friedmana3b1d032009-02-21 00:44:51 +00002160 Expr::EvalResult EvalResult;
2161 if (!VLATy->getSizeExpr() ||
Eli Friedmanadf40d42009-02-26 03:58:54 +00002162 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
2163 !EvalResult.Val.isInt())
Eli Friedmana3b1d032009-02-21 00:44:51 +00002164 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00002165
Eli Friedmana3b1d032009-02-21 00:44:51 +00002166 llvm::APSInt &Res = EvalResult.Val.getInt();
Douglas Gregor04318252009-07-06 15:59:29 +00002167 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
John McCallc5b82252009-10-16 00:14:28 +00002168 // TODO: preserve the size expression in declarator info
2169 return Context.getConstantArrayType(VLATy->getElementType(),
2170 Res, ArrayType::Normal, 0);
Douglas Gregor04318252009-07-06 15:59:29 +00002171 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00002172
2173 SizeIsNegative = true;
2174 return QualType();
2175}
2176
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002177/// \brief Register the given locally-scoped external C declaration so
2178/// that it can be found later for redeclarations
Mike Stump11289f42009-09-09 15:08:12 +00002179void
John McCall1f82f242009-11-18 22:49:29 +00002180Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
2181 const LookupResult &Previous,
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002182 Scope *S) {
2183 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
2184 "Decl is not a locally-scoped decl!");
2185 // Note that we have a locally-scoped external with this name.
2186 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
2187
John McCall1f82f242009-11-18 22:49:29 +00002188 if (!Previous.isSingleResult())
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002189 return;
2190
John McCall1f82f242009-11-18 22:49:29 +00002191 NamedDecl *PrevDecl = Previous.getFoundDecl();
2192
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002193 // If there was a previous declaration of this variable, it may be
2194 // in our identifier chain. Update the identifier chain with the new
2195 // declaration.
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002196 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002197 // The previous declaration was found on the identifer resolver
2198 // chain, so remove it from its scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002199 while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002200 S = S->getParent();
2201
2202 if (S)
Chris Lattner83f095c2009-03-28 19:18:32 +00002203 S->RemoveDecl(DeclPtrTy::make(PrevDecl));
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002204 }
2205}
2206
Eli Friedman574c7452009-04-07 19:37:57 +00002207/// \brief Diagnose function specifiers on a declaration of an identifier that
2208/// does not identify a function.
2209void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
2210 // FIXME: We should probably indicate the identifier in question to avoid
2211 // confusion for constructs like "inline int a(), b;"
2212 if (D.getDeclSpec().isInlineSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00002213 Diag(D.getDeclSpec().getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00002214 diag::err_inline_non_function);
2215
2216 if (D.getDeclSpec().isVirtualSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00002217 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00002218 diag::err_virtual_non_function);
2219
2220 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00002221 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00002222 diag::err_explicit_non_function);
2223}
2224
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002225NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002226Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCallbcd03502009-12-07 02:54:59 +00002227 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00002228 LookupResult &Previous, bool &Redeclaration) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002229 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2230 if (D.getCXXScopeSpec().isSet()) {
2231 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2232 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002233 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002234 // Pretend we didn't see the scope specifier.
2235 DC = 0;
2236 }
2237
Douglas Gregor0c880302009-03-11 23:00:04 +00002238 if (getLangOptions().CPlusPlus) {
2239 // Check that there are no default arguments (C++ only).
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002240 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00002241 }
2242
Eli Friedman574c7452009-04-07 19:37:57 +00002243 DiagnoseFunctionSpecifiers(D);
2244
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002245 if (D.getDeclSpec().isThreadSpecified())
2246 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2247
John McCallbcd03502009-12-07 02:54:59 +00002248 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002249 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002250
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002251 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00002252 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00002253
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002254 // Merge the decl with the existing one if appropriate. If the decl is
2255 // in an outer scope, it isn't the same thing.
John McCall1f82f242009-11-18 22:49:29 +00002256 FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false);
2257 if (!Previous.empty()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002258 Redeclaration = true;
John McCall1f82f242009-11-18 22:49:29 +00002259 MergeTypeDefDecl(NewTD, Previous);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002260 }
2261
Chris Lattner9fecd742009-04-19 05:21:20 +00002262 // C99 6.7.7p2: If a typedef name specifies a variably modified type
2263 // then it shall have block scope.
2264 QualType T = NewTD->getUnderlyingType();
2265 if (T->isVariablyModifiedType()) {
2266 CurFunctionNeedsScopeChecking = true;
Mike Stump11289f42009-09-09 15:08:12 +00002267
Chris Lattner9fecd742009-04-19 05:21:20 +00002268 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00002269 bool SizeIsNegative;
2270 QualType FixedTy =
2271 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2272 if (!FixedTy.isNull()) {
2273 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
John McCallbcd03502009-12-07 02:54:59 +00002274 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
Eli Friedmana3b1d032009-02-21 00:44:51 +00002275 } else {
2276 if (SizeIsNegative)
2277 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2278 else if (T->isVariableArrayType())
2279 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
2280 else
2281 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002282 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00002283 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002284 }
2285 }
Douglas Gregor27821ce2009-07-07 16:35:42 +00002286
2287 // If this is the C FILE type, notify the AST context.
2288 if (IdentifierInfo *II = NewTD->getIdentifier())
2289 if (!NewTD->isInvalidDecl() &&
Mike Stumpa4de80b2009-07-28 02:25:19 +00002290 NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
2291 if (II->isStr("FILE"))
2292 Context.setFILEDecl(NewTD);
2293 else if (II->isStr("jmp_buf"))
2294 Context.setjmp_bufDecl(NewTD);
2295 else if (II->isStr("sigjmp_buf"))
2296 Context.setsigjmp_bufDecl(NewTD);
2297 }
2298
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002299 return NewTD;
2300}
2301
Douglas Gregor5d68a202009-02-24 19:23:27 +00002302/// \brief Determines whether the given declaration is an out-of-scope
2303/// previous declaration.
2304///
2305/// This routine should be invoked when name lookup has found a
2306/// previous declaration (PrevDecl) that is not in the scope where a
2307/// new declaration by the same name is being introduced. If the new
2308/// declaration occurs in a local scope, previous declarations with
2309/// linkage may still be considered previous declarations (C99
2310/// 6.2.2p4-5, C++ [basic.link]p6).
2311///
2312/// \param PrevDecl the previous declaration found by name
2313/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00002314///
Douglas Gregor5d68a202009-02-24 19:23:27 +00002315/// \param DC the context in which the new declaration is being
2316/// declared.
2317///
2318/// \returns true if PrevDecl is an out-of-scope previous declaration
2319/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00002320static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00002321isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2322 ASTContext &Context) {
2323 if (!PrevDecl)
2324 return 0;
2325
Douglas Gregoreddf4332009-02-24 20:03:32 +00002326 if (!PrevDecl->hasLinkage())
2327 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00002328
2329 if (Context.getLangOptions().CPlusPlus) {
2330 // C++ [basic.link]p6:
2331 // If there is a visible declaration of an entity with linkage
2332 // having the same name and type, ignoring entities declared
2333 // outside the innermost enclosing namespace scope, the block
2334 // scope declaration declares that same entity and receives the
2335 // linkage of the previous declaration.
2336 DeclContext *OuterContext = DC->getLookupContext();
2337 if (!OuterContext->isFunctionOrMethod())
2338 // This rule only applies to block-scope declarations.
2339 return false;
2340 else {
2341 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2342 if (PrevOuterContext->isRecord())
2343 // We found a member function: ignore it.
2344 return false;
2345 else {
2346 // Find the innermost enclosing namespace for the new and
2347 // previous declarations.
2348 while (!OuterContext->isFileContext())
2349 OuterContext = OuterContext->getParent();
2350 while (!PrevOuterContext->isFileContext())
2351 PrevOuterContext = PrevOuterContext->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002352
Douglas Gregor5d68a202009-02-24 19:23:27 +00002353 // The previous declaration is in a different namespace, so it
2354 // isn't the same function.
Mike Stump11289f42009-09-09 15:08:12 +00002355 if (OuterContext->getPrimaryContext() !=
Douglas Gregor5d68a202009-02-24 19:23:27 +00002356 PrevOuterContext->getPrimaryContext())
2357 return false;
2358 }
2359 }
2360 }
2361
Douglas Gregor5d68a202009-02-24 19:23:27 +00002362 return true;
2363}
2364
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002365NamedDecl*
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002366Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCallbcd03502009-12-07 02:54:59 +00002367 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00002368 LookupResult &Previous,
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002369 MultiTemplateParamsArg TemplateParamLists,
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002370 bool &Redeclaration) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002371 DeclarationName Name = GetNameForDeclarator(D);
2372
2373 // Check that there are no default arguments (C++ only).
2374 if (getLangOptions().CPlusPlus)
2375 CheckExtraCXXDefaultArguments(D);
2376
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002377 VarDecl *NewVD;
2378 VarDecl::StorageClass SC;
2379 switch (D.getDeclSpec().getStorageClassSpec()) {
2380 default: assert(0 && "Unknown storage class!");
2381 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
2382 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
2383 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
2384 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
2385 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
2386 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
2387 case DeclSpec::SCS_mutable:
2388 // mutable can only appear on non-static class members, so it's always
2389 // an error here
2390 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002391 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002392 SC = VarDecl::None;
2393 break;
2394 }
2395
2396 IdentifierInfo *II = Name.getAsIdentifierInfo();
2397 if (!II) {
2398 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2399 << Name.getAsString();
2400 return 0;
2401 }
2402
Eli Friedman574c7452009-04-07 19:37:57 +00002403 DiagnoseFunctionSpecifiers(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00002404
Douglas Gregor212cab32009-03-11 20:22:50 +00002405 if (!DC->isRecord() && S->getFnParent() == 0) {
2406 // C99 6.9p2: The storage-class specifiers auto and register shall not
2407 // appear in the declaration specifiers in an external declaration.
2408 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Mike Stump11289f42009-09-09 15:08:12 +00002409
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00002410 // If this is a register variable with an asm label specified, then this
2411 // is a GNU extension.
2412 if (SC == VarDecl::Register && D.getAsmLabel())
2413 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2414 else
2415 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002416 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002417 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002418 }
Douglas Gregor04e9a032009-03-11 23:52:16 +00002419 if (DC->isRecord() && !CurContext->isRecord()) {
2420 // This is an out-of-line definition of a static data member.
2421 if (SC == VarDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00002422 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor04e9a032009-03-11 23:52:16 +00002423 diag::err_static_out_of_line)
2424 << CodeModificationHint::CreateRemoval(
Chris Lattner3c7b86f2009-12-06 17:36:05 +00002425 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor04e9a032009-03-11 23:52:16 +00002426 } else if (SC == VarDecl::None)
2427 SC = VarDecl::Static;
2428 }
Anders Carlssond2e8adf2009-06-24 00:28:53 +00002429 if (SC == VarDecl::Static) {
2430 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2431 if (RD->isLocalClass())
Mike Stump11289f42009-09-09 15:08:12 +00002432 Diag(D.getIdentifierLoc(),
Anders Carlssond2e8adf2009-06-24 00:28:53 +00002433 diag::err_static_data_member_not_allowed_in_local_class)
2434 << Name << RD->getDeclName();
2435 }
2436 }
Mike Stump11289f42009-09-09 15:08:12 +00002437
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002438 // Match up the template parameter lists with the scope specifier, then
2439 // determine whether we have a template or a template specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002440 bool isExplicitSpecialization = false;
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002441 if (TemplateParameterList *TemplateParams
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002442 = MatchTemplateParametersToScopeSpecifier(
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002443 D.getDeclSpec().getSourceRange().getBegin(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002444 D.getCXXScopeSpec(),
Douglas Gregor1a7ba622009-07-22 22:05:02 +00002445 (TemplateParameterList**)TemplateParamLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002446 TemplateParamLists.size(),
2447 isExplicitSpecialization)) {
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002448 if (TemplateParams->size() > 0) {
2449 // There is no such thing as a variable template.
2450 Diag(D.getIdentifierLoc(), diag::err_template_variable)
2451 << II
2452 << SourceRange(TemplateParams->getTemplateLoc(),
2453 TemplateParams->getRAngleLoc());
2454 return 0;
2455 } else {
2456 // There is an extraneous 'template<>' for this variable. Complain
2457 // about it, but allow the declaration of the variable.
Mike Stump11289f42009-09-09 15:08:12 +00002458 Diag(TemplateParams->getTemplateLoc(),
Douglas Gregore93e46c2009-07-22 23:48:44 +00002459 diag::err_template_variable_noparams)
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002460 << II
2461 << SourceRange(TemplateParams->getTemplateLoc(),
Mike Stump11289f42009-09-09 15:08:12 +00002462 TemplateParams->getRAngleLoc());
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002463
2464 isExplicitSpecialization = true;
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002465 }
Mike Stump11289f42009-09-09 15:08:12 +00002466 }
2467
2468 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +00002469 II, R, TInfo, SC);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002470
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002471 if (D.isInvalidType())
2472 NewVD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002473
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002474 if (D.getDeclSpec().isThreadSpecified()) {
2475 if (NewVD->hasLocalStorage())
2476 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
Eli Friedmandaea3f62009-04-19 21:48:33 +00002477 else if (!Context.Target.isTLSSupported())
2478 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002479 else
2480 NewVD->setThreadSpecified(true);
2481 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002482
Douglas Gregor04e9a032009-03-11 23:52:16 +00002483 // Set the lexical context. If the declarator has a C++ scope specifier, the
2484 // lexical context will be different from the semantic context.
2485 NewVD->setLexicalDeclContext(CurContext);
2486
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002487 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00002488 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002489
2490 // Handle GNU asm-label extension (encoded as an attribute).
2491 if (Expr *E = (Expr*) D.getAsmLabel()) {
2492 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00002493 StringLiteral *SE = cast<StringLiteral>(E);
Benjamin Kramer5f089122009-11-30 17:08:26 +00002494 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getString()));
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002495 }
2496
John McCall1f82f242009-11-18 22:49:29 +00002497 // Don't consider existing declarations that are in a different
2498 // scope and are out-of-semantic-context declarations (if the new
2499 // declaration has linkage).
2500 FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage());
Douglas Gregor86d142a2009-10-08 07:24:58 +00002501
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002502 // Merge the decl with the existing one if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00002503 if (!Previous.empty()) {
2504 if (Previous.isSingleResult() &&
2505 isa<FieldDecl>(Previous.getFoundDecl()) &&
2506 D.getCXXScopeSpec().isSet()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002507 // The user tried to define a non-static data member
2508 // out-of-line (C++ [dcl.meaning]p1).
2509 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
2510 << D.getCXXScopeSpec().getRange();
John McCall1f82f242009-11-18 22:49:29 +00002511 Previous.clear();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002512 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002513 }
2514 } else if (D.getCXXScopeSpec().isSet()) {
2515 // No previous declaration in the qualifying scope.
Douglas Gregore40876a2009-10-13 21:16:44 +00002516 Diag(D.getIdentifierLoc(), diag::err_no_member)
2517 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
2518 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002519 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002520 }
2521
John McCall1f82f242009-11-18 22:49:29 +00002522 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002523
Douglas Gregor86d142a2009-10-08 07:24:58 +00002524 // This is an explicit specialization of a static data member. Check it.
2525 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
John McCall1f82f242009-11-18 22:49:29 +00002526 CheckMemberSpecialization(NewVD, Previous))
Douglas Gregor86d142a2009-10-08 07:24:58 +00002527 NewVD->setInvalidDecl();
John McCall1f82f242009-11-18 22:49:29 +00002528
Ryan Flynne5dc8592009-07-25 22:29:44 +00002529 // attributes declared post-definition are currently ignored
John McCall1f82f242009-11-18 22:49:29 +00002530 if (Previous.isSingleResult()) {
2531 const VarDecl *Def = 0;
2532 VarDecl *PrevDecl = dyn_cast<VarDecl>(Previous.getFoundDecl());
2533 if (PrevDecl && PrevDecl->getDefinition(Def) && D.hasAttributes()) {
Ryan Flynne5dc8592009-07-25 22:29:44 +00002534 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
2535 Diag(Def->getLocation(), diag::note_previous_definition);
2536 }
2537 }
2538
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002539 // If this is a locally-scoped extern C variable, update the map of
2540 // such variables.
Douglas Gregor16618f22009-09-12 00:17:51 +00002541 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002542 !NewVD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00002543 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002544
2545 return NewVD;
2546}
2547
2548/// \brief Perform semantic checking on a newly-created variable
2549/// declaration.
2550///
2551/// This routine performs all of the type-checking required for a
Douglas Gregorf16a8a72009-05-01 15:47:09 +00002552/// variable declaration once it has been built. It is used both to
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002553/// check variables after they have been parsed and their declarators
Douglas Gregorf16a8a72009-05-01 15:47:09 +00002554/// have been translated into a declaration, and to check variables
2555/// that have been instantiated from a template.
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002556///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002557/// Sets NewVD->isInvalidDecl() if an error was encountered.
John McCall1f82f242009-11-18 22:49:29 +00002558void Sema::CheckVariableDeclaration(VarDecl *NewVD,
2559 LookupResult &Previous,
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002560 bool &Redeclaration) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002561 // If the decl is already known invalid, don't check it.
2562 if (NewVD->isInvalidDecl())
2563 return;
Mike Stump11289f42009-09-09 15:08:12 +00002564
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002565 QualType T = NewVD->getType();
2566
2567 if (T->isObjCInterfaceType()) {
2568 Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002569 return NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002570 }
Mike Stump11289f42009-09-09 15:08:12 +00002571
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002572 // Emit an error if an address space was applied to decl with local storage.
2573 // This includes arrays of objects with address space qualifiers, but not
2574 // automatic variables that point to other address spaces.
2575 // ISO/IEC TR 18037 S5.1.2
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002576 if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
2577 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002578 return NewVD->setInvalidDecl();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002579 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00002580
Mike Stumpca5ae662009-04-14 00:57:29 +00002581 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002582 && !NewVD->hasAttr<BlocksAttr>())
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002583 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00002584
Chris Lattner9fecd742009-04-19 05:21:20 +00002585 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00002586 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
2587 NewVD->hasAttr<BlocksAttr>())
Chris Lattner9fecd742009-04-19 05:21:20 +00002588 CurFunctionNeedsScopeChecking = true;
Mike Stump11289f42009-09-09 15:08:12 +00002589
Chris Lattner9fecd742009-04-19 05:21:20 +00002590 if ((isVM && NewVD->hasLinkage()) ||
2591 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00002592 bool SizeIsNegative;
2593 QualType FixedTy =
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002594 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
Mike Stump11289f42009-09-09 15:08:12 +00002595
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002596 if (FixedTy.isNull() && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002597 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002598 // FIXME: This won't give the correct result for
2599 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00002600 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002601
Anders Carlsson6c885802009-02-28 21:56:50 +00002602 if (NewVD->isFileVarDecl())
2603 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002604 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00002605 else if (NewVD->getStorageClass() == VarDecl::Static)
2606 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002607 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00002608 else
2609 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002610 << SizeRange;
2611 return NewVD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002612 }
2613
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002614 if (FixedTy.isNull()) {
Anders Carlsson6c885802009-02-28 21:56:50 +00002615 if (NewVD->isFileVarDecl())
2616 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
2617 else
2618 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002619 return NewVD->setInvalidDecl();
Anders Carlsson6c885802009-02-28 21:56:50 +00002620 }
Mike Stump11289f42009-09-09 15:08:12 +00002621
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002622 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
2623 NewVD->setType(FixedTy);
Anders Carlsson6c885802009-02-28 21:56:50 +00002624 }
2625
John McCall1f82f242009-11-18 22:49:29 +00002626 if (Previous.empty() && NewVD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002627 // Since we did not find anything by this name and we're declaring
2628 // an extern "C" variable, look for a non-visible extern "C"
2629 // declaration with the same name.
2630 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002631 = LocallyScopedExternalDecls.find(NewVD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002632 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00002633 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002634 }
2635
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002636 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002637 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
2638 << T;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002639 return NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002640 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002641
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002642 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00002643 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
2644 return NewVD->setInvalidDecl();
2645 }
Mike Stump11289f42009-09-09 15:08:12 +00002646
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002647 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpa7128632009-05-01 23:41:47 +00002648 Diag(NewVD->getLocation(), diag::err_block_on_vm);
2649 return NewVD->setInvalidDecl();
2650 }
2651
John McCall1f82f242009-11-18 22:49:29 +00002652 if (!Previous.empty()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002653 Redeclaration = true;
John McCall1f82f242009-11-18 22:49:29 +00002654 MergeVarDecl(NewVD, Previous);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002655 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002656}
2657
Douglas Gregor36d1b142009-10-06 17:59:45 +00002658/// \brief Data used with FindOverriddenMethod
2659struct FindOverriddenMethodData {
2660 Sema *S;
2661 CXXMethodDecl *Method;
2662};
2663
2664/// \brief Member lookup function that determines whether a given C++
2665/// method overrides a method in a base class, to be used with
2666/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00002667static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002668 CXXBasePath &Path,
2669 void *UserData) {
2670 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00002671
Douglas Gregor36d1b142009-10-06 17:59:45 +00002672 FindOverriddenMethodData *Data
2673 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00002674
2675 DeclarationName Name = Data->Method->getDeclName();
2676
2677 // FIXME: Do we care about other names here too?
2678 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2679 // We really want to find the base class constructor here.
2680 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
2681 CanQualType CT = Data->S->Context.getCanonicalType(T);
2682
Anders Carlsson5a4f7722009-11-27 01:26:58 +00002683 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00002684 }
2685
2686 for (Path.Decls = BaseRecord->lookup(Name);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002687 Path.Decls.first != Path.Decls.second;
2688 ++Path.Decls.first) {
2689 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*Path.Decls.first)) {
John McCall1f82f242009-11-18 22:49:29 +00002690 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD))
Douglas Gregor36d1b142009-10-06 17:59:45 +00002691 return true;
2692 }
2693 }
2694
2695 return false;
2696}
2697
Sebastian Redld5b24532009-11-18 21:51:29 +00002698/// AddOverriddenMethods - See if a method overrides any in the base classes,
2699/// and if so, check that it's a valid override and remember it.
2700void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2701 // Look for virtual methods in base classes that this method might override.
2702 CXXBasePaths Paths;
2703 FindOverriddenMethodData Data;
2704 Data.Method = MD;
2705 Data.S = this;
2706 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
2707 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
2708 E = Paths.found_decls_end(); I != E; ++I) {
2709 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
2710 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Alexis Hunt96d5c762009-11-21 08:43:09 +00002711 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
2712 !CheckOverridingFunctionAttributes(MD, OldMD))
Anders Carlssonf3935b42009-12-04 05:51:56 +00002713 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00002714 }
2715 }
2716 }
2717}
2718
Mike Stump11289f42009-09-09 15:08:12 +00002719NamedDecl*
Zhongxing Xubece5d62009-01-16 01:13:29 +00002720Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCallbcd03502009-12-07 02:54:59 +00002721 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00002722 LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002723 MultiTemplateParamsArg TemplateParamLists,
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002724 bool IsFunctionDefinition, bool &Redeclaration) {
Zhongxing Xubece5d62009-01-16 01:13:29 +00002725 assert(R.getTypePtr()->isFunctionType());
2726
2727 DeclarationName Name = GetNameForDeclarator(D);
2728 FunctionDecl::StorageClass SC = FunctionDecl::None;
2729 switch (D.getDeclSpec().getStorageClassSpec()) {
2730 default: assert(0 && "Unknown storage class!");
2731 case DeclSpec::SCS_auto:
2732 case DeclSpec::SCS_register:
2733 case DeclSpec::SCS_mutable:
Mike Stump11289f42009-09-09 15:08:12 +00002734 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregore62c0a42009-02-24 01:23:02 +00002735 diag::err_typecheck_sclass_func);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002736 D.setInvalidType();
Zhongxing Xubece5d62009-01-16 01:13:29 +00002737 break;
2738 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
2739 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
Douglas Gregore62c0a42009-02-24 01:23:02 +00002740 case DeclSpec::SCS_static: {
Douglas Gregor04e9a032009-03-11 23:52:16 +00002741 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002742 // C99 6.7.1p5:
2743 // The declaration of an identifier for a function that has
2744 // block scope shall have no explicit storage-class specifier
2745 // other than extern
2746 // See also (C++ [dcl.stc]p4).
Mike Stump11289f42009-09-09 15:08:12 +00002747 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregore62c0a42009-02-24 01:23:02 +00002748 diag::err_static_block_func);
2749 SC = FunctionDecl::None;
2750 } else
Mike Stump11289f42009-09-09 15:08:12 +00002751 SC = FunctionDecl::Static;
Douglas Gregore62c0a42009-02-24 01:23:02 +00002752 break;
2753 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00002754 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
2755 }
2756
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002757 if (D.getDeclSpec().isThreadSpecified())
2758 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2759
John McCalld1e9d832009-08-11 06:59:38 +00002760 bool isFriend = D.getDeclSpec().isFriendSpecified();
Zhongxing Xubece5d62009-01-16 01:13:29 +00002761 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor0c880302009-03-11 23:00:04 +00002762 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Zhongxing Xubece5d62009-01-16 01:13:29 +00002763 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
2764
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002765 // Check that the return type is not an abstract class type.
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002766 // For record types, this is done by the AbstractClassUsageDiagnoser once
Mike Stump11289f42009-09-09 15:08:12 +00002767 // the class has been completely parsed.
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002768 if (!DC->isRecord() &&
Mike Stump11289f42009-09-09 15:08:12 +00002769 RequireNonAbstractType(D.getIdentifierLoc(),
John McCall9dd450b2009-09-21 23:43:11 +00002770 R->getAs<FunctionType>()->getResultType(),
Mike Stump11289f42009-09-09 15:08:12 +00002771 diag::err_abstract_type_in_decl,
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002772 AbstractReturnType))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002773 D.setInvalidType();
Mike Stump11289f42009-09-09 15:08:12 +00002774
Chris Lattner347eec92009-04-11 19:17:25 +00002775 // Do not allow returning a objc interface by-value.
John McCall9dd450b2009-09-21 23:43:11 +00002776 if (R->getAs<FunctionType>()->getResultType()->isObjCInterfaceType()) {
Chris Lattner347eec92009-04-11 19:17:25 +00002777 Diag(D.getIdentifierLoc(),
2778 diag::err_object_cannot_be_passed_returned_by_value) << 0
John McCall9dd450b2009-09-21 23:43:11 +00002779 << R->getAs<FunctionType>()->getResultType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002780 D.setInvalidType();
Chris Lattner347eec92009-04-11 19:17:25 +00002781 }
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002782
Douglas Gregor0c880302009-03-11 23:00:04 +00002783 bool isVirtualOkay = false;
Zhongxing Xubece5d62009-01-16 01:13:29 +00002784 FunctionDecl *NewFD;
John McCallaa74a0c2009-08-28 07:59:38 +00002785
John McCalld1e9d832009-08-11 06:59:38 +00002786 if (isFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002787 // C++ [class.friend]p5
2788 // A function can be defined in a friend declaration of a
2789 // class . . . . Such a function is implicitly inline.
2790 isInline |= IsFunctionDefinition;
John McCallaa74a0c2009-08-28 07:59:38 +00002791 }
John McCalld1e9d832009-08-11 06:59:38 +00002792
Douglas Gregor7861a802009-11-03 01:35:08 +00002793 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
Zhongxing Xubece5d62009-01-16 01:13:29 +00002794 // This is a C++ constructor declaration.
2795 assert(DC->isRecord() &&
2796 "Constructors can only be declared in a member context");
2797
Chris Lattner38378bf2009-04-25 08:28:21 +00002798 R = CheckConstructorDeclarator(D, R, SC);
Zhongxing Xubece5d62009-01-16 01:13:29 +00002799
2800 // Create the new declaration
Mike Stump11289f42009-09-09 15:08:12 +00002801 NewFD = CXXConstructorDecl::Create(Context,
Zhongxing Xubece5d62009-01-16 01:13:29 +00002802 cast<CXXRecordDecl>(DC),
John McCallbcd03502009-12-07 02:54:59 +00002803 D.getIdentifierLoc(), Name, R, TInfo,
Zhongxing Xubece5d62009-01-16 01:13:29 +00002804 isExplicit, isInline,
2805 /*isImplicitlyDeclared=*/false);
Douglas Gregor7861a802009-11-03 01:35:08 +00002806 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
Zhongxing Xubece5d62009-01-16 01:13:29 +00002807 // This is a C++ destructor declaration.
2808 if (DC->isRecord()) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002809 R = CheckDestructorDeclarator(D, SC);
Mike Stump11289f42009-09-09 15:08:12 +00002810
Zhongxing Xubece5d62009-01-16 01:13:29 +00002811 NewFD = CXXDestructorDecl::Create(Context,
2812 cast<CXXRecordDecl>(DC),
Mike Stump11289f42009-09-09 15:08:12 +00002813 D.getIdentifierLoc(), Name, R,
Zhongxing Xubece5d62009-01-16 01:13:29 +00002814 isInline,
2815 /*isImplicitlyDeclared=*/false);
2816
Douglas Gregor0c880302009-03-11 23:00:04 +00002817 isVirtualOkay = true;
Zhongxing Xubece5d62009-01-16 01:13:29 +00002818 } else {
2819 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
2820
2821 // Create a FunctionDecl to satisfy the function definition parsing
2822 // code path.
2823 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +00002824 Name, R, TInfo, SC, isInline,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00002825 /*hasPrototype=*/true);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002826 D.setInvalidType();
Zhongxing Xubece5d62009-01-16 01:13:29 +00002827 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002828 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
Zhongxing Xubece5d62009-01-16 01:13:29 +00002829 if (!DC->isRecord()) {
2830 Diag(D.getIdentifierLoc(),
2831 diag::err_conv_function_not_member);
2832 return 0;
Zhongxing Xubece5d62009-01-16 01:13:29 +00002833 }
Mike Stump11289f42009-09-09 15:08:12 +00002834
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002835 CheckConversionDeclarator(D, R, SC);
2836 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
John McCallbcd03502009-12-07 02:54:59 +00002837 D.getIdentifierLoc(), Name, R, TInfo,
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002838 isInline, isExplicit);
Mike Stump11289f42009-09-09 15:08:12 +00002839
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002840 isVirtualOkay = true;
Zhongxing Xubece5d62009-01-16 01:13:29 +00002841 } else if (DC->isRecord()) {
Anders Carlssona0886932009-04-30 22:41:11 +00002842 // If the of the function is the same as the name of the record, then this
Mike Stump11289f42009-09-09 15:08:12 +00002843 // must be an invalid constructor that has a return type.
2844 // (The parser checks for a return type and makes the declarator a
Anders Carlssona0886932009-04-30 22:41:11 +00002845 // constructor if it has no return type).
Mike Stump11289f42009-09-09 15:08:12 +00002846 // must have an invalid constructor that has a return type
Anders Carlssona0886932009-04-30 22:41:11 +00002847 if (Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
2848 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
2849 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2850 << SourceRange(D.getIdentifierLoc());
2851 return 0;
2852 }
Mike Stump11289f42009-09-09 15:08:12 +00002853
Anders Carlsson623e9792009-11-15 18:59:32 +00002854 bool isStatic = SC == FunctionDecl::Static;
2855
2856 // [class.free]p1:
2857 // Any allocation function for a class T is a static member
2858 // (even if not explicitly declared static).
2859 if (Name.getCXXOverloadedOperator() == OO_New ||
2860 Name.getCXXOverloadedOperator() == OO_Array_New)
2861 isStatic = true;
Anders Carlsson7ade2032009-11-15 19:08:46 +00002862
2863 // [class.free]p6 Any deallocation function for a class X is a static member
2864 // (even if not explicitly declared static).
2865 if (Name.getCXXOverloadedOperator() == OO_Delete ||
2866 Name.getCXXOverloadedOperator() == OO_Array_Delete)
2867 isStatic = true;
Anders Carlsson623e9792009-11-15 18:59:32 +00002868
Zhongxing Xubece5d62009-01-16 01:13:29 +00002869 // This is a C++ method declaration.
2870 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
John McCallbcd03502009-12-07 02:54:59 +00002871 D.getIdentifierLoc(), Name, R, TInfo,
Anders Carlsson623e9792009-11-15 18:59:32 +00002872 isStatic, isInline);
Douglas Gregor0c880302009-03-11 23:00:04 +00002873
Anders Carlsson7ade2032009-11-15 19:08:46 +00002874 isVirtualOkay = !isStatic;
Zhongxing Xubece5d62009-01-16 01:13:29 +00002875 } else {
Douglas Gregor2797d322009-03-19 18:33:54 +00002876 // Determine whether the function was written with a
2877 // prototype. This true when:
2878 // - we're in C++ (where every function has a prototype),
2879 // - there is a prototype in the declarator, or
2880 // - the type R of the function is some kind of typedef or other reference
2881 // to a type name (which eventually refers to a function type).
Mike Stump11289f42009-09-09 15:08:12 +00002882 bool HasPrototype =
Chris Lattner441914e2009-03-17 23:17:04 +00002883 getLangOptions().CPlusPlus ||
Douglas Gregor3729f242009-03-19 18:14:46 +00002884 (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
Douglas Gregord6b05f72009-03-23 16:26:51 +00002885 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
Mike Stump11289f42009-09-09 15:08:12 +00002886
Zhongxing Xubece5d62009-01-16 01:13:29 +00002887 NewFD = FunctionDecl::Create(Context, DC,
2888 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +00002889 Name, R, TInfo, SC, isInline, HasPrototype);
Zhongxing Xubece5d62009-01-16 01:13:29 +00002890 }
2891
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002892 if (D.isInvalidType())
Chris Lattner3f863f62009-04-25 05:44:12 +00002893 NewFD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002894
Zhongxing Xubece5d62009-01-16 01:13:29 +00002895 // Set the lexical context. If the declarator has a C++
John McCallaa74a0c2009-08-28 07:59:38 +00002896 // scope specifier, or is the object of a friend declaration, the
2897 // lexical context will be different from the semantic context.
Zhongxing Xubece5d62009-01-16 01:13:29 +00002898 NewFD->setLexicalDeclContext(CurContext);
2899
Douglas Gregord8d297c2009-07-21 23:53:31 +00002900 // Match up the template parameter lists with the scope specifier, then
2901 // determine whether we have a template or a template specialization.
Douglas Gregorc1da0f02009-06-24 00:23:40 +00002902 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002903 bool isExplicitSpecialization = false;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002904 bool isFunctionTemplateSpecialization = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002905 if (TemplateParameterList *TemplateParams
2906 = MatchTemplateParametersToScopeSpecifier(
2907 D.getDeclSpec().getSourceRange().getBegin(),
2908 D.getCXXScopeSpec(),
Douglas Gregor1a7ba622009-07-22 22:05:02 +00002909 (TemplateParameterList**)TemplateParamLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002910 TemplateParamLists.size(),
2911 isExplicitSpecialization)) {
Douglas Gregorc1da0f02009-06-24 00:23:40 +00002912 if (TemplateParams->size() > 0) {
2913 // This is a function template
Mike Stump11289f42009-09-09 15:08:12 +00002914
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002915 // Check that we can declare a template here.
2916 if (CheckTemplateDeclScope(S, TemplateParams))
2917 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002918
Douglas Gregore704c9d2009-08-27 16:57:43 +00002919 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
Douglas Gregorc1da0f02009-06-24 00:23:40 +00002920 NewFD->getLocation(),
2921 Name, TemplateParams,
2922 NewFD);
Douglas Gregore704c9d2009-08-27 16:57:43 +00002923 FunctionTemplate->setLexicalDeclContext(CurContext);
Douglas Gregorc1da0f02009-06-24 00:23:40 +00002924 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
2925 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002926 // This is a function template specialization.
2927 isFunctionTemplateSpecialization = true;
Douglas Gregorc1da0f02009-06-24 00:23:40 +00002928 }
Mike Stump11289f42009-09-09 15:08:12 +00002929
Douglas Gregor1a7ba622009-07-22 22:05:02 +00002930 // FIXME: Free this memory properly.
2931 TemplateParamLists.release();
Mike Stump11289f42009-09-09 15:08:12 +00002932 }
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002933
Douglas Gregor0c880302009-03-11 23:00:04 +00002934 // C++ [dcl.fct.spec]p5:
2935 // The virtual specifier shall only be used in declarations of
2936 // nonstatic class member functions that appear within a
2937 // member-specification of a class declaration; see 10.3.
2938 //
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002939 if (isVirtual && !NewFD->isInvalidDecl()) {
Douglas Gregor0c880302009-03-11 23:00:04 +00002940 if (!isVirtualOkay) {
Mike Stump11289f42009-09-09 15:08:12 +00002941 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Douglas Gregor0c880302009-03-11 23:00:04 +00002942 diag::err_virtual_non_function);
2943 } else if (!CurContext->isRecord()) {
2944 // 'virtual' was specified outside of the class.
2945 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
2946 << CodeModificationHint::CreateRemoval(
Chris Lattner3c7b86f2009-12-06 17:36:05 +00002947 D.getDeclSpec().getVirtualSpecLoc());
Douglas Gregor0c880302009-03-11 23:00:04 +00002948 } else {
2949 // Okay: Add virtual to the method.
Douglas Gregor0c880302009-03-11 23:00:04 +00002950 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00002951 CurClass->setMethodAsVirtual(NewFD);
Douglas Gregor0c880302009-03-11 23:00:04 +00002952 }
2953 }
2954
John McCall1f82f242009-11-18 22:49:29 +00002955 // Filter out previous declarations that don't match the scope.
2956 FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
2957
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00002958 if (isFriend) {
John McCall1f82f242009-11-18 22:49:29 +00002959 // DC is the namespace in which the function is being declared.
2960 assert((DC->isFileContext() || !Previous.empty()) &&
2961 "previously-undeclared friend function being created "
2962 "in a non-namespace context");
2963
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00002964 if (FunctionTemplate) {
2965 FunctionTemplate->setObjectOfFriendDecl(
John McCall1f82f242009-11-18 22:49:29 +00002966 /* PreviouslyDeclared= */ !Previous.empty());
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00002967 FunctionTemplate->setAccess(AS_public);
2968 }
2969 else
John McCall1f82f242009-11-18 22:49:29 +00002970 NewFD->setObjectOfFriendDecl(/* PreviouslyDeclared= */ !Previous.empty());
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00002971
2972 NewFD->setAccess(AS_public);
2973 }
2974
Mike Stump11289f42009-09-09 15:08:12 +00002975 if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00002976 !CurContext->isRecord()) {
2977 // C++ [class.static]p1:
2978 // A data or function member of a class may be declared static
2979 // in a class definition, in which case it is a static member of
2980 // the class.
2981
2982 // Complain about the 'static' specifier if it's on an out-of-line
2983 // member function definition.
Mike Stump11289f42009-09-09 15:08:12 +00002984 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor04e9a032009-03-11 23:52:16 +00002985 diag::err_static_out_of_line)
2986 << CodeModificationHint::CreateRemoval(
Chris Lattner3c7b86f2009-12-06 17:36:05 +00002987 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor04e9a032009-03-11 23:52:16 +00002988 }
2989
Zhongxing Xubece5d62009-01-16 01:13:29 +00002990 // Handle GNU asm-label extension (encoded as an attribute).
2991 if (Expr *E = (Expr*) D.getAsmLabel()) {
2992 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00002993 StringLiteral *SE = cast<StringLiteral>(E);
Benjamin Kramer5f089122009-11-30 17:08:26 +00002994 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getString()));
Zhongxing Xubece5d62009-01-16 01:13:29 +00002995 }
2996
Chris Lattner9af40c12009-04-25 06:12:16 +00002997 // Copy the parameter declarations from the declarator D to the function
2998 // declaration NewFD, if they are available. First scavenge them into Params.
2999 llvm::SmallVector<ParmVarDecl*, 16> Params;
Zhongxing Xubece5d62009-01-16 01:13:29 +00003000 if (D.getNumTypeObjects() > 0) {
3001 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3002
Zhongxing Xubece5d62009-01-16 01:13:29 +00003003 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
3004 // function that takes no arguments, not a function that takes a
3005 // single void argument.
3006 // We let through "const void" here because Sema::GetTypeForDeclarator
3007 // already checks for that case.
3008 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3009 FTI.ArgInfo[0].Param &&
Chris Lattner83f095c2009-03-28 19:18:32 +00003010 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00003011 // Empty arg list, don't push any params.
Chris Lattner83f095c2009-03-28 19:18:32 +00003012 ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
Zhongxing Xubece5d62009-01-16 01:13:29 +00003013
3014 // In C++, the empty parameter-type-list must be spelled "void"; a
3015 // typedef of void is not permitted.
3016 if (getLangOptions().CPlusPlus &&
Chris Lattner3f863f62009-04-25 05:44:12 +00003017 Param->getType().getUnqualifiedType() != Context.VoidTy)
Douglas Gregor170512f2009-04-01 23:51:29 +00003018 Diag(Param->getLocation(), diag::err_param_typedef_of_void);
Chris Lattner9af40c12009-04-25 06:12:16 +00003019 // FIXME: Leaks decl?
Zhongxing Xubece5d62009-01-16 01:13:29 +00003020 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00003021 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
3022 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
3023 assert(Param->getDeclContext() != NewFD && "Was set before ?");
3024 Param->setDeclContext(NewFD);
3025 Params.push_back(Param);
3026 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003027 }
Mike Stump11289f42009-09-09 15:08:12 +00003028
John McCall9dd450b2009-09-21 23:43:11 +00003029 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00003030 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00003031 // following example, we'll need to synthesize (unnamed)
3032 // parameters for use in the declaration.
3033 //
3034 // @code
3035 // typedef void fn(int);
3036 // fn f;
3037 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003038
Chris Lattner47c0d002009-04-25 06:03:53 +00003039 // Synthesize a parameter for each argument type.
Chris Lattner47c0d002009-04-25 06:03:53 +00003040 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
3041 AE = FT->arg_type_end(); AI != AE; ++AI) {
3042 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC,
3043 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003044 *AI, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00003045 VarDecl::None, 0);
Chris Lattner47c0d002009-04-25 06:03:53 +00003046 Param->setImplicit();
3047 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00003048 }
Chris Lattner49303b22009-04-25 18:38:18 +00003049 } else {
3050 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
3051 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00003052 }
Chris Lattner9af40c12009-04-25 06:12:16 +00003053 // Finally, we know we have the right number of parameters, install them.
Jay Foad7d0479f2009-05-21 09:52:38 +00003054 NewFD->setParams(Context, Params.data(), Params.size());
Mike Stump11289f42009-09-09 15:08:12 +00003055
Douglas Gregor0e876e02009-09-25 23:53:26 +00003056 // If the declarator is a template-id, translate the parser's template
3057 // argument list into our AST format.
3058 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00003059 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00003060 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
3061 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00003062 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
3063 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregor0e876e02009-09-25 23:53:26 +00003064 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3065 TemplateId->getTemplateArgs(),
Douglas Gregor0e876e02009-09-25 23:53:26 +00003066 TemplateId->NumArgs);
3067 translateTemplateArguments(TemplateArgsPtr,
Douglas Gregor0e876e02009-09-25 23:53:26 +00003068 TemplateArgs);
3069 TemplateArgsPtr.release();
3070
3071 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00003072
3073 if (FunctionTemplate) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003074 // FIXME: Diagnose function template with explicit template
Douglas Gregor0e876e02009-09-25 23:53:26 +00003075 // arguments.
3076 HasExplicitTemplateArgs = false;
3077 } else if (!isFunctionTemplateSpecialization &&
3078 !D.getDeclSpec().isFriendSpecified()) {
3079 // We have encountered something that the user meant to be a
3080 // specialization (because it has explicitly-specified template
3081 // arguments) but that was not introduced with a "template<>" (or had
3082 // too few of them).
3083 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
3084 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
3085 << CodeModificationHint::CreateInsertion(
3086 D.getDeclSpec().getSourceRange().getBegin(),
3087 "template<> ");
3088 isFunctionTemplateSpecialization = true;
3089 }
3090 }
John McCall1f82f242009-11-18 22:49:29 +00003091
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003092 if (isFunctionTemplateSpecialization) {
John McCall6b51f282009-11-23 01:53:49 +00003093 if (CheckFunctionTemplateSpecialization(NewFD,
3094 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
John McCall1f82f242009-11-18 22:49:29 +00003095 Previous))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003096 NewFD->setInvalidDecl();
3097 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD) &&
John McCall1f82f242009-11-18 22:49:29 +00003098 CheckMemberSpecialization(NewFD, Previous))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003099 NewFD->setInvalidDecl();
Douglas Gregorcf915552009-10-13 16:30:37 +00003100
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003101 // Perform semantic checking on the function declaration.
3102 bool OverloadableAttrRequired = false; // FIXME: HACK!
John McCall84d87672009-12-10 09:41:52 +00003103 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
Douglas Gregorcf915552009-10-13 16:30:37 +00003104 Redeclaration, /*FIXME:*/OverloadableAttrRequired);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003105
John McCall1f82f242009-11-18 22:49:29 +00003106 assert((NewFD->isInvalidDecl() || !Redeclaration ||
3107 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3108 "previous declaration set still overloaded");
3109
Douglas Gregored5731f2009-11-25 17:50:39 +00003110 // If we have a function template, check the template parameter
3111 // list. This will check and merge default template arguments.
3112 if (FunctionTemplate) {
3113 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
3114 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
3115 PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
3116 D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
3117 : TPC_FunctionTemplate);
3118 }
3119
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003120 if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003121 // An out-of-line member function declaration must also be a
3122 // definition (C++ [dcl.meaning]p1).
Douglas Gregor19c52722009-10-08 15:54:21 +00003123 // Note that this is not the case for explicit specializations of
3124 // function templates or member functions of class templates, per
3125 // C++ [temp.expl.spec]p2.
Douglas Gregor4f15f4d2009-09-17 19:51:30 +00003126 if (!IsFunctionDefinition && !isFriend &&
Douglas Gregorca027af2009-10-12 22:27:17 +00003127 !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003128 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
3129 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003130 NewFD->setInvalidDecl();
John McCall1f82f242009-11-18 22:49:29 +00003131 } else if (!Redeclaration) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003132 // The user tried to provide an out-of-line definition for a
3133 // function that is a member of a class or namespace, but there
Mike Stump11289f42009-09-09 15:08:12 +00003134 // was no such member function declared (C++ [class.mfct]p2,
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003135 // C++ [namespace.memdef]p2). For example:
Mike Stump11289f42009-09-09 15:08:12 +00003136 //
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003137 // class X {
3138 // void f() const;
Mike Stump11289f42009-09-09 15:08:12 +00003139 // };
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003140 //
3141 // void X::f() { } // ill-formed
3142 //
3143 // Complain about this problem, and attempt to suggest close
3144 // matches (e.g., those that differ only in cv-qualifiers and
3145 // whether the parameter types are references).
3146 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
Douglas Gregore40876a2009-10-13 21:16:44 +00003147 << Name << DC << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003148 NewFD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003149
John McCall27b18f82009-11-17 02:14:36 +00003150 LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00003151 ForRedeclaration);
John McCall27b18f82009-11-17 02:14:36 +00003152 LookupQualifiedName(Prev, DC);
Mike Stump11289f42009-09-09 15:08:12 +00003153 assert(!Prev.isAmbiguous() &&
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003154 "Cannot have an ambiguity in previous-declaration lookup");
3155 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3156 Func != FuncEnd; ++Func) {
3157 if (isa<FunctionDecl>(*Func) &&
3158 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
3159 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3160 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003161 }
3162 }
3163
3164 // Handle attributes. We need to have merged decls when handling attributes
3165 // (for example to check for conflicts, etc).
3166 // FIXME: This needs to happen before we merge declarations. Then,
3167 // let attribute merging cope with attribute conflicts.
Douglas Gregor758a8692009-06-17 21:51:59 +00003168 ProcessDeclAttributes(S, NewFD, D);
Ryan Flynne5dc8592009-07-25 22:29:44 +00003169
3170 // attributes declared post-definition are currently ignored
John McCall1f82f242009-11-18 22:49:29 +00003171 if (Redeclaration && Previous.isSingleResult()) {
3172 const FunctionDecl *Def;
3173 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
Ryan Flynne5dc8592009-07-25 22:29:44 +00003174 if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) {
3175 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
3176 Diag(Def->getLocation(), diag::note_previous_definition);
3177 }
3178 }
3179
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003180 AddKnownFunctionAttributes(NewFD);
3181
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003182 if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003183 // If a function name is overloadable in C, then every function
3184 // with that name must be marked "overloadable".
3185 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
3186 << Redeclaration << NewFD;
John McCall1f82f242009-11-18 22:49:29 +00003187 if (!Previous.empty())
3188 Diag(Previous.getRepresentativeDecl()->getLocation(),
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003189 diag::note_attribute_overloadable_prev_overload);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003190 NewFD->addAttr(::new (Context) OverloadableAttr());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003191 }
3192
3193 // If this is a locally-scoped extern C function, update the
3194 // map of such names.
Douglas Gregor16618f22009-09-12 00:17:51 +00003195 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003196 && !NewFD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00003197 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003198
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00003199 // Set this FunctionDecl's range up to the right paren.
3200 NewFD->setLocEnd(D.getSourceRange().getEnd());
3201
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003202 if (FunctionTemplate && NewFD->isInvalidDecl())
3203 FunctionTemplate->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003204
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003205 if (FunctionTemplate)
3206 return FunctionTemplate;
Mike Stump11289f42009-09-09 15:08:12 +00003207
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003208 return NewFD;
3209}
3210
3211/// \brief Perform semantic checking of a new function declaration.
3212///
3213/// Performs semantic analysis of the new function declaration
3214/// NewFD. This routine performs all semantic checking that does not
3215/// require the actual declarator involved in the declaration, and is
3216/// used both for the declaration of functions as they are parsed
3217/// (called via ActOnDeclarator) and for the declaration of functions
3218/// that have been instantiated via C++ template instantiation (called
3219/// via InstantiateDecl).
3220///
Douglas Gregorcf915552009-10-13 16:30:37 +00003221/// \param IsExplicitSpecialiation whether this new function declaration is
3222/// an explicit specialization of the previous declaration.
3223///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003224/// This sets NewFD->isInvalidDecl() to true if there was an error.
John McCall84d87672009-12-10 09:41:52 +00003225void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00003226 LookupResult &Previous,
Douglas Gregorcf915552009-10-13 16:30:37 +00003227 bool IsExplicitSpecialization,
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003228 bool &Redeclaration,
3229 bool &OverloadableAttrRequired) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003230 // If NewFD is already known erroneous, don't do any of this checking.
3231 if (NewFD->isInvalidDecl())
3232 return;
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003233
Eli Friedman54135832009-05-16 12:15:55 +00003234 if (NewFD->getResultType()->isVariablyModifiedType()) {
3235 // Functions returning a variably modified type violate C99 6.7.5.2p2
3236 // because all functions have linkage.
3237 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
3238 return NewFD->setInvalidDecl();
3239 }
3240
Douglas Gregor16618f22009-09-12 00:17:51 +00003241 if (NewFD->isMain())
3242 CheckMain(NewFD);
John McCalld9baf6a2009-07-24 03:03:21 +00003243
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003244 // Check for a previous declaration of this name.
John McCall1f82f242009-11-18 22:49:29 +00003245 if (Previous.empty() && NewFD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003246 // Since we did not find anything by this name and we're declaring
3247 // an extern "C" function, look for a non-visible extern "C"
3248 // declaration with the same name.
3249 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003250 = LocallyScopedExternalDecls.find(NewFD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003251 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00003252 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003253 }
3254
Douglas Gregore62c0a42009-02-24 01:23:02 +00003255 // Merge or overload the declaration with an existing declaration of
3256 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00003257 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003258 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00003259 // a declaration that requires merging. If it's an overload,
3260 // there's no more work to do here; we'll just add the new
3261 // function to the scope.
Douglas Gregor633b7372009-02-13 00:26:38 +00003262
John McCall1f82f242009-11-18 22:49:29 +00003263 NamedDecl *OldDecl = 0;
John McCalldaa3d6b2009-12-09 03:35:25 +00003264 if (!AllowOverloadingOfFunction(Previous, Context)) {
3265 Redeclaration = true;
3266 OldDecl = Previous.getFoundDecl();
3267 } else {
3268 if (!getLangOptions().CPlusPlus) {
3269 OverloadableAttrRequired = true;
3270
3271 // Functions marked "overloadable" must have a prototype (that
3272 // we can't get through declaration merging).
3273 if (!NewFD->getType()->getAs<FunctionProtoType>()) {
3274 Diag(NewFD->getLocation(),
3275 diag::err_attribute_overloadable_no_prototype)
3276 << NewFD;
John McCall1f82f242009-11-18 22:49:29 +00003277 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00003278
3279 // Turn this into a variadic function with no parameters.
3280 QualType R = Context.getFunctionType(
3281 NewFD->getType()->getAs<FunctionType>()->getResultType(),
3282 0, 0, true, 0);
3283 NewFD->setType(R);
3284 return NewFD->setInvalidDecl();
3285 }
3286 }
3287
3288 switch (CheckOverload(NewFD, Previous, OldDecl)) {
3289 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003290 Redeclaration = true;
3291 if (isa<UsingShadowDecl>(OldDecl) && CurContext->isRecord()) {
3292 HideUsingShadowDecl(S, cast<UsingShadowDecl>(OldDecl));
3293 Redeclaration = false;
3294 }
John McCalldaa3d6b2009-12-09 03:35:25 +00003295 break;
3296
3297 case Ovl_NonFunction:
3298 Redeclaration = true;
3299 break;
3300
3301 case Ovl_Overload:
3302 Redeclaration = false;
3303 break;
John McCall1f82f242009-11-18 22:49:29 +00003304 }
3305 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003306
John McCall1f82f242009-11-18 22:49:29 +00003307 if (Redeclaration) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003308 // NewFD and OldDecl represent declarations that need to be
Mike Stump11289f42009-09-09 15:08:12 +00003309 // merged.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003310 if (MergeFunctionDecl(NewFD, OldDecl))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003311 return NewFD->setInvalidDecl();
Zhongxing Xubece5d62009-01-16 01:13:29 +00003312
John McCall1f82f242009-11-18 22:49:29 +00003313 Previous.clear();
3314 Previous.addDecl(OldDecl);
3315
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003316 if (FunctionTemplateDecl *OldTemplateDecl
Douglas Gregorca027af2009-10-12 22:27:17 +00003317 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
Douglas Gregorcf915552009-10-13 16:30:37 +00003318 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
Douglas Gregorca027af2009-10-12 22:27:17 +00003319 FunctionTemplateDecl *NewTemplateDecl
3320 = NewFD->getDescribedFunctionTemplate();
3321 assert(NewTemplateDecl && "Template/non-template mismatch");
3322 if (CXXMethodDecl *Method
3323 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
3324 Method->setAccess(OldTemplateDecl->getAccess());
3325 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
3326 }
Douglas Gregorcf915552009-10-13 16:30:37 +00003327
3328 // If this is an explicit specialization of a member that is a function
3329 // template, mark it as a member specialization.
3330 if (IsExplicitSpecialization &&
3331 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
3332 NewTemplateDecl->setMemberSpecialization();
3333 assert(OldTemplateDecl->isMemberSpecialization());
3334 }
Douglas Gregorca027af2009-10-12 22:27:17 +00003335 } else {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00003336 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
3337 NewFD->setAccess(OldDecl->getAccess());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003338 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00003339 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003340 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00003341 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003342
Anders Carlsson1b12ed42009-09-13 21:33:06 +00003343 // Semantic checking for this function declaration (in isolation).
3344 if (getLangOptions().CPlusPlus) {
3345 // C++-specific checks.
3346 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
3347 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003348 } else if (CXXDestructorDecl *Destructor =
3349 dyn_cast<CXXDestructorDecl>(NewFD)) {
3350 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00003351 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003352
3353 // FIXME: Shouldn't we be able to perform thisc heck even when the class
3354 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00003355 if (!ClassType->isDependentType()) {
3356 DeclarationName Name
3357 = Context.DeclarationNames.getCXXDestructorName(
3358 Context.getCanonicalType(ClassType));
3359 if (NewFD->getDeclName() != Name) {
3360 Diag(NewFD->getLocation(), diag::err_destructor_name);
3361 return NewFD->setInvalidDecl();
3362 }
3363 }
Anders Carlsson2a50e952009-11-15 22:49:34 +00003364
Anders Carlsson1b12ed42009-09-13 21:33:06 +00003365 Record->setUserDeclaredDestructor(true);
3366 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
3367 // user-defined destructor.
3368 Record->setPOD(false);
3369
3370 // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
3371 // declared destructor.
3372 // FIXME: C++0x: don't do this for "= default" destructors
3373 Record->setHasTrivialDestructor(false);
3374 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00003375 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00003376 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00003377 }
3378
3379 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00003380 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
3381 if (!Method->isFunctionTemplateSpecialization() &&
3382 !Method->getDescribedFunctionTemplate())
3383 AddOverriddenMethods(Method->getParent(), Method);
3384 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00003385
Eli Friedman6393aac2009-12-02 07:16:50 +00003386 // Additional checks for the destructor; make sure we do this after we
3387 // figure out whether the destructor is virtual.
3388 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
3389 if (!Destructor->getParent()->isDependentType())
3390 CheckDestructor(Destructor);
3391
Anders Carlsson1b12ed42009-09-13 21:33:06 +00003392 // Extra checking for C++ overloaded operators (C++ [over.oper]).
3393 if (NewFD->isOverloadedOperator() &&
3394 CheckOverloadedOperatorDeclaration(NewFD))
3395 return NewFD->setInvalidDecl();
3396
3397 // In C++, check default arguments now that we have merged decls. Unless
3398 // the lexical context is the class, because in this case this is done
3399 // during delayed parsing anyway.
3400 if (!CurContext->isRecord())
3401 CheckCXXDefaultArguments(NewFD);
3402 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003403}
3404
John McCalld9baf6a2009-07-24 03:03:21 +00003405void Sema::CheckMain(FunctionDecl* FD) {
John McCall02dee0a2009-07-25 04:36:53 +00003406 // C++ [basic.start.main]p3: A program that declares main to be inline
3407 // or static is ill-formed.
3408 // C99 6.7.4p4: In a hosted environment, the inline function specifier
3409 // shall not appear in a declaration of main.
3410 // static main is not an error under C99, but we should warn about it.
Douglas Gregor35b57532009-10-27 21:01:01 +00003411 bool isInline = FD->isInlineSpecified();
John McCall02dee0a2009-07-25 04:36:53 +00003412 bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
3413 if (isInline || isStatic) {
3414 unsigned diagID = diag::warn_unusual_main_decl;
3415 if (isInline || getLangOptions().CPlusPlus)
3416 diagID = diag::err_unusual_main_decl;
3417
3418 int which = isStatic + (isInline << 1) - 1;
3419 Diag(FD->getLocation(), diagID) << which;
3420 }
3421
3422 QualType T = FD->getType();
3423 assert(T->isFunctionType() && "function decl is not of function type");
John McCall9dd450b2009-09-21 23:43:11 +00003424 const FunctionType* FT = T->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00003425
John McCall02dee0a2009-07-25 04:36:53 +00003426 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
3427 // TODO: add a replacement fixit to turn the return type into 'int'.
3428 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
3429 FD->setInvalidDecl(true);
3430 }
3431
3432 // Treat protoless main() as nullary.
3433 if (isa<FunctionNoProtoType>(FT)) return;
3434
3435 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
3436 unsigned nparams = FTP->getNumArgs();
3437 assert(FD->getNumParams() == nparams);
3438
John McCall0e21fcc2009-12-24 09:58:38 +00003439 bool HasExtraParameters = (nparams > 3);
3440
3441 // Darwin passes an undocumented fourth argument of type char**. If
3442 // other platforms start sprouting these, the logic below will start
3443 // getting shifty.
3444 if (nparams == 4 &&
3445 Context.Target.getTriple().getOS() == llvm::Triple::Darwin)
3446 HasExtraParameters = false;
3447
3448 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00003449 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
3450 FD->setInvalidDecl(true);
3451 nparams = 3;
3452 }
3453
3454 // FIXME: a lot of the following diagnostics would be improved
3455 // if we had some location information about types.
3456
3457 QualType CharPP =
3458 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00003459 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00003460
3461 for (unsigned i = 0; i < nparams; ++i) {
3462 QualType AT = FTP->getArgType(i);
3463
3464 bool mismatch = true;
3465
3466 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
3467 mismatch = false;
3468 else if (Expected[i] == CharPP) {
3469 // As an extension, the following forms are okay:
3470 // char const **
3471 // char const * const *
3472 // char * const *
3473
John McCall8ccfcb52009-09-24 19:53:00 +00003474 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00003475 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003476 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
3477 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
John McCall02dee0a2009-07-25 04:36:53 +00003478 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
3479 qs.removeConst();
3480 mismatch = !qs.empty();
3481 }
3482 }
3483
3484 if (mismatch) {
3485 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
3486 // TODO: suggest replacing given type with expected type
3487 FD->setInvalidDecl(true);
3488 }
3489 }
3490
3491 if (nparams == 1 && !FD->isInvalidDecl()) {
3492 Diag(FD->getLocation(), diag::warn_main_one_arg);
3493 }
John McCalld9baf6a2009-07-24 03:03:21 +00003494}
3495
Eli Friedmand5a55bd2008-05-20 13:48:25 +00003496bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00003497 // FIXME: Need strict checking. In C89, we need to check for
3498 // any assignment, increment, decrement, function-calls, or
3499 // commas outside of a sizeof. In C99, it's the same list,
3500 // except that the aforementioned are allowed in unevaluated
3501 // expressions. Everything else falls under the
3502 // "may accept other forms of constant expressions" exception.
3503 // (We never end up here for C++, so the constant expression
3504 // rules there don't matter.)
Chris Lattner0be5aa82009-02-24 21:54:33 +00003505 if (Init->isConstantInitializer(Context))
Eli Friedman7bfab362009-02-22 06:45:27 +00003506 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00003507 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
3508 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00003509 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00003510}
3511
Anders Carlsson250aada2009-08-16 05:13:48 +00003512void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
3513 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003514}
3515
3516/// AddInitializerToDecl - Adds the initializer Init to the
3517/// declaration dcl. If DirectInit is true, this is C++ direct
3518/// initialization rather than copy initialization.
Chris Lattner83f095c2009-03-28 19:18:32 +00003519void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
3520 Decl *RealDecl = dcl.getAs<Decl>();
Chris Lattner8beb9de2007-10-19 20:10:30 +00003521 // If there is no declaration, there was an error parsing it. Just ignore
3522 // the initializer.
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00003523 if (RealDecl == 0)
Chris Lattner8beb9de2007-10-19 20:10:30 +00003524 return;
Mike Stump11289f42009-09-09 15:08:12 +00003525
Douglas Gregor0c880302009-03-11 23:00:04 +00003526 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
3527 // With declarators parsed the way they are, the parser cannot
3528 // distinguish between a normal initializer and a pure-specifier.
3529 // Thus this grotesque test.
3530 IntegerLiteral *IL;
3531 Expr *Init = static_cast<Expr *>(init.get());
3532 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00003533 Context.getCanonicalType(IL->getType()) == Context.IntTy)
3534 CheckPureMethod(Method, Init->getSourceRange());
3535 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00003536 Diag(Method->getLocation(), diag::err_member_function_initialization)
3537 << Method->getDeclName() << Init->getSourceRange();
3538 Method->setInvalidDecl();
3539 }
3540 return;
3541 }
3542
Steve Naroff437b4d82007-09-12 20:13:48 +00003543 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3544 if (!VDecl) {
Douglas Gregor0c880302009-03-11 23:00:04 +00003545 if (getLangOptions().CPlusPlus &&
3546 RealDecl->getLexicalDeclContext()->isRecord() &&
3547 isa<NamedDecl>(RealDecl))
3548 Diag(RealDecl->getLocation(), diag::err_member_initialization)
3549 << cast<NamedDecl>(RealDecl)->getDeclName();
3550 else
3551 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00003552 RealDecl->setInvalidDecl();
3553 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00003554 }
3555
Eli Friedmanc9827d12009-11-14 03:40:14 +00003556 // A definition must end up with a complete type, which means it must be
3557 // complete with the restriction that an array type might be completed by the
3558 // initializer; note that later code assumes this restriction.
3559 QualType BaseDeclType = VDecl->getType();
3560 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
3561 BaseDeclType = Array->getElementType();
3562 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
Eli Friedman337cd3a2009-04-13 21:28:54 +00003563 diag::err_typecheck_decl_incomplete_type)) {
3564 RealDecl->setInvalidDecl();
3565 return;
3566 }
3567
Douglas Gregorc99f1552009-12-03 18:33:45 +00003568 // The variable can not have an abstract class type.
3569 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
3570 diag::err_abstract_type_in_decl,
3571 AbstractVariableType))
3572 VDecl->setInvalidDecl();
3573
Douglas Gregor0760fa12009-03-10 23:43:53 +00003574 const VarDecl *Def = 0;
3575 if (VDecl->getDefinition(Def)) {
Mike Stump11289f42009-09-09 15:08:12 +00003576 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00003577 << VDecl->getDeclName();
3578 Diag(Def->getLocation(), diag::note_previous_definition);
3579 VDecl->setInvalidDecl();
3580 return;
3581 }
3582
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00003583 // Take ownership of the expression, now that we're sure we have somewhere
3584 // to put it.
Anders Carlsson3cbc8592009-05-01 19:30:39 +00003585 Expr *Init = init.takeAs<Expr>();
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00003586 assert(Init && "missing initializer");
3587
Douglas Gregor85dabae2009-12-16 01:38:02 +00003588 // Capture the variable that is being initialized and the style of
3589 // initialization.
3590 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
3591
3592 // FIXME: Poor source location information.
3593 InitializationKind Kind
3594 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
3595 Init->getLocStart(),
3596 Init->getLocEnd())
3597 : InitializationKind::CreateCopy(VDecl->getLocation(),
3598 Init->getLocStart());
3599
Steve Naroff61091402007-09-12 14:07:44 +00003600 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00003601 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00003602 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff08899ff2008-04-15 22:42:06 +00003603 if (VDecl->isBlockVarDecl()) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003604 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
Steve Naroff437b4d82007-09-12 20:13:48 +00003605 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff08899ff2008-04-15 22:42:06 +00003606 VDecl->setInvalidDecl();
3607 } else if (!VDecl->isInvalidDecl()) {
Eli Friedman78275202009-12-19 08:11:05 +00003608 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
Eli Friedman463e5232009-12-22 02:10:53 +00003609 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Eli Friedman78275202009-12-19 08:11:05 +00003610 MultiExprArg(*this, (void**)&Init, 1),
Eli Friedman463e5232009-12-22 02:10:53 +00003611 &DclT);
3612 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00003613 VDecl->setInvalidDecl();
Eli Friedman78275202009-12-19 08:11:05 +00003614 return;
3615 }
Mike Stump11289f42009-09-09 15:08:12 +00003616
Eli Friedman463e5232009-12-22 02:10:53 +00003617 Init = Result.takeAs<Expr>();
3618
Anders Carlsson41e08812008-08-22 05:00:02 +00003619 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmance982572009-02-20 01:34:21 +00003620 // Don't check invalid declarations to avoid emitting useless diagnostics.
3621 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003622 if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
Anders Carlsson41e08812008-08-22 05:00:02 +00003623 CheckForConstantInitializer(Init, DclT);
3624 }
Steve Naroff61091402007-09-12 14:07:44 +00003625 }
Mike Stump11289f42009-09-09 15:08:12 +00003626 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00003627 VDecl->getLexicalDeclContext()->isRecord()) {
3628 // This is an in-class initialization for a static data member, e.g.,
3629 //
3630 // struct S {
3631 // static const int value = 17;
3632 // };
3633
3634 // Attach the initializer
Douglas Gregor31cf12c2009-05-26 18:54:04 +00003635 VDecl->setInit(Context, Init);
Douglas Gregor0c880302009-03-11 23:00:04 +00003636
3637 // C++ [class.mem]p4:
3638 // A member-declarator can contain a constant-initializer only
3639 // if it declares a static member (9.4) of const integral or
3640 // const enumeration type, see 9.4.2.
3641 QualType T = VDecl->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003642 if (!T->isDependentType() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00003643 (!Context.getCanonicalType(T).isConstQualified() ||
3644 !T->isIntegralType())) {
3645 Diag(VDecl->getLocation(), diag::err_member_initialization)
3646 << VDecl->getDeclName() << Init->getSourceRange();
3647 VDecl->setInvalidDecl();
3648 } else {
3649 // C++ [class.static.data]p4:
3650 // If a static data member is of const integral or const
3651 // enumeration type, its declaration in the class definition
3652 // can specify a constant-initializer which shall be an
3653 // integral constant expression (5.19).
3654 if (!Init->isTypeDependent() &&
3655 !Init->getType()->isIntegralType()) {
3656 // We have a non-dependent, non-integral or enumeration type.
Mike Stump11289f42009-09-09 15:08:12 +00003657 Diag(Init->getSourceRange().getBegin(),
Douglas Gregor0c880302009-03-11 23:00:04 +00003658 diag::err_in_class_initializer_non_integral_type)
3659 << Init->getType() << Init->getSourceRange();
3660 VDecl->setInvalidDecl();
3661 } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
3662 // Check whether the expression is a constant expression.
3663 llvm::APSInt Value;
3664 SourceLocation Loc;
3665 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
3666 Diag(Loc, diag::err_in_class_initializer_non_constant)
3667 << Init->getSourceRange();
3668 VDecl->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003669 } else if (!VDecl->getType()->isDependentType())
Eli Friedman06ed2a52009-10-20 08:27:19 +00003670 ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
Douglas Gregor0c880302009-03-11 23:00:04 +00003671 }
3672 }
Steve Naroff08899ff2008-04-15 22:42:06 +00003673 } else if (VDecl->isFileVarDecl()) {
Steve Naroff635168a2009-04-15 15:20:03 +00003674 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff437b4d82007-09-12 20:13:48 +00003675 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00003676 if (!VDecl->isInvalidDecl()) {
3677 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3678 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3679 MultiExprArg(*this, (void**)&Init, 1),
3680 &DclT);
3681 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00003682 VDecl->setInvalidDecl();
Eli Friedman463e5232009-12-22 02:10:53 +00003683 return;
3684 }
3685
3686 Init = Result.takeAs<Expr>();
3687 }
Mike Stump11289f42009-09-09 15:08:12 +00003688
Anders Carlsson41e08812008-08-22 05:00:02 +00003689 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmance982572009-02-20 01:34:21 +00003690 // Don't check invalid declarations to avoid emitting useless diagnostics.
3691 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Anders Carlsson41e08812008-08-22 05:00:02 +00003692 // C99 6.7.8p4. All file scoped initializers need to be constant.
3693 CheckForConstantInitializer(Init, DclT);
3694 }
Steve Naroff61091402007-09-12 14:07:44 +00003695 }
3696 // If the type changed, it means we had an incomplete type that was
Mike Stump11289f42009-09-09 15:08:12 +00003697 // completed by the initializer. For example:
Steve Naroff61091402007-09-12 14:07:44 +00003698 // int ary[] = { 1, 3, 5 };
3699 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00003700 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff437b4d82007-09-12 20:13:48 +00003701 VDecl->setType(DclT);
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00003702 Init->setType(DclT);
3703 }
Mike Stump11289f42009-09-09 15:08:12 +00003704
Anders Carlsson6e997b22009-12-15 20:51:39 +00003705 Init = MaybeCreateCXXExprWithTemporaries(Init);
Steve Naroff61091402007-09-12 14:07:44 +00003706 // Attach the initializer to the decl.
Douglas Gregor31cf12c2009-05-26 18:54:04 +00003707 VDecl->setInit(Context, Init);
Douglas Gregorbeecd582009-04-21 17:11:58 +00003708
3709 // If the previous declaration of VDecl was a tentative definition,
3710 // remove it from the set of tentative definitions.
3711 if (VDecl->getPreviousDeclaration() &&
3712 VDecl->getPreviousDeclaration()->isTentativeDefinition(Context)) {
Chris Lattner0c797362009-09-08 18:19:27 +00003713 bool Deleted = TentativeDefinitions.erase(VDecl->getDeclName());
3714 assert(Deleted && "Unrecorded tentative definition?"); Deleted=Deleted;
Douglas Gregorbeecd582009-04-21 17:11:58 +00003715 }
3716
Eli Friedman7dac3712009-12-20 22:29:11 +00003717 if (getLangOptions().CPlusPlus) {
3718 // Make sure we mark the destructor as used if necessary.
3719 QualType InitType = VDecl->getType();
3720 if (const ArrayType *Array = Context.getAsArrayType(InitType))
3721 InitType = Context.getBaseElementType(Array);
3722 if (InitType->isRecordType())
3723 FinalizeVarWithDestructor(VDecl, InitType);
3724 }
3725
Steve Naroff61091402007-09-12 14:07:44 +00003726 return;
3727}
3728
Mike Stump11289f42009-09-09 15:08:12 +00003729void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
Anders Carlssonae019932009-07-11 00:34:39 +00003730 bool TypeContainsUndeducedAuto) {
Chris Lattner83f095c2009-03-28 19:18:32 +00003731 Decl *RealDecl = dcl.getAs<Decl>();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003732
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00003733 // If there is no declaration, there was an error parsing it. Just ignore it.
3734 if (RealDecl == 0)
3735 return;
3736
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003737 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
3738 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00003739
3740 // Record tentative definitions.
Chris Lattner0c797362009-09-08 18:19:27 +00003741 if (Var->isTentativeDefinition(Context)) {
3742 std::pair<llvm::DenseMap<DeclarationName, VarDecl *>::iterator, bool>
Mike Stump11289f42009-09-09 15:08:12 +00003743 InsertPair =
Chris Lattner0c797362009-09-08 18:19:27 +00003744 TentativeDefinitions.insert(std::make_pair(Var->getDeclName(), Var));
Mike Stump11289f42009-09-09 15:08:12 +00003745
Chris Lattner0c797362009-09-08 18:19:27 +00003746 // Keep the latest definition in the map. If we see 'int i; int i;' we
3747 // want the second one in the map.
3748 InsertPair.first->second = Var;
3749
3750 // However, for the list, we don't care about the order, just make sure
3751 // that there are no dupes for a given declaration name.
3752 if (InsertPair.second)
3753 TentativeDefinitionList.push_back(Var->getDeclName());
3754 }
Douglas Gregorbeecd582009-04-21 17:11:58 +00003755
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003756 // C++ [dcl.init.ref]p3:
3757 // The initializer can be omitted for a reference only in a
3758 // parameter declaration (8.3.5), in the declaration of a
3759 // function return type, in the declaration of a class member
3760 // within its class declaration (9.2), and where the extern
3761 // specifier is explicitly used.
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003762 if (Type->isReferenceType() && !Var->hasExternalStorage()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00003763 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003764 << Var->getDeclName()
3765 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003766 Var->setInvalidDecl();
3767 return;
3768 }
3769
Anders Carlssonae019932009-07-11 00:34:39 +00003770 // C++0x [dcl.spec.auto]p3
3771 if (TypeContainsUndeducedAuto) {
3772 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
3773 << Var->getDeclName() << Type;
3774 Var->setInvalidDecl();
3775 return;
3776 }
Mike Stump11289f42009-09-09 15:08:12 +00003777
Sebastian Redl10600672009-11-05 19:47:47 +00003778 // An array without size is an incomplete type, and there are no special
3779 // rules in C++ to make such a definition acceptable.
3780 if (getLangOptions().CPlusPlus && Type->isIncompleteArrayType() &&
3781 !Var->hasExternalStorage()) {
3782 Diag(Var->getLocation(),
3783 diag::err_typecheck_incomplete_array_needs_initializer);
3784 Var->setInvalidDecl();
3785 return;
3786 }
3787
Douglas Gregor86d142a2009-10-08 07:24:58 +00003788 // C++ [temp.expl.spec]p15:
3789 // An explicit specialization of a static data member of a template is a
3790 // definition if the declaration includes an initializer; otherwise, it
3791 // is a declaration.
3792 if (Var->isStaticDataMember() &&
3793 Var->getInstantiatedFromStaticDataMember() &&
3794 Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3795 return;
3796
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003797 // C++ [dcl.init]p9:
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003798 // If no initializer is specified for an object, and the object
3799 // is of (possibly cv-qualified) non-POD class type (or array
3800 // thereof), the object shall be default-initialized; if the
3801 // object is of const-qualified type, the underlying class type
3802 // shall have a user-declared default constructor.
Douglas Gregor60e40bb2009-09-09 23:58:28 +00003803 //
3804 // FIXME: Diagnose the "user-declared default constructor" bit.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003805 if (getLangOptions().CPlusPlus) {
3806 QualType InitType = Type;
3807 if (const ArrayType *Array = Context.getAsArrayType(Type))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00003808 InitType = Context.getBaseElementType(Array);
Douglas Gregor16618f22009-09-12 00:17:51 +00003809 if ((!Var->hasExternalStorage() && !Var->isExternC()) &&
Douglas Gregor8157b072009-05-29 14:25:00 +00003810 InitType->isRecordType() && !InitType->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003811 if (!RequireCompleteType(Var->getLocation(), InitType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003812 diag::err_invalid_incomplete_type_use)) {
Douglas Gregor39c778b2009-12-20 22:01:25 +00003813 InitializedEntity Entity
3814 = InitializedEntity::InitializeVariable(Var);
3815 InitializationKind Kind
3816 = InitializationKind::CreateDefault(Var->getLocation());
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003817
Douglas Gregor39c778b2009-12-20 22:01:25 +00003818 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
3819 OwningExprResult Init = InitSeq.Perform(*this, Entity, Kind,
3820 MultiExprArg(*this, 0, 0));
3821 if (Init.isInvalid())
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003822 Var->setInvalidDecl();
Douglas Gregor60e40bb2009-09-09 23:58:28 +00003823 else {
Douglas Gregor39c778b2009-12-20 22:01:25 +00003824 Var->setInit(Context,
3825 MaybeCreateCXXExprWithTemporaries(Init.takeAs<Expr>()));
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003826 FinalizeVarWithDestructor(Var, InitType);
Douglas Gregor60e40bb2009-09-09 23:58:28 +00003827 }
Douglas Gregoreeffde32009-10-08 16:41:22 +00003828 } else {
3829 Var->setInvalidDecl();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003830 }
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003831 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00003832
3833 // The variable can not have an abstract class type.
3834 if (RequireNonAbstractType(Var->getLocation(), Type,
3835 diag::err_abstract_type_in_decl,
3836 AbstractVariableType))
3837 Var->setInvalidDecl();
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003838 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003839
Douglas Gregor9774aa12008-10-29 13:50:18 +00003840#if 0
3841 // FIXME: Temporarily disabled because we are not properly parsing
Mike Stump11289f42009-09-09 15:08:12 +00003842 // linkage specifications on declarations, e.g.,
Douglas Gregor9774aa12008-10-29 13:50:18 +00003843 //
3844 // extern "C" const CGPoint CGPointerZero;
3845 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003846 // C++ [dcl.init]p9:
3847 //
3848 // If no initializer is specified for an object, and the
3849 // object is of (possibly cv-qualified) non-POD class type (or
3850 // array thereof), the object shall be default-initialized; if
3851 // the object is of const-qualified type, the underlying class
3852 // type shall have a user-declared default
3853 // constructor. Otherwise, if no initializer is specified for
3854 // an object, the object and its subobjects, if any, have an
3855 // indeterminate initial value; if the object or any of its
3856 // subobjects are of const-qualified type, the program is
3857 // ill-formed.
3858 //
3859 // This isn't technically an error in C, so we don't diagnose it.
3860 //
3861 // FIXME: Actually perform the POD/user-defined default
3862 // constructor check.
3863 if (getLangOptions().CPlusPlus &&
Douglas Gregor9774aa12008-10-29 13:50:18 +00003864 Context.getCanonicalType(Type).isConstQualified() &&
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003865 !Var->hasExternalStorage())
Chris Lattner651d42d2008-11-20 06:38:18 +00003866 Diag(Var->getLocation(), diag::err_const_var_requires_init)
3867 << Var->getName()
3868 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor9774aa12008-10-29 13:50:18 +00003869#endif
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003870 }
3871}
3872
Eli Friedman55b9ecb2009-05-29 01:49:24 +00003873Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
3874 DeclPtrTy *Group,
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003875 unsigned NumDecls) {
3876 llvm::SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00003877
3878 if (DS.isTypeSpecOwned())
3879 Decls.push_back((Decl*)DS.getTypeRep());
3880
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003881 for (unsigned i = 0; i != NumDecls; ++i)
3882 if (Decl *D = Group[i].getAs<Decl>())
3883 Decls.push_back(D);
Mike Stump11289f42009-09-09 15:08:12 +00003884
Steve Naroff61091402007-09-12 14:07:44 +00003885 // Perform semantic analysis that depends on having fully processed both
3886 // the declarator and initializer.
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003887 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
3888 VarDecl *IDecl = dyn_cast<VarDecl>(Decls[i]);
Steve Naroff61091402007-09-12 14:07:44 +00003889 if (!IDecl)
3890 continue;
Steve Naroff61091402007-09-12 14:07:44 +00003891 QualType T = IDecl->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003892
Steve Naroff61091402007-09-12 14:07:44 +00003893 // Block scope. C99 6.7p7: If an identifier for an object is declared with
3894 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003895 if (IDecl->isBlockVarDecl() && !IDecl->hasExternalStorage()) {
Sebastian Redl548e6292009-10-17 19:37:06 +00003896 if (T->isDependentType()) {
3897 // If T is dependent, we should not require a complete type.
3898 // (RequireCompleteType shouldn't be called with dependent types.)
3899 // But we still can at least check if we've got an array of unspecified
3900 // size without an initializer.
3901 if (!IDecl->isInvalidDecl() && T->isIncompleteArrayType() &&
3902 !IDecl->getInit()) {
3903 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
3904 << T;
3905 IDecl->setInvalidDecl();
3906 }
3907 } else if (!IDecl->isInvalidDecl()) {
3908 // If T is an incomplete array type with an initializer list that is
3909 // dependent on something, its size has not been fixed. We could attempt
3910 // to fix the size for such arrays, but we would still have to check
3911 // here for initializers containing a C++0x vararg expansion, e.g.
3912 // template <typename... Args> void f(Args... args) {
3913 // int vals[] = { args };
3914 // }
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003915 const IncompleteArrayType *IAT = Context.getAsIncompleteArrayType(T);
Sebastian Redl548e6292009-10-17 19:37:06 +00003916 Expr *Init = IDecl->getInit();
3917 if (IAT && Init &&
3918 (Init->isTypeDependent() || Init->isValueDependent())) {
3919 // Check that the member type of the array is complete, at least.
3920 if (RequireCompleteType(IDecl->getLocation(), IAT->getElementType(),
3921 diag::err_typecheck_decl_incomplete_type))
3922 IDecl->setInvalidDecl();
3923 } else if (RequireCompleteType(IDecl->getLocation(), T,
3924 diag::err_typecheck_decl_incomplete_type))
3925 IDecl->setInvalidDecl();
3926 }
Steve Naroff61091402007-09-12 14:07:44 +00003927 }
Douglas Gregor47d28592009-07-20 18:46:59 +00003928 // File scope. C99 6.9.2p2: A declaration of an identifier for an
Steve Naroff61091402007-09-12 14:07:44 +00003929 // object that has file scope without an initializer, and without a
3930 // storage-class specifier or with the storage-class specifier "static",
3931 // constitutes a tentative definition. Note: A tentative definition with
3932 // external linkage is valid (C99 6.2.2p5).
Douglas Gregor47d28592009-07-20 18:46:59 +00003933 if (IDecl->isTentativeDefinition(Context) && !IDecl->isInvalidDecl()) {
3934 if (const IncompleteArrayType *ArrayT
3935 = Context.getAsIncompleteArrayType(T)) {
3936 if (RequireCompleteType(IDecl->getLocation(),
3937 ArrayT->getElementType(),
3938 diag::err_illegal_decl_array_incomplete_type))
3939 IDecl->setInvalidDecl();
Mike Stump12b8ce12009-08-04 21:02:39 +00003940 } else if (IDecl->getStorageClass() == VarDecl::Static) {
Steve Naroffacb6fa62008-01-18 20:40:52 +00003941 // C99 6.9.2p3: If the declaration of an identifier for an object is
Douglas Gregor47d28592009-07-20 18:46:59 +00003942 // a tentative definition and has internal linkage (C99 6.2.2p3), the
Steve Naroffacb6fa62008-01-18 20:40:52 +00003943 // declared type shall not be an incomplete type.
Douglas Gregor47d28592009-07-20 18:46:59 +00003944 // NOTE: code such as the following
3945 // static struct s;
3946 // struct s { int a; };
3947 // is accepted by gcc. Hence here we issue a warning instead of
3948 // an error and we do not invalidate the static declaration.
3949 // NOTE: to avoid multiple warnings, only check the first declaration.
3950 if (IDecl->getPreviousDeclaration() == 0)
3951 RequireCompleteType(IDecl->getLocation(), T,
3952 diag::ext_typecheck_decl_incomplete_type);
Douglas Gregor81457422009-03-10 21:58:27 +00003953 }
Steve Naroff61091402007-09-12 14:07:44 +00003954 }
Chris Lattner776fac82007-06-09 00:53:06 +00003955 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003956 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
Jay Foad7d0479f2009-05-21 09:52:38 +00003957 Decls.data(), Decls.size()));
Chris Lattner776fac82007-06-09 00:53:06 +00003958}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00003959
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003960
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003961/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
3962/// to introduce parameters into function prototype scope.
Mike Stump11289f42009-09-09 15:08:12 +00003963Sema::DeclPtrTy
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003964Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00003965 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00003966
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003967 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar0ff41922008-09-03 21:54:21 +00003968 VarDecl::StorageClass StorageClass = VarDecl::None;
3969 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3970 StorageClass = VarDecl::Register;
3971 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003972 Diag(DS.getStorageClassSpecLoc(),
3973 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00003974 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003975 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003976
3977 if (D.getDeclSpec().isThreadSpecified())
3978 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3979
Eli Friedman574c7452009-04-07 19:37:57 +00003980 DiagnoseFunctionSpecifiers(D);
3981
Douglas Gregorcaa8ace2008-05-07 04:49:29 +00003982 // Check that there are no default arguments inside the type of this
3983 // parameter (C++ only).
3984 if (getLangOptions().CPlusPlus)
3985 CheckExtraCXXDefaultArguments(D);
Mike Stump11289f42009-09-09 15:08:12 +00003986
John McCallbcd03502009-12-07 02:54:59 +00003987 TypeSourceInfo *TInfo = 0;
Douglas Gregord6ab8742009-05-28 23:31:59 +00003988 TagDecl *OwnedDecl = 0;
John McCallbcd03502009-12-07 02:54:59 +00003989 QualType parmDeclType = GetTypeForDeclarator(D, S, &TInfo, &OwnedDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003990
Douglas Gregord6ab8742009-05-28 23:31:59 +00003991 if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
3992 // C++ [dcl.fct]p6:
3993 // Types shall not be defined in return or parameter types.
3994 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
3995 << Context.getTypeDeclType(OwnedDecl);
3996 }
3997
Chris Lattnerc284e9b2007-01-23 05:14:32 +00003998 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
3999 // Can this happen for params? We already checked that they don't conflict
4000 // among each other. Here they can only shadow globals, which is ok.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004001 IdentifierInfo *II = D.getIdentifier();
Chris Lattnerd9773512009-01-21 02:38:50 +00004002 if (II) {
John McCall9f3059a2009-10-09 21:13:30 +00004003 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00004004 if (PrevDecl->isTemplateParameter()) {
4005 // Maybe we will complain about the shadowed template parameter.
4006 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4007 // Just pretend that we didn't see the previous declaration.
4008 PrevDecl = 0;
Chris Lattner83f095c2009-03-28 19:18:32 +00004009 } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
Chris Lattnerd9773512009-01-21 02:38:50 +00004010 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004011
Chris Lattnerd9773512009-01-21 02:38:50 +00004012 // Recover by removing the name
4013 II = 0;
4014 D.SetIdentifier(0, D.getIdentifierLoc());
4015 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004016 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00004017 }
Steve Naroff773df5c2007-08-07 22:44:21 +00004018
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004019 // Parameters can not be abstract class types.
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004020 // For record types, this is done by the AbstractClassUsageDiagnoser once
Mike Stump11289f42009-09-09 15:08:12 +00004021 // the class has been completely parsed.
4022 if (!CurContext->isRecord() &&
4023 RequireNonAbstractType(D.getIdentifierLoc(), parmDeclType,
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004024 diag::err_abstract_type_in_decl,
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004025 AbstractParamType))
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004026 D.setInvalidType(true);
Douglas Gregor91f84212008-12-11 16:49:14 +00004027
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004028 QualType T = adjustParameterType(parmDeclType);
Mike Stump11289f42009-09-09 15:08:12 +00004029
John McCall856bbea2009-10-23 21:48:59 +00004030 ParmVarDecl *New
4031 = ParmVarDecl::Create(Context, CurContext, D.getIdentifierLoc(), II,
John McCallbcd03502009-12-07 02:54:59 +00004032 T, TInfo, StorageClass, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004033
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004034 if (D.isInvalidType())
Steve Naroffcf871f52007-08-28 18:45:29 +00004035 New->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +00004036
Steve Naroff32606412009-02-20 22:59:16 +00004037 // Parameter declarators cannot be interface types. All ObjC objects are
4038 // passed by reference.
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004039 if (T->isObjCInterfaceType()) {
Chris Lattnerde5a5312009-04-11 19:08:56 +00004040 Diag(D.getIdentifierLoc(),
4041 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
Steve Naroff32606412009-02-20 22:59:16 +00004042 New->setInvalidDecl();
4043 }
Mike Stump11289f42009-09-09 15:08:12 +00004044
Chris Lattner9713a1c2009-04-11 19:34:56 +00004045 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4046 if (D.getCXXScopeSpec().isSet()) {
4047 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
4048 << D.getCXXScopeSpec().getRange();
4049 New->setInvalidDecl();
4050 }
Tanya Lattnerfd2dcba2009-09-30 20:47:43 +00004051
4052 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4053 // duration shall not be qualified by an address-space qualifier."
4054 // Since all parameters have automatic store duration, they can not have
4055 // an address space.
4056 if (T.getAddressSpace() != 0) {
4057 Diag(D.getIdentifierLoc(),
4058 diag::err_arg_with_address_space);
4059 New->setInvalidDecl();
4060 }
4061
4062
Douglas Gregor91f84212008-12-11 16:49:14 +00004063 // Add the parameter declaration into this scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00004064 S->AddDecl(DeclPtrTy::make(New));
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00004065 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00004066 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00004067
Douglas Gregor758a8692009-06-17 21:51:59 +00004068 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00004069
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004070 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00004071 Diag(New->getLocation(), diag::err_block_on_nonlocal);
4072 }
Chris Lattner83f095c2009-03-28 19:18:32 +00004073 return DeclPtrTy::make(New);
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00004074}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00004075
Douglas Gregor170512f2009-04-01 23:51:29 +00004076void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4077 SourceLocation LocAfterDecls) {
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00004078 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4079 "Not a function declarator!");
4080 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004081
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00004082 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
4083 // for a K&R function.
4084 if (!FTI.hasPrototype) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00004085 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
4086 --i;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004087 if (FTI.ArgInfo[i].Param == 0) {
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00004088 llvm::SmallString<256> Code;
4089 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar07d07852009-10-18 21:17:35 +00004090 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00004091 << ";\n";
Chris Lattner4bd8dd82008-11-19 08:23:25 +00004092 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregor170512f2009-04-01 23:51:29 +00004093 << FTI.ArgInfo[i].Ident
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00004094 << CodeModificationHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00004095
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00004096 // Implicitly declare the argument as type 'int' for lack of a better
4097 // type.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004098 DeclSpec DS;
4099 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00004100 unsigned DiagID; // unused
Mike Stump11289f42009-09-09 15:08:12 +00004101 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCall49bfce42009-08-03 20:12:06 +00004102 PrevSpec, DiagID);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004103 Declarator ParamD(DS, Declarator::KNRTypeListContext);
4104 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor9aa89042009-01-23 16:23:13 +00004105 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00004106 }
4107 }
Mike Stump11289f42009-09-09 15:08:12 +00004108 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00004109}
4110
Chris Lattner83f095c2009-03-28 19:18:32 +00004111Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
4112 Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00004113 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4114 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4115 "Not a function declarator!");
4116 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4117
4118 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004119 // FIXME: Diagnose arguments without names in C.
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00004120 }
Mike Stump11289f42009-09-09 15:08:12 +00004121
Douglas Gregorad590502008-12-15 23:53:10 +00004122 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00004123
Mike Stump11289f42009-09-09 15:08:12 +00004124 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004125 MultiTemplateParamsArg(*this),
4126 /*IsFunctionDefinition=*/true);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004127 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004128}
4129
Anders Carlsson31c7e882009-12-09 03:30:09 +00004130static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
4131 // Don't warn about invalid declarations.
4132 if (FD->isInvalidDecl())
4133 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00004134
Anders Carlsson31c7e882009-12-09 03:30:09 +00004135 // Or declarations that aren't global.
4136 if (!FD->isGlobal())
4137 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00004138
Anders Carlsson31c7e882009-12-09 03:30:09 +00004139 // Don't warn about C++ member functions.
4140 if (isa<CXXMethodDecl>(FD))
4141 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00004142
Anders Carlsson31c7e882009-12-09 03:30:09 +00004143 // Don't warn about 'main'.
4144 if (FD->isMain())
4145 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00004146
Anders Carlsson31c7e882009-12-09 03:30:09 +00004147 // Don't warn about inline functions.
4148 if (FD->isInlineSpecified())
4149 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00004150
4151 // Don't warn about function templates.
4152 if (FD->getDescribedFunctionTemplate())
4153 return false;
4154
4155 // Don't warn about function template specializations.
4156 if (FD->isFunctionTemplateSpecialization())
4157 return false;
4158
Anders Carlsson31c7e882009-12-09 03:30:09 +00004159 bool MissingPrototype = true;
4160 for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
4161 Prev; Prev = Prev->getPreviousDeclaration()) {
4162 // Ignore any declarations that occur in function or method
4163 // scope, because they aren't visible from the header.
4164 if (Prev->getDeclContext()->isFunctionOrMethod())
4165 continue;
4166
4167 MissingPrototype = !Prev->getType()->isFunctionProtoType();
4168 break;
4169 }
4170
4171 return MissingPrototype;
4172}
4173
Chris Lattner83f095c2009-03-28 19:18:32 +00004174Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00004175 // Clear the last template instantiation error context.
4176 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
4177
Douglas Gregor17a7c122009-06-24 00:54:41 +00004178 if (!D)
4179 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00004180 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004181
4182 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorc45a40a2009-08-22 00:34:47 +00004183 = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
4184 FD = FunTmpl->getTemplatedDecl();
4185 else
4186 FD = cast<FunctionDecl>(D.getAs<Decl>());
Douglas Gregorcad304ba2008-10-29 15:10:40 +00004187
Chris Lattner9fecd742009-04-19 05:21:20 +00004188 CurFunctionNeedsScopeChecking = false;
Mike Stump11289f42009-09-09 15:08:12 +00004189
Douglas Gregorcad304ba2008-10-29 15:10:40 +00004190 // See if this is a redefinition.
4191 const FunctionDecl *Definition;
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004192 if (FD->getBody(Definition)) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00004193 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00004194 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00004195 }
4196
Douglas Gregor75a45ba2009-02-16 17:45:42 +00004197 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00004198 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor7a0febe2009-02-17 16:03:01 +00004199 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00004200 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00004201 FD->setInvalidDecl();
4202 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00004203 }
4204
Eli Friedman9ad72442009-03-04 07:30:59 +00004205 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00004206 // (C99 6.9.1p3, C++ [dcl.fct]p6).
4207 QualType ResultType = FD->getResultType();
4208 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00004209 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00004210 RequireCompleteType(FD->getLocation(), ResultType,
4211 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00004212 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00004213
Douglas Gregorf1b876d2009-03-31 16:35:03 +00004214 // GNU warning -Wmissing-prototypes:
4215 // Warn if a global function is defined without a previous
4216 // prototype declaration. This warning is issued even if the
4217 // definition itself provides a prototype. The aim is to detect
4218 // global functions that fail to be declared in header files.
Anders Carlsson31c7e882009-12-09 03:30:09 +00004219 if (ShouldWarnAboutMissingPrototype(FD))
4220 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Douglas Gregorf1b876d2009-03-31 16:35:03 +00004221
Douglas Gregor67da0d92009-05-15 17:59:04 +00004222 if (FnBodyScope)
4223 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00004224
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004225 // Check the validity of our function parameters
4226 CheckParmsForFunctionDef(FD);
4227
4228 // Introduce our parameters into the function scope
4229 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
4230 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc72e6452009-01-09 18:51:29 +00004231 Param->setOwningFunction(FD);
4232
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004233 // If this has an identifier, add it to the scope stack.
Douglas Gregor67da0d92009-05-15 17:59:04 +00004234 if (Param->getIdentifier() && FnBodyScope)
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00004235 PushOnScopeChains(Param, FnBodyScope);
Chris Lattnerf61c8a82007-01-21 19:04:43 +00004236 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004237
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00004238 // Checking attributes of current function definition
4239 // dllimport attribute.
Mike Stump11289f42009-09-09 15:08:12 +00004240 if (FD->getAttr<DLLImportAttr>() &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004241 (!FD->getAttr<DLLExportAttr>())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00004242 // dllimport attribute cannot be applied to definition.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004243 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00004244 Diag(FD->getLocation(),
4245 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
4246 << "dllimport";
4247 FD->setInvalidDecl();
Chris Lattner83f095c2009-03-28 19:18:32 +00004248 return DeclPtrTy::make(FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00004249 } else {
4250 // If a symbol previously declared dllimport is later defined, the
4251 // attribute is ignored in subsequent references, and a warning is
4252 // emitted.
4253 Diag(FD->getLocation(),
4254 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4255 << FD->getNameAsCString() << "dllimport";
4256 }
4257 }
Chris Lattner83f095c2009-03-28 19:18:32 +00004258 return DeclPtrTy::make(FD);
Chris Lattnere168f762006-11-10 05:29:30 +00004259}
4260
Chris Lattner83f095c2009-03-28 19:18:32 +00004261Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
Douglas Gregor67da0d92009-05-15 17:59:04 +00004262 return ActOnFinishFunctionBody(D, move(BodyArg), false);
4263}
4264
4265Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
4266 bool IsInstantiation) {
Chris Lattner83f095c2009-03-28 19:18:32 +00004267 Decl *dcl = D.getAs<Decl>();
Sebastian Redla7b98a72009-04-26 20:35:05 +00004268 Stmt *Body = BodyArg.takeAs<Stmt>();
Douglas Gregorc45a40a2009-08-22 00:34:47 +00004269
4270 FunctionDecl *FD = 0;
4271 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
4272 if (FunTmpl)
4273 FD = FunTmpl->getTemplatedDecl();
4274 else
4275 FD = dyn_cast_or_null<FunctionDecl>(dcl);
4276
4277 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00004278 FD->setBody(Body);
Douglas Gregor16618f22009-09-12 00:17:51 +00004279 if (FD->isMain())
Mike Stump8e79f992009-07-24 02:49:01 +00004280 // C and C++ allow for main to automagically return 0.
John McCallcaa19452009-07-28 01:00:58 +00004281 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
4282 FD->setHasImplicitReturnZero(true);
4283 else
Mike Stump33979f72009-07-22 23:56:57 +00004284 CheckFallThroughForFunctionDef(FD, Body);
Mike Stump11289f42009-09-09 15:08:12 +00004285
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004286 if (!FD->isInvalidDecl())
4287 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Mike Stump11289f42009-09-09 15:08:12 +00004288
Anders Carlsson82fccd02009-12-07 08:24:59 +00004289 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
4290 MaybeMarkVirtualMembersReferenced(Method->getLocation(), Method);
Mike Stump11289f42009-09-09 15:08:12 +00004291
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00004292 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00004293 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00004294 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00004295 MD->setBody(Body);
Mike Stump8e79f992009-07-24 02:49:01 +00004296 CheckFallThroughForFunctionDef(MD, Body);
Argyrios Kyrtzidis02675dc2009-07-18 00:33:33 +00004297 MD->setEndLoc(Body->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004298
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004299 if (!MD->isInvalidDecl())
4300 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Ted Kremenek5a201952009-02-07 01:47:29 +00004301 } else {
4302 Body->Destroy(Context);
Chris Lattner83f095c2009-03-28 19:18:32 +00004303 return DeclPtrTy();
Ted Kremenek5a201952009-02-07 01:47:29 +00004304 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00004305 if (!IsInstantiation)
4306 PopDeclContext();
4307
Chris Lattnere2473062007-05-28 06:28:18 +00004308 // Verify and clean out per-function state.
Eli Friedmanf69d09b2009-02-28 05:41:13 +00004309
Chris Lattnerf95894c2009-04-18 20:05:34 +00004310 assert(&getLabelMap() == &FunctionLabelMap && "Didn't pop block right?");
Mike Stump11289f42009-09-09 15:08:12 +00004311
Chris Lattnere2473062007-05-28 06:28:18 +00004312 // Check goto/label use.
Steve Naroff846b1ec2009-03-13 15:38:40 +00004313 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
Chris Lattner3318e862009-04-18 20:01:55 +00004314 I = FunctionLabelMap.begin(), E = FunctionLabelMap.end(); I != E; ++I) {
Chris Lattnerca4dc2e2009-04-18 19:30:02 +00004315 LabelStmt *L = I->second;
Mike Stump11289f42009-09-09 15:08:12 +00004316
Chris Lattnere2473062007-05-28 06:28:18 +00004317 // Verify that we have no forward references left. If so, there was a goto
4318 // or address of a label taken, but no definition of it. Label fwd
4319 // definitions are indicated with a null substmt.
Chris Lattnerca4dc2e2009-04-18 19:30:02 +00004320 if (L->getSubStmt() != 0)
4321 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004322
Chris Lattnerca4dc2e2009-04-18 19:30:02 +00004323 // Emit error.
4324 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Mike Stump11289f42009-09-09 15:08:12 +00004325
Chris Lattnerca4dc2e2009-04-18 19:30:02 +00004326 // At this point, we have gotos that use the bogus label. Stitch it into
4327 // the function body so that they aren't leaked and that the AST is well
4328 // formed.
4329 if (Body == 0) {
4330 // The whole function wasn't parsed correctly, just delete this.
4331 L->Destroy(Context);
4332 continue;
Chris Lattnere2473062007-05-28 06:28:18 +00004333 }
Mike Stump11289f42009-09-09 15:08:12 +00004334
Chris Lattnerca4dc2e2009-04-18 19:30:02 +00004335 // Otherwise, the body is valid: we want to stitch the label decl into the
4336 // function somewhere so that it is properly owned and so that the goto
4337 // has a valid target. Do this by creating a new compound stmt with the
4338 // label in it.
Sebastian Redla7b98a72009-04-26 20:35:05 +00004339
Chris Lattnerca4dc2e2009-04-18 19:30:02 +00004340 // Give the label a sub-statement.
4341 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
Sebastian Redla7b98a72009-04-26 20:35:05 +00004342
4343 CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
4344 cast<CXXTryStmt>(Body)->getTryBlock() :
4345 cast<CompoundStmt>(Body);
4346 std::vector<Stmt*> Elements(Compound->body_begin(), Compound->body_end());
Chris Lattnerca4dc2e2009-04-18 19:30:02 +00004347 Elements.push_back(L);
Sebastian Redla7b98a72009-04-26 20:35:05 +00004348 Compound->setStmts(Context, &Elements[0], Elements.size());
Chris Lattnere2473062007-05-28 06:28:18 +00004349 }
Chris Lattner3318e862009-04-18 20:01:55 +00004350 FunctionLabelMap.clear();
Eli Friedmanf69d09b2009-02-28 05:41:13 +00004351
4352 if (!Body) return D;
4353
Chris Lattner1d4fc1b2009-04-18 21:00:42 +00004354 // Verify that that gotos and switch cases don't jump into scopes illegally.
Chris Lattner9fecd742009-04-19 05:21:20 +00004355 if (CurFunctionNeedsScopeChecking)
4356 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00004357
4358 // C++ constructors that have function-try-blocks can't have return
4359 // statements in the handlers of that block. (C++ [except.handle]p14)
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00004360 // Verify this.
Douglas Gregorc45a40a2009-08-22 00:34:47 +00004361 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
Sebastian Redl4c018662009-04-27 21:33:24 +00004362 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00004363
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00004364 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
Anders Carlssondee9a302009-11-17 04:44:12 +00004365 MarkBaseAndMemberDestructorsReferenced(Destructor);
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00004366
Douglas Gregora7e3ea32009-11-15 07:07:58 +00004367 // If any errors have occurred, clear out any temporaries that may have
4368 // been leftover. This ensures that these temporaries won't be picked up for
4369 // deletion in some later function.
4370 if (PP.getDiagnostics().hasErrorOccurred())
4371 ExprTemporaries.clear();
4372
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00004373 assert(ExprTemporaries.empty() && "Leftover temporaries in function");
Steve Naroffb313fc32007-11-11 23:20:51 +00004374 return D;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00004375}
4376
Chris Lattnerac18be92006-11-20 06:49:47 +00004377/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4378/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00004379NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004380 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004381 // Before we produce a declaration for an implicitly defined
4382 // function, see whether there was a locally-scoped declaration of
4383 // this name as a function or variable. If so, use that
4384 // (non-visible) declaration, and complain about it.
4385 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4386 = LocallyScopedExternalDecls.find(&II);
4387 if (Pos != LocallyScopedExternalDecls.end()) {
4388 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
4389 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
4390 return Pos->second;
4391 }
4392
Chris Lattner00e26072008-05-05 21:18:06 +00004393 // Extension in C99. Legal in C90, but warn about it.
Daniel Dunbar07d07852009-10-18 21:17:35 +00004394 if (II.getName().startswith("__builtin_"))
Douglas Gregor56fbc372009-09-28 21:14:19 +00004395 Diag(Loc, diag::warn_builtin_unknown) << &II;
4396 else if (getLangOptions().C99)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00004397 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner00e26072008-05-05 21:18:06 +00004398 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00004399 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00004400
Chris Lattnerac18be92006-11-20 06:49:47 +00004401 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00004402 const char *Dummy;
Chris Lattnerac18be92006-11-20 06:49:47 +00004403 DeclSpec DS;
John McCall49bfce42009-08-03 20:12:06 +00004404 unsigned DiagID;
4405 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Chris Lattnerb055f2d2007-02-11 08:19:57 +00004406 Error = Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00004407 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +00004408 Declarator D(DS, Declarator::BlockContext);
Sebastian Redl2b9cacb2009-04-29 17:30:04 +00004409 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
Sebastian Redlfb3f1792009-05-31 11:47:27 +00004410 0, 0, false, SourceLocation(),
Argyrios Kyrtzidis20cf1912009-08-19 23:14:54 +00004411 false, 0,0,0, Loc, Loc, D),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004412 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00004413 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004414
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00004415 // Insert this function into translation-unit scope.
4416
4417 DeclContext *PrevDC = CurContext;
4418 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004419
4420 FunctionDecl *FD =
Douglas Gregor4a75be22009-06-23 21:43:56 +00004421 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
Steve Naroff3913ea42008-04-04 14:32:09 +00004422 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00004423
4424 CurContext = PrevDC;
4425
Douglas Gregore711f702009-02-14 18:57:46 +00004426 AddKnownFunctionAttributes(FD);
4427
Steve Naroff3913ea42008-04-04 14:32:09 +00004428 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +00004429}
4430
Douglas Gregore711f702009-02-14 18:57:46 +00004431/// \brief Adds any function attributes that we know a priori based on
4432/// the declaration of this function.
4433///
4434/// These attributes can apply both to implicitly-declared builtins
4435/// (like __builtin___printf_chk) or to library-declared functions
4436/// like NSLog or printf.
4437void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
4438 if (FD->isInvalidDecl())
4439 return;
4440
4441 // If this is a built-in function, map its builtin attributes to
4442 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +00004443 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +00004444 // Handle printf-formatting attributes.
4445 unsigned FormatIdx;
4446 bool HasVAListArg;
4447 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004448 if (!FD->getAttr<FormatAttr>())
4449 FD->addAttr(::new (Context) FormatAttr("printf", FormatIdx + 1,
Eli Friedmanf4799842009-06-10 04:01:38 +00004450 HasVAListArg ? 0 : FormatIdx + 2));
Douglas Gregore711f702009-02-14 18:57:46 +00004451 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00004452
4453 // Mark const if we don't care about errno and that is the only
4454 // thing preventing the function from being const. This allows
4455 // IRgen to use LLVM intrinsics for such functions.
4456 if (!getLangOptions().MathErrno &&
4457 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004458 if (!FD->getAttr<ConstAttr>())
4459 FD->addAttr(::new (Context) ConstAttr());
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00004460 }
Mike Stumpca6c8752009-07-27 19:14:18 +00004461
4462 if (Context.BuiltinInfo.isNoReturn(BuiltinID))
4463 FD->addAttr(::new (Context) NoReturnAttr());
Chris Lattner8977c432009-12-30 22:06:22 +00004464 if (Context.BuiltinInfo.isNoThrow(BuiltinID))
4465 FD->addAttr(::new (Context) NoThrowAttr());
4466 if (Context.BuiltinInfo.isConst(BuiltinID))
4467 FD->addAttr(::new (Context) ConstAttr());
Douglas Gregore711f702009-02-14 18:57:46 +00004468 }
4469
4470 IdentifierInfo *Name = FD->getIdentifier();
4471 if (!Name)
4472 return;
Mike Stump11289f42009-09-09 15:08:12 +00004473 if ((!getLangOptions().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00004474 FD->getDeclContext()->isTranslationUnit()) ||
4475 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00004476 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +00004477 LinkageSpecDecl::lang_c)) {
4478 // Okay: this could be a libc/libm/Objective-C function we know
4479 // about.
4480 } else
4481 return;
4482
Douglas Gregorfedd4282009-04-22 20:56:09 +00004483 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
Mike Stump82a9e442009-07-28 00:07:08 +00004484 // FIXME: NSLog and NSLogv should be target specific
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004485 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
Douglas Gregore711f702009-02-14 18:57:46 +00004486 // FIXME: We known better than our headers.
4487 const_cast<FormatAttr *>(Format)->setType("printf");
Mike Stump11289f42009-09-09 15:08:12 +00004488 } else
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004489 FD->addAttr(::new (Context) FormatAttr("printf", 1,
Eli Friedmanf4799842009-06-10 04:01:38 +00004490 Name->isStr("NSLogv") ? 0 : 2));
Douglas Gregorfedd4282009-04-22 20:56:09 +00004491 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +00004492 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +00004493 // target-specific builtins, perhaps?
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004494 if (!FD->getAttr<FormatAttr>())
4495 FD->addAttr(::new (Context) FormatAttr("printf", 2,
Eli Friedmanf4799842009-06-10 04:01:38 +00004496 Name->isStr("vasprintf") ? 0 : 3));
Mike Stumpa4de80b2009-07-28 02:25:19 +00004497 }
Douglas Gregore711f702009-02-14 18:57:46 +00004498}
Chris Lattner302b4be2006-11-19 02:31:38 +00004499
John McCall703a3f82009-10-24 08:00:42 +00004500TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00004501 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +00004502 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00004503 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +00004504
John McCallbcd03502009-12-07 02:54:59 +00004505 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +00004506 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +00004507 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +00004508 }
4509
Chris Lattner18b19622007-01-22 07:39:13 +00004510 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004511 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
4512 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +00004513 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +00004514 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004515
John McCallb2e195a2009-09-05 06:31:47 +00004516 if (const TagType *TT = T->getAs<TagType>()) {
Anders Carlsson02751152009-03-10 17:07:44 +00004517 TagDecl *TD = TT->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004518
Anders Carlsson02751152009-03-10 17:07:44 +00004519 // If the TagDecl that the TypedefDecl points to is an anonymous decl
4520 // keep track of the TypedefDecl.
4521 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
4522 TD->setTypedefForAnonDecl(NewTD);
4523 }
4524
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004525 if (D.isInvalidType())
Steve Narofff93b6722007-08-28 20:14:24 +00004526 NewTD->setInvalidDecl();
4527 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00004528}
4529
Douglas Gregord9034f02009-05-14 16:41:31 +00004530
4531/// \brief Determine whether a tag with a given kind is acceptable
4532/// as a redeclaration of the given tag declaration.
4533///
4534/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004535bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Douglas Gregord9034f02009-05-14 16:41:31 +00004536 TagDecl::TagKind NewTag,
4537 SourceLocation NewTagLoc,
4538 const IdentifierInfo &Name) {
4539 // C++ [dcl.type.elab]p3:
4540 // The class-key or enum keyword present in the
4541 // elaborated-type-specifier shall agree in kind with the
4542 // declaration to which the name in theelaborated-type-specifier
4543 // refers. This rule also applies to the form of
4544 // elaborated-type-specifier that declares a class-name or
4545 // friend class since it can be construed as referring to the
4546 // definition of the class. Thus, in any
4547 // elaborated-type-specifier, the enum keyword shall be used to
4548 // refer to an enumeration (7.2), the union class-keyshall be
4549 // used to refer to a union (clause 9), and either the class or
4550 // struct class-key shall be used to refer to a class (clause 9)
4551 // declared using the class or struct class-key.
4552 TagDecl::TagKind OldTag = Previous->getTagKind();
4553 if (OldTag == NewTag)
4554 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004555
Douglas Gregord9034f02009-05-14 16:41:31 +00004556 if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) &&
4557 (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) {
4558 // Warn about the struct/class tag mismatch.
4559 bool isTemplate = false;
4560 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
4561 isTemplate = Record->getDescribedClassTemplate();
4562
4563 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
4564 << (NewTag == TagDecl::TK_class)
4565 << isTemplate << &Name
Douglas Gregord9034f02009-05-14 16:41:31 +00004566 << CodeModificationHint::CreateReplacement(SourceRange(NewTagLoc),
4567 OldTag == TagDecl::TK_class? "class" : "struct");
4568 Diag(Previous->getLocation(), diag::note_previous_use);
4569 return true;
4570 }
4571 return false;
4572}
4573
Steve Naroff30d242c2007-09-15 18:49:24 +00004574/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00004575/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +00004576/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +00004577/// reference/declaration/definition of a tag.
John McCall9bb74a52009-07-31 02:45:11 +00004578Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Chris Lattner83f095c2009-03-28 19:18:32 +00004579 SourceLocation KWLoc, const CXXScopeSpec &SS,
4580 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregord6ab8742009-05-28 23:31:59 +00004581 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004582 MultiTemplateParamsArg TemplateParameterLists,
John McCall7f41d982009-09-11 04:59:25 +00004583 bool &OwnedDecl, bool &IsDependent) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004584 // If this is not a definition, it must have a name.
John McCall9bb74a52009-07-31 02:45:11 +00004585 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +00004586 "Nameless record must be a definition!");
Douglas Gregorded2d7b2009-02-04 19:02:06 +00004587
Douglas Gregord6ab8742009-05-28 23:31:59 +00004588 OwnedDecl = false;
John McCall06f6fe8d2009-09-04 01:14:41 +00004589 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00004590
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004591 // FIXME: Check explicit specializations more carefully.
4592 bool isExplicitSpecialization = false;
John McCall9bb74a52009-07-31 02:45:11 +00004593 if (TUK != TUK_Reference) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00004594 if (TemplateParameterList *TemplateParams
4595 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
4596 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004597 TemplateParameterLists.size(),
4598 isExplicitSpecialization)) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00004599 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00004600 // This is a declaration or definition of a class template (which may
4601 // be a member of another template).
4602 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +00004603 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004604 SS, Name, NameLoc, Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004605 TemplateParams,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004606 AS);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004607 TemplateParameterLists.release();
Douglas Gregore93e46c2009-07-22 23:48:44 +00004608 return Result.get();
4609 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004610 // The "template<>" header is extraneous.
4611 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
4612 << ElaboratedType::getNameForTagKind(Kind) << Name;
4613 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +00004614 }
Mike Stump11289f42009-09-09 15:08:12 +00004615 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004616
4617 TemplateParameterLists.release();
Mike Stump11289f42009-09-09 15:08:12 +00004618 }
4619
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00004620 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00004621 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +00004622 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +00004623 bool Invalid = false;
4624
John McCall1f82f242009-11-18 22:49:29 +00004625 RedeclarationKind Redecl = (TUK != TUK_Reference ? ForRedeclaration
4626 : NotForRedeclaration);
4627
4628 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
John McCall6538c932009-10-10 05:48:19 +00004629
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00004630 if (Name && SS.isNotEmpty()) {
4631 // We have a nested-name tag ('struct foo::bar').
4632
4633 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00004634 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00004635 Name = 0;
4636 goto CreateNewDecl;
4637 }
4638
John McCall7f41d982009-09-11 04:59:25 +00004639 // If this is a friend or a reference to a class in a dependent
4640 // context, don't try to make a decl for it.
4641 if (TUK == TUK_Friend || TUK == TUK_Reference) {
4642 DC = computeDeclContext(SS, false);
4643 if (!DC) {
4644 IsDependent = true;
4645 return DeclPtrTy();
4646 }
4647 }
4648
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004649 if (RequireCompleteDeclContext(SS))
4650 return DeclPtrTy::make((Decl *)0);
4651
Douglas Gregord8d297c2009-07-21 23:53:31 +00004652 DC = computeDeclContext(SS, true);
Douglas Gregor8761da52009-02-03 00:34:39 +00004653 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00004654 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +00004655 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +00004656
John McCall1f82f242009-11-18 22:49:29 +00004657 if (Previous.isAmbiguous())
John McCall6538c932009-10-10 05:48:19 +00004658 return DeclPtrTy();
John McCall6538c932009-10-10 05:48:19 +00004659
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00004660 // A tag 'foo::bar' must already exist.
John McCall1f82f242009-11-18 22:49:29 +00004661 if (Previous.empty()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00004662 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00004663 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004664 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00004665 goto CreateNewDecl;
4666 }
Chris Lattnerd9773512009-01-21 02:38:50 +00004667 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00004668 // If this is a named struct, check to see if there was a previous forward
4669 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +00004670 // FIXME: We're looking into outer scopes here, even when we
4671 // shouldn't be. Doing so can result in ambiguities that we
4672 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +00004673 LookupName(Previous, S);
4674
4675 // Note: there used to be some attempt at recovery here.
4676 if (Previous.isAmbiguous())
4677 return DeclPtrTy();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004678
John McCall9bb74a52009-07-31 02:45:11 +00004679 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004680 // FIXME: This makes sure that we ignore the contexts associated
4681 // with C structs, unions, and enums when looking for a matching
4682 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +00004683 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00004684 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
4685 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004686 }
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00004687 }
4688
John McCall1f82f242009-11-18 22:49:29 +00004689 if (Previous.isSingleResult() &&
4690 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00004691 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +00004692 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +00004693 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00004694 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00004695 }
4696
Douglas Gregor87f54062009-09-15 22:30:29 +00004697 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
4698 DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) {
4699 // This is a declaration of or a reference to "std::bad_alloc".
4700 isStdBadAlloc = true;
4701
John McCall1f82f242009-11-18 22:49:29 +00004702 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +00004703 // std::bad_alloc has been implicitly declared (but made invisible to
4704 // name lookup). Fill in this implicit declaration as the previous
4705 // declaration, so that the declarations get chained appropriately.
John McCall1f82f242009-11-18 22:49:29 +00004706 Previous.addDecl(StdBadAlloc);
Douglas Gregor87f54062009-09-15 22:30:29 +00004707 }
4708 }
John McCall1f82f242009-11-18 22:49:29 +00004709
4710 if (!Previous.empty()) {
4711 assert(Previous.isSingleResult());
4712 NamedDecl *PrevDecl = Previous.getFoundDecl();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004713 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00004714 // If this is a use of a previous tag, or if the tag is already declared
4715 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004716 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +00004717 if (TUK == TUK_Reference || TUK == TUK_Friend ||
4718 isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00004719 // Make sure that this wasn't declared as an enum and now used as a
4720 // struct or something similar.
Douglas Gregord9034f02009-05-14 16:41:31 +00004721 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00004722 bool SafeToContinue
Douglas Gregor170512f2009-04-01 23:51:29 +00004723 = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
4724 Kind != TagDecl::TK_enum);
4725 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +00004726 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00004727 << Name
4728 << CodeModificationHint::CreateReplacement(SourceRange(KWLoc),
4729 PrevTagDecl->getKindName());
4730 else
4731 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +00004732 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00004733
Mike Stump11289f42009-09-09 15:08:12 +00004734 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +00004735 Kind = PrevTagDecl->getTagKind();
4736 else {
4737 // Recover by making this an anonymous redefinition.
4738 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00004739 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +00004740 Invalid = true;
4741 }
4742 }
4743
4744 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004745 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +00004746
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004747 // FIXME: In the future, return a variant or some other clue
4748 // for the consumer of this Decl to know it doesn't own it.
4749 // For our current ASTs this shouldn't be a problem, but will
4750 // need to be changed with DeclGroups.
John McCallc3987482009-10-07 23:34:25 +00004751 if (TUK == TUK_Reference || TUK == TUK_Friend)
John McCall1f82f242009-11-18 22:49:29 +00004752 return DeclPtrTy::make(PrevTagDecl);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00004753
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004754 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +00004755 if (TUK == TUK_Definition) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004756 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00004757 // If we're defining a specialization and the previous definition
4758 // is from an implicit instantiation, don't emit an error
4759 // here; we'll catch this in the general case below.
4760 if (!isExplicitSpecialization ||
4761 !isa<CXXRecordDecl>(Def) ||
4762 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
4763 == TSK_ExplicitSpecialization) {
4764 Diag(NameLoc, diag::err_redefinition) << Name;
4765 Diag(Def->getLocation(), diag::note_previous_definition);
4766 // If this is a redefinition, recover by making this
4767 // struct be anonymous, which will make any later
4768 // references get the previous definition.
4769 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00004770 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004771 Invalid = true;
4772 }
Douglas Gregordee1be82009-01-17 00:42:38 +00004773 } else {
4774 // If the type is currently being defined, complain
4775 // about a nested redefinition.
4776 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
4777 if (Tag->isBeingDefined()) {
4778 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +00004779 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +00004780 diag::note_previous_definition);
4781 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00004782 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +00004783 Invalid = true;
4784 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004785 }
Douglas Gregordee1be82009-01-17 00:42:38 +00004786
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004787 // Okay, this is definition of a previously declared or referenced
4788 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +00004789 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004790 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004791 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +00004792 // have a definition. Just create a new decl.
4793
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004794 } else {
4795 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +00004796 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004797 // new decl/type. We set PrevDecl to NULL so that the entities
4798 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +00004799 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +00004800 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004801 // If we get here, we're going to create a new Decl. If PrevDecl
4802 // is non-NULL, it's a definition of the tag declared by
4803 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004804 } else {
Douglas Gregorfb034662009-01-28 17:15:10 +00004805 // PrevDecl is a namespace, template, or anything else
4806 // that lives in the IDNS_Tag identifier namespace.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00004807 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremenek3060d982008-09-03 18:03:35 +00004808 // The tag name clashes with a namespace name, issue an error and
4809 // recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00004810 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +00004811 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00004812 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00004813 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +00004814 Invalid = true;
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004815 } else {
4816 // The existing declaration isn't relevant to us; we're in a
4817 // new scope, so clear out the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00004818 Previous.clear();
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00004819 }
Chris Lattner8799cf22007-01-23 01:57:16 +00004820 }
John McCall9f545182009-12-04 00:07:04 +00004821 } else if (TUK == TUK_Reference && SS.isEmpty() && Name) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004822 // C++ [basic.scope.pdecl]p5:
Mike Stump11289f42009-09-09 15:08:12 +00004823 // -- for an elaborated-type-specifier of the form
Douglas Gregor658b9552009-01-09 22:42:13 +00004824 //
4825 // class-key identifier
4826 //
4827 // if the elaborated-type-specifier is used in the
4828 // decl-specifier-seq or parameter-declaration-clause of a
4829 // function defined in namespace scope, the identifier is
4830 // declared as a class-name in the namespace that contains
4831 // the declaration; otherwise, except as a friend
4832 // declaration, the identifier is declared in the smallest
4833 // non-class, non-function-prototype scope that contains the
4834 // declaration.
4835 //
4836 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
4837 // C structs and unions.
Douglas Gregord45b93b2009-03-06 18:34:03 +00004838 //
John McCall9f545182009-12-04 00:07:04 +00004839 // It is an error in C++ to declare (rather than define) an enum
4840 // type, including via an elaborated type specifier. We'll
4841 // diagnose that later; for now, declare the enum in the same
4842 // scope as we would have picked for any other tag type.
4843 //
Douglas Gregord45b93b2009-03-06 18:34:03 +00004844 // GNU C also supports this behavior as part of its incomplete
4845 // enum types extension, while GNU C++ does not.
4846 //
Douglas Gregor658b9552009-01-09 22:42:13 +00004847 // Find the context where we'll be declaring the tag.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00004848 // FIXME: We would like to maintain the current DeclContext as the
Mike Stump11289f42009-09-09 15:08:12 +00004849 // lexical context,
Douglas Gregor8761da52009-02-03 00:34:39 +00004850 while (SearchDC->isRecord())
4851 SearchDC = SearchDC->getParent();
Douglas Gregor658b9552009-01-09 22:42:13 +00004852
4853 // Find the scope where we'll be declaring the tag.
Mike Stump11289f42009-09-09 15:08:12 +00004854 while (S->isClassScope() ||
Douglas Gregor658b9552009-01-09 22:42:13 +00004855 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor45a33ec2009-01-12 18:45:55 +00004856 ((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump11289f42009-09-09 15:08:12 +00004857 (S->getEntity() &&
Douglas Gregor45a33ec2009-01-12 18:45:55 +00004858 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregor658b9552009-01-09 22:42:13 +00004859 S = S->getParent();
John McCall07e91c02009-08-06 02:15:43 +00004860
4861 } else if (TUK == TUK_Friend && SS.isEmpty() && Name) {
4862 // C++ [namespace.memdef]p3:
4863 // If a friend declaration in a non-local class first declares a
4864 // class or function, the friend class or function is a member of
4865 // the innermost enclosing namespace.
John McCalld1e9d832009-08-11 06:59:38 +00004866 while (!SearchDC->isFileContext())
John McCall07e91c02009-08-06 02:15:43 +00004867 SearchDC = SearchDC->getParent();
4868
4869 // The entity of a decl scope is a DeclContext; see PushDeclContext.
4870 while (S->getEntity() != SearchDC)
4871 S = S->getParent();
Chris Lattner18b19622007-01-22 07:39:13 +00004872 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004873
Chris Lattner438e5012008-12-17 07:13:27 +00004874CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +00004875
John McCall1f82f242009-11-18 22:49:29 +00004876 TagDecl *PrevDecl = 0;
4877 if (Previous.isSingleResult())
4878 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
4879
Chris Lattnerbf0b7982007-01-23 04:27:41 +00004880 // If there is an identifier, use the location of the identifier as the
4881 // location of the decl, otherwise use the location of the struct/union
4882 // keyword.
4883 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +00004884
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004885 // Otherwise, create a new declaration. If there is a previous
4886 // declaration of the same entity, the two will be linked via
4887 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00004888 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00004889
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00004890 if (Kind == TagDecl::TK_enum) {
Chris Lattner776fac82007-06-09 00:53:06 +00004891 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4892 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor82fe3e32009-07-21 14:46:17 +00004893 New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004894 cast_or_null<EnumDecl>(PrevDecl));
Chris Lattner5f521502007-01-25 06:27:24 +00004895 // If this is an undefined enum, warn.
John McCall9bb74a52009-07-31 02:45:11 +00004896 if (TUK != TUK_Definition && !Invalid) {
Douglas Gregord45b93b2009-03-06 18:34:03 +00004897 unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
4898 : diag::ext_forward_ref_enum;
4899 Diag(Loc, DK);
4900 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00004901 } else {
4902 // struct/union/class
4903
Chris Lattner776fac82007-06-09 00:53:06 +00004904 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4905 // struct X { int A; } D; D should chain to X.
Douglas Gregor87f54062009-09-15 22:30:29 +00004906 if (getLangOptions().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +00004907 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor82fe3e32009-07-21 14:46:17 +00004908 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004909 cast_or_null<CXXRecordDecl>(PrevDecl));
Douglas Gregor87f54062009-09-15 22:30:29 +00004910
4911 if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit()))
4912 StdBadAlloc = cast<CXXRecordDecl>(New);
4913 } else
Douglas Gregor82fe3e32009-07-21 14:46:17 +00004914 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004915 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004916 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004917
4918 if (Kind != TagDecl::TK_enum) {
4919 // Handle #pragma pack: if the #pragma pack stack has non-default
4920 // alignment, make up a packed attribute for this decl. These
4921 // attributes are checked when the ASTContext lays out the
4922 // structure.
4923 //
4924 // It is important for implementing the correct semantics that this
4925 // happen here (in act on tag decl). The #pragma pack stack is
4926 // maintained as a result of parser callbacks which can occur at
4927 // many points during the parsing of a struct declaration (because
4928 // the #pragma tokens are effectively skipped over during the
4929 // parsing of the struct).
Chris Lattner31180bb2009-02-17 01:09:29 +00004930 if (unsigned Alignment = getPragmaPackAlignment())
Anders Carlsson68e0b682009-08-08 18:23:56 +00004931 New->addAttr(::new (Context) PragmaPackAttr(Alignment * 8));
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004932 }
4933
Douglas Gregorfb034662009-01-28 17:15:10 +00004934 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
4935 // C++ [dcl.typedef]p3:
4936 // [...] Similarly, in a given scope, a class or enumeration
4937 // shall not be declared with the same name as a typedef-name
4938 // that is declared in that scope and refers to a type other
4939 // than the class or enumeration itself.
John McCall27b18f82009-11-17 02:14:36 +00004940 LookupResult Lookup(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00004941 ForRedeclaration);
John McCall27b18f82009-11-17 02:14:36 +00004942 LookupName(Lookup, S);
John McCall67c00872009-12-02 08:25:40 +00004943 TypedefDecl *PrevTypedef = Lookup.getAsSingle<TypedefDecl>();
Douglas Gregor505ad492009-09-28 00:47:05 +00004944 NamedDecl *PrevTypedefNamed = PrevTypedef;
4945 if (PrevTypedef && isDeclInScope(PrevTypedefNamed, SearchDC, S) &&
Douglas Gregorfb034662009-01-28 17:15:10 +00004946 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
4947 Context.getCanonicalType(Context.getTypeDeclType(New))) {
4948 Diag(Loc, diag::err_tag_definition_of_typedef)
4949 << Context.getTypeDeclType(New)
4950 << PrevTypedef->getUnderlyingType();
4951 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
4952 Invalid = true;
4953 }
4954 }
4955
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004956 // If this is a specialization of a member class (of a class template),
4957 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +00004958 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004959 Invalid = true;
4960
Douglas Gregordee1be82009-01-17 00:42:38 +00004961 if (Invalid)
4962 New->setInvalidDecl();
4963
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004964 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00004965 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004966
Douglas Gregordee1be82009-01-17 00:42:38 +00004967 // If we're declaring or defining a tag in function prototype scope
4968 // in C, note that this type can only be used within the function.
Douglas Gregor658b9552009-01-09 22:42:13 +00004969 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
4970 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
4971
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004972 // Set the lexical context. If the tag has a C++ scope specifier, the
4973 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +00004974 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +00004975
John McCallaa74a0c2009-08-28 07:59:38 +00004976 // Mark this as a friend decl if applicable.
4977 if (TUK == TUK_Friend)
John McCall1f82f242009-11-18 22:49:29 +00004978 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
John McCallaa74a0c2009-08-28 07:59:38 +00004979
Anders Carlsson5558ca12009-03-26 01:19:02 +00004980 // Set the access specifier.
Eli Friedman1e971082009-08-27 18:44:04 +00004981 if (!Invalid && TUK != TUK_Friend)
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004982 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +00004983
John McCall9bb74a52009-07-31 02:45:11 +00004984 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +00004985 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00004986
Chris Lattner18b19622007-01-22 07:39:13 +00004987 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +00004988 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +00004989 // We might be replacing an existing declaration in the lookup tables;
4990 // if so, borrow its access specifier.
4991 if (PrevDecl)
4992 New->setAccess(PrevDecl->getAccess());
4993
John McCall2dc078f2009-09-02 00:55:30 +00004994 // Friend tag decls are visible in fairly strange ways.
4995 if (!CurContext->isDependentContext()) {
4996 DeclContext *DC = New->getDeclContext()->getLookupContext();
4997 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
4998 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4999 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
5000 }
5001 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +00005002 S = getNonFieldDeclScope(S);
Douglas Gregor8761da52009-02-03 00:34:39 +00005003 PushOnScopeChains(New, S);
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00005004 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005005 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +00005006 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00005007
Douglas Gregor27821ce2009-07-07 16:35:42 +00005008 // If this is the C FILE type, notify the AST context.
5009 if (IdentifierInfo *II = New->getIdentifier())
5010 if (!New->isInvalidDecl() &&
Mike Stumpa4de80b2009-07-28 02:25:19 +00005011 New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +00005012 II->isStr("FILE"))
5013 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +00005014
Douglas Gregord6ab8742009-05-28 23:31:59 +00005015 OwnedDecl = true;
Chris Lattner83f095c2009-03-28 19:18:32 +00005016 return DeclPtrTy::make(New);
Chris Lattner18b19622007-01-22 07:39:13 +00005017}
Chris Lattner1300fb92007-01-23 23:42:53 +00005018
Chris Lattner83f095c2009-03-28 19:18:32 +00005019void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00005020 AdjustDeclIfTemplate(TagD);
Chris Lattner83f095c2009-03-28 19:18:32 +00005021 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005022
5023 // Enter the tag context.
5024 PushDeclContext(S, Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +00005025}
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005026
John McCall1c7e6ec2009-12-20 07:58:13 +00005027void Sema::ActOnStartCXXMemberDeclarations(Scope *S, DeclPtrTy TagD,
5028 SourceLocation LBraceLoc) {
5029 AdjustDeclIfTemplate(TagD);
5030 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD.getAs<Decl>());
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005031
John McCall1c7e6ec2009-12-20 07:58:13 +00005032 FieldCollector->StartClass();
5033
5034 if (!Record->getIdentifier())
5035 return;
5036
5037 // C++ [class]p2:
5038 // [...] The class-name is also inserted into the scope of the
5039 // class itself; this is known as the injected-class-name. For
5040 // purposes of access checking, the injected-class-name is treated
5041 // as if it were a public member name.
5042 CXXRecordDecl *InjectedClassName
5043 = CXXRecordDecl::Create(Context, Record->getTagKind(),
5044 CurContext, Record->getLocation(),
5045 Record->getIdentifier(),
5046 Record->getTagKeywordLoc(),
5047 Record);
5048 InjectedClassName->setImplicit();
5049 InjectedClassName->setAccess(AS_public);
5050 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
5051 InjectedClassName->setDescribedClassTemplate(Template);
5052 PushOnScopeChains(InjectedClassName, S);
5053 assert(InjectedClassName->isInjectedClassName() &&
5054 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005055}
5056
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00005057void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
5058 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00005059 AdjustDeclIfTemplate(TagD);
Chris Lattner83f095c2009-03-28 19:18:32 +00005060 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00005061 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005062
5063 if (isa<CXXRecordDecl>(Tag))
5064 FieldCollector->FinishClass();
5065
5066 // Exit this scope of this tag's definition.
5067 PopDeclContext();
5068
5069 // Notify the consumer that we've defined a tag.
5070 Consumer.HandleTagDeclDefinition(Tag);
5071}
Chris Lattner535b8302008-06-21 19:39:06 +00005072
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00005073// Note that FieldName may be null for anonymous bitfields.
Mike Stump11289f42009-09-09 15:08:12 +00005074bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Eli Friedmanc96d4962009-08-15 21:55:26 +00005075 QualType FieldTy, const Expr *BitWidth,
5076 bool *ZeroWidth) {
5077 // Default to true; that shouldn't confuse checks for emptiness
5078 if (ZeroWidth)
5079 *ZeroWidth = true;
5080
Chris Lattner73bf7b42009-03-05 22:45:59 +00005081 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +00005082 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregor1efa4372009-03-11 18:59:21 +00005083 if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +00005084 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +00005085 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
5086 return true;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00005087 if (FieldName)
5088 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
5089 << FieldName << FieldTy << BitWidth->getSourceRange();
5090 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
5091 << FieldTy << BitWidth->getSourceRange();
Chris Lattner73bf7b42009-03-05 22:45:59 +00005092 }
Douglas Gregor1efa4372009-03-11 18:59:21 +00005093
5094 // If the bit-width is type- or value-dependent, don't try to check
5095 // it now.
5096 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
5097 return false;
5098
Anders Carlsson5df391e2008-12-06 20:33:04 +00005099 llvm::APSInt Value;
5100 if (VerifyIntegerConstantExpression(BitWidth, &Value))
5101 return true;
5102
Eli Friedmanc96d4962009-08-15 21:55:26 +00005103 if (Value != 0 && ZeroWidth)
5104 *ZeroWidth = false;
5105
Chris Lattner81ed6802008-12-12 04:56:04 +00005106 // Zero-width bitfield is ok for anonymous field.
5107 if (Value == 0 && FieldName)
5108 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00005109
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00005110 if (Value.isSigned() && Value.isNegative()) {
5111 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +00005112 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00005113 << FieldName << Value.toString(10);
5114 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
5115 << Value.toString(10);
5116 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00005117
Douglas Gregor1efa4372009-03-11 18:59:21 +00005118 if (!FieldTy->isDependentType()) {
5119 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00005120 if (Value.getZExtValue() > TypeSize) {
5121 if (FieldName)
5122 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
5123 << FieldName << (unsigned)TypeSize;
5124 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
5125 << (unsigned)TypeSize;
5126 }
Douglas Gregor1efa4372009-03-11 18:59:21 +00005127 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00005128
5129 return false;
5130}
5131
Steve Naroff30d242c2007-09-15 18:49:24 +00005132/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00005133/// to create a FieldDecl object for it.
Chris Lattner83f095c2009-03-28 19:18:32 +00005134Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
Mike Stump11289f42009-09-09 15:08:12 +00005135 SourceLocation DeclStart,
Chris Lattner83f095c2009-03-28 19:18:32 +00005136 Declarator &D, ExprTy *BitfieldWidth) {
5137 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
5138 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
5139 AS_public);
5140 return DeclPtrTy::make(Res);
Chris Lattner73bf7b42009-03-05 22:45:59 +00005141}
5142
5143/// HandleField - Analyze a field of a C struct or a C++ data member.
5144///
5145FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
5146 SourceLocation DeclStart,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00005147 Declarator &D, Expr *BitWidth,
5148 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +00005149 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +00005150 SourceLocation Loc = DeclStart;
5151 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00005152
John McCallbcd03502009-12-07 02:54:59 +00005153 TypeSourceInfo *TInfo = 0;
5154 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Chris Lattner090d34c2009-04-12 22:15:02 +00005155 if (getLangOptions().CPlusPlus)
Douglas Gregor1efa4372009-03-11 18:59:21 +00005156 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00005157
Eli Friedman574c7452009-04-07 19:37:57 +00005158 DiagnoseFunctionSpecifiers(D);
5159
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005160 if (D.getDeclSpec().isThreadSpecified())
5161 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5162
John McCall27b18f82009-11-17 02:14:36 +00005163 NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +00005164 ForRedeclaration);
Douglas Gregorf187420f2009-06-17 23:37:01 +00005165
5166 if (PrevDecl && PrevDecl->isTemplateParameter()) {
5167 // Maybe we will complain about the shadowed template parameter.
5168 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5169 // Just pretend that we didn't see the previous declaration.
5170 PrevDecl = 0;
5171 }
5172
Douglas Gregor1efa4372009-03-11 18:59:21 +00005173 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
5174 PrevDecl = 0;
5175
Steve Naroff5ec6ff72009-07-14 14:58:18 +00005176 bool Mutable
5177 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
5178 SourceLocation TSSL = D.getSourceRange().getBegin();
5179 FieldDecl *NewFD
John McCallbcd03502009-12-07 02:54:59 +00005180 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
Steve Naroff5ec6ff72009-07-14 14:58:18 +00005181 AS, PrevDecl, &D);
Douglas Gregor1efa4372009-03-11 18:59:21 +00005182 if (NewFD->isInvalidDecl() && PrevDecl) {
5183 // Don't introduce NewFD into scope; there's already something
5184 // with the same name in the same scope.
5185 } else if (II) {
5186 PushOnScopeChains(NewFD, S);
5187 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005188 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +00005189
5190 return NewFD;
5191}
5192
5193/// \brief Build a new FieldDecl and check its well-formedness.
5194///
5195/// This routine builds a new FieldDecl given the fields name, type,
5196/// record, etc. \p PrevDecl should refer to any previous declaration
5197/// with the same name and in the same scope as the field to be
5198/// created.
5199///
5200/// \returns a new FieldDecl.
5201///
Mike Stump11289f42009-09-09 15:08:12 +00005202/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00005203FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00005204 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +00005205 RecordDecl *Record, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005206 bool Mutable, Expr *BitWidth,
Steve Naroff5ec6ff72009-07-14 14:58:18 +00005207 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00005208 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +00005209 Declarator *D) {
5210 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +00005211 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005212 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005213
Douglas Gregor1efa4372009-03-11 18:59:21 +00005214 // If we receive a broken type, recover by assuming 'int' and
5215 // marking this declaration as invalid.
5216 if (T.isNull()) {
5217 InvalidDecl = true;
5218 T = Context.IntTy;
5219 }
5220
Eli Friedmand0e8de22009-12-07 00:22:08 +00005221 QualType EltTy = Context.getBaseElementType(T);
5222 if (!EltTy->isDependentType() &&
5223 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete))
5224 InvalidDecl = true;
5225
Steve Naroff8eeeb132007-05-08 21:09:37 +00005226 // C99 6.7.2.1p8: A member of a structure or union may have any type other
5227 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +00005228 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00005229 bool SizeIsNegative;
5230 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
5231 SizeIsNegative);
5232 if (!FixedTy.isNull()) {
5233 Diag(Loc, diag::warn_illegal_constant_array_size);
5234 T = FixedTy;
5235 } else {
5236 if (SizeIsNegative)
5237 Diag(Loc, diag::err_typecheck_negative_array_size);
5238 else
5239 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00005240 InvalidDecl = true;
5241 }
Steve Naroff8eeeb132007-05-08 21:09:37 +00005242 }
Mike Stump11289f42009-09-09 15:08:12 +00005243
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005244 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +00005245 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
5246 diag::err_abstract_type_in_decl,
5247 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005248 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +00005249
Eli Friedmanc96d4962009-08-15 21:55:26 +00005250 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +00005251 // If this is declared as a bit-field, check the bit-field.
Eli Friedmand0e8de22009-12-07 00:22:08 +00005252 if (!InvalidDecl && BitWidth &&
5253 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
Douglas Gregor1efa4372009-03-11 18:59:21 +00005254 InvalidDecl = true;
5255 DeleteExpr(BitWidth);
5256 BitWidth = 0;
Eli Friedmanc96d4962009-08-15 21:55:26 +00005257 ZeroWidth = false;
Anders Carlsson5df391e2008-12-06 20:33:04 +00005258 }
Mike Stump11289f42009-09-09 15:08:12 +00005259
John McCallbcd03502009-12-07 02:54:59 +00005260 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00005261 BitWidth, Mutable);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005262 if (InvalidDecl)
5263 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +00005264
Douglas Gregor1efa4372009-03-11 18:59:21 +00005265 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
5266 Diag(Loc, diag::err_duplicate_member) << II;
5267 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5268 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005269 }
5270
Douglas Gregor8a273912009-07-22 18:25:24 +00005271 if (getLangOptions().CPlusPlus) {
Eli Friedmanc96d4962009-08-15 21:55:26 +00005272 CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
5273
5274 if (!T->isPODType())
5275 CXXRecord->setPOD(false);
5276 if (!ZeroWidth)
5277 CXXRecord->setEmpty(false);
5278
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005279 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00005280 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
5281
5282 if (!RDecl->hasTrivialConstructor())
Eli Friedmanc96d4962009-08-15 21:55:26 +00005283 CXXRecord->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +00005284 if (!RDecl->hasTrivialCopyConstructor())
Eli Friedmanc96d4962009-08-15 21:55:26 +00005285 CXXRecord->setHasTrivialCopyConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +00005286 if (!RDecl->hasTrivialCopyAssignment())
Eli Friedmanc96d4962009-08-15 21:55:26 +00005287 CXXRecord->setHasTrivialCopyAssignment(false);
Douglas Gregor8a273912009-07-22 18:25:24 +00005288 if (!RDecl->hasTrivialDestructor())
Eli Friedmanc96d4962009-08-15 21:55:26 +00005289 CXXRecord->setHasTrivialDestructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +00005290
5291 // C++ 9.5p1: An object of a class with a non-trivial
5292 // constructor, a non-trivial copy constructor, a non-trivial
5293 // destructor, or a non-trivial copy assignment operator
5294 // cannot be a member of a union, nor can an array of such
5295 // objects.
5296 // TODO: C++0x alters this restriction significantly.
5297 if (Record->isUnion()) {
5298 // We check for copy constructors before constructors
5299 // because otherwise we'll never get complaints about
5300 // copy constructors.
5301
5302 const CXXSpecialMember invalid = (CXXSpecialMember) -1;
5303
5304 CXXSpecialMember member;
5305 if (!RDecl->hasTrivialCopyConstructor())
5306 member = CXXCopyConstructor;
5307 else if (!RDecl->hasTrivialConstructor())
5308 member = CXXDefaultConstructor;
5309 else if (!RDecl->hasTrivialCopyAssignment())
5310 member = CXXCopyAssignment;
5311 else if (!RDecl->hasTrivialDestructor())
5312 member = CXXDestructor;
5313 else
5314 member = invalid;
5315
5316 if (member != invalid) {
5317 Diag(Loc, diag::err_illegal_union_member) << Name << member;
5318 DiagnoseNontrivial(RT, member);
5319 NewFD->setInvalidDecl();
5320 }
5321 }
5322 }
5323 }
5324
Douglas Gregor1efa4372009-03-11 18:59:21 +00005325 // FIXME: We need to pass in the attributes given an AST
5326 // representation, not a parser representation.
5327 if (D)
Douglas Gregor758a8692009-06-17 21:51:59 +00005328 // FIXME: What to pass instead of TUScope?
5329 ProcessDeclAttributes(TUScope, NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +00005330
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +00005331 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +00005332 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +00005333
Douglas Gregor4261e4c2009-03-11 20:50:30 +00005334 NewFD->setAccess(AS);
5335
5336 // C++ [dcl.init.aggr]p1:
5337 // An aggregate is an array or a class (clause 9) with [...] no
5338 // private or protected non-static data members (clause 11).
5339 // A POD must be an aggregate.
5340 if (getLangOptions().CPlusPlus &&
5341 (AS == AS_private || AS == AS_protected)) {
5342 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
5343 CXXRecord->setAggregate(false);
5344 CXXRecord->setPOD(false);
5345 }
5346
Steve Narofff93b6722007-08-28 20:14:24 +00005347 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00005348}
5349
Douglas Gregor8a273912009-07-22 18:25:24 +00005350/// DiagnoseNontrivial - Given that a class has a non-trivial
5351/// special member, figure out why.
5352void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
5353 QualType QT(T, 0U);
5354 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
5355
5356 // Check whether the member was user-declared.
5357 switch (member) {
5358 case CXXDefaultConstructor:
5359 if (RD->hasUserDeclaredConstructor()) {
5360 typedef CXXRecordDecl::ctor_iterator ctor_iter;
Sebastian Redle24b1622009-10-25 22:31:45 +00005361 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
5362 const FunctionDecl *body = 0;
5363 ci->getBody(body);
5364 if (!body ||
5365 !cast<CXXConstructorDecl>(body)->isImplicitlyDefined(Context)) {
Douglas Gregor8a273912009-07-22 18:25:24 +00005366 SourceLocation CtorLoc = ci->getLocation();
5367 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5368 return;
5369 }
Sebastian Redle24b1622009-10-25 22:31:45 +00005370 }
Douglas Gregor8a273912009-07-22 18:25:24 +00005371
5372 assert(0 && "found no user-declared constructors");
5373 return;
5374 }
5375 break;
5376
5377 case CXXCopyConstructor:
5378 if (RD->hasUserDeclaredCopyConstructor()) {
5379 SourceLocation CtorLoc =
5380 RD->getCopyConstructor(Context, 0)->getLocation();
5381 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5382 return;
5383 }
5384 break;
5385
5386 case CXXCopyAssignment:
5387 if (RD->hasUserDeclaredCopyAssignment()) {
5388 // FIXME: this should use the location of the copy
5389 // assignment, not the type.
5390 SourceLocation TyLoc = RD->getSourceRange().getBegin();
5391 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
5392 return;
5393 }
5394 break;
5395
5396 case CXXDestructor:
5397 if (RD->hasUserDeclaredDestructor()) {
5398 SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation();
5399 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5400 return;
5401 }
5402 break;
5403 }
5404
5405 typedef CXXRecordDecl::base_class_iterator base_iter;
5406
5407 // Virtual bases and members inhibit trivial copying/construction,
5408 // but not trivial destruction.
5409 if (member != CXXDestructor) {
5410 // Check for virtual bases. vbases includes indirect virtual bases,
5411 // so we just iterate through the direct bases.
5412 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
5413 if (bi->isVirtual()) {
5414 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5415 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
5416 return;
5417 }
5418
5419 // Check for virtual methods.
5420 typedef CXXRecordDecl::method_iterator meth_iter;
5421 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
5422 ++mi) {
5423 if (mi->isVirtual()) {
5424 SourceLocation MLoc = mi->getSourceRange().getBegin();
5425 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
5426 return;
5427 }
5428 }
5429 }
Mike Stump11289f42009-09-09 15:08:12 +00005430
Douglas Gregor8a273912009-07-22 18:25:24 +00005431 bool (CXXRecordDecl::*hasTrivial)() const;
5432 switch (member) {
5433 case CXXDefaultConstructor:
5434 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
5435 case CXXCopyConstructor:
5436 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
5437 case CXXCopyAssignment:
5438 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
5439 case CXXDestructor:
5440 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
5441 default:
5442 assert(0 && "unexpected special member"); return;
5443 }
5444
5445 // Check for nontrivial bases (and recurse).
5446 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005447 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
Sebastian Redl1054fae2009-10-25 17:03:50 +00005448 assert(BaseRT && "Don't know how to handle dependent bases");
Douglas Gregor8a273912009-07-22 18:25:24 +00005449 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
5450 if (!(BaseRecTy->*hasTrivial)()) {
5451 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5452 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
5453 DiagnoseNontrivial(BaseRT, member);
5454 return;
5455 }
5456 }
Mike Stump11289f42009-09-09 15:08:12 +00005457
Douglas Gregor8a273912009-07-22 18:25:24 +00005458 // Check for nontrivial members (and recurse).
5459 typedef RecordDecl::field_iterator field_iter;
5460 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
5461 ++fi) {
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005462 QualType EltTy = Context.getBaseElementType((*fi)->getType());
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005463 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00005464 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
5465
5466 if (!(EltRD->*hasTrivial)()) {
5467 SourceLocation FLoc = (*fi)->getLocation();
5468 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
5469 DiagnoseNontrivial(EltRT, member);
5470 return;
5471 }
5472 }
5473 }
5474
5475 assert(0 && "found no explanation for non-trivial member");
5476}
5477
Mike Stump11289f42009-09-09 15:08:12 +00005478/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00005479/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005480static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00005481TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00005482 switch (ivarVisibility) {
Chris Lattner79ef8432008-10-12 00:28:42 +00005483 default: assert(0 && "Unknown visitibility kind");
5484 case tok::objc_private: return ObjCIvarDecl::Private;
5485 case tok::objc_public: return ObjCIvarDecl::Public;
5486 case tok::objc_protected: return ObjCIvarDecl::Protected;
5487 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +00005488 }
5489}
5490
Mike Stump11289f42009-09-09 15:08:12 +00005491/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +00005492/// in order to create an IvarDecl object for it.
Chris Lattner83f095c2009-03-28 19:18:32 +00005493Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00005494 SourceLocation DeclStart,
Fariborz Jahanian68453832009-06-05 18:16:35 +00005495 DeclPtrTy IntfDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005496 Declarator &D, ExprTy *BitfieldWidth,
5497 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +00005498
Fariborz Jahaniande615832008-04-10 23:32:45 +00005499 IdentifierInfo *II = D.getIdentifier();
5500 Expr *BitWidth = (Expr*)BitfieldWidth;
5501 SourceLocation Loc = DeclStart;
5502 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00005503
Fariborz Jahaniande615832008-04-10 23:32:45 +00005504 // FIXME: Unnamed fields can be handled in various different ways, for
5505 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +00005506
John McCallbcd03502009-12-07 02:54:59 +00005507 TypeSourceInfo *TInfo = 0;
5508 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Mike Stump11289f42009-09-09 15:08:12 +00005509
Fariborz Jahaniande615832008-04-10 23:32:45 +00005510 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +00005511 // 6.7.2.1p3, 6.7.2.1p4
Chris Lattner73bf7b42009-03-05 22:45:59 +00005512 if (VerifyBitField(Loc, II, T, BitWidth)) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005513 D.setInvalidType();
Chris Lattner73bf7b42009-03-05 22:45:59 +00005514 DeleteExpr(BitWidth);
5515 BitWidth = 0;
5516 }
Fariborz Jahaniande615832008-04-10 23:32:45 +00005517 } else {
5518 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +00005519
Fariborz Jahaniande615832008-04-10 23:32:45 +00005520 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +00005521
Fariborz Jahaniande615832008-04-10 23:32:45 +00005522 }
Mike Stump11289f42009-09-09 15:08:12 +00005523
Fariborz Jahaniande615832008-04-10 23:32:45 +00005524 // C99 6.7.2.1p8: A member of a structure or union may have any type other
5525 // than a variably modified type.
5526 if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +00005527 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005528 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +00005529 }
Mike Stump11289f42009-09-09 15:08:12 +00005530
Ted Kremenek73295fa2008-07-23 18:04:17 +00005531 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +00005532 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +00005533 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
5534 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +00005535 // Must set ivar's DeclContext to its enclosing interface.
5536 Decl *EnclosingDecl = IntfDecl.getAs<Decl>();
5537 DeclContext *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +00005538 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +00005539 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5540 // Case of ivar declared in an implementation. Context is that of its class.
5541 ObjCInterfaceDecl* IDecl = IMPDecl->getClassInterface();
5542 assert(IDecl && "No class- ActOnIvar");
5543 EnclosingContext = cast_or_null<DeclContext>(IDecl);
Mike Stump12b8ce12009-08-04 21:02:39 +00005544 } else
Fariborz Jahanian68453832009-06-05 18:16:35 +00005545 EnclosingContext = dyn_cast<DeclContext>(EnclosingDecl);
5546 assert(EnclosingContext && "null DeclContext for ivar - ActOnIvar");
Mike Stump11289f42009-09-09 15:08:12 +00005547
Ted Kremenek73295fa2008-07-23 18:04:17 +00005548 // Construct the decl.
Mike Stump11289f42009-09-09 15:08:12 +00005549 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00005550 EnclosingContext, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +00005551 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +00005552
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005553 if (II) {
John McCall27b18f82009-11-17 02:14:36 +00005554 NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +00005555 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +00005556 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005557 && !isa<TagDecl>(PrevDecl)) {
5558 Diag(Loc, diag::err_duplicate_member) << II;
5559 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5560 NewID->setInvalidDecl();
5561 }
5562 }
5563
Ted Kremenek73295fa2008-07-23 18:04:17 +00005564 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +00005565 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +00005566
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005567 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +00005568 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +00005569
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005570 if (II) {
5571 // FIXME: When interfaces are DeclContexts, we'll need to add
5572 // these to the interface.
Chris Lattner83f095c2009-03-28 19:18:32 +00005573 S->AddDecl(DeclPtrTy::make(NewID));
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005574 IdResolver.AddDecl(NewID);
5575 }
5576
Chris Lattner83f095c2009-03-28 19:18:32 +00005577 return DeclPtrTy::make(NewID);
Fariborz Jahaniande615832008-04-10 23:32:45 +00005578}
5579
Fariborz Jahanian343f7092007-09-29 00:54:24 +00005580void Sema::ActOnFields(Scope* S,
Chris Lattner83f095c2009-03-28 19:18:32 +00005581 SourceLocation RecLoc, DeclPtrTy RecDecl,
5582 DeclPtrTy *Fields, unsigned NumFields,
Daniel Dunbar15619c72008-10-03 02:03:53 +00005583 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar325601a2008-10-03 17:33:35 +00005584 AttributeList *Attr) {
Chris Lattner83f095c2009-03-28 19:18:32 +00005585 Decl *EnclosingDecl = RecDecl.getAs<Decl>();
Steve Naroffdb47ee22007-09-14 22:20:54 +00005586 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +00005587
Chris Lattnerd13b8b52009-02-23 22:00:08 +00005588 // If the decl this is being inserted into is invalid, then it may be a
5589 // redeclaration or some other bogus case. Don't try to add fields to it.
5590 if (EnclosingDecl->isInvalidDecl()) {
5591 // FIXME: Deallocate fields?
5592 return;
5593 }
5594
Mike Stump11289f42009-09-09 15:08:12 +00005595
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00005596 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +00005597 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +00005598 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +00005599
Chris Lattnerd13b8b52009-02-23 22:00:08 +00005600 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00005601 for (unsigned i = 0; i != NumFields; ++i) {
Chris Lattner83f095c2009-03-28 19:18:32 +00005602 FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00005603
Chris Lattner720a0542007-01-25 00:44:24 +00005604 // Get the type for the field.
Chris Lattner0fd893e2007-07-31 21:33:24 +00005605 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +00005606
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005607 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00005608 // Remember all fields written by the user.
5609 RecFields.push_back(FD);
5610 }
Mike Stump11289f42009-09-09 15:08:12 +00005611
Chris Lattner73bf7b42009-03-05 22:45:59 +00005612 // If the field is already invalid for some reason, don't emit more
5613 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +00005614 if (FD->isInvalidDecl()) {
5615 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +00005616 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +00005617 }
Mike Stump11289f42009-09-09 15:08:12 +00005618
Douglas Gregorac1fb652009-03-24 19:52:54 +00005619 // C99 6.7.2.1p2:
5620 // A structure or union shall not contain a member with
5621 // incomplete or function type (hence, a structure shall not
5622 // contain an instance of itself, but may contain a pointer to
5623 // an instance of itself), except that the last member of a
5624 // structure with more than one named member may have incomplete
5625 // array type; such a structure (and any union containing,
5626 // possibly recursively, a member that is such a structure)
5627 // shall not be a member of a structure or an element of an
5628 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00005629 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00005630 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +00005631 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005632 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00005633 FD->setInvalidDecl();
5634 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00005635 continue;
Douglas Gregorac1fb652009-03-24 19:52:54 +00005636 } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
5637 Record && Record->isStruct()) {
5638 // Flexible array member.
5639 if (NumNamedMembers < 1) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005640 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005641 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00005642 FD->setInvalidDecl();
5643 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00005644 continue;
5645 }
Chris Lattner720a0542007-01-25 00:44:24 +00005646 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00005647 if (Record)
5648 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +00005649 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00005650 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +00005651 diag::err_field_incomplete)) {
5652 // Incomplete type
5653 FD->setInvalidDecl();
5654 EnclosingDecl->setInvalidDecl();
5655 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005656 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +00005657 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
5658 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00005659 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +00005660 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00005661 } else {
5662 // If this is a struct/class and this is not the last element, reject
5663 // it. Note that GCC supports variable sized arrays in the middle of
5664 // structures.
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00005665 if (i != NumFields-1)
5666 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +00005667 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00005668 else {
5669 // We support flexible arrays at the end of structs in
5670 // other structs as an extension.
5671 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
5672 << FD->getDeclName();
5673 if (Record)
5674 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00005675 }
Chris Lattner720a0542007-01-25 00:44:24 +00005676 }
5677 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00005678 if (Record && FDTTy->getDecl()->hasObjectMember())
5679 Record->setHasObjectMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +00005680 } else if (FDTy->isObjCInterfaceType()) {
5681 /// A field cannot be an Objective-c object
Steve Naroff32606412009-02-20 22:59:16 +00005682 Diag(FD->getLocation(), diag::err_statically_allocated_object);
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00005683 FD->setInvalidDecl();
5684 EnclosingDecl->setInvalidDecl();
5685 continue;
Mike Stump12b8ce12009-08-04 21:02:39 +00005686 } else if (getLangOptions().ObjC1 &&
5687 getLangOptions().getGCMode() != LangOptions::NonGC &&
5688 Record &&
5689 (FD->getType()->isObjCObjectPointerType() ||
5690 FD->getType().isObjCGCStrong()))
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00005691 Record->setHasObjectMember(true);
Chris Lattner82625602007-01-24 02:26:21 +00005692 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005693 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +00005694 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00005695 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005696
Chris Lattner82625602007-01-24 02:26:21 +00005697 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +00005698 if (Record) {
Douglas Gregor91f84212008-12-11 16:49:14 +00005699 Record->completeDefinition(Context);
Chris Lattner622c1932008-02-06 00:51:33 +00005700 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +00005701 ObjCIvarDecl **ClsFields =
5702 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +00005703 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner22298722009-02-20 21:35:13 +00005704 ID->setIVarList(ClsFields, RecFields.size(), Context);
5705 ID->setLocEnd(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +00005706 // Add ivar's to class's DeclContext.
5707 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
5708 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005709 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +00005710 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +00005711 // Must enforce the rule that ivars in the base classes may not be
5712 // duplicates.
Fariborz Jahanian4496c0f2008-12-17 22:21:44 +00005713 if (ID->getSuperClass()) {
Mike Stump11289f42009-09-09 15:08:12 +00005714 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
Fariborz Jahanian4496c0f2008-12-17 22:21:44 +00005715 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
5716 ObjCIvarDecl* Ivar = (*IVI);
Daniel Dunbarbdb23a12009-05-03 01:08:28 +00005717
5718 if (IdentifierInfo *II = Ivar->getIdentifier()) {
5719 ObjCIvarDecl* prevIvar =
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005720 ID->getSuperClass()->lookupInstanceVariable(II);
Daniel Dunbarbdb23a12009-05-03 01:08:28 +00005721 if (prevIvar) {
5722 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
5723 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
5724 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +00005725 }
Fariborz Jahanian4496c0f2008-12-17 22:21:44 +00005726 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +00005727 }
Mike Stump11289f42009-09-09 15:08:12 +00005728 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +00005729 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005730 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +00005731 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
5732 // Ivar declared in @implementation never belongs to the implementation.
5733 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +00005734 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +00005735 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00005736 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00005737 }
Daniel Dunbar325601a2008-10-03 17:33:35 +00005738
5739 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00005740 ProcessDeclAttributeList(S, Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +00005741}
5742
Douglas Gregor954f6b272009-03-17 19:05:46 +00005743EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
5744 EnumConstantDecl *LastEnumConst,
5745 SourceLocation IdLoc,
5746 IdentifierInfo *Id,
5747 ExprArg val) {
5748 Expr *Val = (Expr *)val.get();
5749
5750 llvm::APSInt EnumVal(32);
5751 QualType EltTy;
Douglas Gregorb2186fe2009-11-06 00:03:12 +00005752 if (Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +00005753 if (Enum->isDependentType())
Douglas Gregorb2186fe2009-11-06 00:03:12 +00005754 EltTy = Context.DependentTy;
5755 else {
5756 // Make sure to promote the operand type to int.
5757 UsualUnaryConversions(Val);
5758 if (Val != val.get()) {
5759 val.release();
5760 val = Val;
5761 }
Douglas Gregor954f6b272009-03-17 19:05:46 +00005762
Douglas Gregorb2186fe2009-11-06 00:03:12 +00005763 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
5764 SourceLocation ExpLoc;
Eli Friedmand0e60972009-12-11 01:34:50 +00005765 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Douglas Gregorb2186fe2009-11-06 00:03:12 +00005766 Val = 0;
5767 } else {
5768 EltTy = Val->getType();
5769 }
Douglas Gregor954f6b272009-03-17 19:05:46 +00005770 }
5771 }
Mike Stump11289f42009-09-09 15:08:12 +00005772
Douglas Gregor954f6b272009-03-17 19:05:46 +00005773 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +00005774 if (Enum->isDependentType())
5775 EltTy = Context.DependentTy;
5776 else if (LastEnumConst) {
Douglas Gregor954f6b272009-03-17 19:05:46 +00005777 // Assign the last value + 1.
5778 EnumVal = LastEnumConst->getInitVal();
5779 ++EnumVal;
5780
5781 // Check for overflow on increment.
5782 if (EnumVal < LastEnumConst->getInitVal())
5783 Diag(IdLoc, diag::warn_enum_value_overflow);
Mike Stump11289f42009-09-09 15:08:12 +00005784
Douglas Gregor954f6b272009-03-17 19:05:46 +00005785 EltTy = LastEnumConst->getType();
5786 } else {
5787 // First value, set to zero.
5788 EltTy = Context.IntTy;
5789 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Eli Friedmanee275c82009-12-10 22:29:29 +00005790 EnumVal.setIsSigned(true);
Douglas Gregor954f6b272009-03-17 19:05:46 +00005791 }
5792 }
Mike Stump11289f42009-09-09 15:08:12 +00005793
Douglas Gregorb2186fe2009-11-06 00:03:12 +00005794 assert(!EltTy.isNull() && "Enum constant with NULL type");
5795
Douglas Gregor954f6b272009-03-17 19:05:46 +00005796 val.release();
5797 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +00005798 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +00005799}
5800
5801
Chris Lattner83f095c2009-03-28 19:18:32 +00005802Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
5803 DeclPtrTy lastEnumConst,
5804 SourceLocation IdLoc,
5805 IdentifierInfo *Id,
5806 SourceLocation EqualLoc, ExprTy *val) {
5807 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
Chris Lattner4ef40012007-06-11 01:28:17 +00005808 EnumConstantDecl *LastEnumConst =
Chris Lattner83f095c2009-03-28 19:18:32 +00005809 cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
Chris Lattner4ef40012007-06-11 01:28:17 +00005810 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00005811
Chris Lattner1a76a3c2007-08-26 06:24:45 +00005812 // The scope passed in may not be a decl scope. Zip up the scope tree until
5813 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +00005814 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +00005815
Chris Lattner8116d1b2007-01-25 22:38:29 +00005816 // Verify that there isn't already something declared with this name in this
5817 // scope.
John McCall9f3059a2009-10-09 21:13:30 +00005818 NamedDecl *PrevDecl = LookupSingleName(S, Id, LookupOrdinaryName);
Douglas Gregor5daeee22008-12-08 18:40:42 +00005819 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00005820 // Maybe we will complain about the shadowed template parameter.
5821 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
5822 // Just pretend that we didn't see the previous declaration.
5823 PrevDecl = 0;
5824 }
5825
5826 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +00005827 // When in C++, we may get a TagDecl with the same name; in this case the
5828 // enum constant will 'hide' the tag.
5829 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
5830 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +00005831 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00005832 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +00005833 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +00005834 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00005835 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +00005836 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner309e4862009-02-28 19:37:57 +00005837 if (Val) Val->Destroy(Context);
Chris Lattner83f095c2009-03-28 19:18:32 +00005838 return DeclPtrTy();
Chris Lattner8116d1b2007-01-25 22:38:29 +00005839 }
5840 }
Chris Lattner4ef40012007-06-11 01:28:17 +00005841
Douglas Gregor954f6b272009-03-17 19:05:46 +00005842 EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
5843 IdLoc, Id, Owned(Val));
Chris Lattner0515e4b2007-08-27 21:16:18 +00005844
Chris Lattner8116d1b2007-01-25 22:38:29 +00005845 // Register this decl in the current scope stack.
Douglas Gregor954f6b272009-03-17 19:05:46 +00005846 if (New)
5847 PushOnScopeChains(New, S);
Douglas Gregor2f521192008-12-17 02:04:30 +00005848
Chris Lattner83f095c2009-03-28 19:18:32 +00005849 return DeclPtrTy::make(New);
Chris Lattnerc1915e22007-01-25 07:29:02 +00005850}
5851
Mike Stump6814d1c2009-05-16 07:06:02 +00005852void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
5853 SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00005854 DeclPtrTy *Elements, unsigned NumElements,
5855 Scope *S, AttributeList *Attr) {
Chris Lattner83f095c2009-03-28 19:18:32 +00005856 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
Douglas Gregor07665a62009-01-05 19:45:36 +00005857 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00005858
5859 if (Attr)
5860 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +00005861
Eli Friedmand0e60972009-12-11 01:34:50 +00005862 if (Enum->isDependentType()) {
5863 for (unsigned i = 0; i != NumElements; ++i) {
5864 EnumConstantDecl *ECD =
5865 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5866 if (!ECD) continue;
5867
5868 ECD->setType(EnumType);
5869 }
5870
5871 Enum->completeDefinition(Context, Context.DependentTy, Context.DependentTy);
5872 return;
5873 }
5874
Chris Lattner67933c02007-08-28 05:10:31 +00005875 // TODO: If the result value doesn't fit in an int, it must be a long or long
5876 // long value. ISO C does not support this, but GCC does as an extension,
5877 // emit a warning.
Chris Lattner37e05872008-03-05 18:54:05 +00005878 unsigned IntWidth = Context.Target.getIntWidth();
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00005879 unsigned CharWidth = Context.Target.getCharWidth();
5880 unsigned ShortWidth = Context.Target.getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +00005881
Chris Lattnerb8a501c2007-08-28 06:15:15 +00005882 // Verify that all the values are okay, compute the size of the values, and
5883 // reverse the list.
5884 unsigned NumNegativeBits = 0;
5885 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005886
Chris Lattnerb8a501c2007-08-28 06:15:15 +00005887 // Keep track of whether all elements have type int.
5888 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +00005889
Chris Lattnerc1915e22007-01-25 07:29:02 +00005890 for (unsigned i = 0; i != NumElements; ++i) {
5891 EnumConstantDecl *ECD =
Chris Lattner83f095c2009-03-28 19:18:32 +00005892 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
Chris Lattnerc1915e22007-01-25 07:29:02 +00005893 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +00005894
Chris Lattnerbf478cb2007-08-28 05:27:00 +00005895 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnerbf478cb2007-08-28 05:27:00 +00005896 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner77683132008-02-26 00:33:57 +00005897 assert(InitVal.getBitWidth() >= IntWidth &&
5898 "Should have promoted value to int");
Eli Friedman6a8dc922009-12-16 20:30:08 +00005899 if (!getLangOptions().CPlusPlus && InitVal.getBitWidth() > IntWidth) {
Chris Lattnerbf478cb2007-08-28 05:27:00 +00005900 llvm::APSInt V(InitVal);
5901 V.trunc(IntWidth);
5902 V.extend(InitVal.getBitWidth());
5903 if (V != InitVal)
Chris Lattner651d42d2008-11-20 06:38:18 +00005904 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
5905 << InitVal.toString(10);
Chris Lattnerbf478cb2007-08-28 05:27:00 +00005906 }
Mike Stump11289f42009-09-09 15:08:12 +00005907
Chris Lattnerb8a501c2007-08-28 06:15:15 +00005908 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +00005909 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +00005910 NumPositiveBits = std::max(NumPositiveBits,
5911 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +00005912 else
Chris Lattner49f980c2008-01-14 21:47:29 +00005913 NumNegativeBits = std::max(NumNegativeBits,
5914 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00005915
Chris Lattnerb8a501c2007-08-28 06:15:15 +00005916 // Keep track of whether every enum element has type int (very commmon).
5917 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +00005918 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +00005919 }
Mike Stump11289f42009-09-09 15:08:12 +00005920
Chris Lattnerb8a501c2007-08-28 06:15:15 +00005921 // Figure out the type that should be used for this enum.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00005922 // FIXME: Support -fshort-enums.
Chris Lattnerb8a501c2007-08-28 06:15:15 +00005923 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00005924 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00005925
John McCall56774992009-12-09 09:09:27 +00005926 // C++0x N3000 [conv.prom]p3:
5927 // An rvalue of an unscoped enumeration type whose underlying
5928 // type is not fixed can be converted to an rvalue of the first
5929 // of the following types that can represent all the values of
5930 // the enumeration: int, unsigned int, long int, unsigned long
5931 // int, long long int, or unsigned long long int.
5932 // C99 6.4.4.3p2:
5933 // An identifier declared as an enumeration constant has type int.
5934 // The C99 rule is modified by a gcc extension
5935 QualType BestPromotionType;
5936
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00005937 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
5938
Chris Lattnerb8a501c2007-08-28 06:15:15 +00005939 if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +00005940 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +00005941 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00005942 // If it's packed, check also if it fits a char or a short.
5943 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +00005944 BestType = Context.SignedCharTy;
5945 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +00005946 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00005947 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +00005948 BestType = Context.ShortTy;
5949 BestWidth = ShortWidth;
5950 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00005951 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00005952 BestWidth = IntWidth;
5953 } else {
Chris Lattner37e05872008-03-05 18:54:05 +00005954 BestWidth = Context.Target.getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +00005955
John McCall56774992009-12-09 09:09:27 +00005956 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00005957 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +00005958 } else {
Chris Lattner37e05872008-03-05 18:54:05 +00005959 BestWidth = Context.Target.getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +00005960
Chris Lattner3a370bf2007-08-29 17:31:48 +00005961 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00005962 Diag(Enum->getLocation(), diag::warn_enum_too_large);
5963 BestType = Context.LongLongTy;
5964 }
5965 }
John McCall56774992009-12-09 09:09:27 +00005966 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +00005967 } else {
5968 // If there is no negative value, figure out which of uint, ulong, ulonglong
5969 // fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00005970 // If it's packed, check also if it fits a char or a short.
5971 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +00005972 BestType = Context.UnsignedCharTy;
5973 BestPromotionType = Context.IntTy;
5974 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00005975 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +00005976 BestType = Context.UnsignedShortTy;
5977 BestPromotionType = Context.IntTy;
5978 BestWidth = ShortWidth;
5979 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00005980 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00005981 BestWidth = IntWidth;
John McCall56774992009-12-09 09:09:27 +00005982 BestPromotionType = (NumPositiveBits == BestWidth
5983 ? Context.UnsignedIntTy : Context.IntTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +00005984 } else if (NumPositiveBits <=
Chris Lattner37e05872008-03-05 18:54:05 +00005985 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00005986 BestType = Context.UnsignedLongTy;
John McCall56774992009-12-09 09:09:27 +00005987 BestPromotionType = (NumPositiveBits == BestWidth
5988 ? Context.UnsignedLongTy : Context.LongTy);
Chris Lattner37e05872008-03-05 18:54:05 +00005989 } else {
5990 BestWidth = Context.Target.getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +00005991 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00005992 "How could an initializer get larger than ULL?");
5993 BestType = Context.UnsignedLongLongTy;
John McCall56774992009-12-09 09:09:27 +00005994 BestPromotionType = (NumPositiveBits == BestWidth
5995 ? Context.UnsignedLongLongTy : Context.LongLongTy);
Chris Lattnerb8a501c2007-08-28 06:15:15 +00005996 }
5997 }
Mike Stump11289f42009-09-09 15:08:12 +00005998
John McCall56774992009-12-09 09:09:27 +00005999 // If we're in C and the promotion type is larger than an int, just
6000 // use the underlying type, which is generally the unsigned integer
6001 // type of the same rank as the promotion type. This is how the gcc
6002 // extension works.
6003 if (!getLangOptions().CPlusPlus && BestPromotionType != Context.IntTy)
6004 BestPromotionType = BestType;
6005
Chris Lattner3a370bf2007-08-29 17:31:48 +00006006 // Loop over all of the enumerator constants, changing their types to match
6007 // the type of the enum if needed.
6008 for (unsigned i = 0; i != NumElements; ++i) {
6009 EnumConstantDecl *ECD =
Chris Lattner83f095c2009-03-28 19:18:32 +00006010 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
Chris Lattner3a370bf2007-08-29 17:31:48 +00006011 if (!ECD) continue; // Already issued a diagnostic.
6012
6013 // Standard C says the enumerators have int type, but we allow, as an
6014 // extension, the enumerators to be larger than int size. If each
6015 // enumerator value fits in an int, type it as an int, otherwise type it the
6016 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
6017 // that X has type 'int', not 'unsigned'.
Eli Friedmanee275c82009-12-10 22:29:29 +00006018 if (!getLangOptions().CPlusPlus && ECD->getType() == Context.IntTy)
6019 continue;
Chris Lattner3a370bf2007-08-29 17:31:48 +00006020
6021 // Determine whether the value fits into an int.
6022 llvm::APSInt InitVal = ECD->getInitVal();
6023 bool FitsInInt;
6024 if (InitVal.isUnsigned() || !InitVal.isNegative())
6025 FitsInInt = InitVal.getActiveBits() < IntWidth;
6026 else
6027 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
6028
6029 // If it fits into an integer type, force it. Otherwise force it to match
6030 // the enum decl type.
6031 QualType NewTy;
6032 unsigned NewWidth;
6033 bool NewSign;
Eli Friedmanee275c82009-12-10 22:29:29 +00006034 if (FitsInInt && !getLangOptions().CPlusPlus) {
Chris Lattner3a370bf2007-08-29 17:31:48 +00006035 NewTy = Context.IntTy;
6036 NewWidth = IntWidth;
6037 NewSign = true;
6038 } else if (ECD->getType() == BestType) {
6039 // Already the right type!
Douglas Gregor1d248c52008-12-12 02:00:36 +00006040 if (getLangOptions().CPlusPlus)
6041 // C++ [dcl.enum]p4: Following the closing brace of an
6042 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +00006043 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +00006044 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +00006045 continue;
6046 } else {
6047 NewTy = BestType;
6048 NewWidth = BestWidth;
6049 NewSign = BestType->isSignedIntegerType();
6050 }
6051
6052 // Adjust the APSInt value.
6053 InitVal.extOrTrunc(NewWidth);
6054 InitVal.setIsSigned(NewSign);
6055 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +00006056
Chris Lattner3a370bf2007-08-29 17:31:48 +00006057 // Adjust the Expr initializer and type.
Chris Lattnere53c0362009-01-15 19:19:42 +00006058 if (ECD->getInitExpr())
Mike Stump11289f42009-09-09 15:08:12 +00006059 ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
Eli Friedman06ed2a52009-10-20 08:27:19 +00006060 CastExpr::CK_IntegralCast,
Mike Stump11289f42009-09-09 15:08:12 +00006061 ECD->getInitExpr(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006062 /*isLvalue=*/false));
Douglas Gregor1d248c52008-12-12 02:00:36 +00006063 if (getLangOptions().CPlusPlus)
6064 // C++ [dcl.enum]p4: Following the closing brace of an
6065 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +00006066 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +00006067 ECD->setType(EnumType);
6068 else
6069 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +00006070 }
Mike Stump11289f42009-09-09 15:08:12 +00006071
John McCall56774992009-12-09 09:09:27 +00006072 Enum->completeDefinition(Context, BestType, BestPromotionType);
Chris Lattnerc1915e22007-01-25 07:29:02 +00006073}
Chris Lattner1300fb92007-01-23 23:42:53 +00006074
Chris Lattner83f095c2009-03-28 19:18:32 +00006075Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
6076 ExprArg expr) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00006077 StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
Sebastian Redlc675bab2008-12-13 16:23:55 +00006078
Douglas Gregor278f52e2009-05-30 00:08:05 +00006079 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
6080 Loc, AsmString);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006081 CurContext->addDecl(New);
Douglas Gregor278f52e2009-05-30 00:08:05 +00006082 return DeclPtrTy::make(New);
Anders Carlsson5c6c0592008-02-08 00:33:21 +00006083}
Eli Friedman5ed51982009-06-05 02:44:36 +00006084
6085void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
6086 SourceLocation PragmaLoc,
6087 SourceLocation NameLoc) {
John McCall9f3059a2009-10-09 21:13:30 +00006088 Decl *PrevDecl = LookupSingleName(TUScope, Name, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +00006089
Eli Friedman5ed51982009-06-05 02:44:36 +00006090 if (PrevDecl) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006091 PrevDecl->addAttr(::new (Context) WeakAttr());
Ryan Flynn7d470f32009-07-30 03:15:39 +00006092 } else {
6093 (void)WeakUndeclaredIdentifiers.insert(
6094 std::pair<IdentifierInfo*,WeakInfo>
6095 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +00006096 }
Eli Friedman5ed51982009-06-05 02:44:36 +00006097}
6098
6099void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
6100 IdentifierInfo* AliasName,
6101 SourceLocation PragmaLoc,
6102 SourceLocation NameLoc,
6103 SourceLocation AliasNameLoc) {
John McCall9f3059a2009-10-09 21:13:30 +00006104 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +00006105 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +00006106
Eli Friedman5ed51982009-06-05 02:44:36 +00006107 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +00006108 if (!PrevDecl->hasAttr<AliasAttr>())
6109 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +00006110 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +00006111 } else {
6112 (void)WeakUndeclaredIdentifiers.insert(
6113 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +00006114 }
Eli Friedman5ed51982009-06-05 02:44:36 +00006115}