blob: 3964b755ba73e73863afa34bbbc5839bc83c9424 [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"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000021#include "clang/AST/DeclTemplate.h"
Chris Lattner2c6fcf52008-06-26 18:38:35 +000022#include "clang/AST/ExprCXX.h"
Sebastian Redla7b98a72009-04-26 20:35:05 +000023#include "clang/AST/StmtCXX.h"
Chris Lattner591a6752006-11-19 23:16:18 +000024#include "clang/Parse/DeclSpec.h"
Douglas Gregor15e56022009-10-13 23:27:22 +000025#include "clang/Parse/ParseDiagnostic.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000026#include "clang/Parse/Template.h"
Anders Carlssond624e162009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Steve Naroffe101f952008-01-30 23:46:05 +000028#include "clang/Basic/SourceManager.h"
Anders Carlssond624e162009-08-26 23:45:07 +000029#include "clang/Basic/TargetInfo.h"
Steve Naroffe101f952008-01-30 23:46:05 +000030// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner622c1932008-02-06 00:51:33 +000031#include "clang/Lex/Preprocessor.h"
Mike Stump11289f42009-09-09 15:08:12 +000032#include "clang/Lex/HeaderSearch.h"
John McCall0e21fcc2009-12-24 09:58:38 +000033#include "llvm/ADT/Triple.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000034#include <algorithm>
Douglas Gregor56fbc372009-09-28 21:14:19 +000035#include <cstring>
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000036#include <functional>
Chris Lattner697e5d62006-11-09 06:32:27 +000037using namespace clang;
38
Chris Lattner03b53942009-03-05 01:25:28 +000039/// getDeclName - Return a pretty name for the specified decl if possible, or
Mike Stump11289f42009-09-09 15:08:12 +000040/// an empty string if not. This is used for pretty crash reporting.
Chris Lattner83f095c2009-03-28 19:18:32 +000041std::string Sema::getDeclName(DeclPtrTy d) {
42 Decl *D = d.getAs<Decl>();
Chris Lattner03b53942009-03-05 01:25:28 +000043 if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
44 return DN->getQualifiedNameAsString();
45 return "";
46}
47
Chris Lattner5bbb3c82009-03-29 16:50:03 +000048Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
49 return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
50}
51
Douglas Gregorec6e1892009-02-04 19:16:12 +000052/// \brief If the identifier refers to a type name within this scope,
53/// return the declaration of that type.
54///
55/// This routine performs ordinary name lookup of the identifier II
56/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor9817f4a2009-02-09 15:09:02 +000057/// determine whether the name refers to a type. If so, returns an
58/// opaque pointer (actually a QualType) corresponding to that
59/// type. Otherwise, returns NULL.
Douglas Gregorec6e1892009-02-04 19:16:12 +000060///
61/// If name lookup results in an ambiguity, this routine will complain
62/// and then return NULL.
Douglas Gregor9817f4a2009-02-09 15:09:02 +000063Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +000064 Scope *S, CXXScopeSpec *SS,
Douglas Gregora25d65d2009-11-20 22:03:38 +000065 bool isClassName,
66 TypeTy *ObjectTypePtr) {
67 // Determine where we will perform name lookup.
68 DeclContext *LookupCtx = 0;
69 if (ObjectTypePtr) {
70 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
71 if (ObjectType->isRecordType())
72 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +000073 } else if (SS && SS->isNotEmpty()) {
Douglas Gregora25d65d2009-11-20 22:03:38 +000074 LookupCtx = computeDeclContext(*SS, false);
75
76 if (!LookupCtx) {
77 if (isDependentScopeSpecifier(*SS)) {
78 // C++ [temp.res]p3:
79 // A qualified-id that refers to a type and in which the
80 // nested-name-specifier depends on a template-parameter (14.6.2)
81 // shall be prefixed by the keyword typename to indicate that the
82 // qualified-id denotes a type, forming an
83 // elaborated-type-specifier (7.1.5.3).
84 //
85 // We therefore do not perform any name lookup if the result would
86 // refer to a member of an unknown specialization.
87 if (!isClassName)
88 return 0;
89
90 // We know from the grammar that this name refers to a type, so build a
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +000091 // DependentNameType node to describe the type.
92 // FIXME: Record somewhere that this DependentNameType node has no "typename"
Douglas Gregora25d65d2009-11-20 22:03:38 +000093 // keyword associated with it.
94 return CheckTypenameType((NestedNameSpecifier *)SS->getScopeRep(),
95 II, SS->getRange()).getAsOpaquePtr();
96 }
97
Douglas Gregor5e0962f2009-08-26 18:27:52 +000098 return 0;
Douglas Gregora25d65d2009-11-20 22:03:38 +000099 }
100
101 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
102 return 0;
Douglas Gregor5e0962f2009-08-26 18:27:52 +0000103 }
Eli Friedman9025ec22009-12-21 01:42:38 +0000104
105 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
106 // lookup for class-names.
107 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
108 LookupOrdinaryName;
109 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000110 if (LookupCtx) {
111 // Perform "qualified" name lookup into the declaration context we
112 // computed, which is either the type of the base of a member access
113 // expression or the declaration context associated with a prior
114 // nested-name-specifier.
115 LookupQualifiedName(Result, LookupCtx);
Douglas Gregorc9f9b862009-05-11 19:58:34 +0000116
Douglas Gregora25d65d2009-11-20 22:03:38 +0000117 if (ObjectTypePtr && Result.empty()) {
118 // C++ [basic.lookup.classref]p3:
119 // If the unqualified-id is ~type-name, the type-name is looked up
120 // in the context of the entire postfix-expression. If the type T of
121 // the object expression is of a class type C, the type-name is also
122 // looked up in the scope of class C. At least one of the lookups shall
123 // find a name that refers to (possibly cv-qualified) T.
124 LookupName(Result, S);
125 }
126 } else {
127 // Perform unqualified name lookup.
128 LookupName(Result, S);
129 }
130
Chris Lattnera3778332009-02-16 22:07:16 +0000131 NamedDecl *IIDecl = 0;
John McCall27b18f82009-11-17 02:14:36 +0000132 switch (Result.getResultKind()) {
Chris Lattnera3778332009-02-16 22:07:16 +0000133 case LookupResult::NotFound:
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000134 case LookupResult::NotFoundInCurrentInstantiation:
Chris Lattnera3778332009-02-16 22:07:16 +0000135 case LookupResult::FoundOverloaded:
John McCalle61f2ba2009-11-18 02:36:19 +0000136 case LookupResult::FoundUnresolvedValue:
John McCall58cc69d2010-01-27 01:50:18 +0000137 Result.suppressDiagnostics();
Chris Lattnera3778332009-02-16 22:07:16 +0000138 return 0;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000139
Chris Lattnere40853a2009-10-25 22:09:09 +0000140 case LookupResult::Ambiguous:
John McCall6538c932009-10-10 05:48:19 +0000141 // Recover from type-hiding ambiguities by hiding the type. We'll
142 // do the lookup again when looking for an object, and we can
143 // diagnose the error then. If we don't do this, then the error
144 // about hiding the type will be immediately followed by an error
145 // that only makes sense if the identifier was treated like a type.
John McCall27b18f82009-11-17 02:14:36 +0000146 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
147 Result.suppressDiagnostics();
John McCall6538c932009-10-10 05:48:19 +0000148 return 0;
John McCall27b18f82009-11-17 02:14:36 +0000149 }
John McCall6538c932009-10-10 05:48:19 +0000150
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000151 // Look to see if we have a type anywhere in the list of results.
152 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
153 Res != ResEnd; ++Res) {
154 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump11289f42009-09-09 15:08:12 +0000155 if (!IIDecl ||
156 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor712a3512009-04-13 15:14:38 +0000157 IIDecl->getLocation().getRawEncoding())
158 IIDecl = *Res;
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000159 }
160 }
161
162 if (!IIDecl) {
163 // None of the entities we found is a type, so there is no way
164 // to even assume that the result is a type. In this case, don't
165 // complain about the ambiguity. The parser will either try to
166 // perform this lookup again (e.g., as an object name), which
167 // will produce the ambiguity, or will complain that it expected
168 // a type name.
John McCall27b18f82009-11-17 02:14:36 +0000169 Result.suppressDiagnostics();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000170 return 0;
171 }
172
173 // We found a type within the ambiguous lookup; diagnose the
174 // ambiguity and then return that type. This might be the right
175 // answer, or it might not be, but it suppresses any attempt to
176 // perform the name lookup again.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000177 break;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000178
Chris Lattnera3778332009-02-16 22:07:16 +0000179 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +0000180 IIDecl = Result.getFoundDecl();
Chris Lattnera3778332009-02-16 22:07:16 +0000181 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000182 }
183
Chris Lattner17e15f12009-10-25 17:16:46 +0000184 assert(IIDecl && "Didn't find decl");
John McCall28a6aea2009-11-04 02:18:39 +0000185
Chris Lattner17e15f12009-10-25 17:16:46 +0000186 QualType T;
187 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall28a6aea2009-11-04 02:18:39 +0000188 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCall27b18f82009-11-17 02:14:36 +0000189
Chris Lattner17e15f12009-10-25 17:16:46 +0000190 if (T.isNull())
191 T = Context.getTypeDeclType(TD);
192
Douglas Gregore177b722009-03-19 00:39:20 +0000193 if (SS)
194 T = getQualifiedNameType(*SS, T);
Chris Lattner17e15f12009-10-25 17:16:46 +0000195
196 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Chris Lattner17e15f12009-10-25 17:16:46 +0000197 T = Context.getObjCInterfaceType(IDecl);
John McCalle61f2ba2009-11-18 02:36:19 +0000198 } else if (UnresolvedUsingTypenameDecl *UUDecl =
199 dyn_cast<UnresolvedUsingTypenameDecl>(IIDecl)) {
200 // FIXME: preserve source structure information.
Douglas Gregor02085352010-03-31 20:19:30 +0000201 T = Context.getDependentNameType(ETK_None,
202 UUDecl->getTargetNestedNameSpecifier(),
203 &II);
John McCall27b18f82009-11-17 02:14:36 +0000204 } else {
205 // If it's not plausibly a type, suppress diagnostics.
206 Result.suppressDiagnostics();
Chris Lattner17e15f12009-10-25 17:16:46 +0000207 return 0;
John McCall27b18f82009-11-17 02:14:36 +0000208 }
Douglas Gregor52537682009-03-19 00:18:19 +0000209
Chris Lattner17e15f12009-10-25 17:16:46 +0000210 return T.getAsOpaquePtr();
Chris Lattnere168f762006-11-10 05:29:30 +0000211}
212
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000213/// isTagName() - This method is called *for error recovery purposes only*
214/// to determine if the specified name is a valid tag name ("struct foo"). If
215/// so, this returns the TST for the tag corresponding to it (TST_enum,
216/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
217/// where the user forgot to specify the tag.
218DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
219 // Do a tag name lookup in this scope.
John McCall27b18f82009-11-17 02:14:36 +0000220 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
221 LookupName(R, S, false);
222 R.suppressDiagnostics();
223 if (R.getResultKind() == LookupResult::Found)
John McCall67c00872009-12-02 08:25:40 +0000224 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000225 switch (TD->getTagKind()) {
226 case TagDecl::TK_struct: return DeclSpec::TST_struct;
227 case TagDecl::TK_union: return DeclSpec::TST_union;
228 case TagDecl::TK_class: return DeclSpec::TST_class;
229 case TagDecl::TK_enum: return DeclSpec::TST_enum;
230 }
231 }
Mike Stump11289f42009-09-09 15:08:12 +0000232
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000233 return DeclSpec::TST_unspecified;
234}
235
Douglas Gregor15e56022009-10-13 23:27:22 +0000236bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
237 SourceLocation IILoc,
238 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000239 CXXScopeSpec *SS,
Douglas Gregor15e56022009-10-13 23:27:22 +0000240 TypeTy *&SuggestedType) {
241 // We don't have anything to suggest (yet).
242 SuggestedType = 0;
243
Douglas Gregor2d435302009-12-30 17:04:44 +0000244 // There may have been a typo in the name of the type. Look up typo
245 // results, in case we have something that we can suggest.
246 LookupResult Lookup(*this, &II, IILoc, LookupOrdinaryName,
247 NotForRedeclaration);
248
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000249 if (DeclarationName Corrected = CorrectTypo(Lookup, S, SS, 0, 0, CTC_Type)) {
250 if (NamedDecl *Result = Lookup.getAsSingle<NamedDecl>()) {
251 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
252 !Result->isInvalidDecl()) {
253 // We found a similarly-named type or interface; suggest that.
254 if (!SS || !SS->isSet())
255 Diag(IILoc, diag::err_unknown_typename_suggest)
256 << &II << Lookup.getLookupName()
257 << FixItHint::CreateReplacement(SourceRange(IILoc),
258 Result->getNameAsString());
259 else if (DeclContext *DC = computeDeclContext(*SS, false))
260 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
261 << &II << DC << Lookup.getLookupName() << SS->getRange()
262 << FixItHint::CreateReplacement(SourceRange(IILoc),
263 Result->getNameAsString());
264 else
265 llvm_unreachable("could not have corrected a typo here");
Douglas Gregor2d435302009-12-30 17:04:44 +0000266
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000267 Diag(Result->getLocation(), diag::note_previous_decl)
268 << Result->getDeclName();
269
270 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS);
271 return true;
272 }
273 } else if (Lookup.empty()) {
274 // We corrected to a keyword.
275 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
276 Diag(IILoc, diag::err_unknown_typename_suggest)
277 << &II << Corrected;
278 return true;
Douglas Gregor2d435302009-12-30 17:04:44 +0000279 }
280 }
281
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000282 if (getLangOptions().CPlusPlus) {
283 // See if II is a class template that the user forgot to pass arguments to.
284 UnqualifiedId Name;
285 Name.setIdentifier(&II, IILoc);
286 CXXScopeSpec EmptySS;
287 TemplateTy TemplateResult;
288 if (isTemplateName(S, SS ? *SS : EmptySS, Name, 0, true, TemplateResult)
289 == TNK_Type_template) {
290 TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
291 Diag(IILoc, diag::err_template_missing_args) << TplName;
292 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
293 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
294 << TplDecl->getTemplateParameters()->getSourceRange();
295 }
296 return true;
297 }
298 }
299
Douglas Gregor15e56022009-10-13 23:27:22 +0000300 // FIXME: Should we move the logic that tries to recover from a missing tag
301 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
302
Douglas Gregor2d435302009-12-30 17:04:44 +0000303 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Douglas Gregor15e56022009-10-13 23:27:22 +0000304 Diag(IILoc, diag::err_unknown_typename) << &II;
305 else if (DeclContext *DC = computeDeclContext(*SS, false))
306 Diag(IILoc, diag::err_typename_nested_not_found)
307 << &II << DC << SS->getRange();
308 else if (isDependentScopeSpecifier(*SS)) {
309 Diag(SS->getRange().getBegin(), diag::err_typename_missing)
Daniel Dunbar07d07852009-10-18 21:17:35 +0000310 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000311 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000312 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Douglas Gregor15e56022009-10-13 23:27:22 +0000313 SuggestedType = ActOnTypenameType(SourceLocation(), *SS, II, IILoc).get();
314 } else {
315 assert(SS && SS->isInvalid() &&
316 "Invalid scope specifier has already been diagnosed");
317 }
318
319 return true;
320}
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000321
John McCall5ed6e8f2009-08-18 00:00:49 +0000322// Determines the context to return to after temporarily entering a
323// context. This depends in an unnecessarily complicated way on the
324// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000325DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000326
John McCall5ed6e8f2009-08-18 00:00:49 +0000327 // Functions defined inline within classes aren't parsed until we've
328 // finished parsing the top-level class, so the top-level class is
329 // the context we'll need to return to.
330 if (isa<FunctionDecl>(DC)) {
331 DC = DC->getLexicalParent();
332
333 // A function not defined within a class will always return to its
334 // lexical context.
335 if (!isa<CXXRecordDecl>(DC))
336 return DC;
337
338 // A C++ inline method/friend is parsed *after* the topmost class
339 // it was declared in is fully parsed ("complete"); the topmost
340 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000341 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000342 DC = RD;
343
344 // Return the declaration context of the topmost class the inline method is
345 // declared in.
346 return DC;
347 }
348
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000349 if (isa<ObjCMethodDecl>(DC))
350 return Context.getTranslationUnitDecl();
351
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000352 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000353}
354
Douglas Gregor91f84212008-12-11 16:49:14 +0000355void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000356 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000357 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000358 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000359 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000360}
361
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000362void Sema::PopDeclContext() {
363 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000364
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000365 CurContext = getContainingDC(CurContext);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000366}
367
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000368/// EnterDeclaratorContext - Used when we must lookup names in the context
369/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000370///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000371void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000372 // C++0x [basic.lookup.unqual]p13:
373 // A name used in the definition of a static data member of class
374 // X (after the qualified-id of the static member) is looked up as
375 // if the name was used in a member function of X.
376 // C++0x [basic.lookup.unqual]p14:
377 // If a variable member of a namespace is defined outside of the
378 // scope of its namespace then any name used in the definition of
379 // the variable member (after the declarator-id) is looked up as
380 // if the definition of the variable member occurred in its
381 // namespace.
382 // Both of these imply that we should push a scope whose context
383 // is the semantic context of the declaration. We can't use
384 // PushDeclContext here because that context is not necessarily
385 // lexically contained in the current context. Fortunately,
386 // the containing scope should have the appropriate information.
387
388 assert(!S->getEntity() && "scope already has entity");
389
390#ifndef NDEBUG
391 Scope *Ancestor = S->getParent();
392 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
393 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
394#endif
395
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000396 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000397 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000398}
399
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000400void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000401 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000402
John McCall6df5fef2009-12-19 10:49:29 +0000403 // Switch back to the lexical context. The safety of this is
404 // enforced by an assert in EnterDeclaratorContext.
405 Scope *Ancestor = S->getParent();
406 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
407 CurContext = (DeclContext*) Ancestor->getEntity();
408
409 // We don't need to do anything with the scope, which is going to
410 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000411}
412
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000413/// \brief Determine whether we allow overloading of the function
414/// PrevDecl with another declaration.
415///
416/// This routine determines whether overloading is possible, not
417/// whether some new function is actually an overload. It will return
418/// true in C++ (where we can always provide overloads) or, as an
419/// extension, in C when the previous function is already an
420/// overloaded function declaration or has the "overloadable"
421/// attribute.
John McCall1f82f242009-11-18 22:49:29 +0000422static bool AllowOverloadingOfFunction(LookupResult &Previous,
423 ASTContext &Context) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000424 if (Context.getLangOptions().CPlusPlus)
425 return true;
426
John McCall1f82f242009-11-18 22:49:29 +0000427 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000428 return true;
429
John McCall1f82f242009-11-18 22:49:29 +0000430 return (Previous.getResultKind() == LookupResult::Found
431 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000432}
433
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000434/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +0000435void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +0000436 // Move up the scope chain until we find the nearest enclosing
437 // non-transparent context. The declaration will be introduced into this
438 // scope.
Mike Stump11289f42009-09-09 15:08:12 +0000439 while (S->getEntity() &&
Douglas Gregor07665a62009-01-05 19:45:36 +0000440 ((DeclContext *)S->getEntity())->isTransparentContext())
441 S = S->getParent();
442
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000443 // Add scoped declarations into their context, so that they can be
444 // found later. Declarations without a context won't be inserted
445 // into any context.
John McCall759e32b2009-08-31 22:39:49 +0000446 if (AddToContext)
447 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000448
Chandler Carruthf50ef6e2010-02-21 07:08:09 +0000449 // Out-of-line definitions shouldn't be pushed into scope in C++.
450 // Out-of-line variable and function definitions shouldn't even in C.
451 if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
452 D->isOutOfLine())
453 return;
454
455 // Template instantiations should also not be pushed into scope.
456 if (isa<FunctionDecl>(D) &&
457 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +0000458 return;
459
John McCall9f3059a2009-10-09 21:13:30 +0000460 // If this replaces anything in the current scope,
461 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
462 IEnd = IdResolver.end();
463 for (; I != IEnd; ++I) {
464 if (S->isDeclScope(DeclPtrTy::make(*I)) && D->declarationReplaces(*I)) {
465 S->RemoveDecl(DeclPtrTy::make(*I));
466 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000467
John McCall9f3059a2009-10-09 21:13:30 +0000468 // Should only need to replace one decl.
469 break;
Douglas Gregor38feed82009-04-24 02:57:34 +0000470 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000471 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000472
John McCall9f3059a2009-10-09 21:13:30 +0000473 S->AddDecl(DeclPtrTy::make(D));
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000474 IdResolver.AddDecl(D);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000475}
476
Douglas Gregor505ad492009-09-28 00:47:05 +0000477bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) {
Douglas Gregor505ad492009-09-28 00:47:05 +0000478 return IdResolver.isDeclInScope(D, Ctx, Context, S);
479}
480
John McCall1f82f242009-11-18 22:49:29 +0000481static bool isOutOfScopePreviousDeclaration(NamedDecl *,
482 DeclContext*,
483 ASTContext&);
484
485/// Filters out lookup results that don't fall within the given scope
486/// as determined by isDeclInScope.
487static void FilterLookupForScope(Sema &SemaRef, LookupResult &R,
488 DeclContext *Ctx, Scope *S,
489 bool ConsiderLinkage) {
490 LookupResult::Filter F = R.makeFilter();
491 while (F.hasNext()) {
492 NamedDecl *D = F.next();
493
494 if (SemaRef.isDeclInScope(D, Ctx, S))
495 continue;
496
497 if (ConsiderLinkage &&
498 isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context))
499 continue;
500
501 F.erase();
502 }
503
504 F.done();
505}
506
507static bool isUsingDecl(NamedDecl *D) {
508 return isa<UsingShadowDecl>(D) ||
509 isa<UnresolvedUsingTypenameDecl>(D) ||
510 isa<UnresolvedUsingValueDecl>(D);
511}
512
513/// Removes using shadow declarations from the lookup results.
514static void RemoveUsingDecls(LookupResult &R) {
515 LookupResult::Filter F = R.makeFilter();
516 while (F.hasNext())
517 if (isUsingDecl(F.next()))
518 F.erase();
519
520 F.done();
521}
522
Anders Carlsson2889e0e2009-11-07 07:18:14 +0000523static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +0000524 if (D->isInvalidDecl())
525 return false;
526
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +0000527 if (D->isUsed() || D->hasAttr<UnusedAttr>())
528 return false;
John McCall67da35c2010-02-04 22:26:26 +0000529
530 // White-list anything that isn't a local variable.
531 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
532 !D->getDeclContext()->isFunctionOrMethod())
533 return false;
534
535 // Types of valid local variables should be complete, so this should succeed.
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +0000536 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +0000537
538 // White-list anything with an __attribute__((unused)) type.
539 QualType Ty = VD->getType();
540
541 // Only look at the outermost level of typedef.
542 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
543 if (TT->getDecl()->hasAttr<UnusedAttr>())
544 return false;
545 }
546
547 if (const TagType *TT = Ty->getAs<TagType>()) {
548 const TagDecl *Tag = TT->getDecl();
549 if (Tag->hasAttr<UnusedAttr>())
550 return false;
551
552 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +0000553 if (!RD->hasTrivialConstructor())
554 return false;
555 if (!RD->hasTrivialDestructor())
556 return false;
557 }
558 }
John McCallcef15822010-03-31 02:47:45 +0000559
560 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +0000561 }
562
John McCall67da35c2010-02-04 22:26:26 +0000563 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +0000564}
565
Steve Naroffc62adb62007-10-09 22:01:59 +0000566void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000567 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000568 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +0000569 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000570
Chris Lattner302b4be2006-11-19 02:31:38 +0000571 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
572 I != E; ++I) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000573 Decl *TmpD = (*I).getAs<Decl>();
Steve Naroff9324db12007-09-13 18:10:37 +0000574 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +0000575
Douglas Gregor91f84212008-12-11 16:49:14 +0000576 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
577 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +0000578
Douglas Gregor91f84212008-12-11 16:49:14 +0000579 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +0000580
Douglas Gregor3beaf9b2009-10-08 21:35:42 +0000581 // Diagnose unused variables in this scope.
Douglas Gregor9a28e842010-03-01 23:15:13 +0000582 if (ShouldDiagnoseUnusedDecl(D) &&
583 S->getNumErrorsAtStart() == getDiagnostics().getNumErrors())
Anders Carlsson2889e0e2009-11-07 07:18:14 +0000584 Diag(D->getLocation(), diag::warn_unused_variable) << D->getDeclName();
Douglas Gregor3beaf9b2009-10-08 21:35:42 +0000585
Douglas Gregor91f84212008-12-11 16:49:14 +0000586 // Remove this name from our lexical scope.
587 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +0000588 }
589}
590
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000591/// \brief Look for an Objective-C class in the translation unit.
Douglas Gregor35b0bac2010-01-03 18:01:57 +0000592///
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000593/// \param Id The name of the Objective-C class we're looking for. If
Douglas Gregor35b0bac2010-01-03 18:01:57 +0000594/// typo-correction fixes this name, the Id will be updated
595/// to the fixed name.
596///
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000597/// \param IdLoc The location of the name in the translation unit.
598///
599/// \param TypoCorrection If true, this routine will attempt typo correction
600/// if there is no class with the given name.
601///
602/// \returns The declaration of the named Objective-C class, or NULL if the
603/// class could not be found.
Douglas Gregor35b0bac2010-01-03 18:01:57 +0000604ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000605 SourceLocation IdLoc,
606 bool TypoCorrection) {
Steve Naroff77892752008-04-02 18:30:49 +0000607 // The third "scope" argument is 0 since we aren't enabling lazy built-in
608 // creation from this context.
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000609 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
Mike Stump11289f42009-09-09 15:08:12 +0000610
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000611 if (!IDecl && TypoCorrection) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +0000612 // Perform typo correction at the given location, but only if we
613 // find an Objective-C class name.
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000614 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000615 if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
Douglas Gregor35b0bac2010-01-03 18:01:57 +0000616 (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000617 Diag(IdLoc, diag::err_undef_interface_suggest)
Douglas Gregor35b0bac2010-01-03 18:01:57 +0000618 << Id << IDecl->getDeclName()
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000619 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000620 Diag(IDecl->getLocation(), diag::note_previous_decl)
621 << IDecl->getDeclName();
622
Douglas Gregor35b0bac2010-01-03 18:01:57 +0000623 Id = IDecl->getIdentifier();
624 }
625 }
626
Steve Naroff2fc93f52008-04-02 14:35:35 +0000627 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +0000628}
629
Douglas Gregor45a33ec2009-01-12 18:45:55 +0000630/// getNonFieldDeclScope - Retrieves the innermost scope, starting
631/// from S, where a non-field would be declared. This routine copes
632/// with the difference between C and C++ scoping rules in structs and
633/// unions. For example, the following code is well-formed in C but
634/// ill-formed in C++:
635/// @code
636/// struct S6 {
637/// enum { BAR } e;
638/// };
Mike Stump11289f42009-09-09 15:08:12 +0000639///
Douglas Gregor45a33ec2009-01-12 18:45:55 +0000640/// void test_S6() {
641/// struct S6 a;
642/// a.e = BAR;
643/// }
644/// @endcode
645/// For the declaration of BAR, this routine will return a different
646/// scope. The scope S will be the scope of the unnamed enumeration
647/// within S6. In C++, this routine will return the scope associated
648/// with S6, because the enumeration's scope is a transparent
649/// context but structures can contain non-field names. In C, this
650/// routine will return the translation unit scope, since the
651/// enumeration's scope is a transparent context and structures cannot
652/// contain non-field names.
653Scope *Sema::getNonFieldDeclScope(Scope *S) {
654 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump11289f42009-09-09 15:08:12 +0000655 (S->getEntity() &&
Douglas Gregor45a33ec2009-01-12 18:45:55 +0000656 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
657 (S->isClassScope() && !getLangOptions().CPlusPlus))
658 S = S->getParent();
659 return S;
660}
661
Chris Lattner4dd27102008-05-05 22:18:14 +0000662void Sema::InitBuiltinVaListType() {
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000663 if (!Context.getBuiltinVaListType().isNull())
664 return;
Mike Stump11289f42009-09-09 15:08:12 +0000665
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000666 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000667 NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, SourceLocation(),
668 LookupOrdinaryName, ForRedeclaration);
Steve Naroffeee59eb2007-10-18 22:17:45 +0000669 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000670 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
671}
672
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000673/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
674/// file scope. lazily create a decl for it. ForRedeclaration is true
675/// if we're creating this built-in in anticipation of redeclaring the
676/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000677NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000678 Scope *S, bool ForRedeclaration,
679 SourceLocation Loc) {
Chris Lattner9561a0b2007-01-28 08:20:04 +0000680 Builtin::ID BID = (Builtin::ID)bid;
681
Chris Lattnerff2c1872008-09-28 05:54:29 +0000682 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000683 InitBuiltinVaListType();
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000684
Chris Lattnerecd79c62009-06-14 00:45:47 +0000685 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +0000686 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +0000687 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +0000688 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +0000689 // Okay
690 break;
691
Mike Stump93246cc2009-07-28 23:57:15 +0000692 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +0000693 if (ForRedeclaration)
694 Diag(Loc, diag::err_implicit_decl_requires_stdio)
695 << Context.BuiltinInfo.GetName(BID);
696 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +0000697
Mike Stump93246cc2009-07-28 23:57:15 +0000698 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +0000699 if (ForRedeclaration)
700 Diag(Loc, diag::err_implicit_decl_requires_setjmp)
701 << Context.BuiltinInfo.GetName(BID);
702 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +0000703 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000704
705 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
706 Diag(Loc, diag::ext_implicit_lib_function_decl)
707 << Context.BuiltinInfo.GetName(BID)
708 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +0000709 if (Context.BuiltinInfo.getHeaderName(BID) &&
Chris Lattneraf73cf62009-04-16 03:59:32 +0000710 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
711 != Diagnostic::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000712 Diag(Loc, diag::note_please_include_header)
713 << Context.BuiltinInfo.getHeaderName(BID)
714 << Context.BuiltinInfo.GetName(BID);
715 }
716
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +0000717 FunctionDecl *New = FunctionDecl::Create(Context,
718 Context.getTranslationUnitDecl(),
John McCallbcd03502009-12-07 02:54:59 +0000719 Loc, II, R, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +0000720 FunctionDecl::Extern,
721 FunctionDecl::None, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +0000722 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000723 New->setImplicit();
724
Chris Lattner4dd27102008-05-05 22:18:14 +0000725 // Create Decl objects for each parameter, adding them to the
726 // FunctionDecl.
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000727 if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner4dd27102008-05-05 22:18:14 +0000728 llvm::SmallVector<ParmVarDecl*, 16> Params;
729 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
730 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +0000731 FT->getArgType(i), /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +0000732 VarDecl::None, VarDecl::None, 0));
Douglas Gregord5058122010-02-11 01:19:42 +0000733 New->setParams(Params.data(), Params.size());
Chris Lattner4dd27102008-05-05 22:18:14 +0000734 }
Mike Stump11289f42009-09-09 15:08:12 +0000735
736 AddKnownFunctionAttributes(New);
737
Chris Lattnerc5c95b52008-04-11 07:00:53 +0000738 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +0000739 // FIXME: This is hideous. We need to teach PushOnScopeChains to
740 // relate Scopes to DeclContexts, and probably eliminate CurContext
741 // entirely, but we're not there yet.
742 DeclContext *SavedContext = CurContext;
743 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000744 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +0000745 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +0000746 return New;
747}
748
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000749/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
750/// same name and scope as a previous declaration 'Old'. Figure out
751/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000752/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +0000753///
John McCall1f82f242009-11-18 22:49:29 +0000754void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) {
755 // If the new decl is known invalid already, don't bother doing any
756 // merging checks.
757 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +0000758
Steve Naroff44cfcb62008-09-09 14:32:20 +0000759 // Allow multiple definitions for ObjC built-in typedefs.
760 // FIXME: Verify the underlying types are equivalent!
761 if (getLangOptions().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +0000762 const IdentifierInfo *TypeID = New->getIdentifier();
763 switch (TypeID->getLength()) {
764 default: break;
Mike Stump11289f42009-09-09 15:08:12 +0000765 case 2:
Chris Lattner66e32812008-11-20 05:41:43 +0000766 if (!TypeID->isStr("id"))
767 break;
David Chisnall9f57c292009-08-17 16:35:33 +0000768 Context.ObjCIdRedefinitionType = New->getUnderlyingType();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000769 // Install the built-in type for 'id', ignoring the current definition.
770 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
771 return;
Chris Lattner66e32812008-11-20 05:41:43 +0000772 case 5:
773 if (!TypeID->isStr("Class"))
774 break;
David Chisnall9f57c292009-08-17 16:35:33 +0000775 Context.ObjCClassRedefinitionType = New->getUnderlyingType();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000776 // Install the built-in type for 'Class', ignoring the current definition.
777 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000778 return;
Chris Lattner66e32812008-11-20 05:41:43 +0000779 case 3:
780 if (!TypeID->isStr("SEL"))
781 break;
Fariborz Jahanian04b258c2009-11-25 23:07:42 +0000782 Context.ObjCSelRedefinitionType = New->getUnderlyingType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000783 // Install the built-in type for 'SEL', ignoring the current definition.
784 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000785 return;
Chris Lattner66e32812008-11-20 05:41:43 +0000786 case 8:
787 if (!TypeID->isStr("Protocol"))
788 break;
Steve Naroff44cfcb62008-09-09 14:32:20 +0000789 Context.setObjCProtoType(New->getUnderlyingType());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000790 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +0000791 }
792 // Fall through - the typedef name was not a builtin type.
793 }
John McCall1f82f242009-11-18 22:49:29 +0000794
Douglas Gregorfb034662009-01-28 17:15:10 +0000795 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +0000796 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
797 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +0000798 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000799 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +0000800
801 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000802 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +0000803 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +0000804
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000805 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +0000806 }
Douglas Gregorfb034662009-01-28 17:15:10 +0000807
John McCall1f82f242009-11-18 22:49:29 +0000808 // If the old declaration is invalid, just give up here.
809 if (Old->isInvalidDecl())
810 return New->setInvalidDecl();
811
Mike Stump11289f42009-09-09 15:08:12 +0000812 // Determine the "old" type we'll use for checking and diagnostics.
Douglas Gregorfb034662009-01-28 17:15:10 +0000813 QualType OldType;
814 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
815 OldType = OldTypedef->getUnderlyingType();
816 else
817 OldType = Context.getTypeDeclType(Old);
818
Chris Lattnerf9c49e52008-07-25 18:44:27 +0000819 // If the typedef types are not identical, reject them in all languages and
820 // with any extensions enabled.
Douglas Gregorfb034662009-01-28 17:15:10 +0000821
Mike Stump11289f42009-09-09 15:08:12 +0000822 if (OldType != New->getUnderlyingType() &&
823 Context.getCanonicalType(OldType) !=
Chris Lattnerf9c49e52008-07-25 18:44:27 +0000824 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +0000825 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregorfb034662009-01-28 17:15:10 +0000826 << New->getUnderlyingType() << OldType;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000827 if (Old->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +0000828 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000829 return New->setInvalidDecl();
Chris Lattnerf9c49e52008-07-25 18:44:27 +0000830 }
Mike Stump11289f42009-09-09 15:08:12 +0000831
John McCall91f1a022009-12-30 00:31:22 +0000832 // The types match. Link up the redeclaration chain if the old
833 // declaration was a typedef.
834 // FIXME: this is a potential source of wierdness if the type
835 // spellings don't match exactly.
836 if (isa<TypedefDecl>(Old))
837 New->setPreviousDeclaration(cast<TypedefDecl>(Old));
838
Steve Naroff7cae42b2009-07-10 23:34:53 +0000839 if (getLangOptions().Microsoft)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000840 return;
Eli Friedman61b529f2008-06-11 06:20:39 +0000841
Chris Lattner2581fc32009-04-17 22:04:20 +0000842 if (getLangOptions().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +0000843 // C++ [dcl.typedef]p2:
844 // In a given non-class scope, a typedef specifier can be used to
845 // redefine the name of any type declared in that scope to refer
846 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +0000847 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000848 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +0000849
850 // C++0x [dcl.typedef]p4:
851 // In a given class scope, a typedef specifier can be used to redefine
852 // any class-name declared in that scope that is not also a typedef-name
853 // to refer to the type to which it already refers.
854 //
855 // This wording came in via DR424, which was a correction to the
856 // wording in DR56, which accidentally banned code like:
857 //
858 // struct S {
859 // typedef struct A { } A;
860 // };
861 //
862 // in the C++03 standard. We implement the C++0x semantics, which
863 // allow the above but disallow
864 //
865 // struct S {
866 // typedef int I;
867 // typedef int I;
868 // };
869 //
870 // since that was the intent of DR56.
Douglas Gregord6150262010-01-11 22:30:10 +0000871 if (!isa<TypedefDecl >(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +0000872 return;
873
Chris Lattner2581fc32009-04-17 22:04:20 +0000874 Diag(New->getLocation(), diag::err_redefinition)
875 << New->getDeclName();
876 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000877 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +0000878 }
Eli Friedman61b529f2008-06-11 06:20:39 +0000879
Chris Lattner2581fc32009-04-17 22:04:20 +0000880 // If we have a redefinition of a typedef in C, emit a warning. This warning
881 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +0000882 // -Wtypedef-redefinition. If either the original or the redefinition is
883 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +0000884 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +0000885 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
886 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +0000887 return;
Mike Stump11289f42009-09-09 15:08:12 +0000888
Chris Lattner2581fc32009-04-17 22:04:20 +0000889 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
890 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +0000891 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000892 return;
Chris Lattner01564d92007-01-27 19:27:06 +0000893}
894
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000895/// DeclhasAttr - returns true if decl Declaration already has the target
896/// attribute.
Mike Stump11289f42009-09-09 15:08:12 +0000897static bool
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000898DeclHasAttr(const Decl *decl, const Attr *target) {
899 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
Chris Lattner84966392008-03-03 03:28:21 +0000900 if (attr->getKind() == target->getKind())
901 return true;
902
903 return false;
904}
905
906/// MergeAttributes - append attributes from the Old decl to the New one.
Chris Lattner9a2d50e72009-03-04 06:05:19 +0000907static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000908 for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
909 if (!DeclHasAttr(New, attr) && attr->isMerged()) {
Douglas Gregor76fe50c2009-04-28 06:37:30 +0000910 Attr *NewAttr = attr->clone(C);
911 NewAttr->setInherited(true);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000912 New->addAttr(NewAttr);
Chris Lattner84966392008-03-03 03:28:21 +0000913 }
914 }
915}
916
Douglas Gregora74a2972009-03-06 22:43:54 +0000917/// Used in MergeFunctionDecl to keep track of function parameters in
918/// C.
919struct GNUCompatibleParamWarning {
920 ParmVarDecl *OldParm;
921 ParmVarDecl *NewParm;
922 QualType PromotedType;
923};
924
Anders Carlsson1f78b2b2009-12-04 22:33:25 +0000925
926/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +0000927Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +0000928 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Douglas Gregor507eb872009-12-22 00:34:07 +0000929 if (Ctor->isCopyConstructor())
Anders Carlsson1f78b2b2009-12-04 22:33:25 +0000930 return Sema::CXXCopyConstructor;
Anders Carlsson05bf0092010-04-22 05:40:53 +0000931
932 return Sema::CXXConstructor;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +0000933 }
934
935 if (isa<CXXDestructorDecl>(MD))
936 return Sema::CXXDestructor;
937
938 assert(MD->isCopyAssignment() && "Must have copy assignment operator");
939 return Sema::CXXCopyAssignment;
940}
941
Charles Davisfea48452010-02-18 02:00:42 +0000942/// canREdefineFunction - checks if a function can be redefined. Currently,
943/// only extern inline functions can be redefined, and even then only in
944/// GNU89 mode.
945static bool canRedefineFunction(const FunctionDecl *FD,
946 const LangOptions& LangOpts) {
947 return (LangOpts.GNUMode && !LangOpts.C99 && !LangOpts.CPlusPlus &&
948 FD->isInlineSpecified() &&
949 FD->getStorageClass() == FunctionDecl::Extern);
950}
951
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000952/// MergeFunctionDecl - We just parsed a function 'New' from
953/// declarator D which has the same name and scope as a previous
954/// declaration 'Old'. Figure out how to resolve this situation,
955/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000956///
957/// In C++, New and Old must be declarations that are not
958/// overloaded. Use IsOverload to determine whether New and Old are
959/// overloaded, and to select the Old declaration that New should be
960/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000961///
962/// Returns true if there was an error, false otherwise.
963bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000964 // Verify the old decl was also a function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000965 FunctionDecl *Old = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000966 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000967 = dyn_cast<FunctionTemplateDecl>(OldD))
968 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000969 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000970 Old = dyn_cast<FunctionDecl>(OldD);
Chris Lattnerc511efb2007-01-27 19:32:14 +0000971 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +0000972 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
973 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
974 Diag(Shadow->getTargetDecl()->getLocation(),
975 diag::note_using_decl_target);
976 Diag(Shadow->getUsingDecl()->getLocation(),
977 diag::note_using_decl) << 0;
978 return true;
979 }
980
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +0000981 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000982 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +0000983 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000984 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +0000985 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000986
987 // Determine whether the previous declaration was a definition,
988 // implicit declaration, or a declaration.
989 diag::kind PrevDiag;
990 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +0000991 PrevDiag = diag::note_previous_definition;
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000992 else if (Old->isImplicit())
993 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump11289f42009-09-09 15:08:12 +0000994 else
Chris Lattner0369c572008-11-23 23:12:31 +0000995 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +0000996
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000997 QualType OldQType = Context.getCanonicalType(Old->getType());
998 QualType NewQType = Context.getCanonicalType(New->getType());
Mike Stump11289f42009-09-09 15:08:12 +0000999
Charles Davisfea48452010-02-18 02:00:42 +00001000 // Don't complain about this if we're in GNU89 mode and the old function
1001 // is an extern inline function.
Douglas Gregore62c0a42009-02-24 01:23:02 +00001002 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
1003 New->getStorageClass() == FunctionDecl::Static &&
Charles Davisfea48452010-02-18 02:00:42 +00001004 Old->getStorageClass() != FunctionDecl::Static &&
1005 !canRedefineFunction(Old, getLangOptions())) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00001006 Diag(New->getLocation(), diag::err_static_non_static)
1007 << New;
1008 Diag(Old->getLocation(), PrevDiag);
1009 return true;
1010 }
1011
John McCallcddbad02010-02-04 05:44:44 +00001012 // If a function is first declared with a calling convention, but is
1013 // later declared or defined without one, the second decl assumes the
1014 // calling convention of the first.
1015 //
1016 // For the new decl, we have to look at the NON-canonical type to tell the
1017 // difference between a function that really doesn't have a calling
1018 // convention and one that is declared cdecl. That's because in
1019 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1020 // because it is the default calling convention.
1021 //
1022 // Note also that we DO NOT return at this point, because we still have
1023 // other tests to run.
1024 const FunctionType *OldType = OldQType->getAs<FunctionType>();
1025 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001026 const FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1027 const FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1028 if (OldTypeInfo.getCC() != CC_Default &&
1029 NewTypeInfo.getCC() == CC_Default) {
1030 NewQType = Context.getCallConvType(NewQType, OldTypeInfo.getCC());
John McCallcddbad02010-02-04 05:44:44 +00001031 New->setType(NewQType);
1032 NewQType = Context.getCanonicalType(NewQType);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001033 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1034 NewTypeInfo.getCC())) {
John McCallcddbad02010-02-04 05:44:44 +00001035 // Calling conventions really aren't compatible, so complain.
John McCallab26cfa2010-02-05 21:31:56 +00001036 Diag(New->getLocation(), diag::err_cconv_change)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001037 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1038 << (OldTypeInfo.getCC() == CC_Default)
1039 << (OldTypeInfo.getCC() == CC_Default ? "" :
1040 FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
John McCallab26cfa2010-02-05 21:31:56 +00001041 Diag(Old->getLocation(), diag::note_previous_declaration);
John McCallcddbad02010-02-04 05:44:44 +00001042 return true;
1043 }
1044
John McCallab26cfa2010-02-05 21:31:56 +00001045 // FIXME: diagnose the other way around?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001046 if (OldType->getNoReturnAttr() &&
1047 !NewType->getNoReturnAttr()) {
John McCallab26cfa2010-02-05 21:31:56 +00001048 NewQType = Context.getNoReturnType(NewQType);
1049 New->setType(NewQType);
1050 assert(NewQType.isCanonical());
1051 }
1052
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001053 if (getLangOptions().CPlusPlus) {
1054 // (C++98 13.1p2):
1055 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00001056 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001057 // cannot be overloaded.
Mike Stump11289f42009-09-09 15:08:12 +00001058 QualType OldReturnType
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001059 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001060 QualType NewReturnType
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001061 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
1062 if (OldReturnType != NewReturnType) {
1063 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001064 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001065 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001066 }
1067
1068 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
John McCall43314ab2010-04-13 07:45:41 +00001069 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001070 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00001071 // Preserve triviality.
1072 NewMethod->setTrivial(OldMethod->isTrivial());
1073
1074 bool isFriend = NewMethod->getFriendObjectKind();
1075
1076 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001077 // -- Member function declarations with the same name and the
1078 // same parameter types cannot be overloaded if any of them
1079 // is a static member function declaration.
1080 if (OldMethod->isStatic() || NewMethod->isStatic()) {
1081 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1082 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1083 return true;
1084 }
1085
1086 // C++ [class.mem]p1:
1087 // [...] A member shall not be declared twice in the
1088 // member-specification, except that a nested class or member
1089 // class template can be declared and then later defined.
1090 unsigned NewDiag;
1091 if (isa<CXXConstructorDecl>(OldMethod))
1092 NewDiag = diag::err_constructor_redeclared;
1093 else if (isa<CXXDestructorDecl>(NewMethod))
1094 NewDiag = diag::err_destructor_redeclared;
1095 else if (isa<CXXConversionDecl>(NewMethod))
1096 NewDiag = diag::err_conv_function_redeclared;
1097 else
1098 NewDiag = diag::err_member_redeclared;
1099
1100 Diag(New->getLocation(), NewDiag);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001101 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00001102
1103 // Complain if this is an explicit declaration of a special
1104 // member that was initially declared implicitly.
1105 //
1106 // As an exception, it's okay to befriend such methods in order
1107 // to permit the implicit constructor/destructor/operator calls.
1108 } else if (OldMethod->isImplicit()) {
1109 if (isFriend) {
1110 NewMethod->setImplicit();
1111 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001112 Diag(NewMethod->getLocation(),
1113 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00001114 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001115 return true;
1116 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001117 }
1118 }
1119
1120 // (C++98 8.3.5p3):
1121 // All declarations for a function shall agree exactly in both the
1122 // return type and the parameter-type-list.
Nuno Lopes0e7860f2009-12-23 23:40:33 +00001123 // attributes should be ignored when comparing.
1124 if (Context.getNoReturnType(OldQType, false) ==
1125 Context.getNoReturnType(NewQType, false))
Douglas Gregore62c0a42009-02-24 01:23:02 +00001126 return MergeCompatibleFunctionDecls(New, Old);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001127
1128 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00001129 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001130
1131 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00001132 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001133 if (!getLangOptions().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00001134 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00001135 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1136 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001137 const FunctionProtoType *OldProto = 0;
1138 if (isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001139 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001140 // The old declaration provided a function prototype, but the
1141 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001142 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001143 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1144 OldProto->arg_type_end());
1145 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jay Foad7d0479f2009-05-21 09:52:38 +00001146 ParamTypes.data(), ParamTypes.size(),
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001147 OldProto->isVariadic(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00001148 OldProto->getTypeQuals(),
1149 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001150 OldProto->getExtInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001151 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00001152 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001153
1154 // Synthesize a parameter for each argument type.
1155 llvm::SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00001156 for (FunctionProtoType::arg_type_iterator
1157 ParamType = OldProto->arg_type_begin(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001158 ParamEnd = OldProto->arg_type_end();
1159 ParamType != ParamEnd; ++ParamType) {
1160 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
1161 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00001162 *ParamType, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001163 VarDecl::None, VarDecl::None,
1164 0);
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001165 Param->setImplicit();
1166 Params.push_back(Param);
1167 }
1168
Douglas Gregord5058122010-02-11 01:19:42 +00001169 New->setParams(Params.data(), Params.size());
Mike Stump11289f42009-09-09 15:08:12 +00001170 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001171
Douglas Gregore62c0a42009-02-24 01:23:02 +00001172 return MergeCompatibleFunctionDecls(New, Old);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001173 }
Chris Lattner45d561a2007-11-06 06:07:26 +00001174
Douglas Gregora74a2972009-03-06 22:43:54 +00001175 // GNU C permits a K&R definition to follow a prototype declaration
1176 // if the declared types of the parameters in the K&R definition
1177 // match the types in the prototype declaration, even when the
1178 // promoted types of the parameters from the K&R definition differ
1179 // from the types in the prototype. GCC then keeps the types from
1180 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001181 //
1182 // If a variadic prototype is followed by a non-variadic K&R definition,
1183 // the K&R definition becomes variadic. This is sort of an edge case, but
1184 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1185 // C99 6.9.1p8.
Douglas Gregora74a2972009-03-06 22:43:54 +00001186 if (!getLangOptions().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001187 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00001188 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001189 Old->getNumParams() == New->getNumParams()) {
1190 llvm::SmallVector<QualType, 16> ArgTypes;
1191 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00001192 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00001193 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001194 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00001195 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001196
Douglas Gregora74a2972009-03-06 22:43:54 +00001197 // Determine whether this is the GNU C extension.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001198 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1199 NewProto->getResultType());
1200 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00001201 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001202 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00001203 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1204 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00001205 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregora74a2972009-03-06 22:43:54 +00001206 NewProto->getArgType(Idx))) {
1207 ArgTypes.push_back(NewParm->getType());
1208 } else if (Context.typesAreCompatible(OldParm->getType(),
1209 NewParm->getType())) {
Mike Stump11289f42009-09-09 15:08:12 +00001210 GNUCompatibleParamWarning Warn
Douglas Gregora74a2972009-03-06 22:43:54 +00001211 = { OldParm, NewParm, NewProto->getArgType(Idx) };
1212 Warnings.push_back(Warn);
1213 ArgTypes.push_back(NewParm->getType());
1214 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001215 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00001216 }
1217
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001218 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00001219 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1220 Diag(Warnings[Warn].NewParm->getLocation(),
1221 diag::ext_param_promoted_not_compatible_with_prototype)
1222 << Warnings[Warn].PromotedType
1223 << Warnings[Warn].OldParm->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001224 Diag(Warnings[Warn].OldParm->getLocation(),
Douglas Gregora74a2972009-03-06 22:43:54 +00001225 diag::note_previous_declaration);
1226 }
1227
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001228 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1229 ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00001230 OldProto->isVariadic(), 0,
1231 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001232 OldProto->getExtInfo()));
Douglas Gregora74a2972009-03-06 22:43:54 +00001233 return MergeCompatibleFunctionDecls(New, Old);
1234 }
1235
1236 // Fall through to diagnose conflicting types.
1237 }
1238
Steve Naroff17832a42008-01-16 15:01:34 +00001239 // A function that has already been declared has been redeclared or defined
1240 // with a different type- show appropriate diagnostic
Douglas Gregor15fc9562009-09-12 00:22:50 +00001241 if (unsigned BuiltinID = Old->getBuiltinID()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001242 // The user has declared a builtin function with an incompatible
1243 // signature.
1244 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1245 // The function the user is redeclaring is a library-defined
1246 // function like 'malloc' or 'printf'. Warn about the
Douglas Gregor893c2c92009-03-23 17:47:24 +00001247 // redeclaration, then pretend that we don't know about this
1248 // library built-in.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001249 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1250 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1251 << Old << Old->getType();
Douglas Gregor893c2c92009-03-23 17:47:24 +00001252 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1253 Old->setInvalidDecl();
1254 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001255 }
Steve Naroff17832a42008-01-16 15:01:34 +00001256
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001257 PrevDiag = diag::note_previous_builtin_declaration;
1258 }
1259
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001260 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001261 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001262 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00001263}
1264
Douglas Gregore62c0a42009-02-24 01:23:02 +00001265/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00001266/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00001267///
1268/// This routine handles the merging of attributes and other
1269/// properties of function declarations form the old declaration to
1270/// the new declaration, once we know that New is in fact a
1271/// redeclaration of Old.
1272///
1273/// \returns false
1274bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1275 // Merge the attributes
Chris Lattner9a2d50e72009-03-04 06:05:19 +00001276 MergeAttributes(New, Old, Context);
Douglas Gregore62c0a42009-02-24 01:23:02 +00001277
1278 // Merge the storage class.
Douglas Gregor299d76e2009-09-13 07:46:26 +00001279 if (Old->getStorageClass() != FunctionDecl::Extern &&
1280 Old->getStorageClass() != FunctionDecl::None)
Douglas Gregor76fe50c2009-04-28 06:37:30 +00001281 New->setStorageClass(Old->getStorageClass());
Douglas Gregore62c0a42009-02-24 01:23:02 +00001282
Douglas Gregore62c0a42009-02-24 01:23:02 +00001283 // Merge "pure" flag.
1284 if (Old->isPure())
1285 New->setPure();
1286
1287 // Merge the "deleted" flag.
1288 if (Old->isDeleted())
1289 New->setDeleted();
Mike Stump11289f42009-09-09 15:08:12 +00001290
Douglas Gregore62c0a42009-02-24 01:23:02 +00001291 if (getLangOptions().CPlusPlus)
1292 return MergeCXXFunctionDecl(New, Old);
1293
1294 return false;
1295}
1296
Chris Lattner01564d92007-01-27 19:27:06 +00001297/// MergeVarDecl - We just parsed a variable 'New' which has the same name
1298/// and scope as a previous declaration 'Old'. Figure out how to resolve this
1299/// situation, merging decls or emitting diagnostics as appropriate.
1300///
Mike Stump11289f42009-09-09 15:08:12 +00001301/// Tentative definition rules (C99 6.9.2p2) are checked by
1302/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00001303/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00001304///
John McCall1f82f242009-11-18 22:49:29 +00001305void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
1306 // If the new decl is already invalid, don't do any other checking.
1307 if (New->isInvalidDecl())
1308 return;
Mike Stump11289f42009-09-09 15:08:12 +00001309
Chris Lattnerc511efb2007-01-27 19:32:14 +00001310 // Verify the old decl was also a variable.
John McCall1f82f242009-11-18 22:49:29 +00001311 VarDecl *Old = 0;
1312 if (!Previous.isSingleResult() ||
1313 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001314 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001315 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001316 Diag(Previous.getRepresentativeDecl()->getLocation(),
1317 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001318 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001319 }
Chris Lattner84966392008-03-03 03:28:21 +00001320
Chris Lattner9a2d50e72009-03-04 06:05:19 +00001321 MergeAttributes(New, Old, Context);
Chris Lattner84966392008-03-03 03:28:21 +00001322
Eli Friedman8b7c5262009-01-24 23:49:55 +00001323 // Merge the types
Eli Friedman168fe152009-05-16 13:54:38 +00001324 QualType MergedT;
1325 if (getLangOptions().CPlusPlus) {
1326 if (Context.hasSameType(New->getType(), Old->getType()))
1327 MergedT = New->getType();
Eli Friedmane919e382009-12-10 08:54:47 +00001328 // C++ [basic.link]p10:
1329 // [...] the types specified by all declarations referring to a given
1330 // object or function shall be identical, except that declarations for an
1331 // array object can specify array types that differ by the presence or
1332 // absence of a major array bound (8.3.4).
Mike Stump11289f42009-09-09 15:08:12 +00001333 else if (Old->getType()->isIncompleteArrayType() &&
Douglas Gregor7d983672009-09-09 06:04:29 +00001334 New->getType()->isArrayType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001335 CanQual<ArrayType> OldArray
Douglas Gregor7d983672009-09-09 06:04:29 +00001336 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
Mike Stump11289f42009-09-09 15:08:12 +00001337 CanQual<ArrayType> NewArray
Douglas Gregor7d983672009-09-09 06:04:29 +00001338 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1339 if (OldArray->getElementType() == NewArray->getElementType())
1340 MergedT = New->getType();
Eli Friedmane919e382009-12-10 08:54:47 +00001341 } else if (Old->getType()->isArrayType() &&
1342 New->getType()->isIncompleteArrayType()) {
1343 CanQual<ArrayType> OldArray
1344 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1345 CanQual<ArrayType> NewArray
1346 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1347 if (OldArray->getElementType() == NewArray->getElementType())
1348 MergedT = Old->getType();
Douglas Gregor7d983672009-09-09 06:04:29 +00001349 }
Eli Friedman168fe152009-05-16 13:54:38 +00001350 } else {
1351 MergedT = Context.mergeTypes(New->getType(), Old->getType());
1352 }
Eli Friedman8b7c5262009-01-24 23:49:55 +00001353 if (MergedT.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00001354 Diag(New->getLocation(), diag::err_redefinition_different_type)
Douglas Gregor020713e2009-01-09 19:42:16 +00001355 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001356 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001357 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00001358 }
Eli Friedman8b7c5262009-01-24 23:49:55 +00001359 New->setType(MergedT);
Douglas Gregor04e9a032009-03-11 23:52:16 +00001360
Steve Naroff1e787362008-01-30 00:44:01 +00001361 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
1362 if (New->getStorageClass() == VarDecl::Static &&
Daniel Dunbar0ca16602009-04-14 02:25:56 +00001363 (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001364 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001365 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001366 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00001367 }
Mike Stump11289f42009-09-09 15:08:12 +00001368 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00001369 // For an identifier declared with the storage-class specifier
1370 // extern in a scope in which a prior declaration of that
1371 // identifier is visible,23) if the prior declaration specifies
1372 // internal or external linkage, the linkage of the identifier at
1373 // the later declaration is the same as the linkage specified at
1374 // the prior declaration. If no prior declaration is visible, or
1375 // if the prior declaration specifies no linkage, then the
1376 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00001377 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00001378 /* Okay */;
1379 else if (New->getStorageClass() != VarDecl::Static &&
1380 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001381 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001382 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001383 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00001384 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00001385
Steve Naroffa5629372008-09-17 14:05:40 +00001386 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00001387
Daniel Dunbar0ca16602009-04-14 02:25:56 +00001388 // FIXME: The test for external storage here seems wrong? We still
1389 // need to check for mismatches.
1390 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00001391 // Don't complain about out-of-line definitions of static members.
1392 !(Old->getLexicalDeclContext()->isRecord() &&
1393 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00001394 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001395 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001396 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00001397 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00001398
Eli Friedmand5c0eed2009-04-19 20:27:55 +00001399 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1400 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1401 Diag(Old->getLocation(), diag::note_previous_definition);
1402 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1403 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1404 Diag(Old->getLocation(), diag::note_previous_definition);
1405 }
1406
Sebastian Redlf1842912010-02-02 18:35:11 +00001407 // C++ doesn't have tentative definitions, so go right ahead and check here.
1408 const VarDecl *Def;
Sebastian Redld85be0c2010-02-03 02:08:48 +00001409 if (getLangOptions().CPlusPlus &&
1410 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00001411 (Def = Old->getDefinition())) {
1412 Diag(New->getLocation(), diag::err_redefinition)
1413 << New->getDeclName();
1414 Diag(Def->getLocation(), diag::note_previous_definition);
1415 New->setInvalidDecl();
1416 return;
1417 }
1418
Douglas Gregor0760fa12009-03-10 23:43:53 +00001419 // Keep a chain of previous declarations.
1420 New->setPreviousDeclaration(Old);
John McCall401982f2010-01-20 21:53:11 +00001421
1422 // Inherit access appropriately.
1423 New->setAccess(Old->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00001424}
1425
Chris Lattnerb6738ec2007-01-28 00:38:24 +00001426/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1427/// no declarator (e.g. "struct foo;") is parsed.
Chris Lattner83f095c2009-03-28 19:18:32 +00001428Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Eli Friedman32e6e8e2009-04-09 21:26:42 +00001429 // FIXME: Error on auto/register at file scope
1430 // FIXME: Error on inline/virtual/explicit
Eli Friedmand5c0eed2009-04-19 20:27:55 +00001431 // FIXME: Warn on useless __thread
Eli Friedman32e6e8e2009-04-09 21:26:42 +00001432 // FIXME: Warn on useless const/volatile
1433 // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1434 // FIXME: Warn on useless attributes
John McCallc3987482009-10-07 23:34:25 +00001435 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00001436 TagDecl *Tag = 0;
1437 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1438 DS.getTypeSpecType() == DeclSpec::TST_struct ||
1439 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001440 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallc3987482009-10-07 23:34:25 +00001441 TagD = static_cast<Decl *>(DS.getTypeRep());
1442
1443 if (!TagD) // We probably had an error
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001444 return DeclPtrTy();
1445
John McCall07e91c02009-08-06 02:15:43 +00001446 // Note that the above type specs guarantee that the
1447 // type rep is a Decl, whereas in many of the others
1448 // it's a Type.
John McCallc3987482009-10-07 23:34:25 +00001449 Tag = dyn_cast<TagDecl>(TagD);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001450 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00001451
Nuno Lopese9823fa2009-12-17 11:35:26 +00001452 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1453 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
1454 // or incomplete types shall not be restrict-qualified."
1455 if (TypeQuals & DeclSpec::TQ_restrict)
1456 Diag(DS.getRestrictSpecLoc(),
1457 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
1458 << DS.getSourceRange();
1459 }
1460
Douglas Gregor3dad8422009-09-26 06:47:28 +00001461 if (DS.isFriendSpecified()) {
John McCallc3987482009-10-07 23:34:25 +00001462 // If we're dealing with a class template decl, assume that the
1463 // template routines are handling it.
1464 if (TagD && isa<ClassTemplateDecl>(TagD))
Douglas Gregor3dad8422009-09-26 06:47:28 +00001465 return DeclPtrTy();
John McCallc3987482009-10-07 23:34:25 +00001466 return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
Douglas Gregor3dad8422009-09-26 06:47:28 +00001467 }
1468
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00001469 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
Chris Lattnerecf328e2009-10-25 22:21:57 +00001470 // If there are attributes in the DeclSpec, apply them to the record.
1471 if (const AttributeList *AL = DS.getAttributes())
1472 ProcessDeclAttributeList(S, Record, AL);
1473
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00001474 if (!Record->getDeclName() && Record->isDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00001475 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1476 if (getLangOptions().CPlusPlus ||
1477 Record->getDeclContext()->isRecord())
1478 return BuildAnonymousStructOrUnion(S, DS, Record);
1479
Douglas Gregorf19ac0e2010-04-08 21:33:23 +00001480 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Douglas Gregor2e7cba62009-03-06 23:06:59 +00001481 << DS.getSourceRange();
1482 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00001483
1484 // Microsoft allows unnamed struct/union fields. Don't complain
1485 // about them.
1486 // FIXME: Should we support Microsoft's extensions in this area?
1487 if (Record->getDeclName() && getLangOptions().Microsoft)
Chris Lattner83f095c2009-03-28 19:18:32 +00001488 return DeclPtrTy::make(Tag);
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00001489 }
Douglas Gregor3dad8422009-09-26 06:47:28 +00001490
Mike Stump11289f42009-09-09 15:08:12 +00001491 if (!DS.isMissingDeclaratorOk() &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001492 DS.getTypeSpecType() != DeclSpec::TST_error) {
Douglas Gregor2d9dde0e2009-01-22 16:23:54 +00001493 // Warn about typedefs of enums without names, since this is an
1494 // extension in both Microsoft an GNU.
Douglas Gregor051d8fd2009-01-17 02:55:50 +00001495 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1496 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregor2d9dde0e2009-01-22 16:23:54 +00001497 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregor2b136fe2009-01-13 23:10:51 +00001498 << DS.getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00001499 return DeclPtrTy::make(Tag);
Douglas Gregor2b136fe2009-01-13 23:10:51 +00001500 }
1501
Douglas Gregorf19ac0e2010-04-08 21:33:23 +00001502 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Sebastian Redla2b5e312008-12-28 15:28:59 +00001503 << DS.getSourceRange();
Sebastian Redla2b5e312008-12-28 15:28:59 +00001504 }
Mike Stump11289f42009-09-09 15:08:12 +00001505
Chris Lattner83f095c2009-03-28 19:18:32 +00001506 return DeclPtrTy::make(Tag);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001507}
1508
John McCallea305ed2009-12-18 10:40:03 +00001509/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00001510/// check if there's an existing declaration that can't be overloaded.
1511///
1512/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00001513static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
1514 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00001515 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00001516 DeclarationName Name,
1517 SourceLocation NameLoc,
1518 unsigned diagnostic) {
1519 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
1520 Sema::ForRedeclaration);
1521 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00001522
John McCallea305ed2009-12-18 10:40:03 +00001523 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00001524 return false;
1525
1526 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00001527 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Fariborz Jahanian53967e22010-01-22 18:30:17 +00001528 if (PrevDecl && Owner->isRecord()) {
1529 RecordDecl *Record = cast<RecordDecl>(Owner);
1530 if (!SemaRef.isDeclInScope(PrevDecl, Record, S))
1531 return false;
1532 }
John McCall1f82f242009-11-18 22:49:29 +00001533
John McCallea305ed2009-12-18 10:40:03 +00001534 SemaRef.Diag(NameLoc, diagnostic) << Name;
1535 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00001536
1537 return true;
1538}
1539
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001540/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1541/// anonymous struct or union AnonRecord into the owning context Owner
1542/// and scope S. This routine will be invoked just after we realize
1543/// that an unnamed union or struct is actually an anonymous union or
1544/// struct, e.g.,
1545///
1546/// @code
1547/// union {
1548/// int i;
1549/// float f;
1550/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1551/// // f into the surrounding scope.x
1552/// @endcode
1553///
1554/// This routine is recursive, injecting the names of nested anonymous
1555/// structs/unions into the owning context and scope as well.
1556bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
1557 RecordDecl *AnonRecord) {
John McCall1f82f242009-11-18 22:49:29 +00001558 unsigned diagKind
1559 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
1560 : diag::err_anonymous_struct_member_redecl;
1561
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001562 bool Invalid = false;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001563 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
1564 FEnd = AnonRecord->field_end();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001565 F != FEnd; ++F) {
1566 if ((*F)->getDeclName()) {
Fariborz Jahanian53967e22010-01-22 18:30:17 +00001567 if (CheckAnonMemberRedeclaration(*this, S, Owner, (*F)->getDeclName(),
John McCallea305ed2009-12-18 10:40:03 +00001568 (*F)->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001569 // C++ [class.union]p2:
1570 // The names of the members of an anonymous union shall be
1571 // distinct from the names of any other entity in the
1572 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001573 Invalid = true;
1574 } else {
1575 // C++ [class.union]p2:
1576 // For the purpose of name lookup, after the anonymous union
1577 // definition, the members of the anonymous union are
1578 // considered to have been defined in the scope in which the
1579 // anonymous union is declared.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001580 Owner->makeDeclVisibleInContext(*F);
Chris Lattner83f095c2009-03-28 19:18:32 +00001581 S->AddDecl(DeclPtrTy::make(*F));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001582 IdResolver.AddDecl(*F);
1583 }
1584 } else if (const RecordType *InnerRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001585 = (*F)->getType()->getAs<RecordType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001586 RecordDecl *InnerRecord = InnerRecordType->getDecl();
1587 if (InnerRecord->isAnonymousStructOrUnion())
Mike Stump11289f42009-09-09 15:08:12 +00001588 Invalid = Invalid ||
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001589 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
1590 }
1591 }
1592
1593 return Invalid;
1594}
1595
Douglas Gregorc4df4072010-04-19 22:54:31 +00001596/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
1597/// a VarDecl::StorageClass. Any error reporting is up to the caller:
1598/// illegal input values are mapped to VarDecl::None.
1599static VarDecl::StorageClass
1600StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
1601 switch (StorageClassSpec) {
1602 case DeclSpec::SCS_unspecified: return VarDecl::None;
1603 case DeclSpec::SCS_extern: return VarDecl::Extern;
1604 case DeclSpec::SCS_static: return VarDecl::Static;
1605 case DeclSpec::SCS_auto: return VarDecl::Auto;
1606 case DeclSpec::SCS_register: return VarDecl::Register;
1607 case DeclSpec::SCS_private_extern: return VarDecl::PrivateExtern;
1608 // Illegal SCSs map to None: error reporting is up to the caller.
1609 case DeclSpec::SCS_mutable: // Fall through.
1610 case DeclSpec::SCS_typedef: return VarDecl::None;
1611 }
1612 llvm_unreachable("unknown storage class specifier");
1613}
1614
1615/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
1616/// a FunctionDecl::StorageClass. Any error reporting is up to the caller:
1617/// illegal input values are mapped to FunctionDecl::None.
1618static FunctionDecl::StorageClass
1619StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
1620 switch (StorageClassSpec) {
1621 case DeclSpec::SCS_unspecified: return FunctionDecl::None;
1622 case DeclSpec::SCS_extern: return FunctionDecl::Extern;
1623 case DeclSpec::SCS_static: return FunctionDecl::Static;
1624 case DeclSpec::SCS_private_extern: return FunctionDecl::PrivateExtern;
1625 // Illegal SCSs map to None: error reporting is up to the caller.
1626 case DeclSpec::SCS_auto: // Fall through.
1627 case DeclSpec::SCS_mutable: // Fall through.
1628 case DeclSpec::SCS_register: // Fall through.
1629 case DeclSpec::SCS_typedef: return FunctionDecl::None;
1630 }
1631 llvm_unreachable("unknown storage class specifier");
1632}
1633
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001634/// ActOnAnonymousStructOrUnion - Handle the declaration of an
1635/// anonymous structure or union. Anonymous unions are a C++ feature
1636/// (C++ [class.union]) and a GNU C extension; anonymous structures
Mike Stump11289f42009-09-09 15:08:12 +00001637/// are a GNU C and GNU C++ extension.
Chris Lattner83f095c2009-03-28 19:18:32 +00001638Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1639 RecordDecl *Record) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001640 DeclContext *Owner = Record->getDeclContext();
1641
1642 // Diagnose whether this anonymous struct/union is an extension.
1643 if (Record->isUnion() && !getLangOptions().CPlusPlus)
1644 Diag(Record->getLocation(), diag::ext_anonymous_union);
1645 else if (!Record->isUnion())
1646 Diag(Record->getLocation(), diag::ext_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00001647
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001648 // C and C++ require different kinds of checks for anonymous
1649 // structs/unions.
1650 bool Invalid = false;
1651 if (getLangOptions().CPlusPlus) {
1652 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00001653 unsigned DiagID;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001654 // C++ [class.union]p3:
1655 // Anonymous unions declared in a named namespace or in the
1656 // global namespace shall be declared static.
1657 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1658 (isa<TranslationUnitDecl>(Owner) ||
Mike Stump11289f42009-09-09 15:08:12 +00001659 (isa<NamespaceDecl>(Owner) &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001660 cast<NamespaceDecl>(Owner)->getDeclName()))) {
1661 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1662 Invalid = true;
1663
1664 // Recover by adding 'static'.
John McCall49bfce42009-08-03 20:12:06 +00001665 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1666 PrevSpec, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +00001667 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001668 // C++ [class.union]p3:
1669 // A storage class is not allowed in a declaration of an
1670 // anonymous union in a class scope.
1671 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1672 isa<RecordDecl>(Owner)) {
Mike Stump11289f42009-09-09 15:08:12 +00001673 Diag(DS.getStorageClassSpecLoc(),
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001674 diag::err_anonymous_union_with_storage_spec);
1675 Invalid = true;
1676
1677 // Recover by removing the storage specifier.
1678 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
John McCall49bfce42009-08-03 20:12:06 +00001679 PrevSpec, DiagID);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001680 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00001681
Mike Stump11289f42009-09-09 15:08:12 +00001682 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00001683 // The member-specification of an anonymous union shall only
1684 // define non-static data members. [Note: nested types and
1685 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001686 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1687 MemEnd = Record->decls_end();
Douglas Gregorf4d33272009-01-07 19:46:03 +00001688 Mem != MemEnd; ++Mem) {
1689 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1690 // C++ [class.union]p3:
1691 // An anonymous union shall not have private or protected
1692 // members (clause 11).
1693 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
1694 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1695 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1696 Invalid = true;
1697 }
1698 } else if ((*Mem)->isImplicit()) {
1699 // Any implicit members are fine.
Douglas Gregor8761da52009-02-03 00:34:39 +00001700 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1701 // This is a type that showed up in an
1702 // elaborated-type-specifier inside the anonymous struct or
1703 // union, but which actually declares a type outside of the
1704 // anonymous struct or union. It's okay.
Douglas Gregorf4d33272009-01-07 19:46:03 +00001705 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1706 if (!MemRecord->isAnonymousStructOrUnion() &&
1707 MemRecord->getDeclName()) {
1708 // This is a nested type declaration.
1709 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1710 << (int)Record->isUnion();
1711 Invalid = true;
1712 }
1713 } else {
1714 // We have something that isn't a non-static data
1715 // member. Complain about it.
1716 unsigned DK = diag::err_anonymous_record_bad_member;
1717 if (isa<TypeDecl>(*Mem))
1718 DK = diag::err_anonymous_record_with_type;
1719 else if (isa<FunctionDecl>(*Mem))
1720 DK = diag::err_anonymous_record_with_function;
1721 else if (isa<VarDecl>(*Mem))
1722 DK = diag::err_anonymous_record_with_static;
1723 Diag((*Mem)->getLocation(), DK)
1724 << (int)Record->isUnion();
1725 Invalid = true;
1726 }
1727 }
Mike Stump11289f42009-09-09 15:08:12 +00001728 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001729
1730 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00001731 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1732 << (int)getLangOptions().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001733 Invalid = true;
1734 }
1735
John McCallfa2d6922009-10-22 23:31:08 +00001736 // Mock up a declarator.
1737 Declarator Dc(DS, Declarator::TypeNameContext);
John McCallbcd03502009-12-07 02:54:59 +00001738 TypeSourceInfo *TInfo = 0;
1739 GetTypeForDeclarator(Dc, S, &TInfo);
1740 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00001741
Mike Stump11289f42009-09-09 15:08:12 +00001742 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001743 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001744 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1745 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001746 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001747 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00001748 TInfo,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001749 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregorf4d33272009-01-07 19:46:03 +00001750 Anon->setAccess(AS_public);
1751 if (getLangOptions().CPlusPlus)
1752 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001753 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00001754 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
1755 assert(SCSpec != DeclSpec::SCS_typedef &&
1756 "Parser allowed 'typedef' as storage class VarDecl.");
1757 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
1758 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001759 // mutable can only appear on non-static class members, so it's always
1760 // an error here
1761 Diag(Record->getLocation(), diag::err_mutable_nonmember);
1762 Invalid = true;
1763 SC = VarDecl::None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001764 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00001765 SCSpec = DS.getStorageClassSpecAsWritten();
1766 VarDecl::StorageClass SCAsWritten
1767 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001768
1769 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001770 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001771 Context.getTypeDeclType(Record),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001772 TInfo, SC, SCAsWritten);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001773 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00001774 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001775
1776 // Add the anonymous struct/union object to the current
1777 // context. We'll be referencing this object when we refer to one of
1778 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001779 Owner->addDecl(Anon);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001780
1781 // Inject the members of the anonymous struct/union into the owning
1782 // context and into the identifier resolver chain for name lookup
1783 // purposes.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00001784 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1785 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001786
1787 // Mark this as an anonymous struct/union type. Note that we do not
1788 // do this until after we have already checked and injected the
1789 // members of this anonymous struct/union type, because otherwise
1790 // the members could be injected twice: once by DeclContext when it
1791 // builds its lookup table, and once by
Mike Stump11289f42009-09-09 15:08:12 +00001792 // InjectAnonymousStructOrUnionMembers.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001793 Record->setAnonymousStructOrUnion(true);
1794
1795 if (Invalid)
1796 Anon->setInvalidDecl();
1797
Chris Lattner83f095c2009-03-28 19:18:32 +00001798 return DeclPtrTy::make(Anon);
Chris Lattnerb6738ec2007-01-28 00:38:24 +00001799}
1800
Steve Naroff2fea1392007-09-02 02:04:30 +00001801
Douglas Gregor92751d42008-11-17 22:58:34 +00001802/// GetNameForDeclarator - Determine the full declaration name for the
1803/// given Declarator.
1804DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00001805 return GetNameFromUnqualifiedId(D.getName());
1806}
1807
1808/// \brief Retrieves the canonicalized name from a parsed unqualified-id.
John McCall10eae182009-11-30 22:42:35 +00001809DeclarationName Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
Douglas Gregor7861a802009-11-03 01:35:08 +00001810 switch (Name.getKind()) {
Douglas Gregora121b752009-11-03 16:56:39 +00001811 case UnqualifiedId::IK_Identifier:
1812 return DeclarationName(Name.Identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00001813
Douglas Gregora121b752009-11-03 16:56:39 +00001814 case UnqualifiedId::IK_OperatorFunctionId:
1815 return Context.DeclarationNames.getCXXOperatorName(
Alexis Hunt8818b422009-11-29 03:04:53 +00001816 Name.OperatorFunctionId.Operator);
Alexis Hunt34458502009-11-28 04:44:28 +00001817
1818 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +00001819 return Context.DeclarationNames.getCXXLiteralOperatorName(
1820 Name.Identifier);
Alexis Hunt34458502009-11-28 04:44:28 +00001821
Douglas Gregora121b752009-11-03 16:56:39 +00001822 case UnqualifiedId::IK_ConversionFunctionId: {
1823 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId);
1824 if (Ty.isNull())
1825 return DeclarationName();
Douglas Gregord90fd522009-09-25 21:45:23 +00001826
Douglas Gregora121b752009-11-03 16:56:39 +00001827 return Context.DeclarationNames.getCXXConversionFunctionName(
Alexis Hunt8818b422009-11-29 03:04:53 +00001828 Context.getCanonicalType(Ty));
Douglas Gregora121b752009-11-03 16:56:39 +00001829 }
1830
1831 case UnqualifiedId::IK_ConstructorName: {
1832 QualType Ty = GetTypeFromParser(Name.ConstructorName);
1833 if (Ty.isNull())
1834 return DeclarationName();
1835
1836 return Context.DeclarationNames.getCXXConstructorName(
Alexis Hunt8818b422009-11-29 03:04:53 +00001837 Context.getCanonicalType(Ty));
Douglas Gregora121b752009-11-03 16:56:39 +00001838 }
1839
Douglas Gregor9de54ea2010-01-13 17:31:36 +00001840 case UnqualifiedId::IK_ConstructorTemplateId: {
1841 // In well-formed code, we can only have a constructor
1842 // template-id that refers to the current context, so go there
1843 // to find the actual type being constructed.
1844 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
1845 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
1846 return DeclarationName();
1847
1848 // Determine the type of the class being constructed.
John McCalle78aac42010-03-10 03:28:59 +00001849 QualType CurClassType = Context.getTypeDeclType(CurClass);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00001850
1851 // FIXME: Check two things: that the template-id names the same type as
1852 // CurClassType, and that the template-id does not occur when the name
1853 // was qualified.
1854
1855 return Context.DeclarationNames.getCXXConstructorName(
1856 Context.getCanonicalType(CurClassType));
1857 }
1858
Douglas Gregora121b752009-11-03 16:56:39 +00001859 case UnqualifiedId::IK_DestructorName: {
1860 QualType Ty = GetTypeFromParser(Name.DestructorName);
1861 if (Ty.isNull())
1862 return DeclarationName();
1863
1864 return Context.DeclarationNames.getCXXDestructorName(
1865 Context.getCanonicalType(Ty));
1866 }
1867
1868 case UnqualifiedId::IK_TemplateId: {
1869 TemplateName TName
John McCalld28ae272009-12-02 08:04:21 +00001870 = TemplateName::getFromVoidPointer(Name.TemplateId->Template);
1871 return Context.getNameForTemplate(TName);
Douglas Gregora121b752009-11-03 16:56:39 +00001872 }
Douglas Gregord90fd522009-09-25 21:45:23 +00001873 }
Douglas Gregora121b752009-11-03 16:56:39 +00001874
Douglas Gregor92751d42008-11-17 22:58:34 +00001875 assert(false && "Unknown name kind");
Douglas Gregora121b752009-11-03 16:56:39 +00001876 return DeclarationName();
Douglas Gregor92751d42008-11-17 22:58:34 +00001877}
1878
Douglas Gregor8af63e42009-02-06 17:46:57 +00001879/// isNearlyMatchingFunction - Determine whether the C++ functions
1880/// Declaration and Definition are "nearly" matching. This heuristic
1881/// is used to improve diagnostics in the case where an out-of-line
1882/// function definition doesn't match any declaration within
1883/// the class or namespace.
1884static bool isNearlyMatchingFunction(ASTContext &Context,
1885 FunctionDecl *Declaration,
1886 FunctionDecl *Definition) {
Douglas Gregorad590502008-12-15 23:53:10 +00001887 if (Declaration->param_size() != Definition->param_size())
1888 return false;
1889 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1890 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1891 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1892
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001893 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
1894 DefParamTy.getNonReferenceType()))
Douglas Gregorad590502008-12-15 23:53:10 +00001895 return false;
1896 }
1897
1898 return true;
1899}
1900
Mike Stump11289f42009-09-09 15:08:12 +00001901Sema::DeclPtrTy
1902Sema::HandleDeclarator(Scope *S, Declarator &D,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00001903 MultiTemplateParamsArg TemplateParamLists,
1904 bool IsFunctionDefinition) {
Douglas Gregor92751d42008-11-17 22:58:34 +00001905 DeclarationName Name = GetNameForDeclarator(D);
1906
Chris Lattner02c04392007-07-25 00:24:17 +00001907 // All of these full declarators require an identifier. If it doesn't have
1908 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00001909 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001910 if (!D.isInvalidType()) // Reject this if we think it is valid.
Chris Lattner8c5dd732008-11-11 06:13:16 +00001911 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00001912 diag::err_declarator_need_ident)
1913 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00001914 return DeclPtrTy();
Chris Lattner02c04392007-07-25 00:24:17 +00001915 }
Mike Stump11289f42009-09-09 15:08:12 +00001916
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001917 // The scope passed in may not be a decl scope. Zip up the scope tree until
1918 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00001919 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001920 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001921 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001922
Douglas Gregor15acfb92009-08-06 16:20:37 +00001923 // If this is an out-of-line definition of a member of a class template
1924 // or class template partial specialization, we may need to rebuild the
1925 // type specifier in the declarator. See RebuildTypeInCurrentInstantiation()
1926 // for more information.
1927 // FIXME: cope with decltype(expr) and typeof(expr) once the rebuilder can
1928 // handle expressions properly.
1929 DeclSpec &DS = const_cast<DeclSpec&>(D.getDeclSpec());
1930 if (D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid() &&
1931 isDependentScopeSpecifier(D.getCXXScopeSpec()) &&
1932 (DS.getTypeSpecType() == DeclSpec::TST_typename ||
1933 DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
1934 DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
1935 DS.getTypeSpecType() == DeclSpec::TST_decltype)) {
1936 if (DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(), true)) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001937 // FIXME: Preserve type source info.
1938 QualType T = GetTypeFromParser(DS.getTypeRep());
John McCall4d6d6132009-12-19 09:35:56 +00001939
1940 DeclContext *SavedContext = CurContext;
1941 CurContext = DC;
Douglas Gregor15acfb92009-08-06 16:20:37 +00001942 T = RebuildTypeInCurrentInstantiation(T, D.getIdentifierLoc(), Name);
John McCall4d6d6132009-12-19 09:35:56 +00001943 CurContext = SavedContext;
1944
Douglas Gregor15acfb92009-08-06 16:20:37 +00001945 if (T.isNull())
1946 return DeclPtrTy();
1947 DS.UpdateTypeRep(T.getAsOpaquePtr());
1948 }
1949 }
Mike Stump11289f42009-09-09 15:08:12 +00001950
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001951 DeclContext *DC;
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001952 NamedDecl *New;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001953
John McCallbcd03502009-12-07 02:54:59 +00001954 TypeSourceInfo *TInfo = 0;
1955 QualType R = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregoreddf4332009-02-24 20:03:32 +00001956
John McCall1f82f242009-11-18 22:49:29 +00001957 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
1958 ForRedeclaration);
1959
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001960 // See if this is a redefinition of a variable in the same scope.
Douglas Gregorc2fd6262009-03-06 19:06:37 +00001961 if (D.getCXXScopeSpec().isInvalid()) {
1962 DC = CurContext;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001963 D.setInvalidType();
Douglas Gregorc2fd6262009-03-06 19:06:37 +00001964 } else if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00001965 bool IsLinkageLookup = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001966
1967 // If the declaration we're planning to build will be a function
1968 // or object with linkage, then look for another declaration with
1969 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
1970 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1971 /* Do nothing*/;
1972 else if (R->isFunctionType()) {
Douglas Gregor20749772009-07-07 17:00:05 +00001973 if (CurContext->isFunctionOrMethod() ||
1974 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00001975 IsLinkageLookup = true;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001976 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
John McCall1f82f242009-11-18 22:49:29 +00001977 IsLinkageLookup = true;
Douglas Gregor20749772009-07-07 17:00:05 +00001978 else if (CurContext->getLookupContext()->isTranslationUnit() &&
1979 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00001980 IsLinkageLookup = true;
1981
1982 if (IsLinkageLookup)
1983 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00001984
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001985 DC = CurContext;
John McCall1f82f242009-11-18 22:49:29 +00001986 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001987 } else { // Something like "int foo::x;"
Douglas Gregord8d297c2009-07-21 23:53:31 +00001988 DC = computeDeclContext(D.getCXXScopeSpec(), true);
Mike Stump11289f42009-09-09 15:08:12 +00001989
Douglas Gregor053f6912009-08-26 00:04:55 +00001990 if (!DC) {
1991 // If we could not compute the declaration context, it's because the
1992 // declaration context is dependent but does not refer to a class,
1993 // class template, or class template partial specialization. Complain
1994 // and return early, to avoid the coming semantic disaster.
Mike Stump11289f42009-09-09 15:08:12 +00001995 Diag(D.getIdentifierLoc(),
Douglas Gregor053f6912009-08-26 00:04:55 +00001996 diag::err_template_qualified_declarator_no_match)
1997 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
1998 << D.getCXXScopeSpec().getRange();
1999 return DeclPtrTy();
2000 }
Mike Stump11289f42009-09-09 15:08:12 +00002001
Douglas Gregorcf915552009-10-13 16:30:37 +00002002 if (!DC->isDependentContext() &&
2003 RequireCompleteDeclContext(D.getCXXScopeSpec()))
2004 return DeclPtrTy();
John McCall67da35c2010-02-04 22:26:26 +00002005
2006 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
2007 Diag(D.getIdentifierLoc(),
2008 diag::err_member_def_undefined_record)
2009 << Name << DC << D.getCXXScopeSpec().getRange();
2010 D.setInvalidType();
2011 }
Douglas Gregorcf915552009-10-13 16:30:37 +00002012
John McCall1f82f242009-11-18 22:49:29 +00002013 LookupQualifiedName(Previous, DC);
2014
2015 // Don't consider using declarations as previous declarations for
2016 // out-of-line members.
2017 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002018
2019 // C++ 7.3.1.2p2:
2020 // Members (including explicit specializations of templates) of a named
2021 // namespace can also be defined outside that namespace by explicit
2022 // qualification of the name being defined, provided that the entity being
2023 // defined was already declared in the namespace and the definition appears
2024 // after the point of declaration in a namespace that encloses the
2025 // declarations namespace.
2026 //
Douglas Gregorad590502008-12-15 23:53:10 +00002027 // Note that we only check the context at this point. We don't yet
2028 // have enough information to make sure that PrevDecl is actually
2029 // the declaration we want to match. For example, given:
2030 //
Douglas Gregor4287b372008-12-12 08:25:50 +00002031 // class X {
2032 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00002033 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00002034 // };
2035 //
Douglas Gregorad590502008-12-15 23:53:10 +00002036 // void X::f(int) { } // ill-formed
2037 //
2038 // In this case, PrevDecl will point to the overload set
2039 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00002040 // matches.
Douglas Gregor8af63e42009-02-06 17:46:57 +00002041
2042 // First check whether we named the global scope.
2043 if (isa<TranslationUnitDecl>(DC)) {
Mike Stump11289f42009-09-09 15:08:12 +00002044 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
Douglas Gregor8af63e42009-02-06 17:46:57 +00002045 << Name << D.getCXXScopeSpec().getRange();
Sebastian Redlafb8be72009-11-08 11:36:54 +00002046 } else {
2047 DeclContext *Cur = CurContext;
2048 while (isa<LinkageSpecDecl>(Cur))
2049 Cur = Cur->getParent();
2050 if (!Cur->Encloses(DC)) {
2051 // The qualifying scope doesn't enclose the original declaration.
2052 // Emit diagnostic based on current scope.
2053 SourceLocation L = D.getIdentifierLoc();
2054 SourceRange R = D.getCXXScopeSpec().getRange();
2055 if (isa<FunctionDecl>(Cur))
2056 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
2057 else
2058 Diag(L, diag::err_invalid_declarator_scope)
2059 << Name << cast<NamedDecl>(DC) << R;
2060 D.setInvalidType();
2061 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002062 }
2063 }
2064
John McCall1f82f242009-11-18 22:49:29 +00002065 if (Previous.isSingleResult() &&
2066 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00002067 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002068 if (!D.isInvalidType())
John McCall1f82f242009-11-18 22:49:29 +00002069 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
2070 Previous.getFoundDecl()))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002071 D.setInvalidType();
Mike Stump11289f42009-09-09 15:08:12 +00002072
Douglas Gregor5101c242008-12-05 18:15:24 +00002073 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00002074 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00002075 }
2076
Douglas Gregor83a586e2008-04-13 21:07:44 +00002077 // In C++, the previous declaration we find might be a tag type
2078 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00002079 // tag type. Note that this does does not apply if we're declaring a
2080 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00002081 if (Previous.isSingleTagDecl() &&
Douglas Gregorfb034662009-01-28 17:15:10 +00002082 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00002083 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00002084
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002085 bool Redeclaration = false;
Chris Lattner01a7c532007-01-25 23:09:03 +00002086 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002087 if (TemplateParamLists.size()) {
2088 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
2089 return DeclPtrTy();
2090 }
Mike Stump11289f42009-09-09 15:08:12 +00002091
John McCallbcd03502009-12-07 02:54:59 +00002092 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
Douglas Gregoreddf4332009-02-24 20:03:32 +00002093 } else if (R->isFunctionType()) {
John McCallbcd03502009-12-07 02:54:59 +00002094 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002095 move(TemplateParamLists),
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002096 IsFunctionDefinition, Redeclaration);
Chris Lattner01a7c532007-01-25 23:09:03 +00002097 } else {
John McCallbcd03502009-12-07 02:54:59 +00002098 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002099 move(TemplateParamLists),
2100 Redeclaration);
Chris Lattner01a7c532007-01-25 23:09:03 +00002101 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00002102
2103 if (New == 0)
Chris Lattner83f095c2009-03-28 19:18:32 +00002104 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00002105
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002106 // If this has an identifier and is not an invalid redeclaration or
2107 // function template specialization, add it to the scope stack.
Eli Friedman73168192009-12-08 05:40:03 +00002108 if (Name && !(Redeclaration && New->isInvalidDecl()))
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00002109 PushOnScopeChains(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00002110
Chris Lattner83f095c2009-03-28 19:18:32 +00002111 return DeclPtrTy::make(New);
Chris Lattnere168f762006-11-10 05:29:30 +00002112}
2113
Eli Friedmana3b1d032009-02-21 00:44:51 +00002114/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2115/// types into constant array types in certain situations which would otherwise
2116/// be errors (for GCC compatibility).
2117static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2118 ASTContext &Context,
2119 bool &SizeIsNegative) {
2120 // This method tries to turn a variable array into a constant
2121 // array even when the size isn't an ICE. This is necessary
2122 // for compatibility with code that depends on gcc's buggy
2123 // constant expression folding, like struct {char x[(int)(char*)2];}
2124 SizeIsNegative = false;
2125
John McCall8ccfcb52009-09-24 19:53:00 +00002126 QualifierCollector Qs;
2127 const Type *Ty = Qs.strip(T);
2128
2129 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00002130 QualType Pointee = PTy->getPointeeType();
2131 QualType FixedType =
2132 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
2133 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00002134 FixedType = Context.getPointerType(FixedType);
John McCall8ccfcb52009-09-24 19:53:00 +00002135 return Qs.apply(FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00002136 }
2137
2138 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00002139 if (!VLATy)
2140 return QualType();
2141 // FIXME: We should probably handle this case
2142 if (VLATy->getElementType()->isVariablyModifiedType())
2143 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00002144
Eli Friedmana3b1d032009-02-21 00:44:51 +00002145 Expr::EvalResult EvalResult;
2146 if (!VLATy->getSizeExpr() ||
Eli Friedmanadf40d42009-02-26 03:58:54 +00002147 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
2148 !EvalResult.Val.isInt())
Eli Friedmana3b1d032009-02-21 00:44:51 +00002149 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00002150
Eli Friedmana3b1d032009-02-21 00:44:51 +00002151 llvm::APSInt &Res = EvalResult.Val.getInt();
Douglas Gregor04318252009-07-06 15:59:29 +00002152 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
John McCallc5b82252009-10-16 00:14:28 +00002153 // TODO: preserve the size expression in declarator info
2154 return Context.getConstantArrayType(VLATy->getElementType(),
2155 Res, ArrayType::Normal, 0);
Douglas Gregor04318252009-07-06 15:59:29 +00002156 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00002157
2158 SizeIsNegative = true;
2159 return QualType();
2160}
2161
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002162/// \brief Register the given locally-scoped external C declaration so
2163/// that it can be found later for redeclarations
Mike Stump11289f42009-09-09 15:08:12 +00002164void
John McCall1f82f242009-11-18 22:49:29 +00002165Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
2166 const LookupResult &Previous,
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002167 Scope *S) {
2168 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
2169 "Decl is not a locally-scoped decl!");
2170 // Note that we have a locally-scoped external with this name.
2171 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
2172
John McCall1f82f242009-11-18 22:49:29 +00002173 if (!Previous.isSingleResult())
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002174 return;
2175
John McCall1f82f242009-11-18 22:49:29 +00002176 NamedDecl *PrevDecl = Previous.getFoundDecl();
2177
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002178 // If there was a previous declaration of this variable, it may be
2179 // in our identifier chain. Update the identifier chain with the new
2180 // declaration.
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002181 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002182 // The previous declaration was found on the identifer resolver
2183 // chain, so remove it from its scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002184 while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002185 S = S->getParent();
2186
2187 if (S)
Chris Lattner83f095c2009-03-28 19:18:32 +00002188 S->RemoveDecl(DeclPtrTy::make(PrevDecl));
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002189 }
2190}
2191
Eli Friedman574c7452009-04-07 19:37:57 +00002192/// \brief Diagnose function specifiers on a declaration of an identifier that
2193/// does not identify a function.
2194void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
2195 // FIXME: We should probably indicate the identifier in question to avoid
2196 // confusion for constructs like "inline int a(), b;"
2197 if (D.getDeclSpec().isInlineSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00002198 Diag(D.getDeclSpec().getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00002199 diag::err_inline_non_function);
2200
2201 if (D.getDeclSpec().isVirtualSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00002202 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00002203 diag::err_virtual_non_function);
2204
2205 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00002206 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00002207 diag::err_explicit_non_function);
2208}
2209
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002210NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002211Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCallbcd03502009-12-07 02:54:59 +00002212 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00002213 LookupResult &Previous, bool &Redeclaration) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002214 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2215 if (D.getCXXScopeSpec().isSet()) {
2216 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2217 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002218 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002219 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00002220 DC = CurContext;
2221 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002222 }
2223
Douglas Gregor0c880302009-03-11 23:00:04 +00002224 if (getLangOptions().CPlusPlus) {
2225 // Check that there are no default arguments (C++ only).
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002226 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00002227 }
2228
Eli Friedman574c7452009-04-07 19:37:57 +00002229 DiagnoseFunctionSpecifiers(D);
2230
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002231 if (D.getDeclSpec().isThreadSpecified())
2232 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2233
John McCallbcd03502009-12-07 02:54:59 +00002234 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002235 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002236
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002237 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00002238 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00002239
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002240 // Merge the decl with the existing one if appropriate. If the decl is
2241 // in an outer scope, it isn't the same thing.
John McCall1f82f242009-11-18 22:49:29 +00002242 FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false);
2243 if (!Previous.empty()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002244 Redeclaration = true;
John McCall1f82f242009-11-18 22:49:29 +00002245 MergeTypeDefDecl(NewTD, Previous);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002246 }
2247
Chris Lattner9fecd742009-04-19 05:21:20 +00002248 // C99 6.7.7p2: If a typedef name specifies a variably modified type
2249 // then it shall have block scope.
2250 QualType T = NewTD->getUnderlyingType();
2251 if (T->isVariablyModifiedType()) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00002252 FunctionNeedsScopeChecking() = true;
Mike Stump11289f42009-09-09 15:08:12 +00002253
Chris Lattner9fecd742009-04-19 05:21:20 +00002254 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00002255 bool SizeIsNegative;
2256 QualType FixedTy =
2257 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2258 if (!FixedTy.isNull()) {
2259 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
John McCallbcd03502009-12-07 02:54:59 +00002260 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
Eli Friedmana3b1d032009-02-21 00:44:51 +00002261 } else {
2262 if (SizeIsNegative)
2263 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2264 else if (T->isVariableArrayType())
2265 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
2266 else
2267 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002268 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00002269 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002270 }
2271 }
Douglas Gregor27821ce2009-07-07 16:35:42 +00002272
2273 // If this is the C FILE type, notify the AST context.
2274 if (IdentifierInfo *II = NewTD->getIdentifier())
2275 if (!NewTD->isInvalidDecl() &&
Mike Stumpa4de80b2009-07-28 02:25:19 +00002276 NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
2277 if (II->isStr("FILE"))
2278 Context.setFILEDecl(NewTD);
2279 else if (II->isStr("jmp_buf"))
2280 Context.setjmp_bufDecl(NewTD);
2281 else if (II->isStr("sigjmp_buf"))
2282 Context.setsigjmp_bufDecl(NewTD);
2283 }
2284
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002285 return NewTD;
2286}
2287
Douglas Gregor5d68a202009-02-24 19:23:27 +00002288/// \brief Determines whether the given declaration is an out-of-scope
2289/// previous declaration.
2290///
2291/// This routine should be invoked when name lookup has found a
2292/// previous declaration (PrevDecl) that is not in the scope where a
2293/// new declaration by the same name is being introduced. If the new
2294/// declaration occurs in a local scope, previous declarations with
2295/// linkage may still be considered previous declarations (C99
2296/// 6.2.2p4-5, C++ [basic.link]p6).
2297///
2298/// \param PrevDecl the previous declaration found by name
2299/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00002300///
Douglas Gregor5d68a202009-02-24 19:23:27 +00002301/// \param DC the context in which the new declaration is being
2302/// declared.
2303///
2304/// \returns true if PrevDecl is an out-of-scope previous declaration
2305/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00002306static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00002307isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2308 ASTContext &Context) {
2309 if (!PrevDecl)
2310 return 0;
2311
Douglas Gregoreddf4332009-02-24 20:03:32 +00002312 if (!PrevDecl->hasLinkage())
2313 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00002314
2315 if (Context.getLangOptions().CPlusPlus) {
2316 // C++ [basic.link]p6:
2317 // If there is a visible declaration of an entity with linkage
2318 // having the same name and type, ignoring entities declared
2319 // outside the innermost enclosing namespace scope, the block
2320 // scope declaration declares that same entity and receives the
2321 // linkage of the previous declaration.
2322 DeclContext *OuterContext = DC->getLookupContext();
2323 if (!OuterContext->isFunctionOrMethod())
2324 // This rule only applies to block-scope declarations.
2325 return false;
2326 else {
2327 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2328 if (PrevOuterContext->isRecord())
2329 // We found a member function: ignore it.
2330 return false;
2331 else {
2332 // Find the innermost enclosing namespace for the new and
2333 // previous declarations.
2334 while (!OuterContext->isFileContext())
2335 OuterContext = OuterContext->getParent();
2336 while (!PrevOuterContext->isFileContext())
2337 PrevOuterContext = PrevOuterContext->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002338
Douglas Gregor5d68a202009-02-24 19:23:27 +00002339 // The previous declaration is in a different namespace, so it
2340 // isn't the same function.
Mike Stump11289f42009-09-09 15:08:12 +00002341 if (OuterContext->getPrimaryContext() !=
Douglas Gregor5d68a202009-02-24 19:23:27 +00002342 PrevOuterContext->getPrimaryContext())
2343 return false;
2344 }
2345 }
2346 }
2347
Douglas Gregor5d68a202009-02-24 19:23:27 +00002348 return true;
2349}
2350
John McCall3e11ebe2010-03-15 10:12:16 +00002351static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
2352 CXXScopeSpec &SS = D.getCXXScopeSpec();
2353 if (!SS.isSet()) return;
2354 DD->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2355 SS.getRange());
2356}
2357
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002358NamedDecl*
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002359Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCallbcd03502009-12-07 02:54:59 +00002360 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00002361 LookupResult &Previous,
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002362 MultiTemplateParamsArg TemplateParamLists,
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002363 bool &Redeclaration) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002364 DeclarationName Name = GetNameForDeclarator(D);
2365
2366 // Check that there are no default arguments (C++ only).
2367 if (getLangOptions().CPlusPlus)
2368 CheckExtraCXXDefaultArguments(D);
2369
Douglas Gregorc4df4072010-04-19 22:54:31 +00002370 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
2371 assert(SCSpec != DeclSpec::SCS_typedef &&
2372 "Parser allowed 'typedef' as storage class VarDecl.");
2373 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
2374 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002375 // mutable can only appear on non-static class members, so it's always
2376 // an error here
2377 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002378 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002379 SC = VarDecl::None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002380 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00002381 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
2382 VarDecl::StorageClass SCAsWritten
2383 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002384
2385 IdentifierInfo *II = Name.getAsIdentifierInfo();
2386 if (!II) {
2387 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2388 << Name.getAsString();
2389 return 0;
2390 }
2391
Eli Friedman574c7452009-04-07 19:37:57 +00002392 DiagnoseFunctionSpecifiers(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00002393
Douglas Gregor212cab32009-03-11 20:22:50 +00002394 if (!DC->isRecord() && S->getFnParent() == 0) {
2395 // C99 6.9p2: The storage-class specifiers auto and register shall not
2396 // appear in the declaration specifiers in an external declaration.
2397 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Mike Stump11289f42009-09-09 15:08:12 +00002398
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00002399 // If this is a register variable with an asm label specified, then this
2400 // is a GNU extension.
2401 if (SC == VarDecl::Register && D.getAsmLabel())
2402 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2403 else
2404 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002405 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002406 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002407 }
Douglas Gregor04e9a032009-03-11 23:52:16 +00002408 if (DC->isRecord() && !CurContext->isRecord()) {
2409 // This is an out-of-line definition of a static data member.
2410 if (SC == VarDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00002411 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor04e9a032009-03-11 23:52:16 +00002412 diag::err_static_out_of_line)
Douglas Gregora771f462010-03-31 17:46:05 +00002413 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor04e9a032009-03-11 23:52:16 +00002414 } else if (SC == VarDecl::None)
2415 SC = VarDecl::Static;
2416 }
Anders Carlssond2e8adf2009-06-24 00:28:53 +00002417 if (SC == VarDecl::Static) {
2418 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2419 if (RD->isLocalClass())
Mike Stump11289f42009-09-09 15:08:12 +00002420 Diag(D.getIdentifierLoc(),
Anders Carlssond2e8adf2009-06-24 00:28:53 +00002421 diag::err_static_data_member_not_allowed_in_local_class)
2422 << Name << RD->getDeclName();
2423 }
2424 }
Mike Stump11289f42009-09-09 15:08:12 +00002425
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002426 // Match up the template parameter lists with the scope specifier, then
2427 // determine whether we have a template or a template specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002428 bool isExplicitSpecialization = false;
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002429 if (TemplateParameterList *TemplateParams
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002430 = MatchTemplateParametersToScopeSpecifier(
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002431 D.getDeclSpec().getSourceRange().getBegin(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002432 D.getCXXScopeSpec(),
Douglas Gregor1a7ba622009-07-22 22:05:02 +00002433 (TemplateParameterList**)TemplateParamLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002434 TemplateParamLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00002435 /*never a friend*/ false,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002436 isExplicitSpecialization)) {
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002437 if (TemplateParams->size() > 0) {
2438 // There is no such thing as a variable template.
2439 Diag(D.getIdentifierLoc(), diag::err_template_variable)
2440 << II
2441 << SourceRange(TemplateParams->getTemplateLoc(),
2442 TemplateParams->getRAngleLoc());
2443 return 0;
2444 } else {
2445 // There is an extraneous 'template<>' for this variable. Complain
2446 // about it, but allow the declaration of the variable.
Mike Stump11289f42009-09-09 15:08:12 +00002447 Diag(TemplateParams->getTemplateLoc(),
Douglas Gregore93e46c2009-07-22 23:48:44 +00002448 diag::err_template_variable_noparams)
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002449 << II
2450 << SourceRange(TemplateParams->getTemplateLoc(),
Mike Stump11289f42009-09-09 15:08:12 +00002451 TemplateParams->getRAngleLoc());
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002452
2453 isExplicitSpecialization = true;
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002454 }
Mike Stump11289f42009-09-09 15:08:12 +00002455 }
2456
Douglas Gregorc4df4072010-04-19 22:54:31 +00002457 VarDecl *NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2458 II, R, TInfo, SC, SCAsWritten);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002459
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002460 if (D.isInvalidType())
2461 NewVD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002462
John McCall3e11ebe2010-03-15 10:12:16 +00002463 SetNestedNameSpecifier(NewVD, D);
2464
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002465 if (D.getDeclSpec().isThreadSpecified()) {
2466 if (NewVD->hasLocalStorage())
2467 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
Eli Friedmandaea3f62009-04-19 21:48:33 +00002468 else if (!Context.Target.isTLSSupported())
2469 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002470 else
2471 NewVD->setThreadSpecified(true);
2472 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002473
Douglas Gregor04e9a032009-03-11 23:52:16 +00002474 // Set the lexical context. If the declarator has a C++ scope specifier, the
2475 // lexical context will be different from the semantic context.
2476 NewVD->setLexicalDeclContext(CurContext);
2477
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002478 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00002479 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002480
2481 // Handle GNU asm-label extension (encoded as an attribute).
2482 if (Expr *E = (Expr*) D.getAsmLabel()) {
2483 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00002484 StringLiteral *SE = cast<StringLiteral>(E);
Ted Kremenek7f4945a2010-02-11 05:28:37 +00002485 NewVD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString()));
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002486 }
2487
John McCalla2a3f7d2010-03-16 21:48:18 +00002488 // Diagnose shadowed variables before filtering for scope.
John McCall2d8c7602010-03-20 04:12:52 +00002489 if (!D.getCXXScopeSpec().isSet())
John McCalldf8b37c2010-03-22 09:20:08 +00002490 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00002491
John McCall1f82f242009-11-18 22:49:29 +00002492 // Don't consider existing declarations that are in a different
2493 // scope and are out-of-semantic-context declarations (if the new
2494 // declaration has linkage).
2495 FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage());
Douglas Gregor86d142a2009-10-08 07:24:58 +00002496
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002497 // Merge the decl with the existing one if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00002498 if (!Previous.empty()) {
2499 if (Previous.isSingleResult() &&
2500 isa<FieldDecl>(Previous.getFoundDecl()) &&
2501 D.getCXXScopeSpec().isSet()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002502 // The user tried to define a non-static data member
2503 // out-of-line (C++ [dcl.meaning]p1).
2504 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
2505 << D.getCXXScopeSpec().getRange();
John McCall1f82f242009-11-18 22:49:29 +00002506 Previous.clear();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002507 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002508 }
2509 } else if (D.getCXXScopeSpec().isSet()) {
2510 // No previous declaration in the qualifying scope.
Douglas Gregore40876a2009-10-13 21:16:44 +00002511 Diag(D.getIdentifierLoc(), diag::err_no_member)
2512 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
2513 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002514 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002515 }
2516
John McCall1f82f242009-11-18 22:49:29 +00002517 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002518
Douglas Gregor86d142a2009-10-08 07:24:58 +00002519 // This is an explicit specialization of a static data member. Check it.
2520 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
John McCall1f82f242009-11-18 22:49:29 +00002521 CheckMemberSpecialization(NewVD, Previous))
Douglas Gregor86d142a2009-10-08 07:24:58 +00002522 NewVD->setInvalidDecl();
John McCall1f82f242009-11-18 22:49:29 +00002523
Ryan Flynne5dc8592009-07-25 22:29:44 +00002524 // attributes declared post-definition are currently ignored
John McCall1f82f242009-11-18 22:49:29 +00002525 if (Previous.isSingleResult()) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00002526 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
2527 if (Def && (Def = Def->getDefinition()) &&
2528 Def != NewVD && D.hasAttributes()) {
Ryan Flynne5dc8592009-07-25 22:29:44 +00002529 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
2530 Diag(Def->getLocation(), diag::note_previous_definition);
2531 }
2532 }
2533
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002534 // If this is a locally-scoped extern C variable, update the map of
2535 // such variables.
Douglas Gregor16618f22009-09-12 00:17:51 +00002536 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002537 !NewVD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00002538 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002539
2540 return NewVD;
2541}
2542
John McCalldf8b37c2010-03-22 09:20:08 +00002543/// \brief Diagnose variable or built-in function shadowing. Implements
2544/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00002545///
John McCalldf8b37c2010-03-22 09:20:08 +00002546/// This method is called whenever a VarDecl is added to a "useful"
2547/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00002548///
John McCall2d8c7602010-03-20 04:12:52 +00002549/// \param S the scope in which the shadowing name is being declared
2550/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00002551///
John McCalldf8b37c2010-03-22 09:20:08 +00002552void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00002553 // Return if warning is ignored.
2554 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow) == Diagnostic::Ignored)
2555 return;
2556
John McCall2d8c7602010-03-20 04:12:52 +00002557 // Don't diagnose declarations at file scope. The scope might not
2558 // have a DeclContext if (e.g.) we're parsing a function prototype.
2559 DeclContext *NewDC = static_cast<DeclContext*>(S->getEntity());
2560 if (NewDC && NewDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00002561 return;
John McCall2d8c7602010-03-20 04:12:52 +00002562
2563 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00002564 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00002565 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00002566
John McCalla2a3f7d2010-03-16 21:48:18 +00002567 NamedDecl* ShadowedDecl = R.getFoundDecl();
2568 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
2569 return;
2570
John McCall2d8c7602010-03-20 04:12:52 +00002571 DeclContext *OldDC = ShadowedDecl->getDeclContext();
2572
2573 // Only warn about certain kinds of shadowing for class members.
2574 if (NewDC && NewDC->isRecord()) {
2575 // In particular, don't warn about shadowing non-class members.
2576 if (!OldDC->isRecord())
2577 return;
2578
2579 // TODO: should we warn about static data members shadowing
2580 // static data members from base classes?
2581
2582 // TODO: don't diagnose for inaccessible shadowed members.
2583 // This is hard to do perfectly because we might friend the
2584 // shadowing context, but that's just a false negative.
2585 }
2586
2587 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00002588 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00002589 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00002590 if (isa<FieldDecl>(ShadowedDecl))
2591 Kind = 3; // field
2592 else
2593 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00002594 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00002595 Kind = 1; // global
2596 else
2597 Kind = 0; // local
2598
John McCall2d8c7602010-03-20 04:12:52 +00002599 DeclarationName Name = R.getLookupName();
2600
John McCalla2a3f7d2010-03-16 21:48:18 +00002601 // Emit warning and note.
John McCall2d8c7602010-03-20 04:12:52 +00002602 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00002603 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
2604}
2605
John McCalldf8b37c2010-03-22 09:20:08 +00002606/// \brief Check -Wshadow without the advantage of a previous lookup.
2607void Sema::CheckShadow(Scope *S, VarDecl *D) {
2608 LookupResult R(*this, D->getDeclName(), D->getLocation(),
2609 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
2610 LookupName(R, S);
2611 CheckShadow(S, D, R);
2612}
2613
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002614/// \brief Perform semantic checking on a newly-created variable
2615/// declaration.
2616///
2617/// This routine performs all of the type-checking required for a
Douglas Gregorf16a8a72009-05-01 15:47:09 +00002618/// variable declaration once it has been built. It is used both to
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002619/// check variables after they have been parsed and their declarators
Douglas Gregorf16a8a72009-05-01 15:47:09 +00002620/// have been translated into a declaration, and to check variables
2621/// that have been instantiated from a template.
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002622///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002623/// Sets NewVD->isInvalidDecl() if an error was encountered.
John McCall1f82f242009-11-18 22:49:29 +00002624void Sema::CheckVariableDeclaration(VarDecl *NewVD,
2625 LookupResult &Previous,
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002626 bool &Redeclaration) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002627 // If the decl is already known invalid, don't check it.
2628 if (NewVD->isInvalidDecl())
2629 return;
Mike Stump11289f42009-09-09 15:08:12 +00002630
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002631 QualType T = NewVD->getType();
2632
2633 if (T->isObjCInterfaceType()) {
2634 Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002635 return NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002636 }
Mike Stump11289f42009-09-09 15:08:12 +00002637
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002638 // Emit an error if an address space was applied to decl with local storage.
2639 // This includes arrays of objects with address space qualifiers, but not
2640 // automatic variables that point to other address spaces.
2641 // ISO/IEC TR 18037 S5.1.2
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002642 if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
2643 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002644 return NewVD->setInvalidDecl();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002645 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00002646
Mike Stumpca5ae662009-04-14 00:57:29 +00002647 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002648 && !NewVD->hasAttr<BlocksAttr>())
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002649 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00002650
Chris Lattner9fecd742009-04-19 05:21:20 +00002651 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00002652 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
Chris Lattner30d0cfd2010-03-01 20:59:53 +00002653 NewVD->hasAttr<BlocksAttr>() ||
2654 // FIXME: We need to diagnose jumps passed initialized variables in C++.
2655 // However, this turns on the scope checker for everything with a variable
2656 // which may impact compile time. See if we can find a better solution
2657 // to this, perhaps only checking functions that contain gotos in C++?
2658 (LangOpts.CPlusPlus && NewVD->hasLocalStorage()))
Douglas Gregor9a28e842010-03-01 23:15:13 +00002659 FunctionNeedsScopeChecking() = true;
Mike Stump11289f42009-09-09 15:08:12 +00002660
Chris Lattner9fecd742009-04-19 05:21:20 +00002661 if ((isVM && NewVD->hasLinkage()) ||
2662 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00002663 bool SizeIsNegative;
2664 QualType FixedTy =
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002665 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
Mike Stump11289f42009-09-09 15:08:12 +00002666
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002667 if (FixedTy.isNull() && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002668 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002669 // FIXME: This won't give the correct result for
2670 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00002671 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002672
Anders Carlsson6c885802009-02-28 21:56:50 +00002673 if (NewVD->isFileVarDecl())
2674 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002675 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00002676 else if (NewVD->getStorageClass() == VarDecl::Static)
2677 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002678 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00002679 else
2680 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002681 << SizeRange;
2682 return NewVD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002683 }
2684
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002685 if (FixedTy.isNull()) {
Anders Carlsson6c885802009-02-28 21:56:50 +00002686 if (NewVD->isFileVarDecl())
2687 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
2688 else
2689 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002690 return NewVD->setInvalidDecl();
Anders Carlsson6c885802009-02-28 21:56:50 +00002691 }
Mike Stump11289f42009-09-09 15:08:12 +00002692
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002693 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
2694 NewVD->setType(FixedTy);
Anders Carlsson6c885802009-02-28 21:56:50 +00002695 }
2696
John McCall1f82f242009-11-18 22:49:29 +00002697 if (Previous.empty() && NewVD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002698 // Since we did not find anything by this name and we're declaring
2699 // an extern "C" variable, look for a non-visible extern "C"
2700 // declaration with the same name.
2701 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002702 = LocallyScopedExternalDecls.find(NewVD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002703 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00002704 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002705 }
2706
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002707 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002708 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
2709 << T;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002710 return NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00002711 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002712
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002713 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00002714 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
2715 return NewVD->setInvalidDecl();
2716 }
Mike Stump11289f42009-09-09 15:08:12 +00002717
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002718 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpa7128632009-05-01 23:41:47 +00002719 Diag(NewVD->getLocation(), diag::err_block_on_vm);
2720 return NewVD->setInvalidDecl();
2721 }
2722
John McCall1f82f242009-11-18 22:49:29 +00002723 if (!Previous.empty()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002724 Redeclaration = true;
John McCall1f82f242009-11-18 22:49:29 +00002725 MergeVarDecl(NewVD, Previous);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002726 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002727}
2728
Douglas Gregor36d1b142009-10-06 17:59:45 +00002729/// \brief Data used with FindOverriddenMethod
2730struct FindOverriddenMethodData {
2731 Sema *S;
2732 CXXMethodDecl *Method;
2733};
2734
2735/// \brief Member lookup function that determines whether a given C++
2736/// method overrides a method in a base class, to be used with
2737/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00002738static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002739 CXXBasePath &Path,
2740 void *UserData) {
2741 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00002742
Douglas Gregor36d1b142009-10-06 17:59:45 +00002743 FindOverriddenMethodData *Data
2744 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00002745
2746 DeclarationName Name = Data->Method->getDeclName();
2747
2748 // FIXME: Do we care about other names here too?
2749 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2750 // We really want to find the base class constructor here.
2751 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
2752 CanQualType CT = Data->S->Context.getCanonicalType(T);
2753
Anders Carlsson5a4f7722009-11-27 01:26:58 +00002754 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00002755 }
2756
2757 for (Path.Decls = BaseRecord->lookup(Name);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002758 Path.Decls.first != Path.Decls.second;
2759 ++Path.Decls.first) {
2760 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*Path.Decls.first)) {
John McCall1f82f242009-11-18 22:49:29 +00002761 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD))
Douglas Gregor36d1b142009-10-06 17:59:45 +00002762 return true;
2763 }
2764 }
2765
2766 return false;
2767}
2768
Sebastian Redld5b24532009-11-18 21:51:29 +00002769/// AddOverriddenMethods - See if a method overrides any in the base classes,
2770/// and if so, check that it's a valid override and remember it.
2771void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2772 // Look for virtual methods in base classes that this method might override.
2773 CXXBasePaths Paths;
2774 FindOverriddenMethodData Data;
2775 Data.Method = MD;
2776 Data.S = this;
2777 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
2778 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
2779 E = Paths.found_decls_end(); I != E; ++I) {
2780 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
2781 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Alexis Hunt96d5c762009-11-21 08:43:09 +00002782 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
2783 !CheckOverridingFunctionAttributes(MD, OldMD))
Anders Carlssonf3935b42009-12-04 05:51:56 +00002784 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00002785 }
2786 }
2787 }
2788}
2789
Mike Stump11289f42009-09-09 15:08:12 +00002790NamedDecl*
Zhongxing Xubece5d62009-01-16 01:13:29 +00002791Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCallbcd03502009-12-07 02:54:59 +00002792 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00002793 LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002794 MultiTemplateParamsArg TemplateParamLists,
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002795 bool IsFunctionDefinition, bool &Redeclaration) {
Zhongxing Xubece5d62009-01-16 01:13:29 +00002796 assert(R.getTypePtr()->isFunctionType());
2797
2798 DeclarationName Name = GetNameForDeclarator(D);
2799 FunctionDecl::StorageClass SC = FunctionDecl::None;
2800 switch (D.getDeclSpec().getStorageClassSpec()) {
2801 default: assert(0 && "Unknown storage class!");
2802 case DeclSpec::SCS_auto:
2803 case DeclSpec::SCS_register:
2804 case DeclSpec::SCS_mutable:
Mike Stump11289f42009-09-09 15:08:12 +00002805 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregore62c0a42009-02-24 01:23:02 +00002806 diag::err_typecheck_sclass_func);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002807 D.setInvalidType();
Zhongxing Xubece5d62009-01-16 01:13:29 +00002808 break;
2809 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
2810 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
Douglas Gregore62c0a42009-02-24 01:23:02 +00002811 case DeclSpec::SCS_static: {
Douglas Gregor04e9a032009-03-11 23:52:16 +00002812 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002813 // C99 6.7.1p5:
2814 // The declaration of an identifier for a function that has
2815 // block scope shall have no explicit storage-class specifier
2816 // other than extern
2817 // See also (C++ [dcl.stc]p4).
Mike Stump11289f42009-09-09 15:08:12 +00002818 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregore62c0a42009-02-24 01:23:02 +00002819 diag::err_static_block_func);
2820 SC = FunctionDecl::None;
2821 } else
Mike Stump11289f42009-09-09 15:08:12 +00002822 SC = FunctionDecl::Static;
Douglas Gregore62c0a42009-02-24 01:23:02 +00002823 break;
2824 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00002825 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
2826 }
2827
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002828 if (D.getDeclSpec().isThreadSpecified())
2829 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2830
John McCalld1e9d832009-08-11 06:59:38 +00002831 bool isFriend = D.getDeclSpec().isFriendSpecified();
Zhongxing Xubece5d62009-01-16 01:13:29 +00002832 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor0c880302009-03-11 23:00:04 +00002833 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Zhongxing Xubece5d62009-01-16 01:13:29 +00002834 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
2835
Douglas Gregorc4df4072010-04-19 22:54:31 +00002836 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
2837 FunctionDecl::StorageClass SCAsWritten
2838 = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
2839
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002840 // Check that the return type is not an abstract class type.
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002841 // For record types, this is done by the AbstractClassUsageDiagnoser once
Mike Stump11289f42009-09-09 15:08:12 +00002842 // the class has been completely parsed.
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002843 if (!DC->isRecord() &&
Mike Stump11289f42009-09-09 15:08:12 +00002844 RequireNonAbstractType(D.getIdentifierLoc(),
John McCall9dd450b2009-09-21 23:43:11 +00002845 R->getAs<FunctionType>()->getResultType(),
Mike Stump11289f42009-09-09 15:08:12 +00002846 diag::err_abstract_type_in_decl,
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002847 AbstractReturnType))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002848 D.setInvalidType();
Mike Stump11289f42009-09-09 15:08:12 +00002849
Chris Lattner347eec92009-04-11 19:17:25 +00002850 // Do not allow returning a objc interface by-value.
John McCall9dd450b2009-09-21 23:43:11 +00002851 if (R->getAs<FunctionType>()->getResultType()->isObjCInterfaceType()) {
Chris Lattner347eec92009-04-11 19:17:25 +00002852 Diag(D.getIdentifierLoc(),
2853 diag::err_object_cannot_be_passed_returned_by_value) << 0
John McCall9dd450b2009-09-21 23:43:11 +00002854 << R->getAs<FunctionType>()->getResultType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002855 D.setInvalidType();
Chris Lattner347eec92009-04-11 19:17:25 +00002856 }
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002857
Douglas Gregor0c880302009-03-11 23:00:04 +00002858 bool isVirtualOkay = false;
Zhongxing Xubece5d62009-01-16 01:13:29 +00002859 FunctionDecl *NewFD;
John McCallaa74a0c2009-08-28 07:59:38 +00002860
John McCalld1e9d832009-08-11 06:59:38 +00002861 if (isFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002862 // C++ [class.friend]p5
2863 // A function can be defined in a friend declaration of a
2864 // class . . . . Such a function is implicitly inline.
2865 isInline |= IsFunctionDefinition;
John McCallaa74a0c2009-08-28 07:59:38 +00002866 }
John McCalld1e9d832009-08-11 06:59:38 +00002867
Douglas Gregor7861a802009-11-03 01:35:08 +00002868 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
Zhongxing Xubece5d62009-01-16 01:13:29 +00002869 // This is a C++ constructor declaration.
2870 assert(DC->isRecord() &&
2871 "Constructors can only be declared in a member context");
2872
Chris Lattner38378bf2009-04-25 08:28:21 +00002873 R = CheckConstructorDeclarator(D, R, SC);
Zhongxing Xubece5d62009-01-16 01:13:29 +00002874
2875 // Create the new declaration
Mike Stump11289f42009-09-09 15:08:12 +00002876 NewFD = CXXConstructorDecl::Create(Context,
Zhongxing Xubece5d62009-01-16 01:13:29 +00002877 cast<CXXRecordDecl>(DC),
John McCallbcd03502009-12-07 02:54:59 +00002878 D.getIdentifierLoc(), Name, R, TInfo,
Zhongxing Xubece5d62009-01-16 01:13:29 +00002879 isExplicit, isInline,
2880 /*isImplicitlyDeclared=*/false);
Douglas Gregor7861a802009-11-03 01:35:08 +00002881 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
Zhongxing Xubece5d62009-01-16 01:13:29 +00002882 // This is a C++ destructor declaration.
2883 if (DC->isRecord()) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002884 R = CheckDestructorDeclarator(D, SC);
Mike Stump11289f42009-09-09 15:08:12 +00002885
Zhongxing Xubece5d62009-01-16 01:13:29 +00002886 NewFD = CXXDestructorDecl::Create(Context,
2887 cast<CXXRecordDecl>(DC),
Mike Stump11289f42009-09-09 15:08:12 +00002888 D.getIdentifierLoc(), Name, R,
Zhongxing Xubece5d62009-01-16 01:13:29 +00002889 isInline,
2890 /*isImplicitlyDeclared=*/false);
John McCall58f10c32010-03-11 09:03:00 +00002891 NewFD->setTypeSourceInfo(TInfo);
Zhongxing Xubece5d62009-01-16 01:13:29 +00002892
Douglas Gregor0c880302009-03-11 23:00:04 +00002893 isVirtualOkay = true;
Zhongxing Xubece5d62009-01-16 01:13:29 +00002894 } else {
2895 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
2896
2897 // Create a FunctionDecl to satisfy the function definition parsing
2898 // code path.
2899 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002900 Name, R, TInfo, SC, SCAsWritten, isInline,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00002901 /*hasPrototype=*/true);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002902 D.setInvalidType();
Zhongxing Xubece5d62009-01-16 01:13:29 +00002903 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002904 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
Zhongxing Xubece5d62009-01-16 01:13:29 +00002905 if (!DC->isRecord()) {
2906 Diag(D.getIdentifierLoc(),
2907 diag::err_conv_function_not_member);
2908 return 0;
Zhongxing Xubece5d62009-01-16 01:13:29 +00002909 }
Mike Stump11289f42009-09-09 15:08:12 +00002910
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002911 CheckConversionDeclarator(D, R, SC);
2912 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
John McCallbcd03502009-12-07 02:54:59 +00002913 D.getIdentifierLoc(), Name, R, TInfo,
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002914 isInline, isExplicit);
Mike Stump11289f42009-09-09 15:08:12 +00002915
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002916 isVirtualOkay = true;
Zhongxing Xubece5d62009-01-16 01:13:29 +00002917 } else if (DC->isRecord()) {
Anders Carlssona0886932009-04-30 22:41:11 +00002918 // If the of the function is the same as the name of the record, then this
Mike Stump11289f42009-09-09 15:08:12 +00002919 // must be an invalid constructor that has a return type.
2920 // (The parser checks for a return type and makes the declarator a
Anders Carlssona0886932009-04-30 22:41:11 +00002921 // constructor if it has no return type).
Mike Stump11289f42009-09-09 15:08:12 +00002922 // must have an invalid constructor that has a return type
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00002923 if (Name.getAsIdentifierInfo() &&
2924 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
Anders Carlssona0886932009-04-30 22:41:11 +00002925 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
2926 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2927 << SourceRange(D.getIdentifierLoc());
2928 return 0;
2929 }
Mike Stump11289f42009-09-09 15:08:12 +00002930
Anders Carlsson623e9792009-11-15 18:59:32 +00002931 bool isStatic = SC == FunctionDecl::Static;
2932
2933 // [class.free]p1:
2934 // Any allocation function for a class T is a static member
2935 // (even if not explicitly declared static).
2936 if (Name.getCXXOverloadedOperator() == OO_New ||
2937 Name.getCXXOverloadedOperator() == OO_Array_New)
2938 isStatic = true;
Anders Carlsson7ade2032009-11-15 19:08:46 +00002939
2940 // [class.free]p6 Any deallocation function for a class X is a static member
2941 // (even if not explicitly declared static).
2942 if (Name.getCXXOverloadedOperator() == OO_Delete ||
2943 Name.getCXXOverloadedOperator() == OO_Array_Delete)
2944 isStatic = true;
Anders Carlsson623e9792009-11-15 18:59:32 +00002945
Zhongxing Xubece5d62009-01-16 01:13:29 +00002946 // This is a C++ method declaration.
2947 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
John McCallbcd03502009-12-07 02:54:59 +00002948 D.getIdentifierLoc(), Name, R, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002949 isStatic, SCAsWritten, isInline);
Douglas Gregor0c880302009-03-11 23:00:04 +00002950
Anders Carlsson7ade2032009-11-15 19:08:46 +00002951 isVirtualOkay = !isStatic;
Zhongxing Xubece5d62009-01-16 01:13:29 +00002952 } else {
Douglas Gregor2797d322009-03-19 18:33:54 +00002953 // Determine whether the function was written with a
2954 // prototype. This true when:
2955 // - we're in C++ (where every function has a prototype),
2956 // - there is a prototype in the declarator, or
2957 // - the type R of the function is some kind of typedef or other reference
2958 // to a type name (which eventually refers to a function type).
Mike Stump11289f42009-09-09 15:08:12 +00002959 bool HasPrototype =
Chris Lattner441914e2009-03-17 23:17:04 +00002960 getLangOptions().CPlusPlus ||
Douglas Gregor3729f242009-03-19 18:14:46 +00002961 (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
Douglas Gregord6b05f72009-03-23 16:26:51 +00002962 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
Mike Stump11289f42009-09-09 15:08:12 +00002963
Zhongxing Xubece5d62009-01-16 01:13:29 +00002964 NewFD = FunctionDecl::Create(Context, DC,
2965 D.getIdentifierLoc(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002966 Name, R, TInfo, SC, SCAsWritten, isInline,
2967 HasPrototype);
Zhongxing Xubece5d62009-01-16 01:13:29 +00002968 }
2969
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002970 if (D.isInvalidType())
Chris Lattner3f863f62009-04-25 05:44:12 +00002971 NewFD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002972
John McCall3e11ebe2010-03-15 10:12:16 +00002973 SetNestedNameSpecifier(NewFD, D);
2974
Zhongxing Xubece5d62009-01-16 01:13:29 +00002975 // Set the lexical context. If the declarator has a C++
John McCallaa74a0c2009-08-28 07:59:38 +00002976 // scope specifier, or is the object of a friend declaration, the
2977 // lexical context will be different from the semantic context.
Zhongxing Xubece5d62009-01-16 01:13:29 +00002978 NewFD->setLexicalDeclContext(CurContext);
2979
Douglas Gregord8d297c2009-07-21 23:53:31 +00002980 // Match up the template parameter lists with the scope specifier, then
2981 // determine whether we have a template or a template specialization.
Douglas Gregorc1da0f02009-06-24 00:23:40 +00002982 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002983 bool isExplicitSpecialization = false;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002984 bool isFunctionTemplateSpecialization = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002985 if (TemplateParameterList *TemplateParams
2986 = MatchTemplateParametersToScopeSpecifier(
2987 D.getDeclSpec().getSourceRange().getBegin(),
2988 D.getCXXScopeSpec(),
Douglas Gregor1a7ba622009-07-22 22:05:02 +00002989 (TemplateParameterList**)TemplateParamLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002990 TemplateParamLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00002991 isFriend,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002992 isExplicitSpecialization)) {
Douglas Gregorc1da0f02009-06-24 00:23:40 +00002993 if (TemplateParams->size() > 0) {
2994 // This is a function template
Mike Stump11289f42009-09-09 15:08:12 +00002995
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002996 // Check that we can declare a template here.
2997 if (CheckTemplateDeclScope(S, TemplateParams))
2998 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002999
Douglas Gregore704c9d2009-08-27 16:57:43 +00003000 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
Douglas Gregorc1da0f02009-06-24 00:23:40 +00003001 NewFD->getLocation(),
3002 Name, TemplateParams,
3003 NewFD);
Douglas Gregore704c9d2009-08-27 16:57:43 +00003004 FunctionTemplate->setLexicalDeclContext(CurContext);
Douglas Gregorc1da0f02009-06-24 00:23:40 +00003005 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
3006 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003007 // This is a function template specialization.
3008 isFunctionTemplateSpecialization = true;
John McCall816d75b2010-03-24 07:46:06 +00003009
John McCallb9c78482010-04-08 09:05:18 +00003010 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
John McCall816d75b2010-03-24 07:46:06 +00003011 if (isFriend && isFunctionTemplateSpecialization) {
John McCall1f0479e2010-03-24 08:27:58 +00003012 // We want to remove the "template<>", found here.
3013 SourceRange RemoveRange = TemplateParams->getSourceRange();
3014
3015 // If we remove the template<> and the name is not a
3016 // template-id, we're actually silently creating a problem:
3017 // the friend declaration will refer to an untemplated decl,
3018 // and clearly the user wants a template specialization. So
3019 // we need to insert '<>' after the name.
3020 SourceLocation InsertLoc;
3021 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
3022 InsertLoc = D.getName().getSourceRange().getEnd();
3023 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
3024 }
3025
John McCall816d75b2010-03-24 07:46:06 +00003026 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
John McCall1f0479e2010-03-24 08:27:58 +00003027 << Name << RemoveRange
Douglas Gregora771f462010-03-31 17:46:05 +00003028 << FixItHint::CreateRemoval(RemoveRange)
3029 << FixItHint::CreateInsertion(InsertLoc, "<>");
John McCall816d75b2010-03-24 07:46:06 +00003030 }
Douglas Gregorc1da0f02009-06-24 00:23:40 +00003031 }
Mike Stump11289f42009-09-09 15:08:12 +00003032
Douglas Gregor1a7ba622009-07-22 22:05:02 +00003033 // FIXME: Free this memory properly.
3034 TemplateParamLists.release();
Mike Stump11289f42009-09-09 15:08:12 +00003035 }
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003036
Douglas Gregor0c880302009-03-11 23:00:04 +00003037 // C++ [dcl.fct.spec]p5:
3038 // The virtual specifier shall only be used in declarations of
3039 // nonstatic class member functions that appear within a
3040 // member-specification of a class declaration; see 10.3.
3041 //
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003042 if (isVirtual && !NewFD->isInvalidDecl()) {
Douglas Gregor0c880302009-03-11 23:00:04 +00003043 if (!isVirtualOkay) {
Mike Stump11289f42009-09-09 15:08:12 +00003044 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Douglas Gregor0c880302009-03-11 23:00:04 +00003045 diag::err_virtual_non_function);
3046 } else if (!CurContext->isRecord()) {
3047 // 'virtual' was specified outside of the class.
3048 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
Douglas Gregora771f462010-03-31 17:46:05 +00003049 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
Douglas Gregor0c880302009-03-11 23:00:04 +00003050 } else {
3051 // Okay: Add virtual to the method.
Douglas Gregor0c880302009-03-11 23:00:04 +00003052 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00003053 CurClass->setMethodAsVirtual(NewFD);
Douglas Gregor0c880302009-03-11 23:00:04 +00003054 }
3055 }
3056
Anders Carlsson77babdb2010-01-24 16:49:46 +00003057 // C++ [dcl.fct.spec]p6:
3058 // The explicit specifier shall be used only in the declaration of a
3059 // constructor or conversion function within its class definition; see 12.3.1
3060 // and 12.3.2.
3061 if (isExplicit && !NewFD->isInvalidDecl()) {
3062 if (!CurContext->isRecord()) {
3063 // 'explicit' was specified outside of the class.
3064 Diag(D.getDeclSpec().getExplicitSpecLoc(),
3065 diag::err_explicit_out_of_class)
Douglas Gregora771f462010-03-31 17:46:05 +00003066 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
Anders Carlsson77babdb2010-01-24 16:49:46 +00003067 } else if (!isa<CXXConstructorDecl>(NewFD) &&
3068 !isa<CXXConversionDecl>(NewFD)) {
3069 // 'explicit' was specified on a function that wasn't a constructor
3070 // or conversion function.
3071 Diag(D.getDeclSpec().getExplicitSpecLoc(),
3072 diag::err_explicit_non_ctor_or_conv_function)
Douglas Gregora771f462010-03-31 17:46:05 +00003073 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
Anders Carlsson77babdb2010-01-24 16:49:46 +00003074 }
3075 }
3076
John McCall1f82f242009-11-18 22:49:29 +00003077 // Filter out previous declarations that don't match the scope.
3078 FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
3079
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003080 if (isFriend) {
John McCall1f82f242009-11-18 22:49:29 +00003081 // DC is the namespace in which the function is being declared.
3082 assert((DC->isFileContext() || !Previous.empty()) &&
3083 "previously-undeclared friend function being created "
3084 "in a non-namespace context");
3085
John McCall2f88d7d2010-03-27 05:57:59 +00003086 // For now, claim that the objects have no previous declaration.
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003087 if (FunctionTemplate) {
John McCall2f88d7d2010-03-27 05:57:59 +00003088 FunctionTemplate->setObjectOfFriendDecl(false);
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003089 FunctionTemplate->setAccess(AS_public);
3090 }
John McCalle820e5e2010-04-13 20:37:33 +00003091 NewFD->setObjectOfFriendDecl(false);
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003092 NewFD->setAccess(AS_public);
3093 }
3094
Mike Stump11289f42009-09-09 15:08:12 +00003095 if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00003096 !CurContext->isRecord()) {
3097 // C++ [class.static]p1:
3098 // A data or function member of a class may be declared static
3099 // in a class definition, in which case it is a static member of
3100 // the class.
3101
3102 // Complain about the 'static' specifier if it's on an out-of-line
3103 // member function definition.
Mike Stump11289f42009-09-09 15:08:12 +00003104 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor04e9a032009-03-11 23:52:16 +00003105 diag::err_static_out_of_line)
Douglas Gregora771f462010-03-31 17:46:05 +00003106 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor04e9a032009-03-11 23:52:16 +00003107 }
3108
Zhongxing Xubece5d62009-01-16 01:13:29 +00003109 // Handle GNU asm-label extension (encoded as an attribute).
3110 if (Expr *E = (Expr*) D.getAsmLabel()) {
3111 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00003112 StringLiteral *SE = cast<StringLiteral>(E);
Ted Kremenek7f4945a2010-02-11 05:28:37 +00003113 NewFD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString()));
Zhongxing Xubece5d62009-01-16 01:13:29 +00003114 }
3115
Chris Lattner9af40c12009-04-25 06:12:16 +00003116 // Copy the parameter declarations from the declarator D to the function
3117 // declaration NewFD, if they are available. First scavenge them into Params.
3118 llvm::SmallVector<ParmVarDecl*, 16> Params;
Zhongxing Xubece5d62009-01-16 01:13:29 +00003119 if (D.getNumTypeObjects() > 0) {
3120 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3121
Zhongxing Xubece5d62009-01-16 01:13:29 +00003122 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
3123 // function that takes no arguments, not a function that takes a
3124 // single void argument.
3125 // We let through "const void" here because Sema::GetTypeForDeclarator
3126 // already checks for that case.
3127 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3128 FTI.ArgInfo[0].Param &&
Chris Lattner83f095c2009-03-28 19:18:32 +00003129 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00003130 // Empty arg list, don't push any params.
Chris Lattner83f095c2009-03-28 19:18:32 +00003131 ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
Zhongxing Xubece5d62009-01-16 01:13:29 +00003132
3133 // In C++, the empty parameter-type-list must be spelled "void"; a
3134 // typedef of void is not permitted.
3135 if (getLangOptions().CPlusPlus &&
Chris Lattner3f863f62009-04-25 05:44:12 +00003136 Param->getType().getUnqualifiedType() != Context.VoidTy)
Douglas Gregor170512f2009-04-01 23:51:29 +00003137 Diag(Param->getLocation(), diag::err_param_typedef_of_void);
Chris Lattner9af40c12009-04-25 06:12:16 +00003138 // FIXME: Leaks decl?
Zhongxing Xubece5d62009-01-16 01:13:29 +00003139 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00003140 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
3141 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
3142 assert(Param->getDeclContext() != NewFD && "Was set before ?");
3143 Param->setDeclContext(NewFD);
3144 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00003145
3146 if (Param->isInvalidDecl())
3147 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00003148 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003149 }
Mike Stump11289f42009-09-09 15:08:12 +00003150
John McCall9dd450b2009-09-21 23:43:11 +00003151 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00003152 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00003153 // following example, we'll need to synthesize (unnamed)
3154 // parameters for use in the declaration.
3155 //
3156 // @code
3157 // typedef void fn(int);
3158 // fn f;
3159 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003160
Chris Lattner47c0d002009-04-25 06:03:53 +00003161 // Synthesize a parameter for each argument type.
Chris Lattner47c0d002009-04-25 06:03:53 +00003162 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
3163 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCallf7b2fb52010-01-22 00:28:27 +00003164 ParmVarDecl *Param = ParmVarDecl::Create(Context, NewFD,
Chris Lattner47c0d002009-04-25 06:03:53 +00003165 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003166 *AI, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00003167 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00003168 VarDecl::None, 0);
Chris Lattner47c0d002009-04-25 06:03:53 +00003169 Param->setImplicit();
3170 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00003171 }
Chris Lattner49303b22009-04-25 18:38:18 +00003172 } else {
3173 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
3174 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00003175 }
Chris Lattner9af40c12009-04-25 06:12:16 +00003176 // Finally, we know we have the right number of parameters, install them.
Douglas Gregord5058122010-02-11 01:19:42 +00003177 NewFD->setParams(Params.data(), Params.size());
Mike Stump11289f42009-09-09 15:08:12 +00003178
Douglas Gregor0e876e02009-09-25 23:53:26 +00003179 // If the declarator is a template-id, translate the parser's template
3180 // argument list into our AST format.
3181 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00003182 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00003183 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
3184 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00003185 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
3186 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregor0e876e02009-09-25 23:53:26 +00003187 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3188 TemplateId->getTemplateArgs(),
Douglas Gregor0e876e02009-09-25 23:53:26 +00003189 TemplateId->NumArgs);
3190 translateTemplateArguments(TemplateArgsPtr,
Douglas Gregor0e876e02009-09-25 23:53:26 +00003191 TemplateArgs);
3192 TemplateArgsPtr.release();
3193
3194 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00003195
3196 if (FunctionTemplate) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003197 // FIXME: Diagnose function template with explicit template
Douglas Gregor0e876e02009-09-25 23:53:26 +00003198 // arguments.
3199 HasExplicitTemplateArgs = false;
3200 } else if (!isFunctionTemplateSpecialization &&
3201 !D.getDeclSpec().isFriendSpecified()) {
3202 // We have encountered something that the user meant to be a
3203 // specialization (because it has explicitly-specified template
3204 // arguments) but that was not introduced with a "template<>" (or had
3205 // too few of them).
3206 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
3207 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
Douglas Gregora771f462010-03-31 17:46:05 +00003208 << FixItHint::CreateInsertion(
Douglas Gregor0e876e02009-09-25 23:53:26 +00003209 D.getDeclSpec().getSourceRange().getBegin(),
3210 "template<> ");
3211 isFunctionTemplateSpecialization = true;
John McCall816d75b2010-03-24 07:46:06 +00003212 } else {
3213 // "friend void foo<>(int);" is an implicit specialization decl.
3214 isFunctionTemplateSpecialization = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00003215 }
John McCallb9c78482010-04-08 09:05:18 +00003216 } else if (isFriend && isFunctionTemplateSpecialization) {
3217 // This combination is only possible in a recovery case; the user
3218 // wrote something like:
3219 // template <> friend void foo(int);
3220 // which we're recovering from as if the user had written:
3221 // friend void foo<>(int);
3222 // Go ahead and fake up a template id.
3223 HasExplicitTemplateArgs = true;
3224 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
3225 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregor0e876e02009-09-25 23:53:26 +00003226 }
John McCall1f82f242009-11-18 22:49:29 +00003227
John McCallb9c78482010-04-08 09:05:18 +00003228 // If it's a friend (and only if it's a friend), it's possible
3229 // that either the specialized function type or the specialized
3230 // template is dependent, and therefore matching will fail. In
3231 // this case, don't check the specialization yet.
3232 if (isFunctionTemplateSpecialization && isFriend &&
3233 (NewFD->getType()->isDependentType() || DC->isDependentContext())) {
3234 assert(HasExplicitTemplateArgs &&
3235 "friend function specialization without template args");
3236 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
3237 Previous))
Douglas Gregor8fdd0e82010-03-24 17:31:23 +00003238 NewFD->setInvalidDecl();
John McCallb9c78482010-04-08 09:05:18 +00003239 } else if (isFunctionTemplateSpecialization) {
3240 if (CheckFunctionTemplateSpecialization(NewFD,
3241 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
3242 Previous))
3243 NewFD->setInvalidDecl();
3244 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
3245 if (CheckMemberSpecialization(NewFD, Previous))
3246 NewFD->setInvalidDecl();
3247 }
John McCall84821e72010-04-13 06:39:49 +00003248
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003249 // Perform semantic checking on the function declaration.
3250 bool OverloadableAttrRequired = false; // FIXME: HACK!
John McCall84d87672009-12-10 09:41:52 +00003251 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
Douglas Gregorcf915552009-10-13 16:30:37 +00003252 Redeclaration, /*FIXME:*/OverloadableAttrRequired);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003253
John McCall1f82f242009-11-18 22:49:29 +00003254 assert((NewFD->isInvalidDecl() || !Redeclaration ||
3255 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3256 "previous declaration set still overloaded");
3257
John McCall2f88d7d2010-03-27 05:57:59 +00003258 if (isFriend && Redeclaration) {
John McCall84821e72010-04-13 06:39:49 +00003259 AccessSpecifier Access = AS_public;
3260 if (!NewFD->isInvalidDecl())
3261 Access = NewFD->getPreviousDeclaration()->getAccess();
3262
John McCall2f88d7d2010-03-27 05:57:59 +00003263 if (FunctionTemplate) {
3264 FunctionTemplate->setObjectOfFriendDecl(true);
3265 FunctionTemplate->setAccess(Access);
3266 } else {
3267 NewFD->setObjectOfFriendDecl(true);
3268 }
3269 NewFD->setAccess(Access);
3270 }
3271
Douglas Gregored5731f2009-11-25 17:50:39 +00003272 // If we have a function template, check the template parameter
3273 // list. This will check and merge default template arguments.
3274 if (FunctionTemplate) {
3275 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
3276 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
3277 PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
3278 D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
3279 : TPC_FunctionTemplate);
3280 }
3281
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003282 if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
John McCall401982f2010-01-20 21:53:11 +00003283 // Fake up an access specifier if it's supposed to be a class member.
John McCall67da35c2010-02-04 22:26:26 +00003284 if (!Redeclaration && isa<CXXRecordDecl>(NewFD->getDeclContext()))
John McCall401982f2010-01-20 21:53:11 +00003285 NewFD->setAccess(AS_public);
3286
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003287 // An out-of-line member function declaration must also be a
3288 // definition (C++ [dcl.meaning]p1).
Douglas Gregor19c52722009-10-08 15:54:21 +00003289 // Note that this is not the case for explicit specializations of
3290 // function templates or member functions of class templates, per
3291 // C++ [temp.expl.spec]p2.
Douglas Gregor4f15f4d2009-09-17 19:51:30 +00003292 if (!IsFunctionDefinition && !isFriend &&
Douglas Gregorca027af2009-10-12 22:27:17 +00003293 !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003294 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
3295 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003296 NewFD->setInvalidDecl();
Douglas Gregore1ad8a12010-01-16 18:09:52 +00003297 } else if (!Redeclaration &&
3298 !(isFriend && CurContext->isDependentContext())) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003299 // The user tried to provide an out-of-line definition for a
3300 // function that is a member of a class or namespace, but there
Mike Stump11289f42009-09-09 15:08:12 +00003301 // was no such member function declared (C++ [class.mfct]p2,
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003302 // C++ [namespace.memdef]p2). For example:
Mike Stump11289f42009-09-09 15:08:12 +00003303 //
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003304 // class X {
3305 // void f() const;
Mike Stump11289f42009-09-09 15:08:12 +00003306 // };
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003307 //
3308 // void X::f() { } // ill-formed
3309 //
3310 // Complain about this problem, and attempt to suggest close
3311 // matches (e.g., those that differ only in cv-qualifiers and
3312 // whether the parameter types are references).
3313 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
Douglas Gregore40876a2009-10-13 21:16:44 +00003314 << Name << DC << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003315 NewFD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003316
John McCall27b18f82009-11-17 02:14:36 +00003317 LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00003318 ForRedeclaration);
John McCall27b18f82009-11-17 02:14:36 +00003319 LookupQualifiedName(Prev, DC);
Mike Stump11289f42009-09-09 15:08:12 +00003320 assert(!Prev.isAmbiguous() &&
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003321 "Cannot have an ambiguity in previous-declaration lookup");
3322 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3323 Func != FuncEnd; ++Func) {
3324 if (isa<FunctionDecl>(*Func) &&
3325 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
3326 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3327 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003328 }
3329 }
3330
3331 // Handle attributes. We need to have merged decls when handling attributes
3332 // (for example to check for conflicts, etc).
3333 // FIXME: This needs to happen before we merge declarations. Then,
3334 // let attribute merging cope with attribute conflicts.
Douglas Gregor758a8692009-06-17 21:51:59 +00003335 ProcessDeclAttributes(S, NewFD, D);
Ryan Flynne5dc8592009-07-25 22:29:44 +00003336
3337 // attributes declared post-definition are currently ignored
John McCall1f82f242009-11-18 22:49:29 +00003338 if (Redeclaration && Previous.isSingleResult()) {
3339 const FunctionDecl *Def;
3340 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
Ryan Flynne5dc8592009-07-25 22:29:44 +00003341 if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) {
3342 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
3343 Diag(Def->getLocation(), diag::note_previous_definition);
3344 }
3345 }
3346
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003347 AddKnownFunctionAttributes(NewFD);
3348
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003349 if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003350 // If a function name is overloadable in C, then every function
3351 // with that name must be marked "overloadable".
3352 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
3353 << Redeclaration << NewFD;
John McCall1f82f242009-11-18 22:49:29 +00003354 if (!Previous.empty())
3355 Diag(Previous.getRepresentativeDecl()->getLocation(),
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003356 diag::note_attribute_overloadable_prev_overload);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003357 NewFD->addAttr(::new (Context) OverloadableAttr());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003358 }
3359
3360 // If this is a locally-scoped extern C function, update the
3361 // map of such names.
Douglas Gregor16618f22009-09-12 00:17:51 +00003362 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003363 && !NewFD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00003364 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003365
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00003366 // Set this FunctionDecl's range up to the right paren.
3367 NewFD->setLocEnd(D.getSourceRange().getEnd());
3368
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003369 if (FunctionTemplate && NewFD->isInvalidDecl())
3370 FunctionTemplate->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003371
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003372 if (FunctionTemplate)
3373 return FunctionTemplate;
Mike Stump11289f42009-09-09 15:08:12 +00003374
Tanya Lattner90073802010-02-12 00:07:30 +00003375
3376 // Keep track of static, non-inlined function definitions that
3377 // have not been used. We will warn later.
3378 // FIXME: Also include static functions declared but not defined.
3379 if (!NewFD->isInvalidDecl() && IsFunctionDefinition
3380 && !NewFD->isInlined() && NewFD->getLinkage() == InternalLinkage
Chris Lattner8a651c72010-04-09 17:25:05 +00003381 && !NewFD->isUsed() && !NewFD->hasAttr<UnusedAttr>()
3382 && !NewFD->hasAttr<ConstructorAttr>()
3383 && !NewFD->hasAttr<DestructorAttr>())
Tanya Lattner90073802010-02-12 00:07:30 +00003384 UnusedStaticFuncs.push_back(NewFD);
3385
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003386 return NewFD;
3387}
3388
3389/// \brief Perform semantic checking of a new function declaration.
3390///
3391/// Performs semantic analysis of the new function declaration
3392/// NewFD. This routine performs all semantic checking that does not
3393/// require the actual declarator involved in the declaration, and is
3394/// used both for the declaration of functions as they are parsed
3395/// (called via ActOnDeclarator) and for the declaration of functions
3396/// that have been instantiated via C++ template instantiation (called
3397/// via InstantiateDecl).
3398///
Douglas Gregorcf915552009-10-13 16:30:37 +00003399/// \param IsExplicitSpecialiation whether this new function declaration is
3400/// an explicit specialization of the previous declaration.
3401///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003402/// This sets NewFD->isInvalidDecl() to true if there was an error.
John McCall84d87672009-12-10 09:41:52 +00003403void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00003404 LookupResult &Previous,
Douglas Gregorcf915552009-10-13 16:30:37 +00003405 bool IsExplicitSpecialization,
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003406 bool &Redeclaration,
3407 bool &OverloadableAttrRequired) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003408 // If NewFD is already known erroneous, don't do any of this checking.
3409 if (NewFD->isInvalidDecl())
3410 return;
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003411
Eli Friedman54135832009-05-16 12:15:55 +00003412 if (NewFD->getResultType()->isVariablyModifiedType()) {
3413 // Functions returning a variably modified type violate C99 6.7.5.2p2
3414 // because all functions have linkage.
3415 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
3416 return NewFD->setInvalidDecl();
3417 }
3418
Douglas Gregor16618f22009-09-12 00:17:51 +00003419 if (NewFD->isMain())
3420 CheckMain(NewFD);
John McCalld9baf6a2009-07-24 03:03:21 +00003421
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003422 // Check for a previous declaration of this name.
John McCall1f82f242009-11-18 22:49:29 +00003423 if (Previous.empty() && NewFD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003424 // Since we did not find anything by this name and we're declaring
3425 // an extern "C" function, look for a non-visible extern "C"
3426 // declaration with the same name.
3427 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003428 = LocallyScopedExternalDecls.find(NewFD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003429 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00003430 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003431 }
3432
Douglas Gregore62c0a42009-02-24 01:23:02 +00003433 // Merge or overload the declaration with an existing declaration of
3434 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00003435 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003436 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00003437 // a declaration that requires merging. If it's an overload,
3438 // there's no more work to do here; we'll just add the new
3439 // function to the scope.
Douglas Gregor633b7372009-02-13 00:26:38 +00003440
John McCall1f82f242009-11-18 22:49:29 +00003441 NamedDecl *OldDecl = 0;
John McCalldaa3d6b2009-12-09 03:35:25 +00003442 if (!AllowOverloadingOfFunction(Previous, Context)) {
3443 Redeclaration = true;
3444 OldDecl = Previous.getFoundDecl();
3445 } else {
3446 if (!getLangOptions().CPlusPlus) {
3447 OverloadableAttrRequired = true;
3448
3449 // Functions marked "overloadable" must have a prototype (that
3450 // we can't get through declaration merging).
3451 if (!NewFD->getType()->getAs<FunctionProtoType>()) {
3452 Diag(NewFD->getLocation(),
3453 diag::err_attribute_overloadable_no_prototype)
3454 << NewFD;
John McCall1f82f242009-11-18 22:49:29 +00003455 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00003456
3457 // Turn this into a variadic function with no parameters.
3458 QualType R = Context.getFunctionType(
3459 NewFD->getType()->getAs<FunctionType>()->getResultType(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003460 0, 0, true, 0, false, false, 0, 0,
3461 FunctionType::ExtInfo());
John McCalldaa3d6b2009-12-09 03:35:25 +00003462 NewFD->setType(R);
3463 return NewFD->setInvalidDecl();
3464 }
3465 }
3466
3467 switch (CheckOverload(NewFD, Previous, OldDecl)) {
3468 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003469 Redeclaration = true;
3470 if (isa<UsingShadowDecl>(OldDecl) && CurContext->isRecord()) {
3471 HideUsingShadowDecl(S, cast<UsingShadowDecl>(OldDecl));
3472 Redeclaration = false;
3473 }
John McCalldaa3d6b2009-12-09 03:35:25 +00003474 break;
3475
3476 case Ovl_NonFunction:
3477 Redeclaration = true;
3478 break;
3479
3480 case Ovl_Overload:
3481 Redeclaration = false;
3482 break;
John McCall1f82f242009-11-18 22:49:29 +00003483 }
3484 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003485
John McCall1f82f242009-11-18 22:49:29 +00003486 if (Redeclaration) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003487 // NewFD and OldDecl represent declarations that need to be
Mike Stump11289f42009-09-09 15:08:12 +00003488 // merged.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003489 if (MergeFunctionDecl(NewFD, OldDecl))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003490 return NewFD->setInvalidDecl();
Zhongxing Xubece5d62009-01-16 01:13:29 +00003491
John McCall1f82f242009-11-18 22:49:29 +00003492 Previous.clear();
3493 Previous.addDecl(OldDecl);
3494
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003495 if (FunctionTemplateDecl *OldTemplateDecl
Douglas Gregorca027af2009-10-12 22:27:17 +00003496 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
Douglas Gregorcf915552009-10-13 16:30:37 +00003497 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
Douglas Gregorca027af2009-10-12 22:27:17 +00003498 FunctionTemplateDecl *NewTemplateDecl
3499 = NewFD->getDescribedFunctionTemplate();
3500 assert(NewTemplateDecl && "Template/non-template mismatch");
3501 if (CXXMethodDecl *Method
3502 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
3503 Method->setAccess(OldTemplateDecl->getAccess());
3504 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
3505 }
Douglas Gregorcf915552009-10-13 16:30:37 +00003506
3507 // If this is an explicit specialization of a member that is a function
3508 // template, mark it as a member specialization.
3509 if (IsExplicitSpecialization &&
3510 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
3511 NewTemplateDecl->setMemberSpecialization();
3512 assert(OldTemplateDecl->isMemberSpecialization());
3513 }
Douglas Gregorca027af2009-10-12 22:27:17 +00003514 } else {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00003515 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
3516 NewFD->setAccess(OldDecl->getAccess());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003517 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00003518 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003519 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00003520 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003521
Anders Carlsson1b12ed42009-09-13 21:33:06 +00003522 // Semantic checking for this function declaration (in isolation).
3523 if (getLangOptions().CPlusPlus) {
3524 // C++-specific checks.
3525 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
3526 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003527 } else if (CXXDestructorDecl *Destructor =
3528 dyn_cast<CXXDestructorDecl>(NewFD)) {
3529 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00003530 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003531
3532 // FIXME: Shouldn't we be able to perform thisc heck even when the class
3533 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00003534 if (!ClassType->isDependentType()) {
3535 DeclarationName Name
3536 = Context.DeclarationNames.getCXXDestructorName(
3537 Context.getCanonicalType(ClassType));
3538 if (NewFD->getDeclName() != Name) {
3539 Diag(NewFD->getLocation(), diag::err_destructor_name);
3540 return NewFD->setInvalidDecl();
3541 }
3542 }
Anders Carlsson2a50e952009-11-15 22:49:34 +00003543
Anders Carlsson1b12ed42009-09-13 21:33:06 +00003544 Record->setUserDeclaredDestructor(true);
3545 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
3546 // user-defined destructor.
3547 Record->setPOD(false);
3548
3549 // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
3550 // declared destructor.
3551 // FIXME: C++0x: don't do this for "= default" destructors
3552 Record->setHasTrivialDestructor(false);
3553 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00003554 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00003555 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00003556 }
3557
3558 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00003559 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
3560 if (!Method->isFunctionTemplateSpecialization() &&
3561 !Method->getDescribedFunctionTemplate())
3562 AddOverriddenMethods(Method->getParent(), Method);
3563 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00003564
Eli Friedman6393aac2009-12-02 07:16:50 +00003565 // Additional checks for the destructor; make sure we do this after we
3566 // figure out whether the destructor is virtual.
3567 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
3568 if (!Destructor->getParent()->isDependentType())
3569 CheckDestructor(Destructor);
3570
Anders Carlsson1b12ed42009-09-13 21:33:06 +00003571 // Extra checking for C++ overloaded operators (C++ [over.oper]).
3572 if (NewFD->isOverloadedOperator() &&
3573 CheckOverloadedOperatorDeclaration(NewFD))
3574 return NewFD->setInvalidDecl();
Alexis Huntc88db062010-01-13 09:01:02 +00003575
3576 // Extra checking for C++0x literal operators (C++0x [over.literal]).
3577 if (NewFD->getLiteralIdentifier() &&
3578 CheckLiteralOperatorDeclaration(NewFD))
3579 return NewFD->setInvalidDecl();
3580
Anders Carlsson1b12ed42009-09-13 21:33:06 +00003581 // In C++, check default arguments now that we have merged decls. Unless
3582 // the lexical context is the class, because in this case this is done
3583 // during delayed parsing anyway.
3584 if (!CurContext->isRecord())
3585 CheckCXXDefaultArguments(NewFD);
3586 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003587}
3588
John McCalld9baf6a2009-07-24 03:03:21 +00003589void Sema::CheckMain(FunctionDecl* FD) {
John McCall02dee0a2009-07-25 04:36:53 +00003590 // C++ [basic.start.main]p3: A program that declares main to be inline
3591 // or static is ill-formed.
3592 // C99 6.7.4p4: In a hosted environment, the inline function specifier
3593 // shall not appear in a declaration of main.
3594 // static main is not an error under C99, but we should warn about it.
Douglas Gregor35b57532009-10-27 21:01:01 +00003595 bool isInline = FD->isInlineSpecified();
John McCall02dee0a2009-07-25 04:36:53 +00003596 bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
3597 if (isInline || isStatic) {
3598 unsigned diagID = diag::warn_unusual_main_decl;
3599 if (isInline || getLangOptions().CPlusPlus)
3600 diagID = diag::err_unusual_main_decl;
3601
3602 int which = isStatic + (isInline << 1) - 1;
3603 Diag(FD->getLocation(), diagID) << which;
3604 }
3605
3606 QualType T = FD->getType();
3607 assert(T->isFunctionType() && "function decl is not of function type");
John McCall9dd450b2009-09-21 23:43:11 +00003608 const FunctionType* FT = T->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00003609
John McCall02dee0a2009-07-25 04:36:53 +00003610 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
3611 // TODO: add a replacement fixit to turn the return type into 'int'.
3612 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
3613 FD->setInvalidDecl(true);
3614 }
3615
3616 // Treat protoless main() as nullary.
3617 if (isa<FunctionNoProtoType>(FT)) return;
3618
3619 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
3620 unsigned nparams = FTP->getNumArgs();
3621 assert(FD->getNumParams() == nparams);
3622
John McCall0e21fcc2009-12-24 09:58:38 +00003623 bool HasExtraParameters = (nparams > 3);
3624
3625 // Darwin passes an undocumented fourth argument of type char**. If
3626 // other platforms start sprouting these, the logic below will start
3627 // getting shifty.
3628 if (nparams == 4 &&
3629 Context.Target.getTriple().getOS() == llvm::Triple::Darwin)
3630 HasExtraParameters = false;
3631
3632 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00003633 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
3634 FD->setInvalidDecl(true);
3635 nparams = 3;
3636 }
3637
3638 // FIXME: a lot of the following diagnostics would be improved
3639 // if we had some location information about types.
3640
3641 QualType CharPP =
3642 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00003643 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00003644
3645 for (unsigned i = 0; i < nparams; ++i) {
3646 QualType AT = FTP->getArgType(i);
3647
3648 bool mismatch = true;
3649
3650 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
3651 mismatch = false;
3652 else if (Expected[i] == CharPP) {
3653 // As an extension, the following forms are okay:
3654 // char const **
3655 // char const * const *
3656 // char * const *
3657
John McCall8ccfcb52009-09-24 19:53:00 +00003658 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00003659 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003660 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
3661 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
John McCall02dee0a2009-07-25 04:36:53 +00003662 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
3663 qs.removeConst();
3664 mismatch = !qs.empty();
3665 }
3666 }
3667
3668 if (mismatch) {
3669 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
3670 // TODO: suggest replacing given type with expected type
3671 FD->setInvalidDecl(true);
3672 }
3673 }
3674
3675 if (nparams == 1 && !FD->isInvalidDecl()) {
3676 Diag(FD->getLocation(), diag::warn_main_one_arg);
3677 }
John McCalld9baf6a2009-07-24 03:03:21 +00003678}
3679
Eli Friedmand5a55bd2008-05-20 13:48:25 +00003680bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00003681 // FIXME: Need strict checking. In C89, we need to check for
3682 // any assignment, increment, decrement, function-calls, or
3683 // commas outside of a sizeof. In C99, it's the same list,
3684 // except that the aforementioned are allowed in unevaluated
3685 // expressions. Everything else falls under the
3686 // "may accept other forms of constant expressions" exception.
3687 // (We never end up here for C++, so the constant expression
3688 // rules there don't matter.)
Chris Lattner0be5aa82009-02-24 21:54:33 +00003689 if (Init->isConstantInitializer(Context))
Eli Friedman7bfab362009-02-22 06:45:27 +00003690 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00003691 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
3692 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00003693 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00003694}
3695
Anders Carlsson250aada2009-08-16 05:13:48 +00003696void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
3697 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003698}
3699
3700/// AddInitializerToDecl - Adds the initializer Init to the
3701/// declaration dcl. If DirectInit is true, this is C++ direct
3702/// initialization rather than copy initialization.
Chris Lattner83f095c2009-03-28 19:18:32 +00003703void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
3704 Decl *RealDecl = dcl.getAs<Decl>();
Chris Lattner8beb9de2007-10-19 20:10:30 +00003705 // If there is no declaration, there was an error parsing it. Just ignore
3706 // the initializer.
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00003707 if (RealDecl == 0)
Chris Lattner8beb9de2007-10-19 20:10:30 +00003708 return;
Mike Stump11289f42009-09-09 15:08:12 +00003709
Douglas Gregor0c880302009-03-11 23:00:04 +00003710 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
3711 // With declarators parsed the way they are, the parser cannot
3712 // distinguish between a normal initializer and a pure-specifier.
3713 // Thus this grotesque test.
3714 IntegerLiteral *IL;
3715 Expr *Init = static_cast<Expr *>(init.get());
3716 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00003717 Context.getCanonicalType(IL->getType()) == Context.IntTy)
3718 CheckPureMethod(Method, Init->getSourceRange());
3719 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00003720 Diag(Method->getLocation(), diag::err_member_function_initialization)
3721 << Method->getDeclName() << Init->getSourceRange();
3722 Method->setInvalidDecl();
3723 }
3724 return;
3725 }
3726
Steve Naroff437b4d82007-09-12 20:13:48 +00003727 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3728 if (!VDecl) {
Douglas Gregor0c880302009-03-11 23:00:04 +00003729 if (getLangOptions().CPlusPlus &&
3730 RealDecl->getLexicalDeclContext()->isRecord() &&
3731 isa<NamedDecl>(RealDecl))
3732 Diag(RealDecl->getLocation(), diag::err_member_initialization)
3733 << cast<NamedDecl>(RealDecl)->getDeclName();
3734 else
3735 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00003736 RealDecl->setInvalidDecl();
3737 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00003738 }
3739
Eli Friedmanc9827d12009-11-14 03:40:14 +00003740 // A definition must end up with a complete type, which means it must be
3741 // complete with the restriction that an array type might be completed by the
3742 // initializer; note that later code assumes this restriction.
3743 QualType BaseDeclType = VDecl->getType();
3744 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
3745 BaseDeclType = Array->getElementType();
3746 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
Eli Friedman337cd3a2009-04-13 21:28:54 +00003747 diag::err_typecheck_decl_incomplete_type)) {
3748 RealDecl->setInvalidDecl();
3749 return;
3750 }
3751
Douglas Gregorc99f1552009-12-03 18:33:45 +00003752 // The variable can not have an abstract class type.
3753 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
3754 diag::err_abstract_type_in_decl,
3755 AbstractVariableType))
3756 VDecl->setInvalidDecl();
3757
Sebastian Redl5ca79842010-02-01 20:16:42 +00003758 const VarDecl *Def;
3759 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003760 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00003761 << VDecl->getDeclName();
3762 Diag(Def->getLocation(), diag::note_previous_definition);
3763 VDecl->setInvalidDecl();
3764 return;
3765 }
3766
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00003767 // Take ownership of the expression, now that we're sure we have somewhere
3768 // to put it.
Anders Carlsson3cbc8592009-05-01 19:30:39 +00003769 Expr *Init = init.takeAs<Expr>();
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00003770 assert(Init && "missing initializer");
3771
Douglas Gregor85dabae2009-12-16 01:38:02 +00003772 // Capture the variable that is being initialized and the style of
3773 // initialization.
3774 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
3775
3776 // FIXME: Poor source location information.
3777 InitializationKind Kind
3778 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
3779 Init->getLocStart(),
3780 Init->getLocEnd())
3781 : InitializationKind::CreateCopy(VDecl->getLocation(),
3782 Init->getLocStart());
3783
Steve Naroff61091402007-09-12 14:07:44 +00003784 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00003785 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00003786 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff08899ff2008-04-15 22:42:06 +00003787 if (VDecl->isBlockVarDecl()) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003788 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
Steve Naroff437b4d82007-09-12 20:13:48 +00003789 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff08899ff2008-04-15 22:42:06 +00003790 VDecl->setInvalidDecl();
3791 } else if (!VDecl->isInvalidDecl()) {
Eli Friedman78275202009-12-19 08:11:05 +00003792 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
Eli Friedman463e5232009-12-22 02:10:53 +00003793 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Eli Friedman78275202009-12-19 08:11:05 +00003794 MultiExprArg(*this, (void**)&Init, 1),
Eli Friedman463e5232009-12-22 02:10:53 +00003795 &DclT);
3796 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00003797 VDecl->setInvalidDecl();
Eli Friedman78275202009-12-19 08:11:05 +00003798 return;
3799 }
Mike Stump11289f42009-09-09 15:08:12 +00003800
Eli Friedman463e5232009-12-22 02:10:53 +00003801 Init = Result.takeAs<Expr>();
3802
Anders Carlsson41e08812008-08-22 05:00:02 +00003803 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmance982572009-02-20 01:34:21 +00003804 // Don't check invalid declarations to avoid emitting useless diagnostics.
3805 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003806 if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
Anders Carlsson41e08812008-08-22 05:00:02 +00003807 CheckForConstantInitializer(Init, DclT);
3808 }
Steve Naroff61091402007-09-12 14:07:44 +00003809 }
Mike Stump11289f42009-09-09 15:08:12 +00003810 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00003811 VDecl->getLexicalDeclContext()->isRecord()) {
3812 // This is an in-class initialization for a static data member, e.g.,
3813 //
3814 // struct S {
3815 // static const int value = 17;
3816 // };
3817
3818 // Attach the initializer
Douglas Gregord5058122010-02-11 01:19:42 +00003819 VDecl->setInit(Init);
Douglas Gregor0c880302009-03-11 23:00:04 +00003820
3821 // C++ [class.mem]p4:
3822 // A member-declarator can contain a constant-initializer only
3823 // if it declares a static member (9.4) of const integral or
3824 // const enumeration type, see 9.4.2.
3825 QualType T = VDecl->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003826 if (!T->isDependentType() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00003827 (!Context.getCanonicalType(T).isConstQualified() ||
3828 !T->isIntegralType())) {
3829 Diag(VDecl->getLocation(), diag::err_member_initialization)
3830 << VDecl->getDeclName() << Init->getSourceRange();
3831 VDecl->setInvalidDecl();
3832 } else {
3833 // C++ [class.static.data]p4:
3834 // If a static data member is of const integral or const
3835 // enumeration type, its declaration in the class definition
3836 // can specify a constant-initializer which shall be an
3837 // integral constant expression (5.19).
3838 if (!Init->isTypeDependent() &&
3839 !Init->getType()->isIntegralType()) {
3840 // We have a non-dependent, non-integral or enumeration type.
Mike Stump11289f42009-09-09 15:08:12 +00003841 Diag(Init->getSourceRange().getBegin(),
Douglas Gregor0c880302009-03-11 23:00:04 +00003842 diag::err_in_class_initializer_non_integral_type)
3843 << Init->getType() << Init->getSourceRange();
3844 VDecl->setInvalidDecl();
3845 } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
3846 // Check whether the expression is a constant expression.
3847 llvm::APSInt Value;
3848 SourceLocation Loc;
3849 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
3850 Diag(Loc, diag::err_in_class_initializer_non_constant)
3851 << Init->getSourceRange();
3852 VDecl->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003853 } else if (!VDecl->getType()->isDependentType())
Eli Friedman06ed2a52009-10-20 08:27:19 +00003854 ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
Douglas Gregor0c880302009-03-11 23:00:04 +00003855 }
3856 }
Steve Naroff08899ff2008-04-15 22:42:06 +00003857 } else if (VDecl->isFileVarDecl()) {
Douglas Gregorc81ca092010-04-19 21:31:25 +00003858 if (VDecl->getStorageClass() == VarDecl::Extern &&
Douglas Gregorfceea362010-04-22 14:36:26 +00003859 (!getLangOptions().CPlusPlus ||
3860 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
Steve Naroff437b4d82007-09-12 20:13:48 +00003861 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00003862 if (!VDecl->isInvalidDecl()) {
3863 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3864 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3865 MultiExprArg(*this, (void**)&Init, 1),
3866 &DclT);
3867 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00003868 VDecl->setInvalidDecl();
Eli Friedman463e5232009-12-22 02:10:53 +00003869 return;
3870 }
3871
3872 Init = Result.takeAs<Expr>();
3873 }
Mike Stump11289f42009-09-09 15:08:12 +00003874
Anders Carlsson41e08812008-08-22 05:00:02 +00003875 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmance982572009-02-20 01:34:21 +00003876 // Don't check invalid declarations to avoid emitting useless diagnostics.
3877 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Anders Carlsson41e08812008-08-22 05:00:02 +00003878 // C99 6.7.8p4. All file scoped initializers need to be constant.
3879 CheckForConstantInitializer(Init, DclT);
3880 }
Steve Naroff61091402007-09-12 14:07:44 +00003881 }
3882 // If the type changed, it means we had an incomplete type that was
Mike Stump11289f42009-09-09 15:08:12 +00003883 // completed by the initializer. For example:
Steve Naroff61091402007-09-12 14:07:44 +00003884 // int ary[] = { 1, 3, 5 };
3885 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00003886 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff437b4d82007-09-12 20:13:48 +00003887 VDecl->setType(DclT);
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00003888 Init->setType(DclT);
3889 }
Mike Stump11289f42009-09-09 15:08:12 +00003890
Anders Carlsson6e997b22009-12-15 20:51:39 +00003891 Init = MaybeCreateCXXExprWithTemporaries(Init);
Steve Naroff61091402007-09-12 14:07:44 +00003892 // Attach the initializer to the decl.
Douglas Gregord5058122010-02-11 01:19:42 +00003893 VDecl->setInit(Init);
Douglas Gregorbeecd582009-04-21 17:11:58 +00003894
Eli Friedman7dac3712009-12-20 22:29:11 +00003895 if (getLangOptions().CPlusPlus) {
3896 // Make sure we mark the destructor as used if necessary.
3897 QualType InitType = VDecl->getType();
Douglas Gregora318efd2010-01-05 19:06:31 +00003898 while (const ArrayType *Array = Context.getAsArrayType(InitType))
Eli Friedman7dac3712009-12-20 22:29:11 +00003899 InitType = Context.getBaseElementType(Array);
John McCall03c48482010-02-02 09:10:11 +00003900 if (const RecordType *Record = InitType->getAs<RecordType>())
3901 FinalizeVarWithDestructor(VDecl, Record);
Eli Friedman7dac3712009-12-20 22:29:11 +00003902 }
3903
Steve Naroff61091402007-09-12 14:07:44 +00003904 return;
3905}
3906
John McCalleae5acb2010-03-31 02:13:20 +00003907/// ActOnInitializerError - Given that there was an error parsing an
3908/// initializer for the given declaration, try to return to some form
3909/// of sanity.
3910void Sema::ActOnInitializerError(DeclPtrTy dcl) {
3911 // Our main concern here is re-establishing invariants like "a
3912 // variable's type is either dependent or complete".
3913 Decl *D = dcl.getAs<Decl>();
3914 if (!D || D->isInvalidDecl()) return;
3915
3916 VarDecl *VD = dyn_cast<VarDecl>(D);
3917 if (!VD) return;
3918
3919 QualType Ty = VD->getType();
3920 if (Ty->isDependentType()) return;
3921
3922 // Require a complete type.
3923 if (RequireCompleteType(VD->getLocation(),
3924 Context.getBaseElementType(Ty),
3925 diag::err_typecheck_decl_incomplete_type)) {
3926 VD->setInvalidDecl();
3927 return;
3928 }
3929
3930 // Require an abstract type.
3931 if (RequireNonAbstractType(VD->getLocation(), Ty,
3932 diag::err_abstract_type_in_decl,
3933 AbstractVariableType)) {
3934 VD->setInvalidDecl();
3935 return;
3936 }
3937
3938 // Don't bother complaining about constructors or destructors,
3939 // though.
3940}
3941
Mike Stump11289f42009-09-09 15:08:12 +00003942void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
Anders Carlssonae019932009-07-11 00:34:39 +00003943 bool TypeContainsUndeducedAuto) {
Chris Lattner83f095c2009-03-28 19:18:32 +00003944 Decl *RealDecl = dcl.getAs<Decl>();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003945
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00003946 // If there is no declaration, there was an error parsing it. Just ignore it.
3947 if (RealDecl == 0)
3948 return;
3949
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003950 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
3951 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00003952
Anders Carlssonae019932009-07-11 00:34:39 +00003953 // C++0x [dcl.spec.auto]p3
3954 if (TypeContainsUndeducedAuto) {
3955 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
3956 << Var->getDeclName() << Type;
3957 Var->setInvalidDecl();
3958 return;
3959 }
Mike Stump11289f42009-09-09 15:08:12 +00003960
Douglas Gregore6565622010-02-09 07:26:29 +00003961 switch (Var->isThisDeclarationADefinition()) {
3962 case VarDecl::Definition:
3963 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
3964 break;
3965
3966 // We have an out-of-line definition of a static data member
3967 // that has an in-class initializer, so we type-check this like
3968 // a declaration.
3969 //
3970 // Fall through
3971
3972 case VarDecl::DeclarationOnly:
3973 // It's only a declaration.
3974
3975 // Block scope. C99 6.7p7: If an identifier for an object is
3976 // declared with no linkage (C99 6.2.2p6), the type for the
3977 // object shall be complete.
3978 if (!Type->isDependentType() && Var->isBlockVarDecl() &&
3979 !Var->getLinkage() && !Var->isInvalidDecl() &&
3980 RequireCompleteType(Var->getLocation(), Type,
3981 diag::err_typecheck_decl_incomplete_type))
3982 Var->setInvalidDecl();
3983
3984 // Make sure that the type is not abstract.
3985 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
3986 RequireNonAbstractType(Var->getLocation(), Type,
3987 diag::err_abstract_type_in_decl,
3988 AbstractVariableType))
3989 Var->setInvalidDecl();
3990 return;
3991
3992 case VarDecl::TentativeDefinition:
3993 // File scope. C99 6.9.2p2: A declaration of an identifier for an
3994 // object that has file scope without an initializer, and without a
3995 // storage-class specifier or with the storage-class specifier "static",
3996 // constitutes a tentative definition. Note: A tentative definition with
3997 // external linkage is valid (C99 6.2.2p5).
3998 if (!Var->isInvalidDecl()) {
3999 if (const IncompleteArrayType *ArrayT
4000 = Context.getAsIncompleteArrayType(Type)) {
4001 if (RequireCompleteType(Var->getLocation(),
4002 ArrayT->getElementType(),
4003 diag::err_illegal_decl_array_incomplete_type))
4004 Var->setInvalidDecl();
4005 } else if (Var->getStorageClass() == VarDecl::Static) {
4006 // C99 6.9.2p3: If the declaration of an identifier for an object is
4007 // a tentative definition and has internal linkage (C99 6.2.2p3), the
4008 // declared type shall not be an incomplete type.
4009 // NOTE: code such as the following
4010 // static struct s;
4011 // struct s { int a; };
4012 // is accepted by gcc. Hence here we issue a warning instead of
4013 // an error and we do not invalidate the static declaration.
4014 // NOTE: to avoid multiple warnings, only check the first declaration.
4015 if (Var->getPreviousDeclaration() == 0)
4016 RequireCompleteType(Var->getLocation(), Type,
4017 diag::ext_typecheck_decl_incomplete_type);
4018 }
4019 }
4020
4021 // Record the tentative definition; we're done.
4022 if (!Var->isInvalidDecl())
4023 TentativeDefinitions.push_back(Var);
4024 return;
4025 }
4026
4027 // Provide a specific diagnostic for uninitialized variable
4028 // definitions with incomplete array type.
4029 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00004030 Diag(Var->getLocation(),
4031 diag::err_typecheck_incomplete_array_needs_initializer);
4032 Var->setInvalidDecl();
4033 return;
4034 }
4035
Douglas Gregore6565622010-02-09 07:26:29 +00004036 // Provide a specific diagnostic for uninitialized variable
4037 // definitions with reference type.
4038 if (Type->isReferenceType()) {
4039 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
4040 << Var->getDeclName()
4041 << SourceRange(Var->getLocation(), Var->getLocation());
4042 Var->setInvalidDecl();
4043 return;
4044 }
4045
4046 // Do not attempt to type-check the default initializer for a
4047 // variable with dependent type.
4048 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00004049 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004050
Douglas Gregore6565622010-02-09 07:26:29 +00004051 if (Var->isInvalidDecl())
4052 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00004053
Douglas Gregore6565622010-02-09 07:26:29 +00004054 if (RequireCompleteType(Var->getLocation(),
4055 Context.getBaseElementType(Type),
4056 diag::err_typecheck_decl_incomplete_type)) {
4057 Var->setInvalidDecl();
4058 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004059 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004060
Douglas Gregore6565622010-02-09 07:26:29 +00004061 // The variable can not have an abstract class type.
4062 if (RequireNonAbstractType(Var->getLocation(), Type,
4063 diag::err_abstract_type_in_decl,
4064 AbstractVariableType)) {
4065 Var->setInvalidDecl();
4066 return;
4067 }
4068
Douglas Gregor589973b2010-03-08 02:45:10 +00004069 const RecordType *Record
4070 = Context.getBaseElementType(Type)->getAs<RecordType>();
4071 if (Record && getLangOptions().CPlusPlus && !getLangOptions().CPlusPlus0x &&
4072 cast<CXXRecordDecl>(Record->getDecl())->isPOD()) {
4073 // C++03 [dcl.init]p9:
4074 // If no initializer is specified for an object, and the
4075 // object is of (possibly cv-qualified) non-POD class type (or
4076 // array thereof), the object shall be default-initialized; if
4077 // the object is of const-qualified type, the underlying class
4078 // type shall have a user-declared default
4079 // constructor. Otherwise, if no initializer is specified for
4080 // a non- static object, the object and its subobjects, if
4081 // any, have an indeterminate initial value); if the object
4082 // or any of its subobjects are of const-qualified type, the
4083 // program is ill-formed.
4084 // FIXME: DPG thinks it is very fishy that C++0x disables this.
4085 } else {
4086 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
4087 InitializationKind Kind
4088 = InitializationKind::CreateDefault(Var->getLocation());
Douglas Gregore6565622010-02-09 07:26:29 +00004089
Douglas Gregor589973b2010-03-08 02:45:10 +00004090 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
4091 OwningExprResult Init = InitSeq.Perform(*this, Entity, Kind,
4092 MultiExprArg(*this, 0, 0));
4093 if (Init.isInvalid())
4094 Var->setInvalidDecl();
4095 else if (Init.get())
Douglas Gregord5058122010-02-11 01:19:42 +00004096 Var->setInit(MaybeCreateCXXExprWithTemporaries(Init.takeAs<Expr>()));
Douglas Gregore6565622010-02-09 07:26:29 +00004097 }
Douglas Gregor589973b2010-03-08 02:45:10 +00004098
4099 if (!Var->isInvalidDecl() && getLangOptions().CPlusPlus && Record)
4100 FinalizeVarWithDestructor(Var, Record);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004101 }
4102}
4103
Eli Friedman55b9ecb2009-05-29 01:49:24 +00004104Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4105 DeclPtrTy *Group,
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004106 unsigned NumDecls) {
4107 llvm::SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00004108
4109 if (DS.isTypeSpecOwned())
4110 Decls.push_back((Decl*)DS.getTypeRep());
4111
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004112 for (unsigned i = 0; i != NumDecls; ++i)
4113 if (Decl *D = Group[i].getAs<Decl>())
4114 Decls.push_back(D);
Mike Stump11289f42009-09-09 15:08:12 +00004115
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004116 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
Jay Foad7d0479f2009-05-21 09:52:38 +00004117 Decls.data(), Decls.size()));
Chris Lattner776fac82007-06-09 00:53:06 +00004118}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00004119
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004120
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004121/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4122/// to introduce parameters into function prototype scope.
Mike Stump11289f42009-09-09 15:08:12 +00004123Sema::DeclPtrTy
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004124Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00004125 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00004126
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004127 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar0ff41922008-09-03 21:54:21 +00004128 VarDecl::StorageClass StorageClass = VarDecl::None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00004129 VarDecl::StorageClass StorageClassAsWritten = VarDecl::None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00004130 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4131 StorageClass = VarDecl::Register;
Douglas Gregorc4df4072010-04-19 22:54:31 +00004132 StorageClassAsWritten = VarDecl::Register;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00004133 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004134 Diag(DS.getStorageClassSpecLoc(),
4135 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00004136 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004137 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004138
4139 if (D.getDeclSpec().isThreadSpecified())
4140 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4141
Eli Friedman574c7452009-04-07 19:37:57 +00004142 DiagnoseFunctionSpecifiers(D);
4143
Douglas Gregorcaa8ace2008-05-07 04:49:29 +00004144 // Check that there are no default arguments inside the type of this
4145 // parameter (C++ only).
4146 if (getLangOptions().CPlusPlus)
4147 CheckExtraCXXDefaultArguments(D);
Mike Stump11289f42009-09-09 15:08:12 +00004148
John McCallbcd03502009-12-07 02:54:59 +00004149 TypeSourceInfo *TInfo = 0;
Douglas Gregord6ab8742009-05-28 23:31:59 +00004150 TagDecl *OwnedDecl = 0;
John McCallbcd03502009-12-07 02:54:59 +00004151 QualType parmDeclType = GetTypeForDeclarator(D, S, &TInfo, &OwnedDecl);
Mike Stump11289f42009-09-09 15:08:12 +00004152
Douglas Gregord6ab8742009-05-28 23:31:59 +00004153 if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
4154 // C++ [dcl.fct]p6:
4155 // Types shall not be defined in return or parameter types.
4156 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
4157 << Context.getTypeDeclType(OwnedDecl);
4158 }
4159
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00004160 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004161 IdentifierInfo *II = D.getIdentifier();
Chris Lattnerd9773512009-01-21 02:38:50 +00004162 if (II) {
John McCall84f02672010-03-18 06:42:38 +00004163 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
4164 ForRedeclaration);
4165 LookupName(R, S);
4166 if (R.isSingleResult()) {
4167 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00004168 if (PrevDecl->isTemplateParameter()) {
4169 // Maybe we will complain about the shadowed template parameter.
4170 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4171 // Just pretend that we didn't see the previous declaration.
4172 PrevDecl = 0;
Chris Lattner83f095c2009-03-28 19:18:32 +00004173 } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
Chris Lattnerd9773512009-01-21 02:38:50 +00004174 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00004175 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004176
Chris Lattnerd9773512009-01-21 02:38:50 +00004177 // Recover by removing the name
4178 II = 0;
4179 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00004180 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00004181 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004182 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00004183 }
Steve Naroff773df5c2007-08-07 22:44:21 +00004184
John McCallf7b2fb52010-01-22 00:28:27 +00004185 // Temporarily put parameter variables in the translation unit, not
4186 // the enclosing context. This prevents them from accidentally
4187 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00004188 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
4189 TInfo, parmDeclType, II,
Douglas Gregorc4df4072010-04-19 22:54:31 +00004190 D.getIdentifierLoc(),
4191 StorageClass, StorageClassAsWritten);
Mike Stump11289f42009-09-09 15:08:12 +00004192
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004193 if (D.isInvalidType())
Douglas Gregor940bca72010-04-12 07:48:19 +00004194 New->setInvalidDecl();
4195
Chris Lattner9713a1c2009-04-11 19:34:56 +00004196 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4197 if (D.getCXXScopeSpec().isSet()) {
4198 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
4199 << D.getCXXScopeSpec().getRange();
4200 New->setInvalidDecl();
4201 }
Douglas Gregor940bca72010-04-12 07:48:19 +00004202
Douglas Gregor91f84212008-12-11 16:49:14 +00004203 // Add the parameter declaration into this scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00004204 S->AddDecl(DeclPtrTy::make(New));
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00004205 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00004206 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00004207
Douglas Gregor758a8692009-06-17 21:51:59 +00004208 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00004209
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004210 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00004211 Diag(New->getLocation(), diag::err_block_on_nonlocal);
4212 }
Chris Lattner83f095c2009-03-28 19:18:32 +00004213 return DeclPtrTy::make(New);
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00004214}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00004215
Douglas Gregor940bca72010-04-12 07:48:19 +00004216ParmVarDecl *Sema::CheckParameter(DeclContext *DC,
4217 TypeSourceInfo *TSInfo, QualType T,
4218 IdentifierInfo *Name,
4219 SourceLocation NameLoc,
Douglas Gregorc4df4072010-04-19 22:54:31 +00004220 VarDecl::StorageClass StorageClass,
4221 VarDecl::StorageClass StorageClassAsWritten) {
Douglas Gregor940bca72010-04-12 07:48:19 +00004222 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, NameLoc, Name,
4223 adjustParameterType(T), TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00004224 StorageClass, StorageClassAsWritten,
4225 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00004226
4227 // Parameters can not be abstract class types.
4228 // For record types, this is done by the AbstractClassUsageDiagnoser once
4229 // the class has been completely parsed.
4230 if (!CurContext->isRecord() &&
4231 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
4232 AbstractParamType))
4233 New->setInvalidDecl();
4234
4235 // Parameter declarators cannot be interface types. All ObjC objects are
4236 // passed by reference.
4237 if (T->isObjCInterfaceType()) {
4238 Diag(NameLoc,
4239 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
4240 New->setInvalidDecl();
4241 }
4242
4243 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4244 // duration shall not be qualified by an address-space qualifier."
4245 // Since all parameters have automatic store duration, they can not have
4246 // an address space.
4247 if (T.getAddressSpace() != 0) {
4248 Diag(NameLoc, diag::err_arg_with_address_space);
4249 New->setInvalidDecl();
4250 }
4251
4252 return New;
4253}
4254
Douglas Gregor170512f2009-04-01 23:51:29 +00004255void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4256 SourceLocation LocAfterDecls) {
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00004257 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4258 "Not a function declarator!");
4259 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004260
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00004261 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
4262 // for a K&R function.
4263 if (!FTI.hasPrototype) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00004264 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
4265 --i;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004266 if (FTI.ArgInfo[i].Param == 0) {
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00004267 llvm::SmallString<256> Code;
4268 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar07d07852009-10-18 21:17:35 +00004269 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00004270 << ";\n";
Chris Lattner4bd8dd82008-11-19 08:23:25 +00004271 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregor170512f2009-04-01 23:51:29 +00004272 << FTI.ArgInfo[i].Ident
Douglas Gregora771f462010-03-31 17:46:05 +00004273 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00004274
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00004275 // Implicitly declare the argument as type 'int' for lack of a better
4276 // type.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004277 DeclSpec DS;
4278 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00004279 unsigned DiagID; // unused
Mike Stump11289f42009-09-09 15:08:12 +00004280 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCall49bfce42009-08-03 20:12:06 +00004281 PrevSpec, DiagID);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004282 Declarator ParamD(DS, Declarator::KNRTypeListContext);
4283 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor9aa89042009-01-23 16:23:13 +00004284 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00004285 }
4286 }
Mike Stump11289f42009-09-09 15:08:12 +00004287 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00004288}
4289
Chris Lattner83f095c2009-03-28 19:18:32 +00004290Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
4291 Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00004292 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4293 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4294 "Not a function declarator!");
4295 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4296
4297 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004298 // FIXME: Diagnose arguments without names in C.
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00004299 }
Mike Stump11289f42009-09-09 15:08:12 +00004300
Douglas Gregorad590502008-12-15 23:53:10 +00004301 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00004302
Mike Stump11289f42009-09-09 15:08:12 +00004303 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004304 MultiTemplateParamsArg(*this),
4305 /*IsFunctionDefinition=*/true);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004306 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004307}
4308
Anders Carlsson31c7e882009-12-09 03:30:09 +00004309static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
4310 // Don't warn about invalid declarations.
4311 if (FD->isInvalidDecl())
4312 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00004313
Anders Carlsson31c7e882009-12-09 03:30:09 +00004314 // Or declarations that aren't global.
4315 if (!FD->isGlobal())
4316 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00004317
Anders Carlsson31c7e882009-12-09 03:30:09 +00004318 // Don't warn about C++ member functions.
4319 if (isa<CXXMethodDecl>(FD))
4320 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00004321
Anders Carlsson31c7e882009-12-09 03:30:09 +00004322 // Don't warn about 'main'.
4323 if (FD->isMain())
4324 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00004325
Anders Carlsson31c7e882009-12-09 03:30:09 +00004326 // Don't warn about inline functions.
4327 if (FD->isInlineSpecified())
4328 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00004329
4330 // Don't warn about function templates.
4331 if (FD->getDescribedFunctionTemplate())
4332 return false;
4333
4334 // Don't warn about function template specializations.
4335 if (FD->isFunctionTemplateSpecialization())
4336 return false;
4337
Anders Carlsson31c7e882009-12-09 03:30:09 +00004338 bool MissingPrototype = true;
4339 for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
4340 Prev; Prev = Prev->getPreviousDeclaration()) {
4341 // Ignore any declarations that occur in function or method
4342 // scope, because they aren't visible from the header.
4343 if (Prev->getDeclContext()->isFunctionOrMethod())
4344 continue;
4345
4346 MissingPrototype = !Prev->getType()->isFunctionProtoType();
4347 break;
4348 }
4349
4350 return MissingPrototype;
4351}
4352
Chris Lattner83f095c2009-03-28 19:18:32 +00004353Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00004354 // Clear the last template instantiation error context.
4355 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
4356
Douglas Gregor17a7c122009-06-24 00:54:41 +00004357 if (!D)
4358 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00004359 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004360
4361 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorc45a40a2009-08-22 00:34:47 +00004362 = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
4363 FD = FunTmpl->getTemplatedDecl();
4364 else
4365 FD = cast<FunctionDecl>(D.getAs<Decl>());
Douglas Gregorcad304ba2008-10-29 15:10:40 +00004366
Douglas Gregor9a28e842010-03-01 23:15:13 +00004367 // Enter a new function scope
4368 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00004369
Douglas Gregorcad304ba2008-10-29 15:10:40 +00004370 // See if this is a redefinition.
Charles Davisfea48452010-02-18 02:00:42 +00004371 // But don't complain if we're in GNU89 mode and the previous definition
4372 // was an extern inline function.
Douglas Gregorcad304ba2008-10-29 15:10:40 +00004373 const FunctionDecl *Definition;
Charles Davisfea48452010-02-18 02:00:42 +00004374 if (FD->getBody(Definition) &&
4375 !canRedefineFunction(Definition, getLangOptions())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00004376 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00004377 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00004378 }
4379
Douglas Gregor75a45ba2009-02-16 17:45:42 +00004380 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00004381 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor7a0febe2009-02-17 16:03:01 +00004382 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00004383 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00004384 FD->setInvalidDecl();
4385 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00004386 }
4387
Eli Friedman9ad72442009-03-04 07:30:59 +00004388 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00004389 // (C99 6.9.1p3, C++ [dcl.fct]p6).
4390 QualType ResultType = FD->getResultType();
4391 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00004392 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00004393 RequireCompleteType(FD->getLocation(), ResultType,
4394 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00004395 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00004396
Douglas Gregorf1b876d2009-03-31 16:35:03 +00004397 // GNU warning -Wmissing-prototypes:
4398 // Warn if a global function is defined without a previous
4399 // prototype declaration. This warning is issued even if the
4400 // definition itself provides a prototype. The aim is to detect
4401 // global functions that fail to be declared in header files.
Anders Carlsson31c7e882009-12-09 03:30:09 +00004402 if (ShouldWarnAboutMissingPrototype(FD))
4403 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Douglas Gregorf1b876d2009-03-31 16:35:03 +00004404
Douglas Gregor67da0d92009-05-15 17:59:04 +00004405 if (FnBodyScope)
4406 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00004407
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004408 // Check the validity of our function parameters
4409 CheckParmsForFunctionDef(FD);
4410
John McCalldf8b37c2010-03-22 09:20:08 +00004411 bool ShouldCheckShadow =
4412 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
4413
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004414 // Introduce our parameters into the function scope
4415 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
4416 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc72e6452009-01-09 18:51:29 +00004417 Param->setOwningFunction(FD);
4418
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004419 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00004420 if (Param->getIdentifier() && FnBodyScope) {
4421 if (ShouldCheckShadow)
4422 CheckShadow(FnBodyScope, Param);
4423
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00004424 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00004425 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00004426 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004427
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00004428 // Checking attributes of current function definition
4429 // dllimport attribute.
Mike Stump11289f42009-09-09 15:08:12 +00004430 if (FD->getAttr<DLLImportAttr>() &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004431 (!FD->getAttr<DLLExportAttr>())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00004432 // dllimport attribute cannot be applied to definition.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004433 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00004434 Diag(FD->getLocation(),
4435 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
4436 << "dllimport";
4437 FD->setInvalidDecl();
Chris Lattner83f095c2009-03-28 19:18:32 +00004438 return DeclPtrTy::make(FD);
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00004439 }
4440
4441 // Visual C++ appears to not think this is an issue, so only issue
4442 // a warning when Microsoft extensions are disabled.
4443 if (!LangOpts.Microsoft) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00004444 // If a symbol previously declared dllimport is later defined, the
4445 // attribute is ignored in subsequent references, and a warning is
4446 // emitted.
4447 Diag(FD->getLocation(),
4448 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4449 << FD->getNameAsCString() << "dllimport";
4450 }
4451 }
Chris Lattner83f095c2009-03-28 19:18:32 +00004452 return DeclPtrTy::make(FD);
Chris Lattnere168f762006-11-10 05:29:30 +00004453}
4454
Chris Lattner83f095c2009-03-28 19:18:32 +00004455Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
Douglas Gregor67da0d92009-05-15 17:59:04 +00004456 return ActOnFinishFunctionBody(D, move(BodyArg), false);
4457}
4458
4459Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
4460 bool IsInstantiation) {
Chris Lattner83f095c2009-03-28 19:18:32 +00004461 Decl *dcl = D.getAs<Decl>();
Sebastian Redla7b98a72009-04-26 20:35:05 +00004462 Stmt *Body = BodyArg.takeAs<Stmt>();
Douglas Gregorc45a40a2009-08-22 00:34:47 +00004463
4464 FunctionDecl *FD = 0;
4465 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
4466 if (FunTmpl)
4467 FD = FunTmpl->getTemplatedDecl();
4468 else
4469 FD = dyn_cast_or_null<FunctionDecl>(dcl);
4470
Ted Kremenek0b405322010-03-23 00:13:23 +00004471 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek918fe842010-03-20 21:06:02 +00004472
Douglas Gregorc45a40a2009-08-22 00:34:47 +00004473 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00004474 FD->setBody(Body);
Ted Kremenek918fe842010-03-20 21:06:02 +00004475 if (FD->isMain()) {
Mike Stump8e79f992009-07-24 02:49:01 +00004476 // C and C++ allow for main to automagically return 0.
John McCallcaa19452009-07-28 01:00:58 +00004477 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
4478 FD->setHasImplicitReturnZero(true);
Ted Kremenek0b405322010-03-23 00:13:23 +00004479 WP.disableCheckFallThrough();
Ted Kremenek918fe842010-03-20 21:06:02 +00004480 }
Mike Stump11289f42009-09-09 15:08:12 +00004481
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004482 if (!FD->isInvalidDecl())
4483 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Mike Stump11289f42009-09-09 15:08:12 +00004484
Anders Carlsson82fccd02009-12-07 08:24:59 +00004485 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
4486 MaybeMarkVirtualMembersReferenced(Method->getLocation(), Method);
Mike Stump11289f42009-09-09 15:08:12 +00004487
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00004488 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00004489 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00004490 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00004491 MD->setBody(Body);
Argyrios Kyrtzidis02675dc2009-07-18 00:33:33 +00004492 MD->setEndLoc(Body->getLocEnd());
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004493 if (!MD->isInvalidDecl())
4494 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Ted Kremenek5a201952009-02-07 01:47:29 +00004495 } else {
4496 Body->Destroy(Context);
Chris Lattner83f095c2009-03-28 19:18:32 +00004497 return DeclPtrTy();
Ted Kremenek5a201952009-02-07 01:47:29 +00004498 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00004499
Chris Lattnere2473062007-05-28 06:28:18 +00004500 // Verify and clean out per-function state.
Eli Friedmanf69d09b2009-02-28 05:41:13 +00004501
Chris Lattnere2473062007-05-28 06:28:18 +00004502 // Check goto/label use.
Steve Naroff846b1ec2009-03-13 15:38:40 +00004503 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
Douglas Gregor9a28e842010-03-01 23:15:13 +00004504 I = getLabelMap().begin(), E = getLabelMap().end(); I != E; ++I) {
Chris Lattnerca4dc2e2009-04-18 19:30:02 +00004505 LabelStmt *L = I->second;
Mike Stump11289f42009-09-09 15:08:12 +00004506
Chris Lattnere2473062007-05-28 06:28:18 +00004507 // Verify that we have no forward references left. If so, there was a goto
4508 // or address of a label taken, but no definition of it. Label fwd
4509 // definitions are indicated with a null substmt.
Chris Lattnerca4dc2e2009-04-18 19:30:02 +00004510 if (L->getSubStmt() != 0)
4511 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004512
Chris Lattnerca4dc2e2009-04-18 19:30:02 +00004513 // Emit error.
4514 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Mike Stump11289f42009-09-09 15:08:12 +00004515
Chris Lattnerca4dc2e2009-04-18 19:30:02 +00004516 // At this point, we have gotos that use the bogus label. Stitch it into
4517 // the function body so that they aren't leaked and that the AST is well
4518 // formed.
4519 if (Body == 0) {
4520 // The whole function wasn't parsed correctly, just delete this.
4521 L->Destroy(Context);
4522 continue;
Chris Lattnere2473062007-05-28 06:28:18 +00004523 }
Mike Stump11289f42009-09-09 15:08:12 +00004524
Chris Lattnerca4dc2e2009-04-18 19:30:02 +00004525 // Otherwise, the body is valid: we want to stitch the label decl into the
4526 // function somewhere so that it is properly owned and so that the goto
4527 // has a valid target. Do this by creating a new compound stmt with the
4528 // label in it.
Sebastian Redla7b98a72009-04-26 20:35:05 +00004529
Chris Lattnerca4dc2e2009-04-18 19:30:02 +00004530 // Give the label a sub-statement.
4531 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
Sebastian Redla7b98a72009-04-26 20:35:05 +00004532
4533 CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
4534 cast<CXXTryStmt>(Body)->getTryBlock() :
4535 cast<CompoundStmt>(Body);
Ted Kremenekf5940962010-03-12 22:22:36 +00004536 llvm::SmallVector<Stmt*, 64> Elements(Compound->body_begin(),
4537 Compound->body_end());
Chris Lattnerca4dc2e2009-04-18 19:30:02 +00004538 Elements.push_back(L);
Ted Kremenekf5940962010-03-12 22:22:36 +00004539 Compound->setStmts(Context, Elements.data(), Elements.size());
Chris Lattnere2473062007-05-28 06:28:18 +00004540 }
Eli Friedmanf69d09b2009-02-28 05:41:13 +00004541
Douglas Gregor9a28e842010-03-01 23:15:13 +00004542 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00004543 // C++ constructors that have function-try-blocks can't have return
4544 // statements in the handlers of that block. (C++ [except.handle]p14)
4545 // Verify this.
4546 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
4547 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
4548
Ted Kremenek918fe842010-03-20 21:06:02 +00004549 // Verify that that gotos and switch cases don't jump into scopes illegally.
4550 // Verify that that gotos and switch cases don't jump into scopes illegally.
Douglas Gregor9a28e842010-03-01 23:15:13 +00004551 if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction())
4552 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00004553
Douglas Gregor9a28e842010-03-01 23:15:13 +00004554 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
John McCalla6309952010-03-16 21:39:52 +00004555 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4556 Destructor->getParent());
Douglas Gregor9a28e842010-03-01 23:15:13 +00004557
4558 // If any errors have occurred, clear out any temporaries that may have
4559 // been leftover. This ensures that these temporaries won't be picked up for
4560 // deletion in some later function.
4561 if (PP.getDiagnostics().hasErrorOccurred())
4562 ExprTemporaries.clear();
Ted Kremenek918fe842010-03-20 21:06:02 +00004563 else if (!isa<FunctionTemplateDecl>(dcl)) {
4564 // Since the body is valid, issue any analysis-based warnings that are
4565 // enabled.
4566 QualType ResultType;
4567 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
4568 ResultType = FD->getResultType();
4569 }
4570 else {
4571 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(dcl);
4572 ResultType = MD->getResultType();
4573 }
Ted Kremenek0b405322010-03-23 00:13:23 +00004574 AnalysisWarnings.IssueWarnings(WP, dcl);
Ted Kremenek918fe842010-03-20 21:06:02 +00004575 }
4576
Douglas Gregor9a28e842010-03-01 23:15:13 +00004577 assert(ExprTemporaries.empty() && "Leftover temporaries in function");
4578 }
4579
John McCalle99d5f32010-03-25 22:08:03 +00004580 if (!IsInstantiation)
4581 PopDeclContext();
4582
Douglas Gregor9a28e842010-03-01 23:15:13 +00004583 PopFunctionOrBlockScope();
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00004584
Douglas Gregora7e3ea32009-11-15 07:07:58 +00004585 // If any errors have occurred, clear out any temporaries that may have
4586 // been leftover. This ensures that these temporaries won't be picked up for
4587 // deletion in some later function.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00004588 if (getDiagnostics().hasErrorOccurred())
Douglas Gregora7e3ea32009-11-15 07:07:58 +00004589 ExprTemporaries.clear();
4590
Steve Naroffb313fc32007-11-11 23:20:51 +00004591 return D;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00004592}
4593
Chris Lattnerac18be92006-11-20 06:49:47 +00004594/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4595/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00004596NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004597 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004598 // Before we produce a declaration for an implicitly defined
4599 // function, see whether there was a locally-scoped declaration of
4600 // this name as a function or variable. If so, use that
4601 // (non-visible) declaration, and complain about it.
4602 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4603 = LocallyScopedExternalDecls.find(&II);
4604 if (Pos != LocallyScopedExternalDecls.end()) {
4605 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
4606 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
4607 return Pos->second;
4608 }
4609
Chris Lattner00e26072008-05-05 21:18:06 +00004610 // Extension in C99. Legal in C90, but warn about it.
Daniel Dunbar07d07852009-10-18 21:17:35 +00004611 if (II.getName().startswith("__builtin_"))
Douglas Gregor56fbc372009-09-28 21:14:19 +00004612 Diag(Loc, diag::warn_builtin_unknown) << &II;
4613 else if (getLangOptions().C99)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00004614 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner00e26072008-05-05 21:18:06 +00004615 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00004616 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00004617
Chris Lattnerac18be92006-11-20 06:49:47 +00004618 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00004619 const char *Dummy;
Chris Lattnerac18be92006-11-20 06:49:47 +00004620 DeclSpec DS;
John McCall49bfce42009-08-03 20:12:06 +00004621 unsigned DiagID;
4622 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Chris Lattnerb055f2d2007-02-11 08:19:57 +00004623 Error = Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00004624 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +00004625 Declarator D(DS, Declarator::BlockContext);
Sebastian Redl2b9cacb2009-04-29 17:30:04 +00004626 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
Sebastian Redlfb3f1792009-05-31 11:47:27 +00004627 0, 0, false, SourceLocation(),
Argyrios Kyrtzidis20cf1912009-08-19 23:14:54 +00004628 false, 0,0,0, Loc, Loc, D),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004629 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00004630 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004631
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00004632 // Insert this function into translation-unit scope.
4633
4634 DeclContext *PrevDC = CurContext;
4635 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004636
4637 FunctionDecl *FD =
Douglas Gregor4a75be22009-06-23 21:43:56 +00004638 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
Steve Naroff3913ea42008-04-04 14:32:09 +00004639 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00004640
4641 CurContext = PrevDC;
4642
Douglas Gregore711f702009-02-14 18:57:46 +00004643 AddKnownFunctionAttributes(FD);
4644
Steve Naroff3913ea42008-04-04 14:32:09 +00004645 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +00004646}
4647
Douglas Gregore711f702009-02-14 18:57:46 +00004648/// \brief Adds any function attributes that we know a priori based on
4649/// the declaration of this function.
4650///
4651/// These attributes can apply both to implicitly-declared builtins
4652/// (like __builtin___printf_chk) or to library-declared functions
4653/// like NSLog or printf.
4654void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
4655 if (FD->isInvalidDecl())
4656 return;
4657
4658 // If this is a built-in function, map its builtin attributes to
4659 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +00004660 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +00004661 // Handle printf-formatting attributes.
4662 unsigned FormatIdx;
4663 bool HasVAListArg;
4664 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004665 if (!FD->getAttr<FormatAttr>())
Ted Kremenek7f4945a2010-02-11 05:28:37 +00004666 FD->addAttr(::new (Context) FormatAttr(Context, "printf", FormatIdx+1,
4667 HasVAListArg ? 0 : FormatIdx+2));
Douglas Gregore711f702009-02-14 18:57:46 +00004668 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00004669
4670 // Mark const if we don't care about errno and that is the only
4671 // thing preventing the function from being const. This allows
4672 // IRgen to use LLVM intrinsics for such functions.
4673 if (!getLangOptions().MathErrno &&
4674 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004675 if (!FD->getAttr<ConstAttr>())
4676 FD->addAttr(::new (Context) ConstAttr());
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00004677 }
Mike Stumpca6c8752009-07-27 19:14:18 +00004678
4679 if (Context.BuiltinInfo.isNoReturn(BuiltinID))
John McCallab26cfa2010-02-05 21:31:56 +00004680 FD->setType(Context.getNoReturnType(FD->getType()));
Chris Lattner8977c432009-12-30 22:06:22 +00004681 if (Context.BuiltinInfo.isNoThrow(BuiltinID))
4682 FD->addAttr(::new (Context) NoThrowAttr());
4683 if (Context.BuiltinInfo.isConst(BuiltinID))
4684 FD->addAttr(::new (Context) ConstAttr());
Douglas Gregore711f702009-02-14 18:57:46 +00004685 }
4686
4687 IdentifierInfo *Name = FD->getIdentifier();
4688 if (!Name)
4689 return;
Mike Stump11289f42009-09-09 15:08:12 +00004690 if ((!getLangOptions().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00004691 FD->getDeclContext()->isTranslationUnit()) ||
4692 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00004693 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +00004694 LinkageSpecDecl::lang_c)) {
4695 // Okay: this could be a libc/libm/Objective-C function we know
4696 // about.
4697 } else
4698 return;
4699
Douglas Gregorfedd4282009-04-22 20:56:09 +00004700 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
Mike Stump82a9e442009-07-28 00:07:08 +00004701 // FIXME: NSLog and NSLogv should be target specific
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004702 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
Douglas Gregore711f702009-02-14 18:57:46 +00004703 // FIXME: We known better than our headers.
Ted Kremenek7f4945a2010-02-11 05:28:37 +00004704 const_cast<FormatAttr *>(Format)->setType(Context, "printf");
Mike Stump11289f42009-09-09 15:08:12 +00004705 } else
Ted Kremenek7f4945a2010-02-11 05:28:37 +00004706 FD->addAttr(::new (Context) FormatAttr(Context, "printf", 1,
Eli Friedmanf4799842009-06-10 04:01:38 +00004707 Name->isStr("NSLogv") ? 0 : 2));
Douglas Gregorfedd4282009-04-22 20:56:09 +00004708 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +00004709 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +00004710 // target-specific builtins, perhaps?
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004711 if (!FD->getAttr<FormatAttr>())
Ted Kremenek7f4945a2010-02-11 05:28:37 +00004712 FD->addAttr(::new (Context) FormatAttr(Context, "printf", 2,
Eli Friedmanf4799842009-06-10 04:01:38 +00004713 Name->isStr("vasprintf") ? 0 : 3));
Mike Stumpa4de80b2009-07-28 02:25:19 +00004714 }
Douglas Gregore711f702009-02-14 18:57:46 +00004715}
Chris Lattner302b4be2006-11-19 02:31:38 +00004716
John McCall703a3f82009-10-24 08:00:42 +00004717TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00004718 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +00004719 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00004720 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +00004721
John McCallbcd03502009-12-07 02:54:59 +00004722 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +00004723 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +00004724 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +00004725 }
4726
Chris Lattner18b19622007-01-22 07:39:13 +00004727 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004728 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
4729 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +00004730 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +00004731 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004732
John McCallb2e195a2009-09-05 06:31:47 +00004733 if (const TagType *TT = T->getAs<TagType>()) {
Anders Carlsson02751152009-03-10 17:07:44 +00004734 TagDecl *TD = TT->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004735
Anders Carlsson02751152009-03-10 17:07:44 +00004736 // If the TagDecl that the TypedefDecl points to is an anonymous decl
4737 // keep track of the TypedefDecl.
4738 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
4739 TD->setTypedefForAnonDecl(NewTD);
4740 }
4741
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004742 if (D.isInvalidType())
Steve Narofff93b6722007-08-28 20:14:24 +00004743 NewTD->setInvalidDecl();
4744 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00004745}
4746
Douglas Gregord9034f02009-05-14 16:41:31 +00004747
4748/// \brief Determine whether a tag with a given kind is acceptable
4749/// as a redeclaration of the given tag declaration.
4750///
4751/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004752bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Douglas Gregord9034f02009-05-14 16:41:31 +00004753 TagDecl::TagKind NewTag,
4754 SourceLocation NewTagLoc,
4755 const IdentifierInfo &Name) {
4756 // C++ [dcl.type.elab]p3:
4757 // The class-key or enum keyword present in the
4758 // elaborated-type-specifier shall agree in kind with the
4759 // declaration to which the name in theelaborated-type-specifier
4760 // refers. This rule also applies to the form of
4761 // elaborated-type-specifier that declares a class-name or
4762 // friend class since it can be construed as referring to the
4763 // definition of the class. Thus, in any
4764 // elaborated-type-specifier, the enum keyword shall be used to
4765 // refer to an enumeration (7.2), the union class-keyshall be
4766 // used to refer to a union (clause 9), and either the class or
4767 // struct class-key shall be used to refer to a class (clause 9)
4768 // declared using the class or struct class-key.
4769 TagDecl::TagKind OldTag = Previous->getTagKind();
4770 if (OldTag == NewTag)
4771 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004772
Douglas Gregord9034f02009-05-14 16:41:31 +00004773 if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) &&
4774 (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) {
4775 // Warn about the struct/class tag mismatch.
4776 bool isTemplate = false;
4777 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
4778 isTemplate = Record->getDescribedClassTemplate();
4779
4780 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
4781 << (NewTag == TagDecl::TK_class)
4782 << isTemplate << &Name
Douglas Gregora771f462010-03-31 17:46:05 +00004783 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Douglas Gregord9034f02009-05-14 16:41:31 +00004784 OldTag == TagDecl::TK_class? "class" : "struct");
4785 Diag(Previous->getLocation(), diag::note_previous_use);
4786 return true;
4787 }
4788 return false;
4789}
4790
Steve Naroff30d242c2007-09-15 18:49:24 +00004791/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00004792/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +00004793/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +00004794/// reference/declaration/definition of a tag.
John McCall9bb74a52009-07-31 02:45:11 +00004795Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004796 SourceLocation KWLoc, CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00004797 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregord6ab8742009-05-28 23:31:59 +00004798 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004799 MultiTemplateParamsArg TemplateParameterLists,
John McCall7f41d982009-09-11 04:59:25 +00004800 bool &OwnedDecl, bool &IsDependent) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00004801 // If this is not a definition, it must have a name.
John McCall9bb74a52009-07-31 02:45:11 +00004802 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +00004803 "Nameless record must be a definition!");
Douglas Gregorded2d7b2009-02-04 19:02:06 +00004804
Douglas Gregord6ab8742009-05-28 23:31:59 +00004805 OwnedDecl = false;
John McCall06f6fe8d2009-09-04 01:14:41 +00004806 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00004807
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004808 // FIXME: Check explicit specializations more carefully.
4809 bool isExplicitSpecialization = false;
John McCall9bb74a52009-07-31 02:45:11 +00004810 if (TUK != TUK_Reference) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00004811 if (TemplateParameterList *TemplateParams
4812 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
4813 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004814 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00004815 TUK == TUK_Friend,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004816 isExplicitSpecialization)) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00004817 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00004818 // This is a declaration or definition of a class template (which may
4819 // be a member of another template).
4820 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +00004821 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004822 SS, Name, NameLoc, Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004823 TemplateParams,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004824 AS);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004825 TemplateParameterLists.release();
Douglas Gregore93e46c2009-07-22 23:48:44 +00004826 return Result.get();
4827 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004828 // The "template<>" header is extraneous.
4829 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
4830 << ElaboratedType::getNameForTagKind(Kind) << Name;
4831 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +00004832 }
Mike Stump11289f42009-09-09 15:08:12 +00004833 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004834
4835 TemplateParameterLists.release();
Mike Stump11289f42009-09-09 15:08:12 +00004836 }
4837
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00004838 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00004839 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +00004840 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +00004841 bool Invalid = false;
4842
Chandler Carrutha419dbb2010-03-01 21:17:36 +00004843 RedeclarationKind Redecl = ForRedeclaration;
4844 if (TUK == TUK_Friend || TUK == TUK_Reference)
4845 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +00004846
4847 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
John McCall6538c932009-10-10 05:48:19 +00004848
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00004849 if (Name && SS.isNotEmpty()) {
4850 // We have a nested-name tag ('struct foo::bar').
4851
4852 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00004853 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00004854 Name = 0;
4855 goto CreateNewDecl;
4856 }
4857
John McCall7f41d982009-09-11 04:59:25 +00004858 // If this is a friend or a reference to a class in a dependent
4859 // context, don't try to make a decl for it.
4860 if (TUK == TUK_Friend || TUK == TUK_Reference) {
4861 DC = computeDeclContext(SS, false);
4862 if (!DC) {
4863 IsDependent = true;
4864 return DeclPtrTy();
4865 }
4866 }
4867
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004868 if (RequireCompleteDeclContext(SS))
4869 return DeclPtrTy::make((Decl *)0);
4870
Douglas Gregord8d297c2009-07-21 23:53:31 +00004871 DC = computeDeclContext(SS, true);
Douglas Gregor8761da52009-02-03 00:34:39 +00004872 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00004873 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +00004874 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +00004875
John McCall1f82f242009-11-18 22:49:29 +00004876 if (Previous.isAmbiguous())
John McCall6538c932009-10-10 05:48:19 +00004877 return DeclPtrTy();
John McCall6538c932009-10-10 05:48:19 +00004878
John McCall1f82f242009-11-18 22:49:29 +00004879 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00004880 // Name lookup did not find anything. However, if the
4881 // nested-name-specifier refers to the current instantiation,
4882 // and that current instantiation has any dependent base
4883 // classes, we might find something at instantiation time: treat
4884 // this as a dependent elaborated-type-specifier.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00004885 if (Previous.wasNotFoundInCurrentInstantiation()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00004886 IsDependent = true;
4887 return DeclPtrTy();
4888 }
4889
4890 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +00004891 Diag(NameLoc, diag::err_not_tag_in_scope)
4892 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00004893 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004894 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00004895 goto CreateNewDecl;
4896 }
Chris Lattnerd9773512009-01-21 02:38:50 +00004897 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00004898 // If this is a named struct, check to see if there was a previous forward
4899 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +00004900 // FIXME: We're looking into outer scopes here, even when we
4901 // shouldn't be. Doing so can result in ambiguities that we
4902 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +00004903 LookupName(Previous, S);
4904
4905 // Note: there used to be some attempt at recovery here.
4906 if (Previous.isAmbiguous())
4907 return DeclPtrTy();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004908
John McCall9bb74a52009-07-31 02:45:11 +00004909 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004910 // FIXME: This makes sure that we ignore the contexts associated
4911 // with C structs, unions, and enums when looking for a matching
4912 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +00004913 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00004914 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
4915 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004916 }
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00004917 }
4918
John McCall1f82f242009-11-18 22:49:29 +00004919 if (Previous.isSingleResult() &&
4920 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00004921 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +00004922 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +00004923 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00004924 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00004925 }
4926
Douglas Gregor87f54062009-09-15 22:30:29 +00004927 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
4928 DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) {
4929 // This is a declaration of or a reference to "std::bad_alloc".
4930 isStdBadAlloc = true;
4931
John McCall1f82f242009-11-18 22:49:29 +00004932 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +00004933 // std::bad_alloc has been implicitly declared (but made invisible to
4934 // name lookup). Fill in this implicit declaration as the previous
4935 // declaration, so that the declarations get chained appropriately.
John McCall1f82f242009-11-18 22:49:29 +00004936 Previous.addDecl(StdBadAlloc);
Douglas Gregor87f54062009-09-15 22:30:29 +00004937 }
4938 }
John McCall1f82f242009-11-18 22:49:29 +00004939
John McCalle9eaf8e2010-03-25 21:28:06 +00004940 // If we didn't find a previous declaration, and this is a reference
4941 // (or friend reference), move to the correct scope. In C++, we
4942 // also need to do a redeclaration lookup there, just in case
4943 // there's a shadow friend decl.
4944 if (Name && Previous.empty() &&
4945 (TUK == TUK_Reference || TUK == TUK_Friend)) {
4946 if (Invalid) goto CreateNewDecl;
4947 assert(SS.isEmpty());
4948
4949 if (TUK == TUK_Reference) {
4950 // C++ [basic.scope.pdecl]p5:
4951 // -- for an elaborated-type-specifier of the form
4952 //
4953 // class-key identifier
4954 //
4955 // if the elaborated-type-specifier is used in the
4956 // decl-specifier-seq or parameter-declaration-clause of a
4957 // function defined in namespace scope, the identifier is
4958 // declared as a class-name in the namespace that contains
4959 // the declaration; otherwise, except as a friend
4960 // declaration, the identifier is declared in the smallest
4961 // non-class, non-function-prototype scope that contains the
4962 // declaration.
4963 //
4964 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
4965 // C structs and unions.
4966 //
4967 // It is an error in C++ to declare (rather than define) an enum
4968 // type, including via an elaborated type specifier. We'll
4969 // diagnose that later; for now, declare the enum in the same
4970 // scope as we would have picked for any other tag type.
4971 //
4972 // GNU C also supports this behavior as part of its incomplete
4973 // enum types extension, while GNU C++ does not.
4974 //
4975 // Find the context where we'll be declaring the tag.
4976 // FIXME: We would like to maintain the current DeclContext as the
4977 // lexical context,
4978 while (SearchDC->isRecord())
4979 SearchDC = SearchDC->getParent();
4980
4981 // Find the scope where we'll be declaring the tag.
4982 while (S->isClassScope() ||
4983 (getLangOptions().CPlusPlus &&
4984 S->isFunctionPrototypeScope()) ||
4985 ((S->getFlags() & Scope::DeclScope) == 0) ||
4986 (S->getEntity() &&
4987 ((DeclContext *)S->getEntity())->isTransparentContext()))
4988 S = S->getParent();
4989 } else {
4990 assert(TUK == TUK_Friend);
4991 // C++ [namespace.memdef]p3:
4992 // If a friend declaration in a non-local class first declares a
4993 // class or function, the friend class or function is a member of
4994 // the innermost enclosing namespace.
4995 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +00004996 }
4997
John McCalle87beb22010-04-23 18:46:30 +00004998 // In C++, we need to do a redeclaration lookup to properly
4999 // diagnose some problems.
John McCalle9eaf8e2010-03-25 21:28:06 +00005000 if (getLangOptions().CPlusPlus) {
5001 Previous.setRedeclarationKind(ForRedeclaration);
5002 LookupQualifiedName(Previous, SearchDC);
5003 }
5004 }
5005
John McCall1f82f242009-11-18 22:49:29 +00005006 if (!Previous.empty()) {
Douglas Gregorce40e2e2010-04-12 16:00:01 +00005007 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCalle87beb22010-04-23 18:46:30 +00005008
5009 // It's okay to have a tag decl in the same scope as a typedef
5010 // which hides a tag decl in the same scope. Finding this
5011 // insanity with a redeclaration lookup can only actually happen
5012 // in C++.
5013 //
5014 // This is also okay for elaborated-type-specifiers, which is
5015 // technically forbidden by the current standard but which is
5016 // okay according to the likely resolution of an open issue;
5017 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
5018 if (getLangOptions().CPlusPlus) {
5019 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(PrevDecl)) {
5020 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
5021 TagDecl *Tag = TT->getDecl();
5022 if (Tag->getDeclName() == Name &&
5023 Tag->getDeclContext()->Equals(TD->getDeclContext())) {
5024 PrevDecl = Tag;
5025 Previous.clear();
5026 Previous.addDecl(Tag);
5027 }
5028 }
5029 }
5030 }
5031
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005032 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00005033 // If this is a use of a previous tag, or if the tag is already declared
5034 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005035 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +00005036 if (TUK == TUK_Reference || TUK == TUK_Friend ||
5037 isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00005038 // Make sure that this wasn't declared as an enum and now used as a
5039 // struct or something similar.
Douglas Gregord9034f02009-05-14 16:41:31 +00005040 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00005041 bool SafeToContinue
Douglas Gregor170512f2009-04-01 23:51:29 +00005042 = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
5043 Kind != TagDecl::TK_enum);
5044 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +00005045 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00005046 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00005047 << FixItHint::CreateReplacement(SourceRange(KWLoc),
5048 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +00005049 else
5050 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +00005051 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00005052
Mike Stump11289f42009-09-09 15:08:12 +00005053 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +00005054 Kind = PrevTagDecl->getTagKind();
5055 else {
5056 // Recover by making this an anonymous redefinition.
5057 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00005058 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +00005059 Invalid = true;
5060 }
5061 }
5062
5063 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005064 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +00005065
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005066 // FIXME: In the future, return a variant or some other clue
5067 // for the consumer of this Decl to know it doesn't own it.
5068 // For our current ASTs this shouldn't be a problem, but will
5069 // need to be changed with DeclGroups.
John McCallc3987482009-10-07 23:34:25 +00005070 if (TUK == TUK_Reference || TUK == TUK_Friend)
John McCall1f82f242009-11-18 22:49:29 +00005071 return DeclPtrTy::make(PrevTagDecl);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00005072
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005073 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +00005074 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005075 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00005076 // If we're defining a specialization and the previous definition
5077 // is from an implicit instantiation, don't emit an error
5078 // here; we'll catch this in the general case below.
5079 if (!isExplicitSpecialization ||
5080 !isa<CXXRecordDecl>(Def) ||
5081 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
5082 == TSK_ExplicitSpecialization) {
5083 Diag(NameLoc, diag::err_redefinition) << Name;
5084 Diag(Def->getLocation(), diag::note_previous_definition);
5085 // If this is a redefinition, recover by making this
5086 // struct be anonymous, which will make any later
5087 // references get the previous definition.
5088 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00005089 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +00005090 Invalid = true;
5091 }
Douglas Gregordee1be82009-01-17 00:42:38 +00005092 } else {
5093 // If the type is currently being defined, complain
5094 // about a nested redefinition.
5095 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
5096 if (Tag->isBeingDefined()) {
5097 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +00005098 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +00005099 diag::note_previous_definition);
5100 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00005101 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +00005102 Invalid = true;
5103 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005104 }
Douglas Gregordee1be82009-01-17 00:42:38 +00005105
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005106 // Okay, this is definition of a previously declared or referenced
5107 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +00005108 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005109 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005110 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +00005111 // have a definition. Just create a new decl.
5112
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005113 } else {
5114 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +00005115 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005116 // new decl/type. We set PrevDecl to NULL so that the entities
5117 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +00005118 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +00005119 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005120 // If we get here, we're going to create a new Decl. If PrevDecl
5121 // is non-NULL, it's a definition of the tag declared by
5122 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +00005123
5124
5125 // Otherwise, PrevDecl is not a tag, but was found with tag
5126 // lookup. This is only actually possible in C++, where a few
5127 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005128 } else {
John McCalle87beb22010-04-23 18:46:30 +00005129 assert(getLangOptions().CPlusPlus);
5130
5131 // Use a better diagnostic if an elaborated-type-specifier
5132 // found the wrong kind of type on the first
5133 // (non-redeclaration) lookup.
5134 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
5135 !Previous.isForRedeclaration()) {
5136 unsigned Kind = 0;
5137 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
5138 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
5139 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
5140 Diag(PrevDecl->getLocation(), diag::note_declared_at);
5141 Invalid = true;
5142
5143 // Otherwise, only diagnose if the declaration is in scope.
5144 } else if (!isDeclInScope(PrevDecl, SearchDC, S)) {
5145 // do nothing
5146
5147 // Diagnose implicit declarations introduced by elaborated types.
5148 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
5149 unsigned Kind = 0;
5150 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
5151 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
5152 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
5153 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
5154 Invalid = true;
5155
5156 // Otherwise it's a declaration. Call out a particularly common
5157 // case here.
5158 } else if (isa<TypedefDecl>(PrevDecl)) {
5159 Diag(NameLoc, diag::err_tag_definition_of_typedef)
5160 << Name
5161 << cast<TypedefDecl>(PrevDecl)->getUnderlyingType();
5162 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
5163 Invalid = true;
5164
5165 // Otherwise, diagnose.
5166 } else {
5167 // The tag name clashes with something else in the target scope,
5168 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00005169 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +00005170 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00005171 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +00005172 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00005173 }
John McCalle87beb22010-04-23 18:46:30 +00005174
5175 // The existing declaration isn't relevant to us; we're in a
5176 // new scope, so clear out the previous declaration.
5177 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +00005178 }
Chris Lattner18b19622007-01-22 07:39:13 +00005179 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00005180
Chris Lattner438e5012008-12-17 07:13:27 +00005181CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +00005182
John McCall1f82f242009-11-18 22:49:29 +00005183 TagDecl *PrevDecl = 0;
5184 if (Previous.isSingleResult())
5185 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
5186
Chris Lattnerbf0b7982007-01-23 04:27:41 +00005187 // If there is an identifier, use the location of the identifier as the
5188 // location of the decl, otherwise use the location of the struct/union
5189 // keyword.
5190 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +00005191
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005192 // Otherwise, create a new declaration. If there is a previous
5193 // declaration of the same entity, the two will be linked via
5194 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00005195 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00005196
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00005197 if (Kind == TagDecl::TK_enum) {
Chris Lattner776fac82007-06-09 00:53:06 +00005198 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
5199 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor82fe3e32009-07-21 14:46:17 +00005200 New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005201 cast_or_null<EnumDecl>(PrevDecl));
Chris Lattner5f521502007-01-25 06:27:24 +00005202 // If this is an undefined enum, warn.
John McCall9bb74a52009-07-31 02:45:11 +00005203 if (TUK != TUK_Definition && !Invalid) {
Douglas Gregord45b93b2009-03-06 18:34:03 +00005204 unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
5205 : diag::ext_forward_ref_enum;
5206 Diag(Loc, DK);
5207 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00005208 } else {
5209 // struct/union/class
5210
Chris Lattner776fac82007-06-09 00:53:06 +00005211 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
5212 // struct X { int A; } D; D should chain to X.
Douglas Gregor87f54062009-09-15 22:30:29 +00005213 if (getLangOptions().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +00005214 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor82fe3e32009-07-21 14:46:17 +00005215 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005216 cast_or_null<CXXRecordDecl>(PrevDecl));
Douglas Gregor87f54062009-09-15 22:30:29 +00005217
5218 if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit()))
5219 StdBadAlloc = cast<CXXRecordDecl>(New);
5220 } else
Douglas Gregor82fe3e32009-07-21 14:46:17 +00005221 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005222 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005223 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005224
John McCall3e11ebe2010-03-15 10:12:16 +00005225 // Maybe add qualifier info.
5226 if (SS.isNotEmpty()) {
5227 NestedNameSpecifier *NNS
5228 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5229 New->setQualifierInfo(NNS, SS.getRange());
5230 }
5231
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005232 if (Kind != TagDecl::TK_enum) {
5233 // Handle #pragma pack: if the #pragma pack stack has non-default
5234 // alignment, make up a packed attribute for this decl. These
5235 // attributes are checked when the ASTContext lays out the
5236 // structure.
5237 //
5238 // It is important for implementing the correct semantics that this
5239 // happen here (in act on tag decl). The #pragma pack stack is
5240 // maintained as a result of parser callbacks which can occur at
5241 // many points during the parsing of a struct declaration (because
5242 // the #pragma tokens are effectively skipped over during the
5243 // parsing of the struct).
Chris Lattner31180bb2009-02-17 01:09:29 +00005244 if (unsigned Alignment = getPragmaPackAlignment())
Anders Carlsson68e0b682009-08-08 18:23:56 +00005245 New->addAttr(::new (Context) PragmaPackAttr(Alignment * 8));
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005246 }
5247
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005248 // If this is a specialization of a member class (of a class template),
5249 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +00005250 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005251 Invalid = true;
5252
Douglas Gregordee1be82009-01-17 00:42:38 +00005253 if (Invalid)
5254 New->setInvalidDecl();
5255
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005256 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00005257 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005258
Douglas Gregordee1be82009-01-17 00:42:38 +00005259 // If we're declaring or defining a tag in function prototype scope
5260 // in C, note that this type can only be used within the function.
Douglas Gregor658b9552009-01-09 22:42:13 +00005261 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
5262 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
5263
Douglas Gregorc811d8f2008-12-15 16:32:14 +00005264 // Set the lexical context. If the tag has a C++ scope specifier, the
5265 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +00005266 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +00005267
John McCallaa74a0c2009-08-28 07:59:38 +00005268 // Mark this as a friend decl if applicable.
5269 if (TUK == TUK_Friend)
John McCall1f82f242009-11-18 22:49:29 +00005270 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
John McCallaa74a0c2009-08-28 07:59:38 +00005271
Anders Carlsson5558ca12009-03-26 01:19:02 +00005272 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +00005273 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +00005274 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +00005275
John McCall9bb74a52009-07-31 02:45:11 +00005276 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +00005277 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00005278
Chris Lattner18b19622007-01-22 07:39:13 +00005279 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +00005280 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +00005281 // We might be replacing an existing declaration in the lookup tables;
5282 // if so, borrow its access specifier.
5283 if (PrevDecl)
5284 New->setAccess(PrevDecl->getAccess());
5285
John McCalle9eaf8e2010-03-25 21:28:06 +00005286 DeclContext *DC = New->getDeclContext()->getLookupContext();
5287 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
5288 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +00005289 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
5290 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +00005291 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +00005292 S = getNonFieldDeclScope(S);
Douglas Gregor8761da52009-02-03 00:34:39 +00005293 PushOnScopeChains(New, S);
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00005294 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005295 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +00005296 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00005297
Douglas Gregor27821ce2009-07-07 16:35:42 +00005298 // If this is the C FILE type, notify the AST context.
5299 if (IdentifierInfo *II = New->getIdentifier())
5300 if (!New->isInvalidDecl() &&
Mike Stumpa4de80b2009-07-28 02:25:19 +00005301 New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +00005302 II->isStr("FILE"))
5303 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +00005304
Douglas Gregord6ab8742009-05-28 23:31:59 +00005305 OwnedDecl = true;
Chris Lattner83f095c2009-03-28 19:18:32 +00005306 return DeclPtrTy::make(New);
Chris Lattner18b19622007-01-22 07:39:13 +00005307}
Chris Lattner1300fb92007-01-23 23:42:53 +00005308
Chris Lattner83f095c2009-03-28 19:18:32 +00005309void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00005310 AdjustDeclIfTemplate(TagD);
Chris Lattner83f095c2009-03-28 19:18:32 +00005311 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005312
5313 // Enter the tag context.
5314 PushDeclContext(S, Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +00005315}
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005316
John McCall1c7e6ec2009-12-20 07:58:13 +00005317void Sema::ActOnStartCXXMemberDeclarations(Scope *S, DeclPtrTy TagD,
5318 SourceLocation LBraceLoc) {
5319 AdjustDeclIfTemplate(TagD);
5320 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD.getAs<Decl>());
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005321
John McCall1c7e6ec2009-12-20 07:58:13 +00005322 FieldCollector->StartClass();
5323
5324 if (!Record->getIdentifier())
5325 return;
5326
5327 // C++ [class]p2:
5328 // [...] The class-name is also inserted into the scope of the
5329 // class itself; this is known as the injected-class-name. For
5330 // purposes of access checking, the injected-class-name is treated
5331 // as if it were a public member name.
5332 CXXRecordDecl *InjectedClassName
5333 = CXXRecordDecl::Create(Context, Record->getTagKind(),
5334 CurContext, Record->getLocation(),
5335 Record->getIdentifier(),
5336 Record->getTagKeywordLoc(),
5337 Record);
5338 InjectedClassName->setImplicit();
5339 InjectedClassName->setAccess(AS_public);
5340 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
5341 InjectedClassName->setDescribedClassTemplate(Template);
5342 PushOnScopeChains(InjectedClassName, S);
5343 assert(InjectedClassName->isInjectedClassName() &&
5344 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005345}
5346
Douglas Gregor859f0ae2010-01-06 17:00:51 +00005347// Traverses the class and any nested classes, making a note of any
5348// dynamic classes that have no key function so that we can mark all of
5349// their virtual member functions as "used" at the end of the translation
5350// unit. This ensures that all functions needed by the vtable will get
5351// instantiated/synthesized.
5352static void
5353RecordDynamicClassesWithNoKeyFunction(Sema &S, CXXRecordDecl *Record,
5354 SourceLocation Loc) {
5355 // We don't look at dependent or undefined classes.
5356 if (Record->isDependentContext() || !Record->isDefinition())
5357 return;
5358
Anders Carlsson0da714a2010-02-06 02:27:10 +00005359 if (Record->isDynamicClass()) {
5360 const CXXMethodDecl *KeyFunction = S.Context.getKeyFunction(Record);
Douglas Gregor859f0ae2010-01-06 17:00:51 +00005361
Anders Carlsson0da714a2010-02-06 02:27:10 +00005362 if (!KeyFunction)
Benjamin Kramer4692faa2010-02-06 09:59:24 +00005363 S.ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(Record,
5364 Loc));
5365
5366 if ((!KeyFunction || (KeyFunction->getBody() && KeyFunction->isInlined()))
5367 && Record->getLinkage() == ExternalLinkage)
Anders Carlsson0da714a2010-02-06 02:27:10 +00005368 S.Diag(Record->getLocation(), diag::warn_weak_vtable) << Record;
5369 }
Douglas Gregor859f0ae2010-01-06 17:00:51 +00005370 for (DeclContext::decl_iterator D = Record->decls_begin(),
5371 DEnd = Record->decls_end();
5372 D != DEnd; ++D) {
5373 if (CXXRecordDecl *Nested = dyn_cast<CXXRecordDecl>(*D))
5374 RecordDynamicClassesWithNoKeyFunction(S, Nested, Loc);
5375 }
5376}
5377
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00005378void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
5379 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00005380 AdjustDeclIfTemplate(TagD);
Chris Lattner83f095c2009-03-28 19:18:32 +00005381 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00005382 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005383
5384 if (isa<CXXRecordDecl>(Tag))
5385 FieldCollector->FinishClass();
5386
5387 // Exit this scope of this tag's definition.
5388 PopDeclContext();
5389
Eli Friedmanb632e302010-03-07 05:49:51 +00005390 if (isa<CXXRecordDecl>(Tag) && !Tag->getLexicalDeclContext()->isRecord())
Douglas Gregor859f0ae2010-01-06 17:00:51 +00005391 RecordDynamicClassesWithNoKeyFunction(*this, cast<CXXRecordDecl>(Tag),
5392 RBraceLoc);
5393
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005394 // Notify the consumer that we've defined a tag.
5395 Consumer.HandleTagDeclDefinition(Tag);
5396}
Chris Lattner535b8302008-06-21 19:39:06 +00005397
John McCall2ff380a2010-03-17 00:38:33 +00005398void Sema::ActOnTagDefinitionError(Scope *S, DeclPtrTy TagD) {
5399 AdjustDeclIfTemplate(TagD);
5400 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
John McCall2ff380a2010-03-17 00:38:33 +00005401 Tag->setInvalidDecl();
5402
John McCall71ba5f22010-03-17 19:25:57 +00005403 // We're undoing ActOnTagStartDefinition here, not
5404 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
5405 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +00005406
5407 PopDeclContext();
5408}
5409
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00005410// Note that FieldName may be null for anonymous bitfields.
Mike Stump11289f42009-09-09 15:08:12 +00005411bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Eli Friedmanc96d4962009-08-15 21:55:26 +00005412 QualType FieldTy, const Expr *BitWidth,
5413 bool *ZeroWidth) {
5414 // Default to true; that shouldn't confuse checks for emptiness
5415 if (ZeroWidth)
5416 *ZeroWidth = true;
5417
Chris Lattner73bf7b42009-03-05 22:45:59 +00005418 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +00005419 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregor1efa4372009-03-11 18:59:21 +00005420 if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +00005421 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +00005422 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
5423 return true;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00005424 if (FieldName)
5425 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
5426 << FieldName << FieldTy << BitWidth->getSourceRange();
5427 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
5428 << FieldTy << BitWidth->getSourceRange();
Chris Lattner73bf7b42009-03-05 22:45:59 +00005429 }
Douglas Gregor1efa4372009-03-11 18:59:21 +00005430
5431 // If the bit-width is type- or value-dependent, don't try to check
5432 // it now.
5433 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
5434 return false;
5435
Anders Carlsson5df391e2008-12-06 20:33:04 +00005436 llvm::APSInt Value;
5437 if (VerifyIntegerConstantExpression(BitWidth, &Value))
5438 return true;
5439
Eli Friedmanc96d4962009-08-15 21:55:26 +00005440 if (Value != 0 && ZeroWidth)
5441 *ZeroWidth = false;
5442
Chris Lattner81ed6802008-12-12 04:56:04 +00005443 // Zero-width bitfield is ok for anonymous field.
5444 if (Value == 0 && FieldName)
5445 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00005446
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00005447 if (Value.isSigned() && Value.isNegative()) {
5448 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +00005449 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00005450 << FieldName << Value.toString(10);
5451 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
5452 << Value.toString(10);
5453 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00005454
Douglas Gregor1efa4372009-03-11 18:59:21 +00005455 if (!FieldTy->isDependentType()) {
5456 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00005457 if (Value.getZExtValue() > TypeSize) {
Anders Carlssond5635fe2010-04-16 15:16:32 +00005458 if (!getLangOptions().CPlusPlus) {
5459 if (FieldName)
5460 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
5461 << FieldName << (unsigned)Value.getZExtValue()
5462 << (unsigned)TypeSize;
5463
5464 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
5465 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
5466 }
5467
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00005468 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +00005469 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
5470 << FieldName << (unsigned)Value.getZExtValue()
5471 << (unsigned)TypeSize;
5472 else
5473 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
5474 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00005475 }
Douglas Gregor1efa4372009-03-11 18:59:21 +00005476 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00005477
5478 return false;
5479}
5480
Steve Naroff30d242c2007-09-15 18:49:24 +00005481/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00005482/// to create a FieldDecl object for it.
Chris Lattner83f095c2009-03-28 19:18:32 +00005483Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
Mike Stump11289f42009-09-09 15:08:12 +00005484 SourceLocation DeclStart,
Chris Lattner83f095c2009-03-28 19:18:32 +00005485 Declarator &D, ExprTy *BitfieldWidth) {
5486 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
5487 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
5488 AS_public);
5489 return DeclPtrTy::make(Res);
Chris Lattner73bf7b42009-03-05 22:45:59 +00005490}
5491
5492/// HandleField - Analyze a field of a C struct or a C++ data member.
5493///
5494FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
5495 SourceLocation DeclStart,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00005496 Declarator &D, Expr *BitWidth,
5497 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +00005498 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +00005499 SourceLocation Loc = DeclStart;
5500 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00005501
John McCallbcd03502009-12-07 02:54:59 +00005502 TypeSourceInfo *TInfo = 0;
5503 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Chris Lattner090d34c2009-04-12 22:15:02 +00005504 if (getLangOptions().CPlusPlus)
Douglas Gregor1efa4372009-03-11 18:59:21 +00005505 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00005506
Eli Friedman574c7452009-04-07 19:37:57 +00005507 DiagnoseFunctionSpecifiers(D);
5508
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005509 if (D.getDeclSpec().isThreadSpecified())
5510 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5511
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005512 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +00005513 ForRedeclaration);
Douglas Gregorf187420f2009-06-17 23:37:01 +00005514
5515 if (PrevDecl && PrevDecl->isTemplateParameter()) {
5516 // Maybe we will complain about the shadowed template parameter.
5517 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5518 // Just pretend that we didn't see the previous declaration.
5519 PrevDecl = 0;
5520 }
5521
Douglas Gregor1efa4372009-03-11 18:59:21 +00005522 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
5523 PrevDecl = 0;
5524
Steve Naroff5ec6ff72009-07-14 14:58:18 +00005525 bool Mutable
5526 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
5527 SourceLocation TSSL = D.getSourceRange().getBegin();
5528 FieldDecl *NewFD
John McCallbcd03502009-12-07 02:54:59 +00005529 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
Steve Naroff5ec6ff72009-07-14 14:58:18 +00005530 AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +00005531
5532 if (NewFD->isInvalidDecl())
5533 Record->setInvalidDecl();
5534
Douglas Gregor1efa4372009-03-11 18:59:21 +00005535 if (NewFD->isInvalidDecl() && PrevDecl) {
5536 // Don't introduce NewFD into scope; there's already something
5537 // with the same name in the same scope.
5538 } else if (II) {
5539 PushOnScopeChains(NewFD, S);
5540 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005541 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +00005542
5543 return NewFD;
5544}
5545
5546/// \brief Build a new FieldDecl and check its well-formedness.
5547///
5548/// This routine builds a new FieldDecl given the fields name, type,
5549/// record, etc. \p PrevDecl should refer to any previous declaration
5550/// with the same name and in the same scope as the field to be
5551/// created.
5552///
5553/// \returns a new FieldDecl.
5554///
Mike Stump11289f42009-09-09 15:08:12 +00005555/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00005556FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00005557 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +00005558 RecordDecl *Record, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005559 bool Mutable, Expr *BitWidth,
Steve Naroff5ec6ff72009-07-14 14:58:18 +00005560 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00005561 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +00005562 Declarator *D) {
5563 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +00005564 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005565 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005566
Douglas Gregor1efa4372009-03-11 18:59:21 +00005567 // If we receive a broken type, recover by assuming 'int' and
5568 // marking this declaration as invalid.
5569 if (T.isNull()) {
5570 InvalidDecl = true;
5571 T = Context.IntTy;
5572 }
5573
Eli Friedmand0e8de22009-12-07 00:22:08 +00005574 QualType EltTy = Context.getBaseElementType(T);
5575 if (!EltTy->isDependentType() &&
5576 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete))
5577 InvalidDecl = true;
5578
Steve Naroff8eeeb132007-05-08 21:09:37 +00005579 // C99 6.7.2.1p8: A member of a structure or union may have any type other
5580 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +00005581 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00005582 bool SizeIsNegative;
5583 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
5584 SizeIsNegative);
5585 if (!FixedTy.isNull()) {
5586 Diag(Loc, diag::warn_illegal_constant_array_size);
5587 T = FixedTy;
5588 } else {
5589 if (SizeIsNegative)
5590 Diag(Loc, diag::err_typecheck_negative_array_size);
5591 else
5592 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00005593 InvalidDecl = true;
5594 }
Steve Naroff8eeeb132007-05-08 21:09:37 +00005595 }
Mike Stump11289f42009-09-09 15:08:12 +00005596
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005597 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +00005598 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
5599 diag::err_abstract_type_in_decl,
5600 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005601 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +00005602
Eli Friedmanc96d4962009-08-15 21:55:26 +00005603 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +00005604 // If this is declared as a bit-field, check the bit-field.
Eli Friedmand0e8de22009-12-07 00:22:08 +00005605 if (!InvalidDecl && BitWidth &&
5606 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
Douglas Gregor1efa4372009-03-11 18:59:21 +00005607 InvalidDecl = true;
5608 DeleteExpr(BitWidth);
5609 BitWidth = 0;
Eli Friedmanc96d4962009-08-15 21:55:26 +00005610 ZeroWidth = false;
Anders Carlsson5df391e2008-12-06 20:33:04 +00005611 }
Mike Stump11289f42009-09-09 15:08:12 +00005612
John McCallbcd03502009-12-07 02:54:59 +00005613 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00005614 BitWidth, Mutable);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005615 if (InvalidDecl)
5616 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +00005617
Douglas Gregor1efa4372009-03-11 18:59:21 +00005618 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
5619 Diag(Loc, diag::err_duplicate_member) << II;
5620 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5621 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005622 }
5623
John McCall67da35c2010-02-04 22:26:26 +00005624 if (!InvalidDecl && getLangOptions().CPlusPlus) {
Eli Friedmanc96d4962009-08-15 21:55:26 +00005625 CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
5626
5627 if (!T->isPODType())
5628 CXXRecord->setPOD(false);
5629 if (!ZeroWidth)
5630 CXXRecord->setEmpty(false);
5631
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005632 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00005633 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
5634
5635 if (!RDecl->hasTrivialConstructor())
Eli Friedmanc96d4962009-08-15 21:55:26 +00005636 CXXRecord->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +00005637 if (!RDecl->hasTrivialCopyConstructor())
Eli Friedmanc96d4962009-08-15 21:55:26 +00005638 CXXRecord->setHasTrivialCopyConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +00005639 if (!RDecl->hasTrivialCopyAssignment())
Eli Friedmanc96d4962009-08-15 21:55:26 +00005640 CXXRecord->setHasTrivialCopyAssignment(false);
Douglas Gregor8a273912009-07-22 18:25:24 +00005641 if (!RDecl->hasTrivialDestructor())
Eli Friedmanc96d4962009-08-15 21:55:26 +00005642 CXXRecord->setHasTrivialDestructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +00005643
5644 // C++ 9.5p1: An object of a class with a non-trivial
5645 // constructor, a non-trivial copy constructor, a non-trivial
5646 // destructor, or a non-trivial copy assignment operator
5647 // cannot be a member of a union, nor can an array of such
5648 // objects.
5649 // TODO: C++0x alters this restriction significantly.
5650 if (Record->isUnion()) {
5651 // We check for copy constructors before constructors
5652 // because otherwise we'll never get complaints about
5653 // copy constructors.
5654
Anders Carlsson05bf0092010-04-22 05:40:53 +00005655 CXXSpecialMember member = CXXInvalid;
Douglas Gregor8a273912009-07-22 18:25:24 +00005656 if (!RDecl->hasTrivialCopyConstructor())
5657 member = CXXCopyConstructor;
5658 else if (!RDecl->hasTrivialConstructor())
Anders Carlsson05bf0092010-04-22 05:40:53 +00005659 member = CXXConstructor;
Douglas Gregor8a273912009-07-22 18:25:24 +00005660 else if (!RDecl->hasTrivialCopyAssignment())
5661 member = CXXCopyAssignment;
5662 else if (!RDecl->hasTrivialDestructor())
5663 member = CXXDestructor;
Douglas Gregor8a273912009-07-22 18:25:24 +00005664
Anders Carlsson05bf0092010-04-22 05:40:53 +00005665 if (member != CXXInvalid) {
Douglas Gregor8a273912009-07-22 18:25:24 +00005666 Diag(Loc, diag::err_illegal_union_member) << Name << member;
5667 DiagnoseNontrivial(RT, member);
5668 NewFD->setInvalidDecl();
5669 }
5670 }
5671 }
5672 }
5673
Douglas Gregor1efa4372009-03-11 18:59:21 +00005674 // FIXME: We need to pass in the attributes given an AST
5675 // representation, not a parser representation.
5676 if (D)
Douglas Gregor758a8692009-06-17 21:51:59 +00005677 // FIXME: What to pass instead of TUScope?
5678 ProcessDeclAttributes(TUScope, NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +00005679
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +00005680 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +00005681 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +00005682
Douglas Gregor4261e4c2009-03-11 20:50:30 +00005683 NewFD->setAccess(AS);
5684
5685 // C++ [dcl.init.aggr]p1:
5686 // An aggregate is an array or a class (clause 9) with [...] no
5687 // private or protected non-static data members (clause 11).
5688 // A POD must be an aggregate.
5689 if (getLangOptions().CPlusPlus &&
5690 (AS == AS_private || AS == AS_protected)) {
5691 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
5692 CXXRecord->setAggregate(false);
5693 CXXRecord->setPOD(false);
5694 }
5695
Steve Narofff93b6722007-08-28 20:14:24 +00005696 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00005697}
5698
Douglas Gregor8a273912009-07-22 18:25:24 +00005699/// DiagnoseNontrivial - Given that a class has a non-trivial
5700/// special member, figure out why.
5701void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
5702 QualType QT(T, 0U);
5703 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
5704
5705 // Check whether the member was user-declared.
5706 switch (member) {
Douglas Gregorfceea362010-04-22 14:36:26 +00005707 case CXXInvalid:
5708 break;
5709
Anders Carlsson05bf0092010-04-22 05:40:53 +00005710 case CXXConstructor:
Douglas Gregor8a273912009-07-22 18:25:24 +00005711 if (RD->hasUserDeclaredConstructor()) {
5712 typedef CXXRecordDecl::ctor_iterator ctor_iter;
Sebastian Redle24b1622009-10-25 22:31:45 +00005713 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
5714 const FunctionDecl *body = 0;
5715 ci->getBody(body);
Anders Carlssonb7229932010-04-20 23:32:58 +00005716 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00005717 SourceLocation CtorLoc = ci->getLocation();
5718 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5719 return;
5720 }
Sebastian Redle24b1622009-10-25 22:31:45 +00005721 }
Douglas Gregor8a273912009-07-22 18:25:24 +00005722
5723 assert(0 && "found no user-declared constructors");
5724 return;
5725 }
5726 break;
5727
5728 case CXXCopyConstructor:
5729 if (RD->hasUserDeclaredCopyConstructor()) {
5730 SourceLocation CtorLoc =
5731 RD->getCopyConstructor(Context, 0)->getLocation();
5732 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5733 return;
5734 }
5735 break;
5736
5737 case CXXCopyAssignment:
5738 if (RD->hasUserDeclaredCopyAssignment()) {
5739 // FIXME: this should use the location of the copy
5740 // assignment, not the type.
5741 SourceLocation TyLoc = RD->getSourceRange().getBegin();
5742 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
5743 return;
5744 }
5745 break;
5746
5747 case CXXDestructor:
5748 if (RD->hasUserDeclaredDestructor()) {
5749 SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation();
5750 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5751 return;
5752 }
5753 break;
5754 }
5755
5756 typedef CXXRecordDecl::base_class_iterator base_iter;
5757
5758 // Virtual bases and members inhibit trivial copying/construction,
5759 // but not trivial destruction.
5760 if (member != CXXDestructor) {
5761 // Check for virtual bases. vbases includes indirect virtual bases,
5762 // so we just iterate through the direct bases.
5763 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
5764 if (bi->isVirtual()) {
5765 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5766 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
5767 return;
5768 }
5769
5770 // Check for virtual methods.
5771 typedef CXXRecordDecl::method_iterator meth_iter;
5772 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
5773 ++mi) {
5774 if (mi->isVirtual()) {
5775 SourceLocation MLoc = mi->getSourceRange().getBegin();
5776 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
5777 return;
5778 }
5779 }
5780 }
Mike Stump11289f42009-09-09 15:08:12 +00005781
Douglas Gregor8a273912009-07-22 18:25:24 +00005782 bool (CXXRecordDecl::*hasTrivial)() const;
5783 switch (member) {
Anders Carlsson05bf0092010-04-22 05:40:53 +00005784 case CXXConstructor:
Douglas Gregor8a273912009-07-22 18:25:24 +00005785 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
5786 case CXXCopyConstructor:
5787 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
5788 case CXXCopyAssignment:
5789 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
5790 case CXXDestructor:
5791 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
5792 default:
5793 assert(0 && "unexpected special member"); return;
5794 }
5795
5796 // Check for nontrivial bases (and recurse).
5797 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005798 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
Sebastian Redl1054fae2009-10-25 17:03:50 +00005799 assert(BaseRT && "Don't know how to handle dependent bases");
Douglas Gregor8a273912009-07-22 18:25:24 +00005800 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
5801 if (!(BaseRecTy->*hasTrivial)()) {
5802 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5803 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
5804 DiagnoseNontrivial(BaseRT, member);
5805 return;
5806 }
5807 }
Mike Stump11289f42009-09-09 15:08:12 +00005808
Douglas Gregor8a273912009-07-22 18:25:24 +00005809 // Check for nontrivial members (and recurse).
5810 typedef RecordDecl::field_iterator field_iter;
5811 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
5812 ++fi) {
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005813 QualType EltTy = Context.getBaseElementType((*fi)->getType());
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005814 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00005815 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
5816
5817 if (!(EltRD->*hasTrivial)()) {
5818 SourceLocation FLoc = (*fi)->getLocation();
5819 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
5820 DiagnoseNontrivial(EltRT, member);
5821 return;
5822 }
5823 }
5824 }
5825
5826 assert(0 && "found no explanation for non-trivial member");
5827}
5828
Mike Stump11289f42009-09-09 15:08:12 +00005829/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00005830/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005831static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00005832TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00005833 switch (ivarVisibility) {
Chris Lattner79ef8432008-10-12 00:28:42 +00005834 default: assert(0 && "Unknown visitibility kind");
5835 case tok::objc_private: return ObjCIvarDecl::Private;
5836 case tok::objc_public: return ObjCIvarDecl::Public;
5837 case tok::objc_protected: return ObjCIvarDecl::Protected;
5838 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +00005839 }
5840}
5841
Mike Stump11289f42009-09-09 15:08:12 +00005842/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +00005843/// in order to create an IvarDecl object for it.
Chris Lattner83f095c2009-03-28 19:18:32 +00005844Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00005845 SourceLocation DeclStart,
Fariborz Jahanian68453832009-06-05 18:16:35 +00005846 DeclPtrTy IntfDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005847 Declarator &D, ExprTy *BitfieldWidth,
5848 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +00005849
Fariborz Jahaniande615832008-04-10 23:32:45 +00005850 IdentifierInfo *II = D.getIdentifier();
5851 Expr *BitWidth = (Expr*)BitfieldWidth;
5852 SourceLocation Loc = DeclStart;
5853 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00005854
Fariborz Jahaniande615832008-04-10 23:32:45 +00005855 // FIXME: Unnamed fields can be handled in various different ways, for
5856 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +00005857
John McCallbcd03502009-12-07 02:54:59 +00005858 TypeSourceInfo *TInfo = 0;
5859 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Mike Stump11289f42009-09-09 15:08:12 +00005860
Fariborz Jahaniande615832008-04-10 23:32:45 +00005861 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +00005862 // 6.7.2.1p3, 6.7.2.1p4
Chris Lattner73bf7b42009-03-05 22:45:59 +00005863 if (VerifyBitField(Loc, II, T, BitWidth)) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005864 D.setInvalidType();
Chris Lattner73bf7b42009-03-05 22:45:59 +00005865 DeleteExpr(BitWidth);
5866 BitWidth = 0;
5867 }
Fariborz Jahaniande615832008-04-10 23:32:45 +00005868 } else {
5869 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +00005870
Fariborz Jahaniande615832008-04-10 23:32:45 +00005871 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +00005872
Fariborz Jahaniande615832008-04-10 23:32:45 +00005873 }
Mike Stump11289f42009-09-09 15:08:12 +00005874
Fariborz Jahaniande615832008-04-10 23:32:45 +00005875 // C99 6.7.2.1p8: A member of a structure or union may have any type other
5876 // than a variably modified type.
5877 if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +00005878 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005879 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +00005880 }
Mike Stump11289f42009-09-09 15:08:12 +00005881
Ted Kremenek73295fa2008-07-23 18:04:17 +00005882 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +00005883 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +00005884 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
5885 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +00005886 // Must set ivar's DeclContext to its enclosing interface.
Daniel Dunbar229385c2010-04-02 18:29:09 +00005887 ObjCContainerDecl *EnclosingDecl = IntfDecl.getAs<ObjCContainerDecl>();
5888 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +00005889 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +00005890 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5891 // Case of ivar declared in an implementation. Context is that of its class.
Daniel Dunbar229385c2010-04-02 18:29:09 +00005892 EnclosingContext = IMPDecl->getClassInterface();
5893 assert(EnclosingContext && "Implementation has no class interface!");
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00005894 } else {
5895 if (ObjCCategoryDecl *CDecl =
5896 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
5897 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
5898 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
5899 return DeclPtrTy();
5900 }
5901 }
Daniel Dunbar229385c2010-04-02 18:29:09 +00005902 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00005903 }
Mike Stump11289f42009-09-09 15:08:12 +00005904
Ted Kremenek73295fa2008-07-23 18:04:17 +00005905 // Construct the decl.
Mike Stump11289f42009-09-09 15:08:12 +00005906 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00005907 EnclosingContext, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +00005908 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +00005909
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005910 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005911 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +00005912 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +00005913 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005914 && !isa<TagDecl>(PrevDecl)) {
5915 Diag(Loc, diag::err_duplicate_member) << II;
5916 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5917 NewID->setInvalidDecl();
5918 }
5919 }
5920
Ted Kremenek73295fa2008-07-23 18:04:17 +00005921 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +00005922 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +00005923
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005924 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +00005925 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +00005926
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005927 if (II) {
5928 // FIXME: When interfaces are DeclContexts, we'll need to add
5929 // these to the interface.
Chris Lattner83f095c2009-03-28 19:18:32 +00005930 S->AddDecl(DeclPtrTy::make(NewID));
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005931 IdResolver.AddDecl(NewID);
5932 }
5933
Chris Lattner83f095c2009-03-28 19:18:32 +00005934 return DeclPtrTy::make(NewID);
Fariborz Jahaniande615832008-04-10 23:32:45 +00005935}
5936
Fariborz Jahanian343f7092007-09-29 00:54:24 +00005937void Sema::ActOnFields(Scope* S,
Chris Lattner83f095c2009-03-28 19:18:32 +00005938 SourceLocation RecLoc, DeclPtrTy RecDecl,
5939 DeclPtrTy *Fields, unsigned NumFields,
Daniel Dunbar15619c72008-10-03 02:03:53 +00005940 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar325601a2008-10-03 17:33:35 +00005941 AttributeList *Attr) {
Chris Lattner83f095c2009-03-28 19:18:32 +00005942 Decl *EnclosingDecl = RecDecl.getAs<Decl>();
Steve Naroffdb47ee22007-09-14 22:20:54 +00005943 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +00005944
Chris Lattnerd13b8b52009-02-23 22:00:08 +00005945 // If the decl this is being inserted into is invalid, then it may be a
5946 // redeclaration or some other bogus case. Don't try to add fields to it.
5947 if (EnclosingDecl->isInvalidDecl()) {
5948 // FIXME: Deallocate fields?
5949 return;
5950 }
5951
Mike Stump11289f42009-09-09 15:08:12 +00005952
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00005953 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +00005954 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +00005955 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +00005956
Chris Lattnerd13b8b52009-02-23 22:00:08 +00005957 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00005958 for (unsigned i = 0; i != NumFields; ++i) {
Chris Lattner83f095c2009-03-28 19:18:32 +00005959 FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00005960
Chris Lattner720a0542007-01-25 00:44:24 +00005961 // Get the type for the field.
Chris Lattner0fd893e2007-07-31 21:33:24 +00005962 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +00005963
Douglas Gregor82ac25e2009-01-08 20:45:30 +00005964 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00005965 // Remember all fields written by the user.
5966 RecFields.push_back(FD);
5967 }
Mike Stump11289f42009-09-09 15:08:12 +00005968
Chris Lattner73bf7b42009-03-05 22:45:59 +00005969 // If the field is already invalid for some reason, don't emit more
5970 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +00005971 if (FD->isInvalidDecl()) {
5972 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +00005973 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +00005974 }
Mike Stump11289f42009-09-09 15:08:12 +00005975
Douglas Gregorac1fb652009-03-24 19:52:54 +00005976 // C99 6.7.2.1p2:
5977 // A structure or union shall not contain a member with
5978 // incomplete or function type (hence, a structure shall not
5979 // contain an instance of itself, but may contain a pointer to
5980 // an instance of itself), except that the last member of a
5981 // structure with more than one named member may have incomplete
5982 // array type; such a structure (and any union containing,
5983 // possibly recursively, a member that is such a structure)
5984 // shall not be a member of a structure or an element of an
5985 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00005986 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00005987 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +00005988 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005989 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00005990 FD->setInvalidDecl();
5991 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00005992 continue;
Douglas Gregorac1fb652009-03-24 19:52:54 +00005993 } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
5994 Record && Record->isStruct()) {
5995 // Flexible array member.
5996 if (NumNamedMembers < 1) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005997 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005998 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00005999 FD->setInvalidDecl();
6000 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00006001 continue;
6002 }
Chris Lattner720a0542007-01-25 00:44:24 +00006003 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00006004 if (Record)
6005 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +00006006 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006007 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +00006008 diag::err_field_incomplete)) {
6009 // Incomplete type
6010 FD->setInvalidDecl();
6011 EnclosingDecl->setInvalidDecl();
6012 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006013 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +00006014 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
6015 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00006016 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +00006017 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00006018 } else {
6019 // If this is a struct/class and this is not the last element, reject
6020 // it. Note that GCC supports variable sized arrays in the middle of
6021 // structures.
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00006022 if (i != NumFields-1)
6023 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +00006024 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00006025 else {
6026 // We support flexible arrays at the end of structs in
6027 // other structs as an extension.
6028 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
6029 << FD->getDeclName();
6030 if (Record)
6031 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00006032 }
Chris Lattner720a0542007-01-25 00:44:24 +00006033 }
6034 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00006035 if (Record && FDTTy->getDecl()->hasObjectMember())
6036 Record->setHasObjectMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +00006037 } else if (FDTy->isObjCInterfaceType()) {
6038 /// A field cannot be an Objective-c object
Steve Naroff32606412009-02-20 22:59:16 +00006039 Diag(FD->getLocation(), diag::err_statically_allocated_object);
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00006040 FD->setInvalidDecl();
6041 EnclosingDecl->setInvalidDecl();
6042 continue;
Mike Stump12b8ce12009-08-04 21:02:39 +00006043 } else if (getLangOptions().ObjC1 &&
6044 getLangOptions().getGCMode() != LangOptions::NonGC &&
6045 Record &&
6046 (FD->getType()->isObjCObjectPointerType() ||
6047 FD->getType().isObjCGCStrong()))
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00006048 Record->setHasObjectMember(true);
Chris Lattner82625602007-01-24 02:26:21 +00006049 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006050 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +00006051 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00006052 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006053
Chris Lattner82625602007-01-24 02:26:21 +00006054 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +00006055 if (Record) {
Douglas Gregord5058122010-02-11 01:19:42 +00006056 Record->completeDefinition();
Chris Lattner622c1932008-02-06 00:51:33 +00006057 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +00006058 ObjCIvarDecl **ClsFields =
6059 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +00006060 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner22298722009-02-20 21:35:13 +00006061 ID->setLocEnd(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +00006062 // Add ivar's to class's DeclContext.
6063 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
6064 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006065 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +00006066 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +00006067 // Must enforce the rule that ivars in the base classes may not be
6068 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00006069 if (ID->getSuperClass())
6070 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +00006071 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +00006072 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006073 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +00006074 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
6075 // Ivar declared in @implementation never belongs to the implementation.
6076 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +00006077 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +00006078 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +00006079 } else if (ObjCCategoryDecl *CDecl =
6080 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00006081 // case of ivars in class extension; all other cases have been
6082 // reported as errors elsewhere.
6083 // FIXME. Class extension does not have a LocEnd field.
6084 // CDecl->setLocEnd(RBrac);
6085 // Add ivar's to class extension's DeclContext.
6086 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
6087 ClsFields[i]->setLexicalDeclContext(CDecl);
6088 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +00006089 }
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00006090 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00006091 }
Daniel Dunbar325601a2008-10-03 17:33:35 +00006092
6093 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00006094 ProcessDeclAttributeList(S, Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +00006095}
6096
Douglas Gregor6791a0d2010-02-01 23:36:03 +00006097/// \brief Determine whether the given integral value is representable within
6098/// the given type T.
6099static bool isRepresentableIntegerValue(ASTContext &Context,
6100 llvm::APSInt &Value,
6101 QualType T) {
6102 assert(T->isIntegralType() && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +00006103 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +00006104
6105 if (Value.isUnsigned() || Value.isNonNegative())
6106 return Value.getActiveBits() < BitWidth;
6107
6108 return Value.getMinSignedBits() <= BitWidth;
6109}
6110
6111// \brief Given an integral type, return the next larger integral type
6112// (or a NULL type of no such type exists).
6113static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
6114 // FIXME: Int128/UInt128 support, which also needs to be introduced into
6115 // enum checking below.
6116 assert(T->isIntegralType() && "Integral type required!");
6117 const unsigned NumTypes = 4;
6118 QualType SignedIntegralTypes[NumTypes] = {
6119 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
6120 };
6121 QualType UnsignedIntegralTypes[NumTypes] = {
6122 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
6123 Context.UnsignedLongLongTy
6124 };
6125
6126 unsigned BitWidth = Context.getTypeSize(T);
6127 QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes
6128 : UnsignedIntegralTypes;
6129 for (unsigned I = 0; I != NumTypes; ++I)
6130 if (Context.getTypeSize(Types[I]) > BitWidth)
6131 return Types[I];
6132
6133 return QualType();
6134}
6135
Douglas Gregor954f6b272009-03-17 19:05:46 +00006136EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
6137 EnumConstantDecl *LastEnumConst,
6138 SourceLocation IdLoc,
6139 IdentifierInfo *Id,
6140 ExprArg val) {
6141 Expr *Val = (Expr *)val.get();
6142
Douglas Gregor6791a0d2010-02-01 23:36:03 +00006143 unsigned IntWidth = Context.Target.getIntWidth();
6144 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +00006145 QualType EltTy;
Douglas Gregorb2186fe2009-11-06 00:03:12 +00006146 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +00006147 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +00006148 EltTy = Context.DependentTy;
6149 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +00006150 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
6151 SourceLocation ExpLoc;
Douglas Gregordc70c3a2010-03-02 17:53:14 +00006152 if (!Val->isValueDependent() &&
6153 VerifyIntegerConstantExpression(Val, &EnumVal)) {
Douglas Gregorb2186fe2009-11-06 00:03:12 +00006154 Val = 0;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00006155 } else {
6156 if (!getLangOptions().CPlusPlus) {
6157 // C99 6.7.2.2p2:
6158 // The expression that defines the value of an enumeration constant
6159 // shall be an integer constant expression that has a value
6160 // representable as an int.
6161
6162 // Complain if the value is not representable in an int.
6163 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
6164 Diag(IdLoc, diag::ext_enum_value_not_int)
6165 << EnumVal.toString(10) << Val->getSourceRange()
Douglas Gregorc0b8c812010-02-17 22:40:11 +00006166 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
Douglas Gregor6791a0d2010-02-01 23:36:03 +00006167 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
6168 // Force the type of the expression to 'int'.
6169 ImpCastExprToType(Val, Context.IntTy, CastExpr::CK_IntegralCast);
6170
6171 if (Val != val.get()) {
6172 val.release();
6173 val = Val;
6174 }
6175 }
6176 }
6177
6178 // C++0x [dcl.enum]p5:
6179 // If the underlying type is not fixed, the type of each enumerator
6180 // is the type of its initializing value:
6181 // - If an initializer is specified for an enumerator, the
6182 // initializing value has the same type as the expression.
Douglas Gregorb2186fe2009-11-06 00:03:12 +00006183 EltTy = Val->getType();
6184 }
Douglas Gregor954f6b272009-03-17 19:05:46 +00006185 }
6186 }
Mike Stump11289f42009-09-09 15:08:12 +00006187
Douglas Gregor954f6b272009-03-17 19:05:46 +00006188 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +00006189 if (Enum->isDependentType())
6190 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00006191 else if (!LastEnumConst) {
6192 // C++0x [dcl.enum]p5:
6193 // If the underlying type is not fixed, the type of each enumerator
6194 // is the type of its initializing value:
6195 // - If no initializer is specified for the first enumerator, the
6196 // initializing value has an unspecified integral type.
6197 //
6198 // GCC uses 'int' for its unspecified integral type, as does
6199 // C99 6.7.2.2p3.
6200 EltTy = Context.IntTy;
6201 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +00006202 // Assign the last value + 1.
6203 EnumVal = LastEnumConst->getInitVal();
6204 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00006205 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +00006206
6207 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +00006208 if (EnumVal < LastEnumConst->getInitVal()) {
6209 // C++0x [dcl.enum]p5:
6210 // If the underlying type is not fixed, the type of each enumerator
6211 // is the type of its initializing value:
6212 //
6213 // - Otherwise the type of the initializing value is the same as
6214 // the type of the initializing value of the preceding enumerator
6215 // unless the incremented value is not representable in that type,
6216 // in which case the type is an unspecified integral type
6217 // sufficient to contain the incremented value. If no such type
6218 // exists, the program is ill-formed.
6219 QualType T = getNextLargerIntegralType(Context, EltTy);
6220 if (T.isNull()) {
6221 // There is no integral type larger enough to represent this
6222 // value. Complain, then allow the value to wrap around.
6223 EnumVal = LastEnumConst->getInitVal();
6224 EnumVal.zext(EnumVal.getBitWidth() * 2);
6225 Diag(IdLoc, diag::warn_enumerator_too_large)
6226 << EnumVal.toString(10);
6227 } else {
6228 EltTy = T;
6229 }
6230
6231 // Retrieve the last enumerator's value, extent that type to the
6232 // type that is supposed to be large enough to represent the incremented
6233 // value, then increment.
6234 EnumVal = LastEnumConst->getInitVal();
6235 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
Douglas Gregorc1cf8142010-04-15 15:53:31 +00006236 EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +00006237 ++EnumVal;
6238
6239 // If we're not in C++, diagnose the overflow of enumerator values,
6240 // which in C99 means that the enumerator value is not representable in
6241 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
6242 // permits enumerator values that are representable in some larger
6243 // integral type.
6244 if (!getLangOptions().CPlusPlus && !T.isNull())
6245 Diag(IdLoc, diag::warn_enum_value_overflow);
6246 } else if (!getLangOptions().CPlusPlus &&
6247 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
6248 // Enforce C99 6.7.2.2p2 even when we compute the next value.
6249 Diag(IdLoc, diag::ext_enum_value_not_int)
6250 << EnumVal.toString(10) << 1;
6251 }
Douglas Gregor954f6b272009-03-17 19:05:46 +00006252 }
6253 }
Mike Stump11289f42009-09-09 15:08:12 +00006254
Douglas Gregordc70c3a2010-03-02 17:53:14 +00006255 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00006256 // Make the enumerator value match the signedness and size of the
6257 // enumerator's type.
Douglas Gregorc1cf8142010-04-15 15:53:31 +00006258 EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +00006259 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
6260 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +00006261
Douglas Gregor954f6b272009-03-17 19:05:46 +00006262 val.release();
6263 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +00006264 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +00006265}
6266
6267
Chris Lattner83f095c2009-03-28 19:18:32 +00006268Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
6269 DeclPtrTy lastEnumConst,
6270 SourceLocation IdLoc,
6271 IdentifierInfo *Id,
6272 SourceLocation EqualLoc, ExprTy *val) {
6273 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
Chris Lattner4ef40012007-06-11 01:28:17 +00006274 EnumConstantDecl *LastEnumConst =
Chris Lattner83f095c2009-03-28 19:18:32 +00006275 cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
Chris Lattner4ef40012007-06-11 01:28:17 +00006276 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00006277
Chris Lattner1a76a3c2007-08-26 06:24:45 +00006278 // The scope passed in may not be a decl scope. Zip up the scope tree until
6279 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +00006280 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +00006281
Chris Lattner8116d1b2007-01-25 22:38:29 +00006282 // Verify that there isn't already something declared with this name in this
6283 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006284 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +00006285 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +00006286 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00006287 // Maybe we will complain about the shadowed template parameter.
6288 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
6289 // Just pretend that we didn't see the previous declaration.
6290 PrevDecl = 0;
6291 }
6292
6293 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +00006294 // When in C++, we may get a TagDecl with the same name; in this case the
6295 // enum constant will 'hide' the tag.
6296 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
6297 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +00006298 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00006299 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +00006300 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +00006301 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00006302 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +00006303 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner309e4862009-02-28 19:37:57 +00006304 if (Val) Val->Destroy(Context);
Chris Lattner83f095c2009-03-28 19:18:32 +00006305 return DeclPtrTy();
Chris Lattner8116d1b2007-01-25 22:38:29 +00006306 }
6307 }
Chris Lattner4ef40012007-06-11 01:28:17 +00006308
Douglas Gregor954f6b272009-03-17 19:05:46 +00006309 EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
6310 IdLoc, Id, Owned(Val));
Chris Lattner0515e4b2007-08-27 21:16:18 +00006311
Chris Lattner8116d1b2007-01-25 22:38:29 +00006312 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +00006313 if (New) {
6314 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +00006315 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +00006316 }
Douglas Gregor2f521192008-12-17 02:04:30 +00006317
Chris Lattner83f095c2009-03-28 19:18:32 +00006318 return DeclPtrTy::make(New);
Chris Lattnerc1915e22007-01-25 07:29:02 +00006319}
6320
Mike Stump6814d1c2009-05-16 07:06:02 +00006321void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
6322 SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00006323 DeclPtrTy *Elements, unsigned NumElements,
6324 Scope *S, AttributeList *Attr) {
Chris Lattner83f095c2009-03-28 19:18:32 +00006325 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
Douglas Gregor07665a62009-01-05 19:45:36 +00006326 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00006327
6328 if (Attr)
6329 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +00006330
Eli Friedmand0e60972009-12-11 01:34:50 +00006331 if (Enum->isDependentType()) {
6332 for (unsigned i = 0; i != NumElements; ++i) {
6333 EnumConstantDecl *ECD =
6334 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6335 if (!ECD) continue;
6336
6337 ECD->setType(EnumType);
6338 }
6339
Douglas Gregord5058122010-02-11 01:19:42 +00006340 Enum->completeDefinition(Context.DependentTy, Context.DependentTy);
Eli Friedmand0e60972009-12-11 01:34:50 +00006341 return;
6342 }
6343
Chris Lattner67933c02007-08-28 05:10:31 +00006344 // TODO: If the result value doesn't fit in an int, it must be a long or long
6345 // long value. ISO C does not support this, but GCC does as an extension,
6346 // emit a warning.
Chris Lattner37e05872008-03-05 18:54:05 +00006347 unsigned IntWidth = Context.Target.getIntWidth();
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00006348 unsigned CharWidth = Context.Target.getCharWidth();
6349 unsigned ShortWidth = Context.Target.getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +00006350
Chris Lattnerb8a501c2007-08-28 06:15:15 +00006351 // Verify that all the values are okay, compute the size of the values, and
6352 // reverse the list.
6353 unsigned NumNegativeBits = 0;
6354 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +00006355
Chris Lattnerb8a501c2007-08-28 06:15:15 +00006356 // Keep track of whether all elements have type int.
6357 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +00006358
Chris Lattnerc1915e22007-01-25 07:29:02 +00006359 for (unsigned i = 0; i != NumElements; ++i) {
6360 EnumConstantDecl *ECD =
Chris Lattner83f095c2009-03-28 19:18:32 +00006361 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
Chris Lattnerc1915e22007-01-25 07:29:02 +00006362 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +00006363
Chris Lattnerbf478cb2007-08-28 05:27:00 +00006364 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +00006365
Chris Lattnerb8a501c2007-08-28 06:15:15 +00006366 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +00006367 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +00006368 NumPositiveBits = std::max(NumPositiveBits,
6369 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +00006370 else
Chris Lattner49f980c2008-01-14 21:47:29 +00006371 NumNegativeBits = std::max(NumNegativeBits,
6372 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00006373
Chris Lattnerb8a501c2007-08-28 06:15:15 +00006374 // Keep track of whether every enum element has type int (very commmon).
6375 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +00006376 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +00006377 }
Mike Stump11289f42009-09-09 15:08:12 +00006378
Chris Lattnerb8a501c2007-08-28 06:15:15 +00006379 // Figure out the type that should be used for this enum.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00006380 // FIXME: Support -fshort-enums.
Chris Lattnerb8a501c2007-08-28 06:15:15 +00006381 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00006382 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00006383
John McCall56774992009-12-09 09:09:27 +00006384 // C++0x N3000 [conv.prom]p3:
6385 // An rvalue of an unscoped enumeration type whose underlying
6386 // type is not fixed can be converted to an rvalue of the first
6387 // of the following types that can represent all the values of
6388 // the enumeration: int, unsigned int, long int, unsigned long
6389 // int, long long int, or unsigned long long int.
6390 // C99 6.4.4.3p2:
6391 // An identifier declared as an enumeration constant has type int.
6392 // The C99 rule is modified by a gcc extension
6393 QualType BestPromotionType;
6394
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00006395 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
6396
Chris Lattnerb8a501c2007-08-28 06:15:15 +00006397 if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +00006398 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +00006399 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00006400 // If it's packed, check also if it fits a char or a short.
6401 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +00006402 BestType = Context.SignedCharTy;
6403 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +00006404 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00006405 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +00006406 BestType = Context.ShortTy;
6407 BestWidth = ShortWidth;
6408 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00006409 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00006410 BestWidth = IntWidth;
6411 } else {
Chris Lattner37e05872008-03-05 18:54:05 +00006412 BestWidth = Context.Target.getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +00006413
John McCall56774992009-12-09 09:09:27 +00006414 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00006415 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +00006416 } else {
Chris Lattner37e05872008-03-05 18:54:05 +00006417 BestWidth = Context.Target.getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +00006418
Chris Lattner3a370bf2007-08-29 17:31:48 +00006419 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00006420 Diag(Enum->getLocation(), diag::warn_enum_too_large);
6421 BestType = Context.LongLongTy;
6422 }
6423 }
John McCall56774992009-12-09 09:09:27 +00006424 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +00006425 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +00006426 // If there is no negative value, figure out the smallest type that fits
6427 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00006428 // If it's packed, check also if it fits a char or a short.
6429 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +00006430 BestType = Context.UnsignedCharTy;
6431 BestPromotionType = Context.IntTy;
6432 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00006433 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +00006434 BestType = Context.UnsignedShortTy;
6435 BestPromotionType = Context.IntTy;
6436 BestWidth = ShortWidth;
6437 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00006438 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00006439 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +00006440 BestPromotionType
6441 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6442 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00006443 } else if (NumPositiveBits <=
Chris Lattner37e05872008-03-05 18:54:05 +00006444 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00006445 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +00006446 BestPromotionType
6447 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6448 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +00006449 } else {
6450 BestWidth = Context.Target.getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +00006451 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00006452 "How could an initializer get larger than ULL?");
6453 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +00006454 BestPromotionType
6455 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6456 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00006457 }
6458 }
Mike Stump11289f42009-09-09 15:08:12 +00006459
Chris Lattner3a370bf2007-08-29 17:31:48 +00006460 // Loop over all of the enumerator constants, changing their types to match
6461 // the type of the enum if needed.
6462 for (unsigned i = 0; i != NumElements; ++i) {
6463 EnumConstantDecl *ECD =
Chris Lattner83f095c2009-03-28 19:18:32 +00006464 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
Chris Lattner3a370bf2007-08-29 17:31:48 +00006465 if (!ECD) continue; // Already issued a diagnostic.
6466
6467 // Standard C says the enumerators have int type, but we allow, as an
6468 // extension, the enumerators to be larger than int size. If each
6469 // enumerator value fits in an int, type it as an int, otherwise type it the
6470 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
6471 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +00006472
6473 // Determine whether the value fits into an int.
6474 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +00006475
6476 // If it fits into an integer type, force it. Otherwise force it to match
6477 // the enum decl type.
6478 QualType NewTy;
6479 unsigned NewWidth;
6480 bool NewSign;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00006481 if (!getLangOptions().CPlusPlus &&
6482 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +00006483 NewTy = Context.IntTy;
6484 NewWidth = IntWidth;
6485 NewSign = true;
6486 } else if (ECD->getType() == BestType) {
6487 // Already the right type!
Douglas Gregor1d248c52008-12-12 02:00:36 +00006488 if (getLangOptions().CPlusPlus)
6489 // C++ [dcl.enum]p4: Following the closing brace of an
6490 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +00006491 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +00006492 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +00006493 continue;
6494 } else {
6495 NewTy = BestType;
6496 NewWidth = BestWidth;
6497 NewSign = BestType->isSignedIntegerType();
6498 }
6499
6500 // Adjust the APSInt value.
6501 InitVal.extOrTrunc(NewWidth);
6502 InitVal.setIsSigned(NewSign);
6503 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +00006504
Chris Lattner3a370bf2007-08-29 17:31:48 +00006505 // Adjust the Expr initializer and type.
Chris Lattnere53c0362009-01-15 19:19:42 +00006506 if (ECD->getInitExpr())
Mike Stump11289f42009-09-09 15:08:12 +00006507 ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
Eli Friedman06ed2a52009-10-20 08:27:19 +00006508 CastExpr::CK_IntegralCast,
Mike Stump11289f42009-09-09 15:08:12 +00006509 ECD->getInitExpr(),
Anders Carlsson975979382010-04-23 22:18:37 +00006510 /*InheritancePath=*/0,
Ted Kremenek5a201952009-02-07 01:47:29 +00006511 /*isLvalue=*/false));
Douglas Gregor1d248c52008-12-12 02:00:36 +00006512 if (getLangOptions().CPlusPlus)
6513 // C++ [dcl.enum]p4: Following the closing brace of an
6514 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +00006515 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +00006516 ECD->setType(EnumType);
6517 else
6518 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +00006519 }
Mike Stump11289f42009-09-09 15:08:12 +00006520
Douglas Gregord5058122010-02-11 01:19:42 +00006521 Enum->completeDefinition(BestType, BestPromotionType);
Chris Lattnerc1915e22007-01-25 07:29:02 +00006522}
Chris Lattner1300fb92007-01-23 23:42:53 +00006523
Chris Lattner83f095c2009-03-28 19:18:32 +00006524Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
6525 ExprArg expr) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00006526 StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
Sebastian Redlc675bab2008-12-13 16:23:55 +00006527
Douglas Gregor278f52e2009-05-30 00:08:05 +00006528 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
6529 Loc, AsmString);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006530 CurContext->addDecl(New);
Douglas Gregor278f52e2009-05-30 00:08:05 +00006531 return DeclPtrTy::make(New);
Anders Carlsson5c6c0592008-02-08 00:33:21 +00006532}
Eli Friedman5ed51982009-06-05 02:44:36 +00006533
6534void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
6535 SourceLocation PragmaLoc,
6536 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006537 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +00006538
Eli Friedman5ed51982009-06-05 02:44:36 +00006539 if (PrevDecl) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006540 PrevDecl->addAttr(::new (Context) WeakAttr());
Ryan Flynn7d470f32009-07-30 03:15:39 +00006541 } else {
6542 (void)WeakUndeclaredIdentifiers.insert(
6543 std::pair<IdentifierInfo*,WeakInfo>
6544 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +00006545 }
Eli Friedman5ed51982009-06-05 02:44:36 +00006546}
6547
6548void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
6549 IdentifierInfo* AliasName,
6550 SourceLocation PragmaLoc,
6551 SourceLocation NameLoc,
6552 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006553 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
6554 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +00006555 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +00006556
Eli Friedman5ed51982009-06-05 02:44:36 +00006557 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +00006558 if (!PrevDecl->hasAttr<AliasAttr>())
6559 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +00006560 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +00006561 } else {
6562 (void)WeakUndeclaredIdentifiers.insert(
6563 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +00006564 }
Eli Friedman5ed51982009-06-05 02:44:36 +00006565}