blob: ad83908e4512944e7d72a9fdaa66687d461667b8 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6953a072008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner33aad6e2008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallSet.h"
28using namespace clang;
29
Argiris Kirtzidis46403632008-08-01 10:35:27 +000030Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
Steve Naroff6384a012008-04-02 14:35:35 +000031 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
32
Douglas Gregor1d661552008-04-13 21:07:44 +000033 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
34 isa<ObjCInterfaceDecl>(IIDecl) ||
35 isa<TagDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000036 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000037 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000038}
39
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000040DeclContext *Sema::getDCParent(DeclContext *DC) {
41 // If CurContext is a ObjC method, getParent() will return NULL.
42 if (isa<ObjCMethodDecl>(DC))
43 return Context.getTranslationUnitDecl();
44
45 // A C++ inline method is parsed *after* the topmost class it was declared in
46 // is fully parsed (it's "complete").
47 // The parsing of a C++ inline method happens at the declaration context of
48 // the topmost (non-nested) class it is declared in.
49 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
50 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
51 DC = MD->getParent();
52 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
53 DC = RD;
54
55 // Return the declaration context of the topmost class the inline method is
56 // declared in.
57 return DC;
58 }
59
60 return DC->getParent();
61}
62
Chris Lattneref87a202008-04-22 18:39:57 +000063void Sema::PushDeclContext(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000064 assert(getDCParent(DC) == CurContext &&
65 "The next DeclContext should be directly contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000066 CurContext = DC;
Chris Lattnereee57c02008-04-04 06:12:32 +000067}
68
Chris Lattnerf3874bc2008-04-06 04:47:34 +000069void Sema::PopDeclContext() {
70 assert(CurContext && "DeclContext imbalance!");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000071 CurContext = getDCParent(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +000072}
73
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000074/// Add this decl to the scope shadowed decl chains.
75void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000076 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000077
78 // C++ [basic.scope]p4:
79 // -- exactly one declaration shall declare a class name or
80 // enumeration name that is not a typedef name and the other
81 // declarations shall all refer to the same object or
82 // enumerator, or all refer to functions and function templates;
83 // in this case the class name or enumeration name is hidden.
84 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
85 // We are pushing the name of a tag (enum or class).
Argiris Kirtzidis94805232008-07-17 17:49:50 +000086 IdentifierResolver::iterator
87 I = IdResolver.begin(TD->getIdentifier(),
88 TD->getDeclContext(), false/*LookInParentCtx*/);
89 if (I != IdResolver.end() &&
90 IdResolver.isDeclInScope(*I, TD->getDeclContext(), S)) {
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000091 // There is already a declaration with the same name in the same
92 // scope. It must be found before we find the new declaration,
93 // so swap the order on the shadowed declaration chain.
94
Argiris Kirtzidis94805232008-07-17 17:49:50 +000095 IdResolver.AddShadowedDecl(TD, *I);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000096 return;
97 }
98 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000099 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000100}
101
Steve Naroff9637a9b2007-10-09 22:01:59 +0000102void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000103 if (S->decl_empty()) return;
104 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000105
Chris Lattner4b009652007-07-25 00:24:17 +0000106 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
107 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000108 Decl *TmpD = static_cast<Decl*>(*I);
109 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000110
111 if (isa<CXXFieldDecl>(TmpD)) continue;
112
113 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
114 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000115
Chris Lattner4b009652007-07-25 00:24:17 +0000116 IdentifierInfo *II = D->getIdentifier();
117 if (!II) continue;
118
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000119 // We only want to remove the decls from the identifier decl chains for local
120 // scopes, when inside a function/method.
121 if (S->getFnParent() != 0)
122 IdResolver.RemoveDecl(D);
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000123
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000124 // Chain this decl to the containing DeclContext.
125 D->setNext(CurContext->getDeclChain());
126 CurContext->setDeclChain(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000127 }
128}
129
Steve Naroffe57c21a2008-04-01 23:04:06 +0000130/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
131/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000132ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000133 // The third "scope" argument is 0 since we aren't enabling lazy built-in
134 // creation from this context.
135 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000136
Steve Naroff6384a012008-04-02 14:35:35 +0000137 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000138}
139
Steve Naroffe57c21a2008-04-01 23:04:06 +0000140/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000141/// namespace.
Steve Naroff6384a012008-04-02 14:35:35 +0000142Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
143 Scope *S, bool enableLazyBuiltinCreation) {
Chris Lattner4b009652007-07-25 00:24:17 +0000144 if (II == 0) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000145 unsigned NS = NSI;
146 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
147 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000148
Chris Lattner4b009652007-07-25 00:24:17 +0000149 // Scan up the scope chain looking for a decl that matches this identifier
150 // that is in the appropriate namespace. This search should not take long, as
151 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000152 for (IdentifierResolver::iterator
Argiris Kirtzidis94805232008-07-17 17:49:50 +0000153 I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I)
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000154 if ((*I)->getIdentifierNamespace() & NS)
155 return *I;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000156
Chris Lattner4b009652007-07-25 00:24:17 +0000157 // If we didn't find a use of this identifier, and if the identifier
158 // corresponds to a compiler builtin, create the decl object for the builtin
159 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1d661552008-04-13 21:07:44 +0000160 if (NS & Decl::IDNS_Ordinary) {
Steve Naroff6384a012008-04-02 14:35:35 +0000161 if (enableLazyBuiltinCreation) {
162 // If this is a builtin on this (or all) targets, create the decl.
163 if (unsigned BuiltinID = II->getBuiltinID())
164 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
165 }
Steve Naroffe57c21a2008-04-01 23:04:06 +0000166 if (getLangOptions().ObjC1) {
167 // @interface and @compatibility_alias introduce typedef-like names.
168 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000169 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000170 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000171 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
172 if (IDI != ObjCInterfaceDecls.end())
173 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000174 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
175 if (I != ObjCAliasDecls.end())
176 return I->second->getClassInterface();
177 }
Chris Lattner4b009652007-07-25 00:24:17 +0000178 }
179 return 0;
180}
181
Chris Lattnera9c87f22008-05-05 22:18:14 +0000182void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000183 if (!Context.getBuiltinVaListType().isNull())
184 return;
185
186 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000187 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000188 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000189 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
190}
191
Chris Lattner4b009652007-07-25 00:24:17 +0000192/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
193/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000194ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
195 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000196 Builtin::ID BID = (Builtin::ID)bid;
197
Anders Carlsson36760332007-10-15 20:28:48 +0000198 if (BID == Builtin::BI__builtin_va_start ||
Chris Lattnera9c87f22008-05-05 22:18:14 +0000199 BID == Builtin::BI__builtin_va_copy ||
Chris Lattnerdf40dbf2008-07-09 17:26:36 +0000200 BID == Builtin::BI__builtin_va_end ||
201 BID == Builtin::BI__builtin_stdarg_start)
Anders Carlsson36760332007-10-15 20:28:48 +0000202 InitBuiltinVaListType();
203
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000204 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000205 FunctionDecl *New = FunctionDecl::Create(Context,
206 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000207 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000208 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000209
Chris Lattnera9c87f22008-05-05 22:18:14 +0000210 // Create Decl objects for each parameter, adding them to the
211 // FunctionDecl.
212 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
213 llvm::SmallVector<ParmVarDecl*, 16> Params;
214 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
215 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
216 FT->getArgType(i), VarDecl::None, 0,
217 0));
218 New->setParams(&Params[0], Params.size());
219 }
220
221
222
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000223 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000224 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000225 return New;
226}
227
228/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
229/// and scope as a previous declaration 'Old'. Figure out how to resolve this
230/// situation, merging decls or emitting diagnostics as appropriate.
231///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000232TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000233 // Verify the old decl was also a typedef.
234 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
235 if (!Old) {
236 Diag(New->getLocation(), diag::err_redefinition_different_kind,
237 New->getName());
238 Diag(OldD->getLocation(), diag::err_previous_definition);
239 return New;
240 }
241
Chris Lattnerbef8d622008-07-25 18:44:27 +0000242 // If the typedef types are not identical, reject them in all languages and
243 // with any extensions enabled.
244 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
245 Context.getCanonicalType(Old->getUnderlyingType()) !=
246 Context.getCanonicalType(New->getUnderlyingType())) {
247 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
248 New->getUnderlyingType().getAsString(),
249 Old->getUnderlyingType().getAsString());
250 Diag(Old->getLocation(), diag::err_previous_definition);
251 return Old;
252 }
253
Steve Naroffae84af82007-10-31 18:42:27 +0000254 // Allow multiple definitions for ObjC built-in typedefs.
255 // FIXME: Verify the underlying types are equivalent!
Ted Kremenek42730c52008-01-07 19:49:32 +0000256 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroffae84af82007-10-31 18:42:27 +0000257 return Old;
Eli Friedman324d5032008-06-11 06:20:39 +0000258
259 if (getLangOptions().Microsoft) return New;
260
Steve Naroffa9eae582008-01-30 23:46:05 +0000261 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
262 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
263 // *either* declaration is in a system header. The code below implements
264 // this adhoc compatibility rule. FIXME: The following code will not
265 // work properly when compiling ".i" files (containing preprocessed output).
266 SourceManager &SrcMgr = Context.getSourceManager();
Steve Naroffa9eae582008-01-30 23:46:05 +0000267 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
Eli Friedman324d5032008-06-11 06:20:39 +0000268 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
269 if (OldDeclFile) {
270 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
271 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
272 if (OldDirType != DirectoryLookup::NormalHeaderDir)
273 return New;
274 }
275 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
276 if (NewDeclFile) {
277 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
278 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
279 if (NewDirType != DirectoryLookup::NormalHeaderDir)
280 return New;
281 }
282
Ted Kremenek64845ce2008-05-23 21:28:18 +0000283 Diag(New->getLocation(), diag::err_redefinition, New->getName());
284 Diag(Old->getLocation(), diag::err_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000285 return New;
286}
287
Chris Lattner6953a072008-06-26 18:38:35 +0000288/// DeclhasAttr - returns true if decl Declaration already has the target
289/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000290static bool DeclHasAttr(const Decl *decl, const Attr *target) {
291 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
292 if (attr->getKind() == target->getKind())
293 return true;
294
295 return false;
296}
297
298/// MergeAttributes - append attributes from the Old decl to the New one.
299static void MergeAttributes(Decl *New, Decl *Old) {
300 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
301
Chris Lattner402b3372008-03-03 03:28:21 +0000302 while (attr) {
303 tmp = attr;
304 attr = attr->getNext();
305
306 if (!DeclHasAttr(New, tmp)) {
307 New->addAttr(tmp);
308 } else {
309 tmp->setNext(0);
310 delete(tmp);
311 }
312 }
Nuno Lopes77654342008-06-01 22:53:53 +0000313
314 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000315}
316
Chris Lattner3e254fb2008-04-08 04:40:51 +0000317/// MergeFunctionDecl - We just parsed a function 'New' from
318/// declarator D which has the same name and scope as a previous
319/// declaration 'Old'. Figure out how to resolve this situation,
320/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor42214c52008-04-21 02:02:58 +0000321/// Redeclaration will be set true if thisNew is a redeclaration OldD.
322FunctionDecl *
323Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
324 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000325 // Verify the old decl was also a function.
326 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
327 if (!Old) {
328 Diag(New->getLocation(), diag::err_redefinition_different_kind,
329 New->getName());
330 Diag(OldD->getLocation(), diag::err_previous_definition);
331 return New;
332 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000333
Chris Lattner42a21742008-04-06 23:10:54 +0000334 QualType OldQType = Context.getCanonicalType(Old->getType());
335 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000336
Chris Lattner3e254fb2008-04-08 04:40:51 +0000337 // C++ [dcl.fct]p3:
338 // All declarations for a function shall agree exactly in both the
339 // return type and the parameter-type-list.
Douglas Gregor42214c52008-04-21 02:02:58 +0000340 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
341 MergeAttributes(New, Old);
342 Redeclaration = true;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000343 return MergeCXXFunctionDecl(New, Old);
Douglas Gregor42214c52008-04-21 02:02:58 +0000344 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000345
346 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000347 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000348 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000349 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000350 MergeAttributes(New, Old);
351 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000352 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000353 }
Chris Lattner1470b072007-11-06 06:07:26 +0000354
Steve Naroff6c9e7922008-01-16 15:01:34 +0000355 // A function that has already been declared has been redeclared or defined
356 // with a different type- show appropriate diagnostic
Steve Naroff9104f3c2008-04-04 14:32:09 +0000357 diag::kind PrevDiag;
Douglas Gregor42214c52008-04-21 02:02:58 +0000358 if (Old->isThisDeclarationADefinition())
Steve Naroff9104f3c2008-04-04 14:32:09 +0000359 PrevDiag = diag::err_previous_definition;
360 else if (Old->isImplicit())
361 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000362 else
Steve Naroff9104f3c2008-04-04 14:32:09 +0000363 PrevDiag = diag::err_previous_declaration;
Steve Naroff6c9e7922008-01-16 15:01:34 +0000364
Chris Lattner4b009652007-07-25 00:24:17 +0000365 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
366 // TODO: This is totally simplistic. It should handle merging functions
367 // together etc, merging extern int X; int X; ...
Steve Naroff6c9e7922008-01-16 15:01:34 +0000368 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
369 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000370 return New;
371}
372
Steve Naroffb5e78152008-08-08 17:50:35 +0000373/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000374static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000375 if (VD->isFileVarDecl())
376 return (!VD->getInit() &&
377 (VD->getStorageClass() == VarDecl::None ||
378 VD->getStorageClass() == VarDecl::Static));
379 return false;
380}
381
382/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
383/// when dealing with C "tentative" external object definitions (C99 6.9.2).
384void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
385 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000386 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000387
388 for (IdentifierResolver::iterator
389 I = IdResolver.begin(VD->getIdentifier(),
390 VD->getDeclContext(), false/*LookInParentCtx*/),
391 E = IdResolver.end(); I != E; ++I) {
392 if (*I != VD && IdResolver.isDeclInScope(*I, VD->getDeclContext(), S)) {
393 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
394
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000395 // Handle the following case:
396 // int a[10];
397 // int a[]; - the code below makes sure we set the correct type.
398 // int a[11]; - this is an error, size isn't 10.
399 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
400 OldDecl->getType()->isConstantArrayType())
401 VD->setType(OldDecl->getType());
402
Steve Naroffb5e78152008-08-08 17:50:35 +0000403 // Check for "tentative" definitions. We can't accomplish this in
404 // MergeVarDecl since the initializer hasn't been attached.
405 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
406 continue;
407
408 // Handle __private_extern__ just like extern.
409 if (OldDecl->getStorageClass() != VarDecl::Extern &&
410 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
411 VD->getStorageClass() != VarDecl::Extern &&
412 VD->getStorageClass() != VarDecl::PrivateExtern) {
413 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
414 Diag(OldDecl->getLocation(), diag::err_previous_definition);
415 }
416 }
417 }
418}
419
Chris Lattner4b009652007-07-25 00:24:17 +0000420/// MergeVarDecl - We just parsed a variable 'New' which has the same name
421/// and scope as a previous declaration 'Old'. Figure out how to resolve this
422/// situation, merging decls or emitting diagnostics as appropriate.
423///
Steve Naroffb5e78152008-08-08 17:50:35 +0000424/// Tentative definition rules (C99 6.9.2p2) are checked by
425/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
426/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000427///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000428VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000429 // Verify the old decl was also a variable.
430 VarDecl *Old = dyn_cast<VarDecl>(OldD);
431 if (!Old) {
432 Diag(New->getLocation(), diag::err_redefinition_different_kind,
433 New->getName());
434 Diag(OldD->getLocation(), diag::err_previous_definition);
435 return New;
436 }
Chris Lattner402b3372008-03-03 03:28:21 +0000437
438 MergeAttributes(New, Old);
439
Chris Lattner4b009652007-07-25 00:24:17 +0000440 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000441 QualType OldCType = Context.getCanonicalType(Old->getType());
442 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff12508172008-08-09 16:04:40 +0000443 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000444 Diag(New->getLocation(), diag::err_redefinition, New->getName());
445 Diag(Old->getLocation(), diag::err_previous_definition);
446 return New;
447 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000448 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
449 if (New->getStorageClass() == VarDecl::Static &&
450 (Old->getStorageClass() == VarDecl::None ||
451 Old->getStorageClass() == VarDecl::Extern)) {
452 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
453 Diag(Old->getLocation(), diag::err_previous_definition);
454 return New;
455 }
456 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
457 if (New->getStorageClass() != VarDecl::Static &&
458 Old->getStorageClass() == VarDecl::Static) {
459 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
460 Diag(Old->getLocation(), diag::err_previous_definition);
461 return New;
462 }
Steve Naroffb5e78152008-08-08 17:50:35 +0000463 // File scoped variables are analyzed in FinalizeDeclaratorGroup.
464 if (!New->isFileVarDecl()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000465 Diag(New->getLocation(), diag::err_redefinition, New->getName());
466 Diag(Old->getLocation(), diag::err_previous_definition);
467 }
468 return New;
469}
470
Chris Lattner3e254fb2008-04-08 04:40:51 +0000471/// CheckParmsForFunctionDef - Check that the parameters of the given
472/// function are appropriate for the definition of a function. This
473/// takes care of any checks that cannot be performed on the
474/// declaration itself, e.g., that the types of each of the function
475/// parameters are complete.
476bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
477 bool HasInvalidParm = false;
478 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
479 ParmVarDecl *Param = FD->getParamDecl(p);
480
481 // C99 6.7.5.3p4: the parameters in a parameter type list in a
482 // function declarator that is part of a function definition of
483 // that function shall not have incomplete type.
484 if (Param->getType()->isIncompleteType() &&
485 !Param->isInvalidDecl()) {
486 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
487 Param->getType().getAsString());
488 Param->setInvalidDecl();
489 HasInvalidParm = true;
490 }
491 }
492
493 return HasInvalidParm;
494}
495
496/// CreateImplicitParameter - Creates an implicit function parameter
497/// in the scope S and with the given type. This routine is used, for
498/// example, to create the implicit "self" parameter in an Objective-C
499/// method.
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000500ImplicitParamDecl *
Chris Lattner3e254fb2008-04-08 04:40:51 +0000501Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
502 SourceLocation IdLoc, QualType Type) {
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000503 ImplicitParamDecl *New = ImplicitParamDecl::Create(Context, CurContext,
504 IdLoc, Id, Type, 0);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000505 if (Id)
506 PushOnScopeChains(New, S);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000507
508 return New;
509}
510
Chris Lattner4b009652007-07-25 00:24:17 +0000511/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
512/// no declarator (e.g. "struct foo;") is parsed.
513Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
514 // TODO: emit error on 'int;' or 'const enum foo;'.
515 // TODO: emit error on 'typedef int;'
516 // if (!DS.isMissingDeclaratorOk()) Diag(...);
517
Steve Naroffedafc0b2007-11-17 21:37:36 +0000518 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000519}
520
Steve Narofff0b23542008-01-10 22:15:12 +0000521bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000522 // Get the type before calling CheckSingleAssignmentConstraints(), since
523 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000524 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000525
Chris Lattner005ed752008-01-04 18:04:52 +0000526 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
527 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
528 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000529}
530
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000531bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000532 const ArrayType *AT = Context.getAsArrayType(DeclT);
533
534 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000535 // C99 6.7.8p14. We have an array of character type with unknown size
536 // being initialized to a string literal.
537 llvm::APSInt ConstVal(32);
538 ConstVal = strLiteral->getByteLength() + 1;
539 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000540 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000541 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000542 } else {
543 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000544 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000545 // FIXME: Avoid truncation for 64-bit length strings.
546 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000547 Diag(strLiteral->getSourceRange().getBegin(),
548 diag::warn_initializer_string_for_char_array_too_long,
549 strLiteral->getSourceRange());
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000550 }
551 // Set type from "char *" to "constant array of char".
552 strLiteral->setType(DeclT);
553 // For now, we always return false (meaning success).
554 return false;
555}
556
557StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000558 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +0000559 if (AT && AT->getElementType()->isCharType()) {
560 return dyn_cast<StringLiteral>(Init);
561 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000562 return 0;
563}
564
Steve Narofff3cb5142008-01-25 00:51:06 +0000565bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroff8e9337f2008-01-21 23:53:58 +0000566 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
567 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +0000568 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Steve Naroff8e9337f2008-01-21 23:53:58 +0000569 return Diag(VAT->getSizeExpr()->getLocStart(),
570 diag::err_variable_object_no_init,
571 VAT->getSizeExpr()->getSourceRange());
572
Steve Naroffcb69fb72007-12-10 22:44:33 +0000573 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
574 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000575 // FIXME: Handle wide strings
576 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
577 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000578
579 if (DeclType->isArrayType())
580 return Diag(Init->getLocStart(),
581 diag::err_array_init_list_required,
582 Init->getSourceRange());
583
Steve Narofff0b23542008-01-10 22:15:12 +0000584 return CheckSingleInitializer(Init, DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000585 }
Eli Friedman38b7a912008-06-06 19:40:52 +0000586
Steve Naroffc4d4a482008-05-01 22:18:59 +0000587 InitListChecker CheckInitList(this, InitList, DeclType);
588 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +0000589}
590
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000591Sema::DeclTy *
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000592Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000593 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000594 IdentifierInfo *II = D.getIdentifier();
595
596 // All of these full declarators require an identifier. If it doesn't have
597 // one, the ParsedFreeStandingDeclSpec action should be used.
598 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000599 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000600 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000601 D.getDeclSpec().getSourceRange(), D.getSourceRange());
602 return 0;
603 }
604
Chris Lattnera7549902007-08-26 06:24:45 +0000605 // The scope passed in may not be a decl scope. Zip up the scope tree until
606 // we find one that is.
607 while ((S->getFlags() & Scope::DeclScope) == 0)
608 S = S->getParent();
609
Chris Lattner4b009652007-07-25 00:24:17 +0000610 // See if this is a redefinition of a variable in the same scope.
Steve Naroff6384a012008-04-02 14:35:35 +0000611 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000612 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000613 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000614
615 // In C++, the previous declaration we find might be a tag type
616 // (class or enum). In this case, the new declaration will hide the
617 // tag type.
618 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
619 PrevDecl = 0;
620
Chris Lattner82bb4792007-11-14 06:34:38 +0000621 QualType R = GetTypeForDeclarator(D, S);
622 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
623
Chris Lattner4b009652007-07-25 00:24:17 +0000624 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000625 // Check that there are no default arguments (C++ only).
626 if (getLangOptions().CPlusPlus)
627 CheckExtraCXXDefaultArguments(D);
628
Chris Lattner82bb4792007-11-14 06:34:38 +0000629 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000630 if (!NewTD) return 0;
631
632 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000633 ProcessDeclAttributes(NewTD, D);
Steve Narofff8a09432008-01-09 23:34:55 +0000634 // Merge the decl with the existing one if appropriate. If the decl is
635 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000636 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000637 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
638 if (NewTD == 0) return 0;
639 }
640 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000641 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000642 // C99 6.7.7p2: If a typedef name specifies a variably modified type
643 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000644 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
645 // FIXME: Diagnostic needs to be fixed.
646 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff5eb879b2007-08-31 17:20:07 +0000647 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000648 }
649 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000650 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000651 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000652 switch (D.getDeclSpec().getStorageClassSpec()) {
653 default: assert(0 && "Unknown storage class!");
654 case DeclSpec::SCS_auto:
655 case DeclSpec::SCS_register:
656 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
657 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000658 InvalidDecl = true;
659 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000660 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
661 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
662 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000663 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000664 }
665
Chris Lattner4c7802b2008-03-15 21:24:04 +0000666 bool isInline = D.getDeclSpec().isInlineSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000667 FunctionDecl *NewFD;
668 if (D.getContext() == Declarator::MemberContext) {
669 // This is a C++ method declaration.
670 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
671 D.getIdentifierLoc(), II, R,
672 (SC == FunctionDecl::Static), isInline,
673 LastDeclarator);
674 } else {
675 NewFD = FunctionDecl::Create(Context, CurContext,
676 D.getIdentifierLoc(),
677 II, R, SC, isInline,
678 LastDeclarator);
679 }
Ted Kremenek117f1862008-02-27 22:18:07 +0000680 // Handle attributes.
Chris Lattner9b384ca2008-06-29 00:02:00 +0000681 ProcessDeclAttributes(NewFD, D);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000682
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000683 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000684 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000685 // The parser guarantees this is a string.
686 StringLiteral *SE = cast<StringLiteral>(E);
687 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
688 SE->getByteLength())));
689 }
690
Chris Lattner3e254fb2008-04-08 04:40:51 +0000691 // Copy the parameter declarations from the declarator D to
692 // the function declaration NewFD, if they are available.
Eli Friedman769e7302008-08-25 21:31:01 +0000693 if (D.getNumTypeObjects() > 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000694 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
695
696 // Create Decl objects for each parameter, adding them to the
697 // FunctionDecl.
698 llvm::SmallVector<ParmVarDecl*, 16> Params;
699
700 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
701 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +0000702 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +0000703 // We let through "const void" here because Sema::GetTypeForDeclarator
704 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000705 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
706 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +0000707 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
708 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +0000709 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
710
Chris Lattnerda7b5f02008-04-10 02:26:16 +0000711 // In C++, the empty parameter-type-list must be spelled "void"; a
712 // typedef of void is not permitted.
713 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +0000714 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +0000715 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
716 }
717
Eli Friedman769e7302008-08-25 21:31:01 +0000718 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000719 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
720 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
721 }
722
723 NewFD->setParams(&Params[0], Params.size());
724 }
725
Steve Narofff8a09432008-01-09 23:34:55 +0000726 // Merge the decl with the existing one if appropriate. Since C functions
727 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000728 if (PrevDecl &&
729 (!getLangOptions().CPlusPlus ||
730 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000731 bool Redeclaration = false;
732 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Chris Lattner4b009652007-07-25 00:24:17 +0000733 if (NewFD == 0) return 0;
Douglas Gregor42214c52008-04-21 02:02:58 +0000734 if (Redeclaration) {
Eli Friedmand2701812008-05-27 05:07:37 +0000735 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregor42214c52008-04-21 02:02:58 +0000736 }
Chris Lattner4b009652007-07-25 00:24:17 +0000737 }
738 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000739
740 // In C++, check default arguments now that we have merged decls.
741 if (getLangOptions().CPlusPlus)
742 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +0000743 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000744 // Check that there are no default arguments (C++ only).
745 if (getLangOptions().CPlusPlus)
746 CheckExtraCXXDefaultArguments(D);
747
Ted Kremenek42730c52008-01-07 19:49:32 +0000748 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000749 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
750 D.getIdentifier()->getName());
751 InvalidDecl = true;
752 }
Chris Lattner4b009652007-07-25 00:24:17 +0000753
754 VarDecl *NewVD;
755 VarDecl::StorageClass SC;
756 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +0000757 default: assert(0 && "Unknown storage class!");
758 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
759 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
760 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
761 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
762 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
763 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000764 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000765 if (D.getContext() == Declarator::MemberContext) {
766 assert(SC == VarDecl::Static && "Invalid storage class for member!");
767 // This is a static data member for a C++ class.
768 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
769 D.getIdentifierLoc(), II,
770 R, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000771 } else {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000772 if (S->getFnParent() == 0) {
773 // C99 6.9p2: The storage-class specifiers auto and register shall not
774 // appear in the declaration specifiers in an external declaration.
775 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
776 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
777 R.getAsString());
778 InvalidDecl = true;
779 }
780 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
781 II, R, SC, LastDeclarator);
782 } else {
783 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
784 II, R, SC, LastDeclarator);
785 }
Steve Naroffcae537d2007-08-28 18:45:29 +0000786 }
Chris Lattner4b009652007-07-25 00:24:17 +0000787 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000788 ProcessDeclAttributes(NewVD, D);
Nate Begemanea583262008-03-14 18:07:10 +0000789
Daniel Dunbarced89142008-08-06 00:03:29 +0000790 // Handle GNU asm-label extension (encoded as an attribute).
791 if (Expr *E = (Expr*) D.getAsmLabel()) {
792 // The parser guarantees this is a string.
793 StringLiteral *SE = cast<StringLiteral>(E);
794 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
795 SE->getByteLength())));
796 }
797
Nate Begemanea583262008-03-14 18:07:10 +0000798 // Emit an error if an address space was applied to decl with local storage.
799 // This includes arrays of objects with address space qualifiers, but not
800 // automatic variables that point to other address spaces.
801 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +0000802 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
803 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
804 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +0000805 }
Steve Narofff8a09432008-01-09 23:34:55 +0000806 // Merge the decl with the existing one if appropriate. If the decl is
807 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000808 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000809 NewVD = MergeVarDecl(NewVD, PrevDecl);
810 if (NewVD == 0) return 0;
811 }
Chris Lattner4b009652007-07-25 00:24:17 +0000812 New = NewVD;
813 }
814
815 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000816 if (II)
817 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000818 // If any semantic error occurred, mark the decl as invalid.
819 if (D.getInvalidType() || InvalidDecl)
820 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000821
822 return New;
823}
824
Eli Friedman02c22ce2008-05-20 13:48:25 +0000825bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
826 switch (Init->getStmtClass()) {
827 default:
828 Diag(Init->getExprLoc(),
829 diag::err_init_element_not_constant, Init->getSourceRange());
830 return true;
831 case Expr::ParenExprClass: {
832 const ParenExpr* PE = cast<ParenExpr>(Init);
833 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
834 }
835 case Expr::CompoundLiteralExprClass:
836 return cast<CompoundLiteralExpr>(Init)->isFileScope();
837 case Expr::DeclRefExprClass: {
838 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +0000839 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
840 if (VD->hasGlobalStorage())
841 return false;
842 Diag(Init->getExprLoc(),
843 diag::err_init_element_not_constant, Init->getSourceRange());
844 return true;
845 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000846 if (isa<FunctionDecl>(D))
847 return false;
848 Diag(Init->getExprLoc(),
849 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Narofff0b23542008-01-10 22:15:12 +0000850 return true;
851 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000852 case Expr::MemberExprClass: {
853 const MemberExpr *M = cast<MemberExpr>(Init);
854 if (M->isArrow())
855 return CheckAddressConstantExpression(M->getBase());
856 return CheckAddressConstantExpressionLValue(M->getBase());
857 }
858 case Expr::ArraySubscriptExprClass: {
859 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
860 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
861 return CheckAddressConstantExpression(ASE->getBase()) ||
862 CheckArithmeticConstantExpression(ASE->getIdx());
863 }
864 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +0000865 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +0000866 return false;
867 case Expr::UnaryOperatorClass: {
868 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
869
870 // C99 6.6p9
871 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +0000872 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +0000873
874 Diag(Init->getExprLoc(),
875 diag::err_init_element_not_constant, Init->getSourceRange());
876 return true;
877 }
878 }
879}
880
881bool Sema::CheckAddressConstantExpression(const Expr* Init) {
882 switch (Init->getStmtClass()) {
883 default:
884 Diag(Init->getExprLoc(),
885 diag::err_init_element_not_constant, Init->getSourceRange());
886 return true;
887 case Expr::ParenExprClass: {
888 const ParenExpr* PE = cast<ParenExpr>(Init);
889 return CheckAddressConstantExpression(PE->getSubExpr());
890 }
891 case Expr::StringLiteralClass:
892 case Expr::ObjCStringLiteralClass:
893 return false;
894 case Expr::CallExprClass: {
895 const CallExpr *CE = cast<CallExpr>(Init);
896 if (CE->isBuiltinConstantExpr())
897 return false;
898 Diag(Init->getExprLoc(),
899 diag::err_init_element_not_constant, Init->getSourceRange());
900 return true;
901 }
902 case Expr::UnaryOperatorClass: {
903 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
904
905 // C99 6.6p9
906 if (Exp->getOpcode() == UnaryOperator::AddrOf)
907 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
908
909 if (Exp->getOpcode() == UnaryOperator::Extension)
910 return CheckAddressConstantExpression(Exp->getSubExpr());
911
912 Diag(Init->getExprLoc(),
913 diag::err_init_element_not_constant, Init->getSourceRange());
914 return true;
915 }
916 case Expr::BinaryOperatorClass: {
917 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
918 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
919
920 Expr *PExp = Exp->getLHS();
921 Expr *IExp = Exp->getRHS();
922 if (IExp->getType()->isPointerType())
923 std::swap(PExp, IExp);
924
925 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
926 return CheckAddressConstantExpression(PExp) ||
927 CheckArithmeticConstantExpression(IExp);
928 }
Eli Friedman1fad3c62008-08-25 20:46:57 +0000929 case Expr::ImplicitCastExprClass:
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +0000930 case Expr::ExplicitCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +0000931 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +0000932 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
933 // Check for implicit promotion
934 if (SubExpr->getType()->isFunctionType() ||
935 SubExpr->getType()->isArrayType())
936 return CheckAddressConstantExpressionLValue(SubExpr);
937 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000938
939 // Check for pointer->pointer cast
940 if (SubExpr->getType()->isPointerType())
941 return CheckAddressConstantExpression(SubExpr);
942
Eli Friedman1fad3c62008-08-25 20:46:57 +0000943 if (SubExpr->getType()->isIntegralType()) {
944 // Check for the special-case of a pointer->int->pointer cast;
945 // this isn't standard, but some code requires it. See
946 // PR2720 for an example.
947 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
948 if (SubCast->getSubExpr()->getType()->isPointerType()) {
949 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
950 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
951 if (IntWidth >= PointerWidth) {
952 return CheckAddressConstantExpression(SubCast->getSubExpr());
953 }
954 }
955 }
956 }
957 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +0000958 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +0000959 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000960
961 Diag(Init->getExprLoc(),
962 diag::err_init_element_not_constant, Init->getSourceRange());
963 return true;
964 }
965 case Expr::ConditionalOperatorClass: {
966 // FIXME: Should we pedwarn here?
967 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
968 if (!Exp->getCond()->getType()->isArithmeticType()) {
969 Diag(Init->getExprLoc(),
970 diag::err_init_element_not_constant, Init->getSourceRange());
971 return true;
972 }
973 if (CheckArithmeticConstantExpression(Exp->getCond()))
974 return true;
975 if (Exp->getLHS() &&
976 CheckAddressConstantExpression(Exp->getLHS()))
977 return true;
978 return CheckAddressConstantExpression(Exp->getRHS());
979 }
980 case Expr::AddrLabelExprClass:
981 return false;
982 }
983}
984
Eli Friedman998dffb2008-06-09 05:05:07 +0000985static const Expr* FindExpressionBaseAddress(const Expr* E);
986
987static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
988 switch (E->getStmtClass()) {
989 default:
990 return E;
991 case Expr::ParenExprClass: {
992 const ParenExpr* PE = cast<ParenExpr>(E);
993 return FindExpressionBaseAddressLValue(PE->getSubExpr());
994 }
995 case Expr::MemberExprClass: {
996 const MemberExpr *M = cast<MemberExpr>(E);
997 if (M->isArrow())
998 return FindExpressionBaseAddress(M->getBase());
999 return FindExpressionBaseAddressLValue(M->getBase());
1000 }
1001 case Expr::ArraySubscriptExprClass: {
1002 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1003 return FindExpressionBaseAddress(ASE->getBase());
1004 }
1005 case Expr::UnaryOperatorClass: {
1006 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1007
1008 if (Exp->getOpcode() == UnaryOperator::Deref)
1009 return FindExpressionBaseAddress(Exp->getSubExpr());
1010
1011 return E;
1012 }
1013 }
1014}
1015
1016static const Expr* FindExpressionBaseAddress(const Expr* E) {
1017 switch (E->getStmtClass()) {
1018 default:
1019 return E;
1020 case Expr::ParenExprClass: {
1021 const ParenExpr* PE = cast<ParenExpr>(E);
1022 return FindExpressionBaseAddress(PE->getSubExpr());
1023 }
1024 case Expr::UnaryOperatorClass: {
1025 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1026
1027 // C99 6.6p9
1028 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1029 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1030
1031 if (Exp->getOpcode() == UnaryOperator::Extension)
1032 return FindExpressionBaseAddress(Exp->getSubExpr());
1033
1034 return E;
1035 }
1036 case Expr::BinaryOperatorClass: {
1037 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1038
1039 Expr *PExp = Exp->getLHS();
1040 Expr *IExp = Exp->getRHS();
1041 if (IExp->getType()->isPointerType())
1042 std::swap(PExp, IExp);
1043
1044 return FindExpressionBaseAddress(PExp);
1045 }
1046 case Expr::ImplicitCastExprClass: {
1047 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1048
1049 // Check for implicit promotion
1050 if (SubExpr->getType()->isFunctionType() ||
1051 SubExpr->getType()->isArrayType())
1052 return FindExpressionBaseAddressLValue(SubExpr);
1053
1054 // Check for pointer->pointer cast
1055 if (SubExpr->getType()->isPointerType())
1056 return FindExpressionBaseAddress(SubExpr);
1057
1058 // We assume that we have an arithmetic expression here;
1059 // if we don't, we'll figure it out later
1060 return 0;
1061 }
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001062 case Expr::ExplicitCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001063 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1064
1065 // Check for pointer->pointer cast
1066 if (SubExpr->getType()->isPointerType())
1067 return FindExpressionBaseAddress(SubExpr);
1068
1069 // We assume that we have an arithmetic expression here;
1070 // if we don't, we'll figure it out later
1071 return 0;
1072 }
1073 }
1074}
1075
Eli Friedman02c22ce2008-05-20 13:48:25 +00001076bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1077 switch (Init->getStmtClass()) {
1078 default:
1079 Diag(Init->getExprLoc(),
1080 diag::err_init_element_not_constant, Init->getSourceRange());
1081 return true;
1082 case Expr::ParenExprClass: {
1083 const ParenExpr* PE = cast<ParenExpr>(Init);
1084 return CheckArithmeticConstantExpression(PE->getSubExpr());
1085 }
1086 case Expr::FloatingLiteralClass:
1087 case Expr::IntegerLiteralClass:
1088 case Expr::CharacterLiteralClass:
1089 case Expr::ImaginaryLiteralClass:
1090 case Expr::TypesCompatibleExprClass:
1091 case Expr::CXXBoolLiteralExprClass:
1092 return false;
1093 case Expr::CallExprClass: {
1094 const CallExpr *CE = cast<CallExpr>(Init);
1095 if (CE->isBuiltinConstantExpr())
1096 return false;
1097 Diag(Init->getExprLoc(),
1098 diag::err_init_element_not_constant, Init->getSourceRange());
1099 return true;
1100 }
1101 case Expr::DeclRefExprClass: {
1102 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1103 if (isa<EnumConstantDecl>(D))
1104 return false;
1105 Diag(Init->getExprLoc(),
1106 diag::err_init_element_not_constant, Init->getSourceRange());
1107 return true;
1108 }
1109 case Expr::CompoundLiteralExprClass:
1110 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1111 // but vectors are allowed to be magic.
1112 if (Init->getType()->isVectorType())
1113 return false;
1114 Diag(Init->getExprLoc(),
1115 diag::err_init_element_not_constant, Init->getSourceRange());
1116 return true;
1117 case Expr::UnaryOperatorClass: {
1118 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1119
1120 switch (Exp->getOpcode()) {
1121 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1122 // See C99 6.6p3.
1123 default:
1124 Diag(Init->getExprLoc(),
1125 diag::err_init_element_not_constant, Init->getSourceRange());
1126 return true;
1127 case UnaryOperator::SizeOf:
1128 case UnaryOperator::AlignOf:
1129 case UnaryOperator::OffsetOf:
1130 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1131 // See C99 6.5.3.4p2 and 6.6p3.
1132 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1133 return false;
1134 Diag(Init->getExprLoc(),
1135 diag::err_init_element_not_constant, Init->getSourceRange());
1136 return true;
1137 case UnaryOperator::Extension:
1138 case UnaryOperator::LNot:
1139 case UnaryOperator::Plus:
1140 case UnaryOperator::Minus:
1141 case UnaryOperator::Not:
1142 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1143 }
1144 }
1145 case Expr::SizeOfAlignOfTypeExprClass: {
1146 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1147 // Special check for void types, which are allowed as an extension
1148 if (Exp->getArgumentType()->isVoidType())
1149 return false;
1150 // alignof always evaluates to a constant.
1151 // FIXME: is sizeof(int[3.0]) a constant expression?
1152 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1153 Diag(Init->getExprLoc(),
1154 diag::err_init_element_not_constant, Init->getSourceRange());
1155 return true;
1156 }
1157 return false;
1158 }
1159 case Expr::BinaryOperatorClass: {
1160 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1161
1162 if (Exp->getLHS()->getType()->isArithmeticType() &&
1163 Exp->getRHS()->getType()->isArithmeticType()) {
1164 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1165 CheckArithmeticConstantExpression(Exp->getRHS());
1166 }
1167
Eli Friedman998dffb2008-06-09 05:05:07 +00001168 if (Exp->getLHS()->getType()->isPointerType() &&
1169 Exp->getRHS()->getType()->isPointerType()) {
1170 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1171 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1172
1173 // Only allow a null (constant integer) base; we could
1174 // allow some additional cases if necessary, but this
1175 // is sufficient to cover offsetof-like constructs.
1176 if (!LHSBase && !RHSBase) {
1177 return CheckAddressConstantExpression(Exp->getLHS()) ||
1178 CheckAddressConstantExpression(Exp->getRHS());
1179 }
1180 }
1181
Eli Friedman02c22ce2008-05-20 13:48:25 +00001182 Diag(Init->getExprLoc(),
1183 diag::err_init_element_not_constant, Init->getSourceRange());
1184 return true;
1185 }
1186 case Expr::ImplicitCastExprClass:
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001187 case Expr::ExplicitCastExprClass: {
1188 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman02c22ce2008-05-20 13:48:25 +00001189 if (SubExpr->getType()->isArithmeticType())
1190 return CheckArithmeticConstantExpression(SubExpr);
1191
1192 Diag(Init->getExprLoc(),
1193 diag::err_init_element_not_constant, Init->getSourceRange());
1194 return true;
1195 }
1196 case Expr::ConditionalOperatorClass: {
1197 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1198 if (CheckArithmeticConstantExpression(Exp->getCond()))
1199 return true;
1200 if (Exp->getLHS() &&
1201 CheckArithmeticConstantExpression(Exp->getLHS()))
1202 return true;
1203 return CheckArithmeticConstantExpression(Exp->getRHS());
1204 }
1205 }
1206}
1207
1208bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopese7280452008-07-07 16:46:50 +00001209 Init = Init->IgnoreParens();
1210
Eli Friedman02c22ce2008-05-20 13:48:25 +00001211 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1212 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1213 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1214
Nuno Lopese7280452008-07-07 16:46:50 +00001215 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1216 return CheckForConstantInitializer(e->getInitializer(), DclT);
1217
Eli Friedman02c22ce2008-05-20 13:48:25 +00001218 if (Init->getType()->isReferenceType()) {
1219 // FIXME: Work out how the heck reference types work
1220 return false;
1221#if 0
1222 // A reference is constant if the address of the expression
1223 // is constant
1224 // We look through initlists here to simplify
1225 // CheckAddressConstantExpressionLValue.
1226 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1227 assert(Exp->getNumInits() > 0 &&
1228 "Refernce initializer cannot be empty");
1229 Init = Exp->getInit(0);
1230 }
1231 return CheckAddressConstantExpressionLValue(Init);
1232#endif
1233 }
1234
1235 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1236 unsigned numInits = Exp->getNumInits();
1237 for (unsigned i = 0; i < numInits; i++) {
1238 // FIXME: Need to get the type of the declaration for C++,
1239 // because it could be a reference?
1240 if (CheckForConstantInitializer(Exp->getInit(i),
1241 Exp->getInit(i)->getType()))
1242 return true;
1243 }
1244 return false;
1245 }
1246
1247 if (Init->isNullPointerConstant(Context))
1248 return false;
1249 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001250 QualType InitTy = Context.getCanonicalType(Init->getType())
1251 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00001252 if (InitTy == Context.BoolTy) {
1253 // Special handling for pointers implicitly cast to bool;
1254 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1255 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1256 Expr* SubE = ICE->getSubExpr();
1257 if (SubE->getType()->isPointerType() ||
1258 SubE->getType()->isArrayType() ||
1259 SubE->getType()->isFunctionType()) {
1260 return CheckAddressConstantExpression(Init);
1261 }
1262 }
1263 } else if (InitTy->isIntegralType()) {
1264 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001265 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00001266 SubE = CE->getSubExpr();
1267 // Special check for pointer cast to int; we allow as an extension
1268 // an address constant cast to an integer if the integer
1269 // is of an appropriate width (this sort of code is apparently used
1270 // in some places).
1271 // FIXME: Add pedwarn?
1272 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1273 if (SubE && (SubE->getType()->isPointerType() ||
1274 SubE->getType()->isArrayType() ||
1275 SubE->getType()->isFunctionType())) {
1276 unsigned IntWidth = Context.getTypeSize(Init->getType());
1277 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1278 if (IntWidth >= PointerWidth)
1279 return CheckAddressConstantExpression(Init);
1280 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001281 }
1282
1283 return CheckArithmeticConstantExpression(Init);
1284 }
1285
1286 if (Init->getType()->isPointerType())
1287 return CheckAddressConstantExpression(Init);
1288
Eli Friedman25086f02008-05-30 18:14:48 +00001289 // An array type at the top level that isn't an init-list must
1290 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00001291 if (Init->getType()->isArrayType())
1292 return false;
1293
1294 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1295 Init->getSourceRange());
1296 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00001297}
1298
Steve Naroff6a0e2092007-09-12 14:07:44 +00001299void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001300 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001301 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001302 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00001303
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001304 // If there is no declaration, there was an error parsing it. Just ignore
1305 // the initializer.
1306 if (RealDecl == 0) {
1307 delete Init;
1308 return;
1309 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001310
Steve Naroff420d0f52007-09-12 20:13:48 +00001311 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1312 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00001313 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1314 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00001315 RealDecl->setInvalidDecl();
1316 return;
1317 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001318 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00001319 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00001320 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001321 if (VDecl->isBlockVarDecl()) {
1322 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001323 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00001324 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001325 VDecl->setInvalidDecl();
1326 } else if (!VDecl->isInvalidDecl()) {
Steve Narofff3cb5142008-01-25 00:51:06 +00001327 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001328 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00001329
1330 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1331 if (!getLangOptions().CPlusPlus) {
1332 if (SC == VarDecl::Static) // C99 6.7.8p4.
1333 CheckForConstantInitializer(Init, DclT);
1334 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001335 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001336 } else if (VDecl->isFileVarDecl()) {
1337 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00001338 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001339 if (!VDecl->isInvalidDecl())
Steve Narofff3cb5142008-01-25 00:51:06 +00001340 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001341 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001342
Anders Carlssonea7140a2008-08-22 05:00:02 +00001343 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1344 if (!getLangOptions().CPlusPlus) {
1345 // C99 6.7.8p4. All file scoped initializers need to be constant.
1346 CheckForConstantInitializer(Init, DclT);
1347 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001348 }
1349 // If the type changed, it means we had an incomplete type that was
1350 // completed by the initializer. For example:
1351 // int ary[] = { 1, 3, 5 };
1352 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00001353 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001354 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00001355 Init->setType(DclT);
1356 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001357
1358 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00001359 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001360 return;
1361}
1362
Chris Lattner4b009652007-07-25 00:24:17 +00001363/// The declarators are chained together backwards, reverse the list.
1364Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1365 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001366 Decl *GroupDecl = static_cast<Decl*>(group);
1367 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00001368 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00001369
1370 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1371 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001372 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00001373 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001374 else { // reverse the list.
1375 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001376 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001377 Group->setNextDeclarator(NewGroup);
1378 NewGroup = Group;
1379 Group = Next;
1380 }
1381 }
1382 // Perform semantic analysis that depends on having fully processed both
1383 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001384 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00001385 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1386 if (!IDecl)
1387 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001388 QualType T = IDecl->getType();
1389
1390 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1391 // static storage duration, it shall not have a variable length array.
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001392 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1393 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001394 if (T->isVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001395 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1396 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001397 }
1398 }
1399 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1400 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001401 if (IDecl->isBlockVarDecl() &&
1402 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001403 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +00001404 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1405 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001406 IDecl->setInvalidDecl();
1407 }
1408 }
1409 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1410 // object that has file scope without an initializer, and without a
1411 // storage-class specifier or with the storage-class specifier "static",
1412 // constitutes a tentative definition. Note: A tentative definition with
1413 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00001414 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00001415 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00001416 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1417 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001418 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00001419 // C99 6.9.2p3: If the declaration of an identifier for an object is
1420 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1421 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +00001422 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1423 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001424 IDecl->setInvalidDecl();
1425 }
1426 }
Steve Naroffb5e78152008-08-08 17:50:35 +00001427 if (IDecl->isFileVarDecl())
1428 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001429 }
1430 return NewGroup;
1431}
Steve Naroff91b03f72007-08-28 03:03:08 +00001432
Chris Lattner3e254fb2008-04-08 04:40:51 +00001433/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1434/// to introduce parameters into function prototype scope.
1435Sema::DeclTy *
1436Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00001437 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001438
1439 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1440 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1441 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1442 Diag(DS.getStorageClassSpecLoc(),
1443 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001444 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001445 }
1446 if (DS.isThreadSpecified()) {
1447 Diag(DS.getThreadSpecLoc(),
1448 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001449 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001450 }
1451
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001452 // Check that there are no default arguments inside the type of this
1453 // parameter (C++ only).
1454 if (getLangOptions().CPlusPlus)
1455 CheckExtraCXXDefaultArguments(D);
1456
Chris Lattner3e254fb2008-04-08 04:40:51 +00001457 // In this context, we *do not* check D.getInvalidType(). If the declarator
1458 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1459 // though it will not reflect the user specified type.
1460 QualType parmDeclType = GetTypeForDeclarator(D, S);
1461
1462 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1463
Chris Lattner4b009652007-07-25 00:24:17 +00001464 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1465 // Can this happen for params? We already checked that they don't conflict
1466 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001467 IdentifierInfo *II = D.getIdentifier();
1468 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1469 if (S->isDeclScope(PrevDecl)) {
1470 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1471 dyn_cast<NamedDecl>(PrevDecl)->getName());
1472
1473 // Recover by removing the name
1474 II = 0;
1475 D.SetIdentifier(0, D.getIdentifierLoc());
1476 }
Chris Lattner4b009652007-07-25 00:24:17 +00001477 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00001478
1479 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1480 // Doing the promotion here has a win and a loss. The win is the type for
1481 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1482 // code generator). The loss is the orginal type isn't preserved. For example:
1483 //
1484 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1485 // int blockvardecl[5];
1486 // sizeof(parmvardecl); // size == 4
1487 // sizeof(blockvardecl); // size == 20
1488 // }
1489 //
1490 // For expressions, all implicit conversions are captured using the
1491 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1492 //
1493 // FIXME: If a source translation tool needs to see the original type, then
1494 // we need to consider storing both types (in ParmVarDecl)...
1495 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00001496 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00001497 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00001498 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00001499 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00001500 parmDeclType = Context.getPointerType(parmDeclType);
1501
Chris Lattner3e254fb2008-04-08 04:40:51 +00001502 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1503 D.getIdentifierLoc(), II,
1504 parmDeclType, VarDecl::None,
1505 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00001506
Chris Lattner3e254fb2008-04-08 04:40:51 +00001507 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00001508 New->setInvalidDecl();
1509
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001510 if (II)
1511 PushOnScopeChains(New, S);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00001512
Chris Lattner9b384ca2008-06-29 00:02:00 +00001513 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00001514 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001515
Chris Lattner4b009652007-07-25 00:24:17 +00001516}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001517
Chris Lattnerea148702007-10-09 17:14:05 +00001518Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001519 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00001520 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1521 "Not a function declarator!");
1522 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001523
Chris Lattner4b009652007-07-25 00:24:17 +00001524 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1525 // for a K&R function.
1526 if (!FTI.hasPrototype) {
1527 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001528 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001529 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1530 FTI.ArgInfo[i].Ident->getName());
1531 // Implicitly declare the argument as type 'int' for lack of a better
1532 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001533 DeclSpec DS;
1534 const char* PrevSpec; // unused
1535 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1536 PrevSpec);
1537 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1538 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1539 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00001540 }
1541 }
Chris Lattner4b009652007-07-25 00:24:17 +00001542 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001543 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00001544 }
1545
1546 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001547
1548 // See if this is a redefinition.
Steve Naroffe57c21a2008-04-01 23:04:06 +00001549 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroff6384a012008-04-02 14:35:35 +00001550 GlobalScope);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001551 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1552 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1553 const FunctionDecl *Definition;
1554 if (FD->getBody(Definition)) {
1555 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1556 D.getIdentifier()->getName());
1557 Diag(Definition->getLocation(), diag::err_previous_definition);
1558 }
Steve Naroff1d5bd642008-01-14 20:51:29 +00001559 }
1560 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001561
1562 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001563 ActOnDeclarator(GlobalScope, D, 0));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001564}
1565
1566Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1567 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00001568 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001569 PushDeclContext(FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001570
1571 // Check the validity of our function parameters
1572 CheckParmsForFunctionDef(FD);
1573
1574 // Introduce our parameters into the function scope
1575 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1576 ParmVarDecl *Param = FD->getParamDecl(p);
1577 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001578 if (Param->getIdentifier())
1579 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001580 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001581
Chris Lattner4b009652007-07-25 00:24:17 +00001582 return FD;
1583}
1584
Steve Naroff99ee4302007-11-11 23:20:51 +00001585Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1586 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff3ac43f92008-07-25 17:57:26 +00001587 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001588 FD->setBody((Stmt*)Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001589 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00001590 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001591 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00001592 } else
1593 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001594 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00001595 // Verify and clean out per-function state.
1596
1597 // Check goto/label use.
1598 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1599 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1600 // Verify that we have no forward references left. If so, there was a goto
1601 // or address of a label taken, but no definition of it. Label fwd
1602 // definitions are indicated with a null substmt.
1603 if (I->second->getSubStmt() == 0) {
1604 LabelStmt *L = I->second;
1605 // Emit error.
1606 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1607
1608 // At this point, we have gotos that use the bogus label. Stitch it into
1609 // the function body so that they aren't leaked and that the AST is well
1610 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00001611 if (Body) {
1612 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1613 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1614 } else {
1615 // The whole function wasn't parsed correctly, just delete this.
1616 delete L;
1617 }
Chris Lattner4b009652007-07-25 00:24:17 +00001618 }
1619 }
1620 LabelMap.clear();
1621
Steve Naroff99ee4302007-11-11 23:20:51 +00001622 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001623}
1624
Chris Lattner4b009652007-07-25 00:24:17 +00001625/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1626/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001627ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1628 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001629 // Extension in C99. Legal in C90, but warn about it.
1630 if (getLangOptions().C99)
Chris Lattner4b009652007-07-25 00:24:17 +00001631 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001632 else
Chris Lattner4b009652007-07-25 00:24:17 +00001633 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1634
1635 // FIXME: handle stuff like:
1636 // void foo() { extern float X(); }
1637 // void bar() { X(); } <-- implicit decl for X in another scope.
1638
1639 // Set a Declarator for the implicit definition: int foo();
1640 const char *Dummy;
1641 DeclSpec DS;
1642 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1643 Error = Error; // Silence warning.
1644 assert(!Error && "Error setting up implicit decl!");
1645 Declarator D(DS, Declarator::BlockContext);
1646 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1647 D.SetIdentifier(&II, Loc);
1648
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001649 // Insert this function into translation-unit scope.
1650
1651 DeclContext *PrevDC = CurContext;
1652 CurContext = Context.getTranslationUnitDecl();
1653
Steve Naroff9104f3c2008-04-04 14:32:09 +00001654 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001655 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00001656 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001657
1658 CurContext = PrevDC;
1659
Steve Naroff9104f3c2008-04-04 14:32:09 +00001660 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00001661}
1662
1663
Chris Lattner82bb4792007-11-14 06:34:38 +00001664TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00001665 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00001666 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001667 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00001668
1669 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00001670 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1671 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00001672 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00001673 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001674 if (D.getInvalidType())
1675 NewTD->setInvalidDecl();
1676 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00001677}
1678
Steve Naroff0acc9c92007-09-15 18:49:24 +00001679/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001680/// former case, Name will be non-null. In the later case, Name will be null.
1681/// TagType indicates what kind of tag this is. TK indicates whether this is a
1682/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001683Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001684 SourceLocation KWLoc, IdentifierInfo *Name,
1685 SourceLocation NameLoc, AttributeList *Attr) {
1686 // If this is a use of an existing tag, it must have a name.
1687 assert((Name != 0 || TK == TK_Definition) &&
1688 "Nameless record must be a definition!");
1689
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001690 TagDecl::TagKind Kind;
Chris Lattner4b009652007-07-25 00:24:17 +00001691 switch (TagType) {
1692 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001693 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1694 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1695 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1696 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001697 }
1698
1699 // If this is a named struct, check to see if there was a previous forward
1700 // declaration or definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001701 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1702 if (ScopedDecl *PrevDecl =
1703 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Chris Lattner4b009652007-07-25 00:24:17 +00001704
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001705 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1706 "unexpected Decl type");
1707 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001708 // If this is a use of a previous tag, or if the tag is already declared
1709 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001710 // rementions the tag), reuse the decl.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001711 if (TK == TK_Reference ||
1712 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001713 // Make sure that this wasn't declared as an enum and now used as a
1714 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001715 if (PrevTagDecl->getTagKind() != Kind) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001716 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1717 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001718 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001719 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001720 PrevDecl = 0;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001721 } else {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001722 // If this is a use or a forward declaration, we're good.
1723 if (TK != TK_Definition)
1724 return PrevDecl;
1725
1726 // Diagnose attempts to redefine a tag.
1727 if (PrevTagDecl->isDefinition()) {
1728 Diag(NameLoc, diag::err_redefinition, Name->getName());
1729 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1730 // If this is a redefinition, recover by making this struct be
1731 // anonymous, which will make any later references get the previous
1732 // definition.
1733 Name = 0;
1734 } else {
1735 // Okay, this is definition of a previously declared or referenced
1736 // tag. Move the location of the decl to be the definition site.
1737 PrevDecl->setLocation(NameLoc);
1738 return PrevDecl;
1739 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001740 }
Chris Lattner4b009652007-07-25 00:24:17 +00001741 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001742 // If we get here, this is a definition of a new struct type in a nested
1743 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1744 // type.
1745 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00001746 // PrevDecl is a namespace.
1747 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1748 // The tag name clashes with a namespace name, issue an error and recover
1749 // by making this tag be anonymous.
1750 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1751 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1752 Name = 0;
1753 }
Chris Lattner4b009652007-07-25 00:24:17 +00001754 }
Chris Lattner4b009652007-07-25 00:24:17 +00001755 }
1756
1757 // If there is an identifier, use the location of the identifier as the
1758 // location of the decl, otherwise use the location of the struct/union
1759 // keyword.
1760 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1761
1762 // Otherwise, if this is the first time we've seen this tag, create the decl.
1763 TagDecl *New;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001764 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00001765 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1766 // enum X { A, B, C } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00001767 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001768 // If this is an undefined enum, warn.
1769 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001770 } else {
1771 // struct/union/class
1772
Chris Lattner4b009652007-07-25 00:24:17 +00001773 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1774 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001775 if (getLangOptions().CPlusPlus)
1776 // FIXME: Look for a way to use RecordDecl for simple structs.
1777 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1778 else
1779 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1780 }
Chris Lattner4b009652007-07-25 00:24:17 +00001781
1782 // If this has an identifier, add it to the scope stack.
1783 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001784 // The scope passed in may not be a decl scope. Zip up the scope tree until
1785 // we find one that is.
1786 while ((S->getFlags() & Scope::DeclScope) == 0)
1787 S = S->getParent();
1788
1789 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001790 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00001791 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00001792
Chris Lattnerd7e83d82008-06-28 23:58:55 +00001793 if (Attr)
1794 ProcessDeclAttributeList(New, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00001795 return New;
1796}
1797
Chris Lattner1bf58f62008-06-21 19:39:06 +00001798/// Collect the instance variables declared in an Objective-C object. Used in
1799/// the creation of structures from objects using the @defs directive.
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001800static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattnere705e5e2008-07-21 22:17:28 +00001801 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00001802 if (Class->getSuperClass())
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001803 CollectIvars(Class->getSuperClass(), Ctx, ivars);
1804
1805 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
1806 for (ObjCInterfaceDecl::ivar_iterator I=Class->ivar_begin(), E=Class->ivar_end();
1807 I!=E; ++I) {
1808
1809 ObjCIvarDecl* ID = *I;
1810 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
1811 ID->getIdentifier(),
1812 ID->getType(),
1813 ID->getBitWidth()));
1814 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00001815}
1816
1817/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1818/// instance variables of ClassName into Decls.
1819void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1820 IdentifierInfo *ClassName,
Chris Lattnere705e5e2008-07-21 22:17:28 +00001821 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00001822 // Check that ClassName is a valid class
1823 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1824 if (!Class) {
1825 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1826 return;
1827 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00001828 // Collect the instance variables
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001829 CollectIvars(Class, Context, Decls);
Chris Lattner1bf58f62008-06-21 19:39:06 +00001830}
1831
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001832QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1833 // This method tries to turn a variable array into a constant
1834 // array even when the size isn't an ICE. This is necessary
1835 // for compatibility with code that depends on gcc's buggy
1836 // constant expression folding, like struct {char x[(int)(char*)2];}
1837 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc7436af2008-07-03 04:20:39 +00001838 APValue Result;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001839 if (VLATy->getSizeExpr() &&
Chris Lattner334b1942008-07-11 19:19:21 +00001840 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
1841 llvm::APSInt &Res = Result.getInt();
1842 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1843 return Context.getConstantArrayType(VLATy->getElementType(),
1844 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001845 }
1846 }
1847 return QualType();
1848}
1849
Steve Naroff0acc9c92007-09-15 18:49:24 +00001850/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001851/// to create a FieldDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001852Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner4b009652007-07-25 00:24:17 +00001853 SourceLocation DeclStart,
1854 Declarator &D, ExprTy *BitfieldWidth) {
1855 IdentifierInfo *II = D.getIdentifier();
1856 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001857 SourceLocation Loc = DeclStart;
1858 if (II) Loc = D.getIdentifierLoc();
1859
1860 // FIXME: Unnamed fields can be handled in various different ways, for
1861 // example, unnamed unions inject all members into the struct namespace!
1862
1863
1864 if (BitWidth) {
1865 // TODO: Validate.
1866 //printf("WARNING: BITFIELDS IGNORED!\n");
1867
1868 // 6.7.2.1p3
1869 // 6.7.2.1p4
1870
1871 } else {
1872 // Not a bitfield.
1873
1874 // validate II.
1875
1876 }
1877
1878 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001879 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1880 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001881
Chris Lattner4b009652007-07-25 00:24:17 +00001882 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1883 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00001884 if (T->isVariablyModifiedType()) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001885 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
1886 if (!FixedTy.isNull()) {
1887 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
1888 T = FixedTy;
1889 } else {
1890 // FIXME: This diagnostic needs work
1891 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1892 InvalidDecl = true;
1893 }
Chris Lattner4b009652007-07-25 00:24:17 +00001894 }
Chris Lattner4b009652007-07-25 00:24:17 +00001895 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001896 FieldDecl *NewFD;
1897
1898 if (getLangOptions().CPlusPlus) {
1899 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
1900 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
1901 Loc, II, T, BitWidth);
1902 if (II)
1903 PushOnScopeChains(NewFD, S);
1904 }
1905 else
1906 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff75494892007-09-11 21:17:26 +00001907
Chris Lattner9b384ca2008-06-29 00:02:00 +00001908 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00001909
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001910 if (D.getInvalidType() || InvalidDecl)
1911 NewFD->setInvalidDecl();
1912 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001913}
1914
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001915/// TranslateIvarVisibility - Translate visibility from a token ID to an
1916/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00001917static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001918TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00001919 switch (ivarVisibility) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001920 case tok::objc_private: return ObjCIvarDecl::Private;
1921 case tok::objc_public: return ObjCIvarDecl::Public;
1922 case tok::objc_protected: return ObjCIvarDecl::Protected;
1923 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001924 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00001925 }
1926}
1927
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001928/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1929/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001930Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001931 SourceLocation DeclStart,
1932 Declarator &D, ExprTy *BitfieldWidth,
1933 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001934 IdentifierInfo *II = D.getIdentifier();
1935 Expr *BitWidth = (Expr*)BitfieldWidth;
1936 SourceLocation Loc = DeclStart;
1937 if (II) Loc = D.getIdentifierLoc();
1938
1939 // FIXME: Unnamed fields can be handled in various different ways, for
1940 // example, unnamed unions inject all members into the struct namespace!
1941
1942
1943 if (BitWidth) {
1944 // TODO: Validate.
1945 //printf("WARNING: BITFIELDS IGNORED!\n");
1946
1947 // 6.7.2.1p3
1948 // 6.7.2.1p4
1949
1950 } else {
1951 // Not a bitfield.
1952
1953 // validate II.
1954
1955 }
1956
1957 QualType T = GetTypeForDeclarator(D, S);
1958 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1959 bool InvalidDecl = false;
1960
1961 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1962 // than a variably modified type.
1963 if (T->isVariablyModifiedType()) {
1964 // FIXME: This diagnostic needs work
1965 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1966 InvalidDecl = true;
1967 }
1968
Ted Kremenek173dd312008-07-23 18:04:17 +00001969 // Get the visibility (access control) for this ivar.
1970 ObjCIvarDecl::AccessControl ac =
1971 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
1972 : ObjCIvarDecl::None;
1973
1974 // Construct the decl.
1975 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00001976 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001977
Ted Kremenek173dd312008-07-23 18:04:17 +00001978 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00001979 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001980
1981 if (D.getInvalidType() || InvalidDecl)
1982 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00001983
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001984 return NewID;
1985}
1986
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00001987void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001988 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001989 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001990 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001991 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1992 assert(EnclosingDecl && "missing record or interface decl");
1993 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1994
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001995 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001996 // Diagnose code like:
1997 // struct S { struct S {} X; };
1998 // We discover this when we complete the outer S. Reject and ignore the
1999 // outer S.
2000 Diag(Record->getLocation(), diag::err_nested_redefinition,
2001 Record->getKindName());
2002 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002003 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002004 return;
2005 }
Chris Lattner4b009652007-07-25 00:24:17 +00002006 // Verify that all the fields are okay.
2007 unsigned NumNamedMembers = 0;
2008 llvm::SmallVector<FieldDecl*, 32> RecFields;
2009 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00002010
Chris Lattner4b009652007-07-25 00:24:17 +00002011 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002012
Steve Naroff9bb759f2007-09-14 22:20:54 +00002013 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2014 assert(FD && "missing field decl");
2015
2016 // Remember all fields.
2017 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00002018
2019 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00002020 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00002021
Chris Lattner4b009652007-07-25 00:24:17 +00002022 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00002023 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002024 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00002025 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002026 FD->setInvalidDecl();
2027 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002028 continue;
2029 }
Chris Lattner4b009652007-07-25 00:24:17 +00002030 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2031 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002032 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002033 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002034 FD->setInvalidDecl();
2035 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002036 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002037 }
Chris Lattner4b009652007-07-25 00:24:17 +00002038 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002039 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00002040 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00002041 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002042 FD->setInvalidDecl();
2043 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002044 continue;
2045 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002046 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00002047 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2048 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002049 FD->setInvalidDecl();
2050 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002051 continue;
2052 }
Chris Lattner4b009652007-07-25 00:24:17 +00002053 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002054 if (Record)
2055 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002056 }
Chris Lattner4b009652007-07-25 00:24:17 +00002057 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2058 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00002059 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002060 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2061 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002062 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002063 Record->setHasFlexibleArrayMember(true);
2064 } else {
2065 // If this is a struct/class and this is not the last element, reject
2066 // it. Note that GCC supports variable sized arrays in the middle of
2067 // structures.
2068 if (i != NumFields-1) {
2069 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2070 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002071 FD->setInvalidDecl();
2072 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002073 continue;
2074 }
Chris Lattner4b009652007-07-25 00:24:17 +00002075 // We support flexible arrays at the end of structs in other structs
2076 // as an extension.
2077 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2078 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002079 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002080 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002081 }
2082 }
2083 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002084 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00002085 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002086 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2087 FD->getName());
2088 FD->setInvalidDecl();
2089 EnclosingDecl->setInvalidDecl();
2090 continue;
2091 }
Chris Lattner4b009652007-07-25 00:24:17 +00002092 // Keep track of the number of named members.
2093 if (IdentifierInfo *II = FD->getIdentifier()) {
2094 // Detect duplicate member names.
2095 if (!FieldIDs.insert(II)) {
2096 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2097 // Find the previous decl.
2098 SourceLocation PrevLoc;
2099 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2100 assert(i != e && "Didn't find previous def!");
2101 if (RecFields[i]->getIdentifier() == II) {
2102 PrevLoc = RecFields[i]->getLocation();
2103 break;
2104 }
2105 }
2106 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002107 FD->setInvalidDecl();
2108 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002109 continue;
2110 }
2111 ++NumNamedMembers;
2112 }
Chris Lattner4b009652007-07-25 00:24:17 +00002113 }
2114
Chris Lattner4b009652007-07-25 00:24:17 +00002115 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00002116 if (Record) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002117 Record->defineBody(&RecFields[0], RecFields.size());
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +00002118 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2119 // Sema::ActOnFinishCXXClassDef.
2120 if (!isa<CXXRecordDecl>(Record))
2121 Consumer.HandleTagDeclDefinition(Record);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002122 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00002123 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2124 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2125 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2126 else if (ObjCImplementationDecl *IMPDecl =
2127 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002128 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2129 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00002130 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00002131 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00002132 }
Chris Lattner4b009652007-07-25 00:24:17 +00002133}
2134
Steve Naroff0acc9c92007-09-15 18:49:24 +00002135Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00002136 DeclTy *lastEnumConst,
2137 SourceLocation IdLoc, IdentifierInfo *Id,
2138 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00002139 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002140 EnumConstantDecl *LastEnumConst =
2141 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2142 Expr *Val = static_cast<Expr*>(val);
2143
Chris Lattnera7549902007-08-26 06:24:45 +00002144 // The scope passed in may not be a decl scope. Zip up the scope tree until
2145 // we find one that is.
2146 while ((S->getFlags() & Scope::DeclScope) == 0)
2147 S = S->getParent();
2148
Chris Lattner4b009652007-07-25 00:24:17 +00002149 // Verify that there isn't already something declared with this name in this
2150 // scope.
Steve Naroff6384a012008-04-02 14:35:35 +00002151 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00002152 // When in C++, we may get a TagDecl with the same name; in this case the
2153 // enum constant will 'hide' the tag.
2154 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2155 "Received TagDecl when not in C++!");
2156 if (!isa<TagDecl>(PrevDecl) &&
2157 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002158 if (isa<EnumConstantDecl>(PrevDecl))
2159 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2160 else
2161 Diag(IdLoc, diag::err_redefinition, Id->getName());
2162 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002163 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00002164 return 0;
2165 }
2166 }
2167
2168 llvm::APSInt EnumVal(32);
2169 QualType EltTy;
2170 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00002171 // Make sure to promote the operand type to int.
2172 UsualUnaryConversions(Val);
2173
Chris Lattner4b009652007-07-25 00:24:17 +00002174 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2175 SourceLocation ExpLoc;
2176 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
2177 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2178 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002179 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00002180 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00002181 } else {
2182 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002183 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00002184 }
2185
2186 if (!Val) {
2187 if (LastEnumConst) {
2188 // Assign the last value + 1.
2189 EnumVal = LastEnumConst->getInitVal();
2190 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00002191
2192 // Check for overflow on increment.
2193 if (EnumVal < LastEnumConst->getInitVal())
2194 Diag(IdLoc, diag::warn_enum_value_overflow);
2195
Chris Lattnere7f53a42007-08-27 17:37:24 +00002196 EltTy = LastEnumConst->getType();
2197 } else {
2198 // First value, set to zero.
2199 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002200 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00002201 }
Chris Lattner4b009652007-07-25 00:24:17 +00002202 }
2203
Chris Lattnere4650482008-03-15 06:12:44 +00002204 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00002205 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2206 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00002207 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00002208
2209 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002210 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002211 return New;
2212}
2213
Steve Naroffb0726b82008-08-07 14:08:16 +00002214// FIXME: For consistency with ActOnFields(), we should have the parser
2215// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002216void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00002217 DeclTy **Elements, unsigned NumElements) {
2218 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Chris Lattner4b009652007-07-25 00:24:17 +00002219
Steve Naroffb0726b82008-08-07 14:08:16 +00002220 if (Enum && Enum->isDefinition()) {
2221 // Diagnose code like:
2222 // enum e0 {
2223 // E0 = sizeof(enum e0 { E1 })
2224 // };
2225 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2226 Enum->getName());
2227 Diag(EnumLoc, diag::err_previous_definition);
2228 Enum->setInvalidDecl();
2229 return;
2230 }
Chris Lattner435c3fd2007-08-28 05:10:31 +00002231 // TODO: If the result value doesn't fit in an int, it must be a long or long
2232 // long value. ISO C does not support this, but GCC does as an extension,
2233 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002234 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00002235
Chris Lattner206754a2007-08-28 06:15:15 +00002236 // Verify that all the values are okay, compute the size of the values, and
2237 // reverse the list.
2238 unsigned NumNegativeBits = 0;
2239 unsigned NumPositiveBits = 0;
2240
2241 // Keep track of whether all elements have type int.
2242 bool AllElementsInt = true;
2243
Chris Lattner4b009652007-07-25 00:24:17 +00002244 EnumConstantDecl *EltList = 0;
2245 for (unsigned i = 0; i != NumElements; ++i) {
2246 EnumConstantDecl *ECD =
2247 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2248 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002249
2250 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002251 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002252 assert(InitVal.getBitWidth() >= IntWidth &&
2253 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00002254 if (InitVal.getBitWidth() > IntWidth) {
2255 llvm::APSInt V(InitVal);
2256 V.trunc(IntWidth);
2257 V.extend(InitVal.getBitWidth());
2258 if (V != InitVal)
2259 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattneread053a2008-08-17 07:19:51 +00002260 InitVal.toString(10));
Chris Lattnercb33ae12007-08-28 05:27:00 +00002261 }
Chris Lattner206754a2007-08-28 06:15:15 +00002262
2263 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002264 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00002265 NumPositiveBits = std::max(NumPositiveBits,
2266 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00002267 else
Chris Lattneraff63f02008-01-14 21:47:29 +00002268 NumNegativeBits = std::max(NumNegativeBits,
2269 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00002270
Chris Lattner206754a2007-08-28 06:15:15 +00002271 // Keep track of whether every enum element has type int (very commmon).
2272 if (AllElementsInt)
2273 AllElementsInt = ECD->getType() == Context.IntTy;
2274
Chris Lattner4b009652007-07-25 00:24:17 +00002275 ECD->setNextDeclarator(EltList);
2276 EltList = ECD;
2277 }
2278
Chris Lattner206754a2007-08-28 06:15:15 +00002279 // Figure out the type that should be used for this enum.
2280 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2281 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002282 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00002283
2284 if (NumNegativeBits) {
2285 // If there is a negative value, figure out the smallest integer type (of
2286 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002287 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002288 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002289 BestWidth = IntWidth;
2290 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002291 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002292
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002293 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002294 BestType = Context.LongTy;
2295 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002296 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002297
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002298 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002299 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2300 BestType = Context.LongLongTy;
2301 }
2302 }
2303 } else {
2304 // If there is no negative value, figure out which of uint, ulong, ulonglong
2305 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002306 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002307 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002308 BestWidth = IntWidth;
2309 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00002310 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00002311 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002312 } else {
2313 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002314 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00002315 "How could an initializer get larger than ULL?");
2316 BestType = Context.UnsignedLongLongTy;
2317 }
2318 }
2319
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002320 // Loop over all of the enumerator constants, changing their types to match
2321 // the type of the enum if needed.
2322 for (unsigned i = 0; i != NumElements; ++i) {
2323 EnumConstantDecl *ECD =
2324 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2325 if (!ECD) continue; // Already issued a diagnostic.
2326
2327 // Standard C says the enumerators have int type, but we allow, as an
2328 // extension, the enumerators to be larger than int size. If each
2329 // enumerator value fits in an int, type it as an int, otherwise type it the
2330 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2331 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002332 if (ECD->getType() == Context.IntTy) {
2333 // Make sure the init value is signed.
2334 llvm::APSInt IV = ECD->getInitVal();
2335 IV.setIsSigned(true);
2336 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002337 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002338 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002339
2340 // Determine whether the value fits into an int.
2341 llvm::APSInt InitVal = ECD->getInitVal();
2342 bool FitsInInt;
2343 if (InitVal.isUnsigned() || !InitVal.isNegative())
2344 FitsInInt = InitVal.getActiveBits() < IntWidth;
2345 else
2346 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2347
2348 // If it fits into an integer type, force it. Otherwise force it to match
2349 // the enum decl type.
2350 QualType NewTy;
2351 unsigned NewWidth;
2352 bool NewSign;
2353 if (FitsInInt) {
2354 NewTy = Context.IntTy;
2355 NewWidth = IntWidth;
2356 NewSign = true;
2357 } else if (ECD->getType() == BestType) {
2358 // Already the right type!
2359 continue;
2360 } else {
2361 NewTy = BestType;
2362 NewWidth = BestWidth;
2363 NewSign = BestType->isSignedIntegerType();
2364 }
2365
2366 // Adjust the APSInt value.
2367 InitVal.extOrTrunc(NewWidth);
2368 InitVal.setIsSigned(NewSign);
2369 ECD->setInitVal(InitVal);
2370
2371 // Adjust the Expr initializer and type.
2372 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2373 ECD->setType(NewTy);
2374 }
Chris Lattner206754a2007-08-28 06:15:15 +00002375
Chris Lattner90a018d2007-08-28 18:24:31 +00002376 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002377 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00002378}
2379
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002380Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2381 ExprTy *expr) {
2382 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2383
Chris Lattner81db64a2008-03-16 00:16:02 +00002384 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002385}
2386
Chris Lattner806a5f52008-01-12 07:05:38 +00002387Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00002388 SourceLocation LBrace,
2389 SourceLocation RBrace,
2390 const char *Lang,
2391 unsigned StrSize,
2392 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00002393 LinkageSpecDecl::LanguageIDs Language;
2394 Decl *dcl = static_cast<Decl *>(D);
2395 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2396 Language = LinkageSpecDecl::lang_c;
2397 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2398 Language = LinkageSpecDecl::lang_cxx;
2399 else {
2400 Diag(Loc, diag::err_bad_language);
2401 return 0;
2402 }
2403
2404 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00002405 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00002406}