blob: d1cbdc8eeb27d58435cfd7db0ef9ccd50d270ca6 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Anders Carlssonf78915f2008-02-15 07:04:12 +000018#include "clang/AST/Attr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/AST/Builtins.h"
20#include "clang/AST/Decl.h"
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +000021#include "clang/AST/DeclCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/AST/Expr.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000023#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/AST/Type.h"
25#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Scope.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000027#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "clang/Basic/LangOptions.h"
29#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000030#include "clang/Basic/SourceManager.h"
31// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000032#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000033#include "clang/Lex/HeaderSearch.h"
Steve Naroff563477d2007-09-18 23:55:05 +000034#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000036#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000037using namespace clang;
38
Argyrios Kyrtzidis39caa082008-08-01 10:35:27 +000039Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
Steve Naroffb327ce02008-04-02 14:35:35 +000040 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
41
Douglas Gregor2ce52f32008-04-13 21:07:44 +000042 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
43 isa<ObjCInterfaceDecl>(IIDecl) ||
44 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000045 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000046 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000047}
48
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000049DeclContext *Sema::getDCParent(DeclContext *DC) {
50 // If CurContext is a ObjC method, getParent() will return NULL.
51 if (isa<ObjCMethodDecl>(DC))
52 return Context.getTranslationUnitDecl();
53
54 // A C++ inline method is parsed *after* the topmost class it was declared in
55 // is fully parsed (it's "complete").
56 // The parsing of a C++ inline method happens at the declaration context of
57 // the topmost (non-nested) class it is declared in.
58 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
59 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
60 DC = MD->getParent();
61 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
62 DC = RD;
63
64 // Return the declaration context of the topmost class the inline method is
65 // declared in.
66 return DC;
67 }
68
69 return DC->getParent();
70}
71
Chris Lattner9fdf9c62008-04-22 18:39:57 +000072void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000073 assert(getDCParent(DC) == CurContext &&
74 "The next DeclContext should be directly contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000075 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000076}
77
Chris Lattnerb048c982008-04-06 04:47:34 +000078void Sema::PopDeclContext() {
79 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000080 CurContext = getDCParent(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000081}
82
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000083/// Add this decl to the scope shadowed decl chains.
84void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000085 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000086
87 // C++ [basic.scope]p4:
88 // -- exactly one declaration shall declare a class name or
89 // enumeration name that is not a typedef name and the other
90 // declarations shall all refer to the same object or
91 // enumerator, or all refer to functions and function templates;
92 // in this case the class name or enumeration name is hidden.
93 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
94 // We are pushing the name of a tag (enum or class).
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +000095 IdentifierResolver::iterator
96 I = IdResolver.begin(TD->getIdentifier(),
97 TD->getDeclContext(), false/*LookInParentCtx*/);
98 if (I != IdResolver.end() &&
99 IdResolver.isDeclInScope(*I, TD->getDeclContext(), S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000100 // There is already a declaration with the same name in the same
101 // scope. It must be found before we find the new declaration,
102 // so swap the order on the shadowed declaration chain.
103
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000104 IdResolver.AddShadowedDecl(TD, *I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000105 return;
106 }
107 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000108 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000109}
110
Steve Naroffb216c882007-10-09 22:01:59 +0000111void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000112 if (S->decl_empty()) return;
113 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000114
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
116 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000117 Decl *TmpD = static_cast<Decl*>(*I);
118 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000119
120 if (isa<CXXFieldDecl>(TmpD)) continue;
121
122 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
123 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffc752d042007-09-13 18:10:37 +0000124
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 IdentifierInfo *II = D->getIdentifier();
126 if (!II) continue;
127
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000128 // We only want to remove the decls from the identifier decl chains for local
129 // scopes, when inside a function/method.
130 if (S->getFnParent() != 0)
131 IdResolver.RemoveDecl(D);
Chris Lattner7f925cc2008-04-11 07:00:53 +0000132
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000133 // Chain this decl to the containing DeclContext.
134 D->setNext(CurContext->getDeclChain());
135 CurContext->setDeclChain(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000136 }
137}
138
Steve Naroffe8043c32008-04-01 23:04:06 +0000139/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
140/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000141ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000142 // The third "scope" argument is 0 since we aren't enabling lazy built-in
143 // creation from this context.
144 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000145
Steve Naroffb327ce02008-04-02 14:35:35 +0000146 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000147}
148
Steve Naroffe8043c32008-04-01 23:04:06 +0000149/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000150/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000151Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
152 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000154 unsigned NS = NSI;
155 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
156 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000157
Reid Spencer5f016e22007-07-11 17:01:13 +0000158 // Scan up the scope chain looking for a decl that matches this identifier
159 // that is in the appropriate namespace. This search should not take long, as
160 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000161 for (IdentifierResolver::iterator
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000162 I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I)
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000163 if ((*I)->getIdentifierNamespace() & NS)
164 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000165
Reid Spencer5f016e22007-07-11 17:01:13 +0000166 // If we didn't find a use of this identifier, and if the identifier
167 // corresponds to a compiler builtin, create the decl object for the builtin
168 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000169 if (NS & Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000170 if (enableLazyBuiltinCreation) {
171 // If this is a builtin on this (or all) targets, create the decl.
172 if (unsigned BuiltinID = II->getBuiltinID())
173 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
174 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000175 if (getLangOptions().ObjC1) {
176 // @interface and @compatibility_alias introduce typedef-like names.
177 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000178 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000179 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000180 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
181 if (IDI != ObjCInterfaceDecls.end())
182 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000183 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
184 if (I != ObjCAliasDecls.end())
185 return I->second->getClassInterface();
186 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 }
188 return 0;
189}
190
Chris Lattner95e2c712008-05-05 22:18:14 +0000191void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000192 if (!Context.getBuiltinVaListType().isNull())
193 return;
194
195 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000196 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000197 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000198 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
199}
200
Reid Spencer5f016e22007-07-11 17:01:13 +0000201/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
202/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000203ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
204 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000205 Builtin::ID BID = (Builtin::ID)bid;
206
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000207 if (BID == Builtin::BI__builtin_va_start ||
Chris Lattner95e2c712008-05-05 22:18:14 +0000208 BID == Builtin::BI__builtin_va_copy ||
Chris Lattnerf8396b62008-07-09 17:26:36 +0000209 BID == Builtin::BI__builtin_va_end ||
210 BID == Builtin::BI__builtin_stdarg_start)
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000211 InitBuiltinVaListType();
212
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000213 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000214 FunctionDecl *New = FunctionDecl::Create(Context,
215 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000216 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000217 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000218
Chris Lattner95e2c712008-05-05 22:18:14 +0000219 // Create Decl objects for each parameter, adding them to the
220 // FunctionDecl.
221 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
222 llvm::SmallVector<ParmVarDecl*, 16> Params;
223 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
224 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
225 FT->getArgType(i), VarDecl::None, 0,
226 0));
227 New->setParams(&Params[0], Params.size());
228 }
229
230
231
Chris Lattner7f925cc2008-04-11 07:00:53 +0000232 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000233 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000234 return New;
235}
236
237/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
238/// and scope as a previous declaration 'Old'. Figure out how to resolve this
239/// situation, merging decls or emitting diagnostics as appropriate.
240///
Steve Naroffe8043c32008-04-01 23:04:06 +0000241TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000242 // Verify the old decl was also a typedef.
243 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
244 if (!Old) {
245 Diag(New->getLocation(), diag::err_redefinition_different_kind,
246 New->getName());
247 Diag(OldD->getLocation(), diag::err_previous_definition);
248 return New;
249 }
250
Chris Lattner99cb9972008-07-25 18:44:27 +0000251 // If the typedef types are not identical, reject them in all languages and
252 // with any extensions enabled.
253 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
254 Context.getCanonicalType(Old->getUnderlyingType()) !=
255 Context.getCanonicalType(New->getUnderlyingType())) {
256 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
257 New->getUnderlyingType().getAsString(),
258 Old->getUnderlyingType().getAsString());
259 Diag(Old->getLocation(), diag::err_previous_definition);
260 return Old;
261 }
262
Steve Naroff8ee529b2007-10-31 18:42:27 +0000263 // Allow multiple definitions for ObjC built-in typedefs.
264 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000266 return Old;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000267
268 if (getLangOptions().Microsoft) return New;
269
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000270 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
271 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
272 // *either* declaration is in a system header. The code below implements
273 // this adhoc compatibility rule. FIXME: The following code will not
274 // work properly when compiling ".i" files (containing preprocessed output).
275 SourceManager &SrcMgr = Context.getSourceManager();
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000276 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
Eli Friedman54ecfce2008-06-11 06:20:39 +0000277 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
278 if (OldDeclFile) {
279 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
280 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
281 if (OldDirType != DirectoryLookup::NormalHeaderDir)
282 return New;
283 }
284 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
285 if (NewDeclFile) {
286 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
287 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
288 if (NewDirType != DirectoryLookup::NormalHeaderDir)
289 return New;
290 }
291
Ted Kremenek2d05c082008-05-23 21:28:18 +0000292 Diag(New->getLocation(), diag::err_redefinition, New->getName());
293 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000294 return New;
295}
296
Chris Lattner6b6b5372008-06-26 18:38:35 +0000297/// DeclhasAttr - returns true if decl Declaration already has the target
298/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000299static bool DeclHasAttr(const Decl *decl, const Attr *target) {
300 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
301 if (attr->getKind() == target->getKind())
302 return true;
303
304 return false;
305}
306
307/// MergeAttributes - append attributes from the Old decl to the New one.
308static void MergeAttributes(Decl *New, Decl *Old) {
309 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
310
Chris Lattnerddee4232008-03-03 03:28:21 +0000311 while (attr) {
312 tmp = attr;
313 attr = attr->getNext();
314
315 if (!DeclHasAttr(New, tmp)) {
316 New->addAttr(tmp);
317 } else {
318 tmp->setNext(0);
319 delete(tmp);
320 }
321 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000322
323 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000324}
325
Chris Lattner04421082008-04-08 04:40:51 +0000326/// MergeFunctionDecl - We just parsed a function 'New' from
327/// declarator D which has the same name and scope as a previous
328/// declaration 'Old'. Figure out how to resolve this situation,
329/// merging decls or emitting diagnostics as appropriate.
Douglas Gregorf0097952008-04-21 02:02:58 +0000330/// Redeclaration will be set true if thisNew is a redeclaration OldD.
331FunctionDecl *
332Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
333 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 // Verify the old decl was also a function.
335 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
336 if (!Old) {
337 Diag(New->getLocation(), diag::err_redefinition_different_kind,
338 New->getName());
339 Diag(OldD->getLocation(), diag::err_previous_definition);
340 return New;
341 }
Chris Lattner04421082008-04-08 04:40:51 +0000342
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000343 QualType OldQType = Context.getCanonicalType(Old->getType());
344 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000345
Chris Lattner04421082008-04-08 04:40:51 +0000346 // C++ [dcl.fct]p3:
347 // All declarations for a function shall agree exactly in both the
348 // return type and the parameter-type-list.
Douglas Gregorf0097952008-04-21 02:02:58 +0000349 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
350 MergeAttributes(New, Old);
351 Redeclaration = true;
Chris Lattner04421082008-04-08 04:40:51 +0000352 return MergeCXXFunctionDecl(New, Old);
Douglas Gregorf0097952008-04-21 02:02:58 +0000353 }
Chris Lattner04421082008-04-08 04:40:51 +0000354
355 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000356 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000357 if (!getLangOptions().CPlusPlus &&
358 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000359 MergeAttributes(New, Old);
360 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000361 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000362 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000363
Steve Naroff837618c2008-01-16 15:01:34 +0000364 // A function that has already been declared has been redeclared or defined
365 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000366 diag::kind PrevDiag;
Douglas Gregorf0097952008-04-21 02:02:58 +0000367 if (Old->isThisDeclarationADefinition())
Steve Naroffe2ef8152008-04-04 14:32:09 +0000368 PrevDiag = diag::err_previous_definition;
369 else if (Old->isImplicit())
370 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000371 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000372 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000373
Reid Spencer5f016e22007-07-11 17:01:13 +0000374 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
375 // TODO: This is totally simplistic. It should handle merging functions
376 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000377 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
378 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 return New;
380}
381
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000382/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000383static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000384 if (VD->isFileVarDecl())
385 return (!VD->getInit() &&
386 (VD->getStorageClass() == VarDecl::None ||
387 VD->getStorageClass() == VarDecl::Static));
388 return false;
389}
390
391/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
392/// when dealing with C "tentative" external object definitions (C99 6.9.2).
393void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
394 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000395 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000396
397 for (IdentifierResolver::iterator
398 I = IdResolver.begin(VD->getIdentifier(),
399 VD->getDeclContext(), false/*LookInParentCtx*/),
400 E = IdResolver.end(); I != E; ++I) {
401 if (*I != VD && IdResolver.isDeclInScope(*I, VD->getDeclContext(), S)) {
402 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
403
Steve Narofff855e6f2008-08-10 15:20:13 +0000404 // Handle the following case:
405 // int a[10];
406 // int a[]; - the code below makes sure we set the correct type.
407 // int a[11]; - this is an error, size isn't 10.
408 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
409 OldDecl->getType()->isConstantArrayType())
410 VD->setType(OldDecl->getType());
411
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000412 // Check for "tentative" definitions. We can't accomplish this in
413 // MergeVarDecl since the initializer hasn't been attached.
414 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
415 continue;
416
417 // Handle __private_extern__ just like extern.
418 if (OldDecl->getStorageClass() != VarDecl::Extern &&
419 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
420 VD->getStorageClass() != VarDecl::Extern &&
421 VD->getStorageClass() != VarDecl::PrivateExtern) {
422 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
423 Diag(OldDecl->getLocation(), diag::err_previous_definition);
424 }
425 }
426 }
427}
428
Reid Spencer5f016e22007-07-11 17:01:13 +0000429/// MergeVarDecl - We just parsed a variable 'New' which has the same name
430/// and scope as a previous declaration 'Old'. Figure out how to resolve this
431/// situation, merging decls or emitting diagnostics as appropriate.
432///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000433/// Tentative definition rules (C99 6.9.2p2) are checked by
434/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
435/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000436///
Steve Naroffe8043c32008-04-01 23:04:06 +0000437VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000438 // Verify the old decl was also a variable.
439 VarDecl *Old = dyn_cast<VarDecl>(OldD);
440 if (!Old) {
441 Diag(New->getLocation(), diag::err_redefinition_different_kind,
442 New->getName());
443 Diag(OldD->getLocation(), diag::err_previous_definition);
444 return New;
445 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000446
447 MergeAttributes(New, Old);
448
Reid Spencer5f016e22007-07-11 17:01:13 +0000449 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000450 QualType OldCType = Context.getCanonicalType(Old->getType());
451 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000452 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000453 Diag(New->getLocation(), diag::err_redefinition, New->getName());
454 Diag(Old->getLocation(), diag::err_previous_definition);
455 return New;
456 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000457 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
458 if (New->getStorageClass() == VarDecl::Static &&
459 (Old->getStorageClass() == VarDecl::None ||
460 Old->getStorageClass() == VarDecl::Extern)) {
461 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
462 Diag(Old->getLocation(), diag::err_previous_definition);
463 return New;
464 }
465 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
466 if (New->getStorageClass() != VarDecl::Static &&
467 Old->getStorageClass() == VarDecl::Static) {
468 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
469 Diag(Old->getLocation(), diag::err_previous_definition);
470 return New;
471 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000472 // File scoped variables are analyzed in FinalizeDeclaratorGroup.
473 if (!New->isFileVarDecl()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 Diag(New->getLocation(), diag::err_redefinition, New->getName());
475 Diag(Old->getLocation(), diag::err_previous_definition);
476 }
477 return New;
478}
479
Chris Lattner04421082008-04-08 04:40:51 +0000480/// CheckParmsForFunctionDef - Check that the parameters of the given
481/// function are appropriate for the definition of a function. This
482/// takes care of any checks that cannot be performed on the
483/// declaration itself, e.g., that the types of each of the function
484/// parameters are complete.
485bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
486 bool HasInvalidParm = false;
487 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
488 ParmVarDecl *Param = FD->getParamDecl(p);
489
490 // C99 6.7.5.3p4: the parameters in a parameter type list in a
491 // function declarator that is part of a function definition of
492 // that function shall not have incomplete type.
493 if (Param->getType()->isIncompleteType() &&
494 !Param->isInvalidDecl()) {
495 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
496 Param->getType().getAsString());
497 Param->setInvalidDecl();
498 HasInvalidParm = true;
499 }
500 }
501
502 return HasInvalidParm;
503}
504
505/// CreateImplicitParameter - Creates an implicit function parameter
506/// in the scope S and with the given type. This routine is used, for
507/// example, to create the implicit "self" parameter in an Objective-C
508/// method.
Chris Lattner41110242008-06-17 18:05:57 +0000509ImplicitParamDecl *
Chris Lattner04421082008-04-08 04:40:51 +0000510Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
511 SourceLocation IdLoc, QualType Type) {
Chris Lattner41110242008-06-17 18:05:57 +0000512 ImplicitParamDecl *New = ImplicitParamDecl::Create(Context, CurContext,
513 IdLoc, Id, Type, 0);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000514 if (Id)
515 PushOnScopeChains(New, S);
Chris Lattner04421082008-04-08 04:40:51 +0000516
517 return New;
518}
519
Reid Spencer5f016e22007-07-11 17:01:13 +0000520/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
521/// no declarator (e.g. "struct foo;") is parsed.
522Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
523 // TODO: emit error on 'int;' or 'const enum foo;'.
524 // TODO: emit error on 'typedef int;'
525 // if (!DS.isMissingDeclaratorOk()) Diag(...);
526
Steve Naroff92199282007-11-17 21:37:36 +0000527 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000528}
529
Steve Naroffd0091aa2008-01-10 22:15:12 +0000530bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000531 // Get the type before calling CheckSingleAssignmentConstraints(), since
532 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000533 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000534
Chris Lattner5cf216b2008-01-04 18:04:52 +0000535 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
536 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
537 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000538}
539
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000540bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000541 const ArrayType *AT = Context.getAsArrayType(DeclT);
542
543 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000544 // C99 6.7.8p14. We have an array of character type with unknown size
545 // being initialized to a string literal.
546 llvm::APSInt ConstVal(32);
547 ConstVal = strLiteral->getByteLength() + 1;
548 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000549 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000550 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000551 } else {
552 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000553 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000554 // FIXME: Avoid truncation for 64-bit length strings.
555 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000556 Diag(strLiteral->getSourceRange().getBegin(),
557 diag::warn_initializer_string_for_char_array_too_long,
558 strLiteral->getSourceRange());
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000559 }
560 // Set type from "char *" to "constant array of char".
561 strLiteral->setType(DeclT);
562 // For now, we always return false (meaning success).
563 return false;
564}
565
566StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000567 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000568 if (AT && AT->getElementType()->isCharType()) {
569 return dyn_cast<StringLiteral>(Init);
570 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000571 return 0;
572}
573
Steve Naroffa9960332008-01-25 00:51:06 +0000574bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000575 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
576 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000577 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Steve Naroffca107302008-01-21 23:53:58 +0000578 return Diag(VAT->getSizeExpr()->getLocStart(),
579 diag::err_variable_object_no_init,
580 VAT->getSizeExpr()->getSourceRange());
581
Steve Naroff2fdc3742007-12-10 22:44:33 +0000582 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
583 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000584 // FIXME: Handle wide strings
585 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
586 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000587
588 if (DeclType->isArrayType())
589 return Diag(Init->getLocStart(),
590 diag::err_array_init_list_required,
591 Init->getSourceRange());
592
Steve Naroffd0091aa2008-01-10 22:15:12 +0000593 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000594 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000595
Steve Naroff0cca7492008-05-01 22:18:59 +0000596 InitListChecker CheckInitList(this, InitList, DeclType);
597 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000598}
599
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000600Sema::DeclTy *
Daniel Dunbar914701e2008-08-05 16:28:08 +0000601Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000602 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000603 IdentifierInfo *II = D.getIdentifier();
604
Chris Lattnere80a59c2007-07-25 00:24:17 +0000605 // All of these full declarators require an identifier. If it doesn't have
606 // one, the ParsedFreeStandingDeclSpec action should be used.
607 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000608 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000609 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000610 D.getDeclSpec().getSourceRange(), D.getSourceRange());
611 return 0;
612 }
613
Chris Lattner31e05722007-08-26 06:24:45 +0000614 // The scope passed in may not be a decl scope. Zip up the scope tree until
615 // we find one that is.
616 while ((S->getFlags() & Scope::DeclScope) == 0)
617 S = S->getParent();
618
Reid Spencer5f016e22007-07-11 17:01:13 +0000619 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000620 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000621 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000622 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000623
624 // In C++, the previous declaration we find might be a tag type
625 // (class or enum). In this case, the new declaration will hide the
626 // tag type.
627 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
628 PrevDecl = 0;
629
Chris Lattner41af0932007-11-14 06:34:38 +0000630 QualType R = GetTypeForDeclarator(D, S);
631 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
632
Reid Spencer5f016e22007-07-11 17:01:13 +0000633 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000634 // Check that there are no default arguments (C++ only).
635 if (getLangOptions().CPlusPlus)
636 CheckExtraCXXDefaultArguments(D);
637
Chris Lattner41af0932007-11-14 06:34:38 +0000638 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000639 if (!NewTD) return 0;
640
641 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000642 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000643 // Merge the decl with the existing one if appropriate. If the decl is
644 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000645 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000646 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
647 if (NewTD == 0) return 0;
648 }
649 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000650 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000651 // C99 6.7.7p2: If a typedef name specifies a variably modified type
652 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000653 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
654 // FIXME: Diagnostic needs to be fixed.
655 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000656 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000657 }
658 }
Chris Lattner41af0932007-11-14 06:34:38 +0000659 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000660 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000661 switch (D.getDeclSpec().getStorageClassSpec()) {
662 default: assert(0 && "Unknown storage class!");
663 case DeclSpec::SCS_auto:
664 case DeclSpec::SCS_register:
665 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
666 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000667 InvalidDecl = true;
668 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000669 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
670 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
671 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000672 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000673 }
674
Chris Lattnera98e58d2008-03-15 21:24:04 +0000675 bool isInline = D.getDeclSpec().isInlineSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000676 FunctionDecl *NewFD;
677 if (D.getContext() == Declarator::MemberContext) {
678 // This is a C++ method declaration.
679 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
680 D.getIdentifierLoc(), II, R,
681 (SC == FunctionDecl::Static), isInline,
682 LastDeclarator);
683 } else {
684 NewFD = FunctionDecl::Create(Context, CurContext,
685 D.getIdentifierLoc(),
686 II, R, SC, isInline,
687 LastDeclarator);
688 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000689 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +0000690 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +0000691
Daniel Dunbara80f8742008-08-05 01:35:17 +0000692 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +0000693 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +0000694 // The parser guarantees this is a string.
695 StringLiteral *SE = cast<StringLiteral>(E);
696 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
697 SE->getByteLength())));
698 }
699
Chris Lattner04421082008-04-08 04:40:51 +0000700 // Copy the parameter declarations from the declarator D to
701 // the function declaration NewFD, if they are available.
702 if (D.getNumTypeObjects() > 0 &&
703 D.getTypeObject(0).Fun.hasPrototype) {
704 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
705
706 // Create Decl objects for each parameter, adding them to the
707 // FunctionDecl.
708 llvm::SmallVector<ParmVarDecl*, 16> Params;
709
710 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
711 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000712 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000713 // We let through "const void" here because Sema::GetTypeForDeclarator
714 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000715 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
716 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000717 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
718 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000719 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
720
Chris Lattnerdef026a2008-04-10 02:26:16 +0000721 // In C++, the empty parameter-type-list must be spelled "void"; a
722 // typedef of void is not permitted.
723 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000724 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000725 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
726 }
727
Chris Lattner04421082008-04-08 04:40:51 +0000728 } else {
729 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
730 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
731 }
732
733 NewFD->setParams(&Params[0], Params.size());
734 }
735
Steve Naroffffce4d52008-01-09 23:34:55 +0000736 // Merge the decl with the existing one if appropriate. Since C functions
737 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000738 if (PrevDecl &&
739 (!getLangOptions().CPlusPlus ||
740 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000741 bool Redeclaration = false;
742 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +0000743 if (NewFD == 0) return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +0000744 if (Redeclaration) {
Eli Friedman27424962008-05-27 05:07:37 +0000745 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregorf0097952008-04-21 02:02:58 +0000746 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000747 }
748 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000749
750 // In C++, check default arguments now that we have merged decls.
751 if (getLangOptions().CPlusPlus)
752 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000753 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000754 // Check that there are no default arguments (C++ only).
755 if (getLangOptions().CPlusPlus)
756 CheckExtraCXXDefaultArguments(D);
757
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000758 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000759 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
760 D.getIdentifier()->getName());
761 InvalidDecl = true;
762 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000763
764 VarDecl *NewVD;
765 VarDecl::StorageClass SC;
766 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000767 default: assert(0 && "Unknown storage class!");
768 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
769 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
770 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
771 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
772 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
773 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000774 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000775 if (D.getContext() == Declarator::MemberContext) {
776 assert(SC == VarDecl::Static && "Invalid storage class for member!");
777 // This is a static data member for a C++ class.
778 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
779 D.getIdentifierLoc(), II,
780 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000781 } else {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000782 if (S->getFnParent() == 0) {
783 // C99 6.9p2: The storage-class specifiers auto and register shall not
784 // appear in the declaration specifiers in an external declaration.
785 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
786 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
787 R.getAsString());
788 InvalidDecl = true;
789 }
790 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
791 II, R, SC, LastDeclarator);
792 } else {
793 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
794 II, R, SC, LastDeclarator);
795 }
Steve Naroff53a32342007-08-28 18:45:29 +0000796 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000797 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000798 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +0000799
Daniel Dunbara735ad82008-08-06 00:03:29 +0000800 // Handle GNU asm-label extension (encoded as an attribute).
801 if (Expr *E = (Expr*) D.getAsmLabel()) {
802 // The parser guarantees this is a string.
803 StringLiteral *SE = cast<StringLiteral>(E);
804 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
805 SE->getByteLength())));
806 }
807
Nate Begemanc8e89a82008-03-14 18:07:10 +0000808 // Emit an error if an address space was applied to decl with local storage.
809 // This includes arrays of objects with address space qualifiers, but not
810 // automatic variables that point to other address spaces.
811 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000812 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
813 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
814 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000815 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000816 // Merge the decl with the existing one if appropriate. If the decl is
817 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000818 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000819 NewVD = MergeVarDecl(NewVD, PrevDecl);
820 if (NewVD == 0) return 0;
821 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000822 New = NewVD;
823 }
824
825 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000826 if (II)
827 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000828 // If any semantic error occurred, mark the decl as invalid.
829 if (D.getInvalidType() || InvalidDecl)
830 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000831
832 return New;
833}
834
Eli Friedmanc594b322008-05-20 13:48:25 +0000835bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
836 switch (Init->getStmtClass()) {
837 default:
838 Diag(Init->getExprLoc(),
839 diag::err_init_element_not_constant, Init->getSourceRange());
840 return true;
841 case Expr::ParenExprClass: {
842 const ParenExpr* PE = cast<ParenExpr>(Init);
843 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
844 }
845 case Expr::CompoundLiteralExprClass:
846 return cast<CompoundLiteralExpr>(Init)->isFileScope();
847 case Expr::DeclRefExprClass: {
848 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +0000849 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
850 if (VD->hasGlobalStorage())
851 return false;
852 Diag(Init->getExprLoc(),
853 diag::err_init_element_not_constant, Init->getSourceRange());
854 return true;
855 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000856 if (isa<FunctionDecl>(D))
857 return false;
858 Diag(Init->getExprLoc(),
859 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Naroffd0091aa2008-01-10 22:15:12 +0000860 return true;
861 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000862 case Expr::MemberExprClass: {
863 const MemberExpr *M = cast<MemberExpr>(Init);
864 if (M->isArrow())
865 return CheckAddressConstantExpression(M->getBase());
866 return CheckAddressConstantExpressionLValue(M->getBase());
867 }
868 case Expr::ArraySubscriptExprClass: {
869 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
870 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
871 return CheckAddressConstantExpression(ASE->getBase()) ||
872 CheckArithmeticConstantExpression(ASE->getIdx());
873 }
874 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +0000875 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +0000876 return false;
877 case Expr::UnaryOperatorClass: {
878 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
879
880 // C99 6.6p9
881 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +0000882 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +0000883
884 Diag(Init->getExprLoc(),
885 diag::err_init_element_not_constant, Init->getSourceRange());
886 return true;
887 }
888 }
889}
890
891bool Sema::CheckAddressConstantExpression(const Expr* Init) {
892 switch (Init->getStmtClass()) {
893 default:
894 Diag(Init->getExprLoc(),
895 diag::err_init_element_not_constant, Init->getSourceRange());
896 return true;
897 case Expr::ParenExprClass: {
898 const ParenExpr* PE = cast<ParenExpr>(Init);
899 return CheckAddressConstantExpression(PE->getSubExpr());
900 }
901 case Expr::StringLiteralClass:
902 case Expr::ObjCStringLiteralClass:
903 return false;
904 case Expr::CallExprClass: {
905 const CallExpr *CE = cast<CallExpr>(Init);
906 if (CE->isBuiltinConstantExpr())
907 return false;
908 Diag(Init->getExprLoc(),
909 diag::err_init_element_not_constant, Init->getSourceRange());
910 return true;
911 }
912 case Expr::UnaryOperatorClass: {
913 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
914
915 // C99 6.6p9
916 if (Exp->getOpcode() == UnaryOperator::AddrOf)
917 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
918
919 if (Exp->getOpcode() == UnaryOperator::Extension)
920 return CheckAddressConstantExpression(Exp->getSubExpr());
921
922 Diag(Init->getExprLoc(),
923 diag::err_init_element_not_constant, Init->getSourceRange());
924 return true;
925 }
926 case Expr::BinaryOperatorClass: {
927 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
928 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
929
930 Expr *PExp = Exp->getLHS();
931 Expr *IExp = Exp->getRHS();
932 if (IExp->getType()->isPointerType())
933 std::swap(PExp, IExp);
934
935 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
936 return CheckAddressConstantExpression(PExp) ||
937 CheckArithmeticConstantExpression(IExp);
938 }
939 case Expr::ImplicitCastExprClass: {
940 const Expr* SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
941
942 // Check for implicit promotion
943 if (SubExpr->getType()->isFunctionType() ||
944 SubExpr->getType()->isArrayType())
945 return CheckAddressConstantExpressionLValue(SubExpr);
946
947 // Check for pointer->pointer cast
948 if (SubExpr->getType()->isPointerType())
949 return CheckAddressConstantExpression(SubExpr);
950
951 if (SubExpr->getType()->isArithmeticType())
952 return CheckArithmeticConstantExpression(SubExpr);
953
954 Diag(Init->getExprLoc(),
955 diag::err_init_element_not_constant, Init->getSourceRange());
956 return true;
957 }
958 case Expr::CastExprClass: {
959 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
960
961 // Check for pointer->pointer cast
962 if (SubExpr->getType()->isPointerType())
963 return CheckAddressConstantExpression(SubExpr);
964
965 // FIXME: Should we pedwarn for (int*)(0+0)?
966 if (SubExpr->getType()->isArithmeticType())
967 return CheckArithmeticConstantExpression(SubExpr);
968
969 Diag(Init->getExprLoc(),
970 diag::err_init_element_not_constant, Init->getSourceRange());
971 return true;
972 }
973 case Expr::ConditionalOperatorClass: {
974 // FIXME: Should we pedwarn here?
975 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
976 if (!Exp->getCond()->getType()->isArithmeticType()) {
977 Diag(Init->getExprLoc(),
978 diag::err_init_element_not_constant, Init->getSourceRange());
979 return true;
980 }
981 if (CheckArithmeticConstantExpression(Exp->getCond()))
982 return true;
983 if (Exp->getLHS() &&
984 CheckAddressConstantExpression(Exp->getLHS()))
985 return true;
986 return CheckAddressConstantExpression(Exp->getRHS());
987 }
988 case Expr::AddrLabelExprClass:
989 return false;
990 }
991}
992
Eli Friedman4caf0552008-06-09 05:05:07 +0000993static const Expr* FindExpressionBaseAddress(const Expr* E);
994
995static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
996 switch (E->getStmtClass()) {
997 default:
998 return E;
999 case Expr::ParenExprClass: {
1000 const ParenExpr* PE = cast<ParenExpr>(E);
1001 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1002 }
1003 case Expr::MemberExprClass: {
1004 const MemberExpr *M = cast<MemberExpr>(E);
1005 if (M->isArrow())
1006 return FindExpressionBaseAddress(M->getBase());
1007 return FindExpressionBaseAddressLValue(M->getBase());
1008 }
1009 case Expr::ArraySubscriptExprClass: {
1010 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1011 return FindExpressionBaseAddress(ASE->getBase());
1012 }
1013 case Expr::UnaryOperatorClass: {
1014 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1015
1016 if (Exp->getOpcode() == UnaryOperator::Deref)
1017 return FindExpressionBaseAddress(Exp->getSubExpr());
1018
1019 return E;
1020 }
1021 }
1022}
1023
1024static const Expr* FindExpressionBaseAddress(const Expr* E) {
1025 switch (E->getStmtClass()) {
1026 default:
1027 return E;
1028 case Expr::ParenExprClass: {
1029 const ParenExpr* PE = cast<ParenExpr>(E);
1030 return FindExpressionBaseAddress(PE->getSubExpr());
1031 }
1032 case Expr::UnaryOperatorClass: {
1033 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1034
1035 // C99 6.6p9
1036 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1037 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1038
1039 if (Exp->getOpcode() == UnaryOperator::Extension)
1040 return FindExpressionBaseAddress(Exp->getSubExpr());
1041
1042 return E;
1043 }
1044 case Expr::BinaryOperatorClass: {
1045 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1046
1047 Expr *PExp = Exp->getLHS();
1048 Expr *IExp = Exp->getRHS();
1049 if (IExp->getType()->isPointerType())
1050 std::swap(PExp, IExp);
1051
1052 return FindExpressionBaseAddress(PExp);
1053 }
1054 case Expr::ImplicitCastExprClass: {
1055 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1056
1057 // Check for implicit promotion
1058 if (SubExpr->getType()->isFunctionType() ||
1059 SubExpr->getType()->isArrayType())
1060 return FindExpressionBaseAddressLValue(SubExpr);
1061
1062 // Check for pointer->pointer cast
1063 if (SubExpr->getType()->isPointerType())
1064 return FindExpressionBaseAddress(SubExpr);
1065
1066 // We assume that we have an arithmetic expression here;
1067 // if we don't, we'll figure it out later
1068 return 0;
1069 }
1070 case Expr::CastExprClass: {
1071 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1072
1073 // Check for pointer->pointer cast
1074 if (SubExpr->getType()->isPointerType())
1075 return FindExpressionBaseAddress(SubExpr);
1076
1077 // We assume that we have an arithmetic expression here;
1078 // if we don't, we'll figure it out later
1079 return 0;
1080 }
1081 }
1082}
1083
Eli Friedmanc594b322008-05-20 13:48:25 +00001084bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1085 switch (Init->getStmtClass()) {
1086 default:
1087 Diag(Init->getExprLoc(),
1088 diag::err_init_element_not_constant, Init->getSourceRange());
1089 return true;
1090 case Expr::ParenExprClass: {
1091 const ParenExpr* PE = cast<ParenExpr>(Init);
1092 return CheckArithmeticConstantExpression(PE->getSubExpr());
1093 }
1094 case Expr::FloatingLiteralClass:
1095 case Expr::IntegerLiteralClass:
1096 case Expr::CharacterLiteralClass:
1097 case Expr::ImaginaryLiteralClass:
1098 case Expr::TypesCompatibleExprClass:
1099 case Expr::CXXBoolLiteralExprClass:
1100 return false;
1101 case Expr::CallExprClass: {
1102 const CallExpr *CE = cast<CallExpr>(Init);
1103 if (CE->isBuiltinConstantExpr())
1104 return false;
1105 Diag(Init->getExprLoc(),
1106 diag::err_init_element_not_constant, Init->getSourceRange());
1107 return true;
1108 }
1109 case Expr::DeclRefExprClass: {
1110 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1111 if (isa<EnumConstantDecl>(D))
1112 return false;
1113 Diag(Init->getExprLoc(),
1114 diag::err_init_element_not_constant, Init->getSourceRange());
1115 return true;
1116 }
1117 case Expr::CompoundLiteralExprClass:
1118 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1119 // but vectors are allowed to be magic.
1120 if (Init->getType()->isVectorType())
1121 return false;
1122 Diag(Init->getExprLoc(),
1123 diag::err_init_element_not_constant, Init->getSourceRange());
1124 return true;
1125 case Expr::UnaryOperatorClass: {
1126 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1127
1128 switch (Exp->getOpcode()) {
1129 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1130 // See C99 6.6p3.
1131 default:
1132 Diag(Init->getExprLoc(),
1133 diag::err_init_element_not_constant, Init->getSourceRange());
1134 return true;
1135 case UnaryOperator::SizeOf:
1136 case UnaryOperator::AlignOf:
1137 case UnaryOperator::OffsetOf:
1138 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1139 // See C99 6.5.3.4p2 and 6.6p3.
1140 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1141 return false;
1142 Diag(Init->getExprLoc(),
1143 diag::err_init_element_not_constant, Init->getSourceRange());
1144 return true;
1145 case UnaryOperator::Extension:
1146 case UnaryOperator::LNot:
1147 case UnaryOperator::Plus:
1148 case UnaryOperator::Minus:
1149 case UnaryOperator::Not:
1150 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1151 }
1152 }
1153 case Expr::SizeOfAlignOfTypeExprClass: {
1154 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1155 // Special check for void types, which are allowed as an extension
1156 if (Exp->getArgumentType()->isVoidType())
1157 return false;
1158 // alignof always evaluates to a constant.
1159 // FIXME: is sizeof(int[3.0]) a constant expression?
1160 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1161 Diag(Init->getExprLoc(),
1162 diag::err_init_element_not_constant, Init->getSourceRange());
1163 return true;
1164 }
1165 return false;
1166 }
1167 case Expr::BinaryOperatorClass: {
1168 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1169
1170 if (Exp->getLHS()->getType()->isArithmeticType() &&
1171 Exp->getRHS()->getType()->isArithmeticType()) {
1172 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1173 CheckArithmeticConstantExpression(Exp->getRHS());
1174 }
1175
Eli Friedman4caf0552008-06-09 05:05:07 +00001176 if (Exp->getLHS()->getType()->isPointerType() &&
1177 Exp->getRHS()->getType()->isPointerType()) {
1178 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1179 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1180
1181 // Only allow a null (constant integer) base; we could
1182 // allow some additional cases if necessary, but this
1183 // is sufficient to cover offsetof-like constructs.
1184 if (!LHSBase && !RHSBase) {
1185 return CheckAddressConstantExpression(Exp->getLHS()) ||
1186 CheckAddressConstantExpression(Exp->getRHS());
1187 }
1188 }
1189
Eli Friedmanc594b322008-05-20 13:48:25 +00001190 Diag(Init->getExprLoc(),
1191 diag::err_init_element_not_constant, Init->getSourceRange());
1192 return true;
1193 }
1194 case Expr::ImplicitCastExprClass:
1195 case Expr::CastExprClass: {
1196 const Expr *SubExpr;
1197 if (const CastExpr *C = dyn_cast<CastExpr>(Init)) {
1198 SubExpr = C->getSubExpr();
1199 } else {
1200 SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
1201 }
1202
1203 if (SubExpr->getType()->isArithmeticType())
1204 return CheckArithmeticConstantExpression(SubExpr);
1205
1206 Diag(Init->getExprLoc(),
1207 diag::err_init_element_not_constant, Init->getSourceRange());
1208 return true;
1209 }
1210 case Expr::ConditionalOperatorClass: {
1211 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1212 if (CheckArithmeticConstantExpression(Exp->getCond()))
1213 return true;
1214 if (Exp->getLHS() &&
1215 CheckArithmeticConstantExpression(Exp->getLHS()))
1216 return true;
1217 return CheckArithmeticConstantExpression(Exp->getRHS());
1218 }
1219 }
1220}
1221
1222bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopes9a979c32008-07-07 16:46:50 +00001223 Init = Init->IgnoreParens();
1224
Eli Friedmanc594b322008-05-20 13:48:25 +00001225 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1226 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1227 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1228
Nuno Lopes9a979c32008-07-07 16:46:50 +00001229 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1230 return CheckForConstantInitializer(e->getInitializer(), DclT);
1231
Eli Friedmanc594b322008-05-20 13:48:25 +00001232 if (Init->getType()->isReferenceType()) {
1233 // FIXME: Work out how the heck reference types work
1234 return false;
1235#if 0
1236 // A reference is constant if the address of the expression
1237 // is constant
1238 // We look through initlists here to simplify
1239 // CheckAddressConstantExpressionLValue.
1240 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1241 assert(Exp->getNumInits() > 0 &&
1242 "Refernce initializer cannot be empty");
1243 Init = Exp->getInit(0);
1244 }
1245 return CheckAddressConstantExpressionLValue(Init);
1246#endif
1247 }
1248
1249 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1250 unsigned numInits = Exp->getNumInits();
1251 for (unsigned i = 0; i < numInits; i++) {
1252 // FIXME: Need to get the type of the declaration for C++,
1253 // because it could be a reference?
1254 if (CheckForConstantInitializer(Exp->getInit(i),
1255 Exp->getInit(i)->getType()))
1256 return true;
1257 }
1258 return false;
1259 }
1260
1261 if (Init->isNullPointerConstant(Context))
1262 return false;
1263 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001264 QualType InitTy = Context.getCanonicalType(Init->getType())
1265 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001266 if (InitTy == Context.BoolTy) {
1267 // Special handling for pointers implicitly cast to bool;
1268 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1269 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1270 Expr* SubE = ICE->getSubExpr();
1271 if (SubE->getType()->isPointerType() ||
1272 SubE->getType()->isArrayType() ||
1273 SubE->getType()->isFunctionType()) {
1274 return CheckAddressConstantExpression(Init);
1275 }
1276 }
1277 } else if (InitTy->isIntegralType()) {
1278 Expr* SubE = 0;
1279 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init))
1280 SubE = ICE->getSubExpr();
1281 else if (CastExpr* CE = dyn_cast<CastExpr>(Init))
1282 SubE = CE->getSubExpr();
1283 // Special check for pointer cast to int; we allow as an extension
1284 // an address constant cast to an integer if the integer
1285 // is of an appropriate width (this sort of code is apparently used
1286 // in some places).
1287 // FIXME: Add pedwarn?
1288 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1289 if (SubE && (SubE->getType()->isPointerType() ||
1290 SubE->getType()->isArrayType() ||
1291 SubE->getType()->isFunctionType())) {
1292 unsigned IntWidth = Context.getTypeSize(Init->getType());
1293 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1294 if (IntWidth >= PointerWidth)
1295 return CheckAddressConstantExpression(Init);
1296 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001297 }
1298
1299 return CheckArithmeticConstantExpression(Init);
1300 }
1301
1302 if (Init->getType()->isPointerType())
1303 return CheckAddressConstantExpression(Init);
1304
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001305 // An array type at the top level that isn't an init-list must
1306 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001307 if (Init->getType()->isArrayType())
1308 return false;
1309
1310 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1311 Init->getSourceRange());
1312 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001313}
1314
Steve Naroffbb204692007-09-12 14:07:44 +00001315void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001316 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001317 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001318 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001319
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001320 // If there is no declaration, there was an error parsing it. Just ignore
1321 // the initializer.
1322 if (RealDecl == 0) {
1323 delete Init;
1324 return;
1325 }
Steve Naroffbb204692007-09-12 14:07:44 +00001326
Steve Naroff410e3e22007-09-12 20:13:48 +00001327 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1328 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001329 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1330 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001331 RealDecl->setInvalidDecl();
1332 return;
1333 }
Steve Naroffbb204692007-09-12 14:07:44 +00001334 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001335 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001336 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001337 if (VDecl->isBlockVarDecl()) {
1338 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001339 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001340 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001341 VDecl->setInvalidDecl();
1342 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +00001343 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001344 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001345 if (SC == VarDecl::Static) // C99 6.7.8p4.
1346 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001347 }
Steve Naroff248a7532008-04-15 22:42:06 +00001348 } else if (VDecl->isFileVarDecl()) {
1349 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001350 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001351 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +00001352 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001353 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001354
1355 // C99 6.7.8p4. All file scoped initializers need to be constant.
1356 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001357 }
1358 // If the type changed, it means we had an incomplete type that was
1359 // completed by the initializer. For example:
1360 // int ary[] = { 1, 3, 5 };
1361 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001362 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001363 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001364 Init->setType(DclT);
1365 }
Steve Naroffbb204692007-09-12 14:07:44 +00001366
1367 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001368 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001369 return;
1370}
1371
Reid Spencer5f016e22007-07-11 17:01:13 +00001372/// The declarators are chained together backwards, reverse the list.
1373Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1374 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001375 Decl *GroupDecl = static_cast<Decl*>(group);
1376 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001377 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001378
1379 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1380 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001381 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001382 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001383 else { // reverse the list.
1384 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001385 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001386 Group->setNextDeclarator(NewGroup);
1387 NewGroup = Group;
1388 Group = Next;
1389 }
1390 }
1391 // Perform semantic analysis that depends on having fully processed both
1392 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001393 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001394 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1395 if (!IDecl)
1396 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001397 QualType T = IDecl->getType();
1398
1399 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1400 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001401 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1402 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001403 if (T->isVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001404 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1405 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001406 }
1407 }
1408 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1409 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001410 if (IDecl->isBlockVarDecl() &&
1411 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001412 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001413 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1414 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001415 IDecl->setInvalidDecl();
1416 }
1417 }
1418 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1419 // object that has file scope without an initializer, and without a
1420 // storage-class specifier or with the storage-class specifier "static",
1421 // constitutes a tentative definition. Note: A tentative definition with
1422 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001423 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001424 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001425 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1426 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001427 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001428 // C99 6.9.2p3: If the declaration of an identifier for an object is
1429 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1430 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001431 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1432 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001433 IDecl->setInvalidDecl();
1434 }
1435 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001436 if (IDecl->isFileVarDecl())
1437 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001438 }
1439 return NewGroup;
1440}
Steve Naroffe1223f72007-08-28 03:03:08 +00001441
Chris Lattner04421082008-04-08 04:40:51 +00001442/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1443/// to introduce parameters into function prototype scope.
1444Sema::DeclTy *
1445Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00001446 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001447
1448 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1449 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1450 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1451 Diag(DS.getStorageClassSpecLoc(),
1452 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001453 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001454 }
1455 if (DS.isThreadSpecified()) {
1456 Diag(DS.getThreadSpecLoc(),
1457 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001458 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001459 }
1460
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001461 // Check that there are no default arguments inside the type of this
1462 // parameter (C++ only).
1463 if (getLangOptions().CPlusPlus)
1464 CheckExtraCXXDefaultArguments(D);
1465
Chris Lattner04421082008-04-08 04:40:51 +00001466 // In this context, we *do not* check D.getInvalidType(). If the declarator
1467 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1468 // though it will not reflect the user specified type.
1469 QualType parmDeclType = GetTypeForDeclarator(D, S);
1470
1471 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1472
Reid Spencer5f016e22007-07-11 17:01:13 +00001473 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1474 // Can this happen for params? We already checked that they don't conflict
1475 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001476 IdentifierInfo *II = D.getIdentifier();
1477 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1478 if (S->isDeclScope(PrevDecl)) {
1479 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1480 dyn_cast<NamedDecl>(PrevDecl)->getName());
1481
1482 // Recover by removing the name
1483 II = 0;
1484 D.SetIdentifier(0, D.getIdentifierLoc());
1485 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001487
1488 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1489 // Doing the promotion here has a win and a loss. The win is the type for
1490 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1491 // code generator). The loss is the orginal type isn't preserved. For example:
1492 //
1493 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1494 // int blockvardecl[5];
1495 // sizeof(parmvardecl); // size == 4
1496 // sizeof(blockvardecl); // size == 20
1497 // }
1498 //
1499 // For expressions, all implicit conversions are captured using the
1500 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1501 //
1502 // FIXME: If a source translation tool needs to see the original type, then
1503 // we need to consider storing both types (in ParmVarDecl)...
1504 //
Chris Lattnere6327742008-04-02 05:18:44 +00001505 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001506 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001507 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001508 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001509 parmDeclType = Context.getPointerType(parmDeclType);
1510
Chris Lattner04421082008-04-08 04:40:51 +00001511 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1512 D.getIdentifierLoc(), II,
1513 parmDeclType, VarDecl::None,
1514 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001515
Chris Lattner04421082008-04-08 04:40:51 +00001516 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001517 New->setInvalidDecl();
1518
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001519 if (II)
1520 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001521
Chris Lattner3ff30c82008-06-29 00:02:00 +00001522 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001524
Reid Spencer5f016e22007-07-11 17:01:13 +00001525}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001526
Chris Lattnerb652cea2007-10-09 17:14:05 +00001527Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001528 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00001529 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1530 "Not a function declarator!");
1531 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001532
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1534 // for a K&R function.
1535 if (!FTI.hasPrototype) {
1536 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001537 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1539 FTI.ArgInfo[i].Ident->getName());
1540 // Implicitly declare the argument as type 'int' for lack of a better
1541 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001542 DeclSpec DS;
1543 const char* PrevSpec; // unused
1544 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1545 PrevSpec);
1546 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1547 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1548 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001549 }
1550 }
Chris Lattner52804082008-02-17 19:31:09 +00001551
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 // Since this is a function definition, act as though we have information
1553 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001554 if (FTI.NumArgs)
1555 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001556 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001557 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 }
1559
1560 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001561
1562 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001563 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001564 GlobalScope);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001565 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1566 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1567 const FunctionDecl *Definition;
1568 if (FD->getBody(Definition)) {
1569 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1570 D.getIdentifier()->getName());
1571 Diag(Definition->getLocation(), diag::err_previous_definition);
1572 }
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001573 }
1574 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001575
1576 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00001577 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001578}
1579
1580Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1581 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00001582 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattnerb048c982008-04-06 04:47:34 +00001583 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001584
1585 // Check the validity of our function parameters
1586 CheckParmsForFunctionDef(FD);
1587
1588 // Introduce our parameters into the function scope
1589 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1590 ParmVarDecl *Param = FD->getParamDecl(p);
1591 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001592 if (Param->getIdentifier())
1593 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 }
Chris Lattner04421082008-04-08 04:40:51 +00001595
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 return FD;
1597}
1598
Steve Naroffd6d054d2007-11-11 23:20:51 +00001599Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1600 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00001601 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001602 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001603 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00001604 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001605 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00001606 } else
1607 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00001608 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 // Verify and clean out per-function state.
1610
1611 // Check goto/label use.
1612 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1613 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1614 // Verify that we have no forward references left. If so, there was a goto
1615 // or address of a label taken, but no definition of it. Label fwd
1616 // definitions are indicated with a null substmt.
1617 if (I->second->getSubStmt() == 0) {
1618 LabelStmt *L = I->second;
1619 // Emit error.
1620 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1621
1622 // At this point, we have gotos that use the bogus label. Stitch it into
1623 // the function body so that they aren't leaked and that the AST is well
1624 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001625 if (Body) {
1626 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1627 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1628 } else {
1629 // The whole function wasn't parsed correctly, just delete this.
1630 delete L;
1631 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001632 }
1633 }
1634 LabelMap.clear();
1635
Steve Naroffd6d054d2007-11-11 23:20:51 +00001636 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001637}
1638
Reid Spencer5f016e22007-07-11 17:01:13 +00001639/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1640/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001641ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1642 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001643 // Extension in C99. Legal in C90, but warn about it.
1644 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001646 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1648
1649 // FIXME: handle stuff like:
1650 // void foo() { extern float X(); }
1651 // void bar() { X(); } <-- implicit decl for X in another scope.
1652
1653 // Set a Declarator for the implicit definition: int foo();
1654 const char *Dummy;
1655 DeclSpec DS;
1656 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1657 Error = Error; // Silence warning.
1658 assert(!Error && "Error setting up implicit decl!");
1659 Declarator D(DS, Declarator::BlockContext);
1660 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1661 D.SetIdentifier(&II, Loc);
1662
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001663 // Insert this function into translation-unit scope.
1664
1665 DeclContext *PrevDC = CurContext;
1666 CurContext = Context.getTranslationUnitDecl();
1667
Steve Naroffe2ef8152008-04-04 14:32:09 +00001668 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00001669 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001670 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001671
1672 CurContext = PrevDC;
1673
Steve Naroffe2ef8152008-04-04 14:32:09 +00001674 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001675}
1676
1677
Chris Lattner41af0932007-11-14 06:34:38 +00001678TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001679 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001681 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001682
1683 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001684 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1685 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001686 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001687 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001688 if (D.getInvalidType())
1689 NewTD->setInvalidDecl();
1690 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001691}
1692
Steve Naroff08d92e42007-09-15 18:49:24 +00001693/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001694/// former case, Name will be non-null. In the later case, Name will be null.
1695/// TagType indicates what kind of tag this is. TK indicates whether this is a
1696/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001697Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 SourceLocation KWLoc, IdentifierInfo *Name,
1699 SourceLocation NameLoc, AttributeList *Attr) {
1700 // If this is a use of an existing tag, it must have a name.
1701 assert((Name != 0 || TK == TK_Definition) &&
1702 "Nameless record must be a definition!");
1703
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001704 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00001705 switch (TagType) {
1706 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001707 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1708 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1709 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1710 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 }
1712
1713 // If this is a named struct, check to see if there was a previous forward
1714 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001715 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1716 if (ScopedDecl *PrevDecl =
1717 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001718
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001719 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1720 "unexpected Decl type");
1721 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00001722 // If this is a use of a previous tag, or if the tag is already declared
1723 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001724 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001725 if (TK == TK_Reference ||
1726 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00001727 // Make sure that this wasn't declared as an enum and now used as a
1728 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001729 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001730 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1731 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00001732 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001733 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00001734 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001735 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00001736 // If this is a use or a forward declaration, we're good.
1737 if (TK != TK_Definition)
1738 return PrevDecl;
1739
1740 // Diagnose attempts to redefine a tag.
1741 if (PrevTagDecl->isDefinition()) {
1742 Diag(NameLoc, diag::err_redefinition, Name->getName());
1743 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1744 // If this is a redefinition, recover by making this struct be
1745 // anonymous, which will make any later references get the previous
1746 // definition.
1747 Name = 0;
1748 } else {
1749 // Okay, this is definition of a previously declared or referenced
1750 // tag. Move the location of the decl to be the definition site.
1751 PrevDecl->setLocation(NameLoc);
1752 return PrevDecl;
1753 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001754 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001755 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001756 // If we get here, this is a definition of a new struct type in a nested
1757 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1758 // type.
1759 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00001760 // PrevDecl is a namespace.
1761 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1762 // The tag name clashes with a namespace name, issue an error and recover
1763 // by making this tag be anonymous.
1764 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1765 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1766 Name = 0;
1767 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001768 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 }
1770
1771 // If there is an identifier, use the location of the identifier as the
1772 // location of the decl, otherwise use the location of the struct/union
1773 // keyword.
1774 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1775
1776 // Otherwise, if this is the first time we've seen this tag, create the decl.
1777 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001778 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1780 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001781 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001782 // If this is an undefined enum, warn.
1783 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001784 } else {
1785 // struct/union/class
1786
Reid Spencer5f016e22007-07-11 17:01:13 +00001787 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1788 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001789 if (getLangOptions().CPlusPlus)
1790 // FIXME: Look for a way to use RecordDecl for simple structs.
1791 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1792 else
1793 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1794 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001795
1796 // If this has an identifier, add it to the scope stack.
1797 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001798 // The scope passed in may not be a decl scope. Zip up the scope tree until
1799 // we find one that is.
1800 while ((S->getFlags() & Scope::DeclScope) == 0)
1801 S = S->getParent();
1802
1803 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001804 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001805 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001806
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00001807 if (Attr)
1808 ProcessDeclAttributeList(New, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001809 return New;
1810}
1811
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001812/// Collect the instance variables declared in an Objective-C object. Used in
1813/// the creation of structures from objects using the @defs directive.
1814static void CollectIvars(ObjCInterfaceDecl *Class,
Chris Lattner7caeabd2008-07-21 22:17:28 +00001815 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001816 if (Class->getSuperClass())
1817 CollectIvars(Class->getSuperClass(), ivars);
1818 ivars.append(Class->ivar_begin(), Class->ivar_end());
1819}
1820
1821/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1822/// instance variables of ClassName into Decls.
1823void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1824 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00001825 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001826 // Check that ClassName is a valid class
1827 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1828 if (!Class) {
1829 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1830 return;
1831 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001832 // Collect the instance variables
1833 CollectIvars(Class, Decls);
1834}
1835
Eli Friedman1b76ada2008-06-03 21:01:11 +00001836QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1837 // This method tries to turn a variable array into a constant
1838 // array even when the size isn't an ICE. This is necessary
1839 // for compatibility with code that depends on gcc's buggy
1840 // constant expression folding, like struct {char x[(int)(char*)2];}
1841 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc44eec62008-07-03 04:20:39 +00001842 APValue Result;
Eli Friedman1b76ada2008-06-03 21:01:11 +00001843 if (VLATy->getSizeExpr() &&
Chris Lattnercf0f51d2008-07-11 19:19:21 +00001844 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
1845 llvm::APSInt &Res = Result.getInt();
1846 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1847 return Context.getConstantArrayType(VLATy->getElementType(),
1848 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00001849 }
1850 }
1851 return QualType();
1852}
1853
Steve Naroff08d92e42007-09-15 18:49:24 +00001854/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001855/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001856Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001857 SourceLocation DeclStart,
1858 Declarator &D, ExprTy *BitfieldWidth) {
1859 IdentifierInfo *II = D.getIdentifier();
1860 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001861 SourceLocation Loc = DeclStart;
1862 if (II) Loc = D.getIdentifierLoc();
1863
1864 // FIXME: Unnamed fields can be handled in various different ways, for
1865 // example, unnamed unions inject all members into the struct namespace!
1866
1867
1868 if (BitWidth) {
1869 // TODO: Validate.
1870 //printf("WARNING: BITFIELDS IGNORED!\n");
1871
1872 // 6.7.2.1p3
1873 // 6.7.2.1p4
1874
1875 } else {
1876 // Not a bitfield.
1877
1878 // validate II.
1879
1880 }
1881
1882 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001883 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1884 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001885
Reid Spencer5f016e22007-07-11 17:01:13 +00001886 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1887 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001888 if (T->isVariablyModifiedType()) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00001889 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
1890 if (!FixedTy.isNull()) {
1891 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
1892 T = FixedTy;
1893 } else {
1894 // FIXME: This diagnostic needs work
1895 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1896 InvalidDecl = true;
1897 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001898 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001900 FieldDecl *NewFD;
1901
1902 if (getLangOptions().CPlusPlus) {
1903 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
1904 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
1905 Loc, II, T, BitWidth);
1906 if (II)
1907 PushOnScopeChains(NewFD, S);
1908 }
1909 else
1910 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00001911
Chris Lattner3ff30c82008-06-29 00:02:00 +00001912 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00001913
Steve Naroff5912a352007-08-28 20:14:24 +00001914 if (D.getInvalidType() || InvalidDecl)
1915 NewFD->setInvalidDecl();
1916 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001917}
1918
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001919/// TranslateIvarVisibility - Translate visibility from a token ID to an
1920/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001921static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001922TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001923 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001924 case tok::objc_private: return ObjCIvarDecl::Private;
1925 case tok::objc_public: return ObjCIvarDecl::Public;
1926 case tok::objc_protected: return ObjCIvarDecl::Protected;
1927 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001928 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001929 }
1930}
1931
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001932/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1933/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001934Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001935 SourceLocation DeclStart,
1936 Declarator &D, ExprTy *BitfieldWidth,
1937 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001938 IdentifierInfo *II = D.getIdentifier();
1939 Expr *BitWidth = (Expr*)BitfieldWidth;
1940 SourceLocation Loc = DeclStart;
1941 if (II) Loc = D.getIdentifierLoc();
1942
1943 // FIXME: Unnamed fields can be handled in various different ways, for
1944 // example, unnamed unions inject all members into the struct namespace!
1945
1946
1947 if (BitWidth) {
1948 // TODO: Validate.
1949 //printf("WARNING: BITFIELDS IGNORED!\n");
1950
1951 // 6.7.2.1p3
1952 // 6.7.2.1p4
1953
1954 } else {
1955 // Not a bitfield.
1956
1957 // validate II.
1958
1959 }
1960
1961 QualType T = GetTypeForDeclarator(D, S);
1962 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1963 bool InvalidDecl = false;
1964
1965 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1966 // than a variably modified type.
1967 if (T->isVariablyModifiedType()) {
1968 // FIXME: This diagnostic needs work
1969 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1970 InvalidDecl = true;
1971 }
1972
Ted Kremenekb8db21d2008-07-23 18:04:17 +00001973 // Get the visibility (access control) for this ivar.
1974 ObjCIvarDecl::AccessControl ac =
1975 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
1976 : ObjCIvarDecl::None;
1977
1978 // Construct the decl.
1979 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00001980 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001981
Ted Kremenekb8db21d2008-07-23 18:04:17 +00001982 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00001983 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001984
1985 if (D.getInvalidType() || InvalidDecl)
1986 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00001987
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001988 return NewID;
1989}
1990
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001991void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001992 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001993 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001994 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00001995 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1996 assert(EnclosingDecl && "missing record or interface decl");
1997 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1998
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001999 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002000 // Diagnose code like:
2001 // struct S { struct S {} X; };
2002 // We discover this when we complete the outer S. Reject and ignore the
2003 // outer S.
2004 Diag(Record->getLocation(), diag::err_nested_redefinition,
2005 Record->getKindName());
2006 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002007 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002008 return;
2009 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002010 // Verify that all the fields are okay.
2011 unsigned NumNamedMembers = 0;
2012 llvm::SmallVector<FieldDecl*, 32> RecFields;
2013 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002014
Reid Spencer5f016e22007-07-11 17:01:13 +00002015 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002016
Steve Naroff74216642007-09-14 22:20:54 +00002017 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2018 assert(FD && "missing field decl");
2019
2020 // Remember all fields.
2021 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002022
2023 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002024 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002025
Reid Spencer5f016e22007-07-11 17:01:13 +00002026 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002027 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00002028 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00002029 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002030 FD->setInvalidDecl();
2031 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002032 continue;
2033 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002034 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2035 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002036 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002037 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002038 FD->setInvalidDecl();
2039 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002040 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002041 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002042 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002043 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002044 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002045 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002046 FD->setInvalidDecl();
2047 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002048 continue;
2049 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002050 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00002051 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2052 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002053 FD->setInvalidDecl();
2054 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002055 continue;
2056 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002057 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002058 if (Record)
2059 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002060 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002061 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2062 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002063 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002064 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2065 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002066 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002067 Record->setHasFlexibleArrayMember(true);
2068 } else {
2069 // If this is a struct/class and this is not the last element, reject
2070 // it. Note that GCC supports variable sized arrays in the middle of
2071 // structures.
2072 if (i != NumFields-1) {
2073 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2074 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002075 FD->setInvalidDecl();
2076 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002077 continue;
2078 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002079 // We support flexible arrays at the end of structs in other structs
2080 // as an extension.
2081 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2082 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002083 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002084 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002085 }
2086 }
2087 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002088 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002089 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002090 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2091 FD->getName());
2092 FD->setInvalidDecl();
2093 EnclosingDecl->setInvalidDecl();
2094 continue;
2095 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002096 // Keep track of the number of named members.
2097 if (IdentifierInfo *II = FD->getIdentifier()) {
2098 // Detect duplicate member names.
2099 if (!FieldIDs.insert(II)) {
2100 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2101 // Find the previous decl.
2102 SourceLocation PrevLoc;
2103 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2104 assert(i != e && "Didn't find previous def!");
2105 if (RecFields[i]->getIdentifier() == II) {
2106 PrevLoc = RecFields[i]->getLocation();
2107 break;
2108 }
2109 }
2110 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002111 FD->setInvalidDecl();
2112 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002113 continue;
2114 }
2115 ++NumNamedMembers;
2116 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002117 }
2118
Reid Spencer5f016e22007-07-11 17:01:13 +00002119 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002120 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002121 Record->defineBody(&RecFields[0], RecFields.size());
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00002122 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2123 // Sema::ActOnFinishCXXClassDef.
2124 if (!isa<CXXRecordDecl>(Record))
2125 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00002126 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002127 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2128 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2129 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2130 else if (ObjCImplementationDecl *IMPDecl =
2131 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002132 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2133 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002134 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002135 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002136 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002137}
2138
Steve Naroff08d92e42007-09-15 18:49:24 +00002139Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002140 DeclTy *lastEnumConst,
2141 SourceLocation IdLoc, IdentifierInfo *Id,
2142 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002143 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002144 EnumConstantDecl *LastEnumConst =
2145 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2146 Expr *Val = static_cast<Expr*>(val);
2147
Chris Lattner31e05722007-08-26 06:24:45 +00002148 // The scope passed in may not be a decl scope. Zip up the scope tree until
2149 // we find one that is.
2150 while ((S->getFlags() & Scope::DeclScope) == 0)
2151 S = S->getParent();
2152
Reid Spencer5f016e22007-07-11 17:01:13 +00002153 // Verify that there isn't already something declared with this name in this
2154 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002155 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00002156 // When in C++, we may get a TagDecl with the same name; in this case the
2157 // enum constant will 'hide' the tag.
2158 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2159 "Received TagDecl when not in C++!");
2160 if (!isa<TagDecl>(PrevDecl) &&
2161 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002162 if (isa<EnumConstantDecl>(PrevDecl))
2163 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2164 else
2165 Diag(IdLoc, diag::err_redefinition, Id->getName());
2166 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002167 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002168 return 0;
2169 }
2170 }
2171
2172 llvm::APSInt EnumVal(32);
2173 QualType EltTy;
2174 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002175 // Make sure to promote the operand type to int.
2176 UsualUnaryConversions(Val);
2177
Reid Spencer5f016e22007-07-11 17:01:13 +00002178 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2179 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002180 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002181 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2182 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002183 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002184 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002185 } else {
2186 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002187 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002188 }
2189
2190 if (!Val) {
2191 if (LastEnumConst) {
2192 // Assign the last value + 1.
2193 EnumVal = LastEnumConst->getInitVal();
2194 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002195
2196 // Check for overflow on increment.
2197 if (EnumVal < LastEnumConst->getInitVal())
2198 Diag(IdLoc, diag::warn_enum_value_overflow);
2199
Chris Lattnerb7416f92007-08-27 17:37:24 +00002200 EltTy = LastEnumConst->getType();
2201 } else {
2202 // First value, set to zero.
2203 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002204 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002205 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002206 }
2207
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002208 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002209 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2210 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002211 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002212
2213 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002214 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002215 return New;
2216}
2217
Steve Naroff02408c62008-08-07 14:08:16 +00002218// FIXME: For consistency with ActOnFields(), we should have the parser
2219// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00002220void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002221 DeclTy **Elements, unsigned NumElements) {
2222 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00002223
Steve Naroff02408c62008-08-07 14:08:16 +00002224 if (Enum && Enum->isDefinition()) {
2225 // Diagnose code like:
2226 // enum e0 {
2227 // E0 = sizeof(enum e0 { E1 })
2228 // };
2229 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2230 Enum->getName());
2231 Diag(EnumLoc, diag::err_previous_definition);
2232 Enum->setInvalidDecl();
2233 return;
2234 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00002235 // TODO: If the result value doesn't fit in an int, it must be a long or long
2236 // long value. ISO C does not support this, but GCC does as an extension,
2237 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002238 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002239
Chris Lattnerac609682007-08-28 06:15:15 +00002240 // Verify that all the values are okay, compute the size of the values, and
2241 // reverse the list.
2242 unsigned NumNegativeBits = 0;
2243 unsigned NumPositiveBits = 0;
2244
2245 // Keep track of whether all elements have type int.
2246 bool AllElementsInt = true;
2247
Reid Spencer5f016e22007-07-11 17:01:13 +00002248 EnumConstantDecl *EltList = 0;
2249 for (unsigned i = 0; i != NumElements; ++i) {
2250 EnumConstantDecl *ECD =
2251 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2252 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002253
2254 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002255 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002256 assert(InitVal.getBitWidth() >= IntWidth &&
2257 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002258 if (InitVal.getBitWidth() > IntWidth) {
2259 llvm::APSInt V(InitVal);
2260 V.trunc(IntWidth);
2261 V.extend(InitVal.getBitWidth());
2262 if (V != InitVal)
2263 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
2264 InitVal.toString());
2265 }
Chris Lattnerac609682007-08-28 06:15:15 +00002266
2267 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002268 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002269 NumPositiveBits = std::max(NumPositiveBits,
2270 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002271 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002272 NumNegativeBits = std::max(NumNegativeBits,
2273 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002274
Chris Lattnerac609682007-08-28 06:15:15 +00002275 // Keep track of whether every enum element has type int (very commmon).
2276 if (AllElementsInt)
2277 AllElementsInt = ECD->getType() == Context.IntTy;
2278
Reid Spencer5f016e22007-07-11 17:01:13 +00002279 ECD->setNextDeclarator(EltList);
2280 EltList = ECD;
2281 }
2282
Chris Lattnerac609682007-08-28 06:15:15 +00002283 // Figure out the type that should be used for this enum.
2284 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2285 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002286 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002287
2288 if (NumNegativeBits) {
2289 // If there is a negative value, figure out the smallest integer type (of
2290 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002291 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002292 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002293 BestWidth = IntWidth;
2294 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002295 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002296
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002297 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002298 BestType = Context.LongTy;
2299 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002300 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002301
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002302 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002303 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2304 BestType = Context.LongLongTy;
2305 }
2306 }
2307 } else {
2308 // If there is no negative value, figure out which of uint, ulong, ulonglong
2309 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002310 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002311 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002312 BestWidth = IntWidth;
2313 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002314 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002315 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002316 } else {
2317 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002318 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002319 "How could an initializer get larger than ULL?");
2320 BestType = Context.UnsignedLongLongTy;
2321 }
2322 }
2323
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002324 // Loop over all of the enumerator constants, changing their types to match
2325 // the type of the enum if needed.
2326 for (unsigned i = 0; i != NumElements; ++i) {
2327 EnumConstantDecl *ECD =
2328 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2329 if (!ECD) continue; // Already issued a diagnostic.
2330
2331 // Standard C says the enumerators have int type, but we allow, as an
2332 // extension, the enumerators to be larger than int size. If each
2333 // enumerator value fits in an int, type it as an int, otherwise type it the
2334 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2335 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002336 if (ECD->getType() == Context.IntTy) {
2337 // Make sure the init value is signed.
2338 llvm::APSInt IV = ECD->getInitVal();
2339 IV.setIsSigned(true);
2340 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002341 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002342 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002343
2344 // Determine whether the value fits into an int.
2345 llvm::APSInt InitVal = ECD->getInitVal();
2346 bool FitsInInt;
2347 if (InitVal.isUnsigned() || !InitVal.isNegative())
2348 FitsInInt = InitVal.getActiveBits() < IntWidth;
2349 else
2350 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2351
2352 // If it fits into an integer type, force it. Otherwise force it to match
2353 // the enum decl type.
2354 QualType NewTy;
2355 unsigned NewWidth;
2356 bool NewSign;
2357 if (FitsInInt) {
2358 NewTy = Context.IntTy;
2359 NewWidth = IntWidth;
2360 NewSign = true;
2361 } else if (ECD->getType() == BestType) {
2362 // Already the right type!
2363 continue;
2364 } else {
2365 NewTy = BestType;
2366 NewWidth = BestWidth;
2367 NewSign = BestType->isSignedIntegerType();
2368 }
2369
2370 // Adjust the APSInt value.
2371 InitVal.extOrTrunc(NewWidth);
2372 InitVal.setIsSigned(NewSign);
2373 ECD->setInitVal(InitVal);
2374
2375 // Adjust the Expr initializer and type.
2376 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2377 ECD->setType(NewTy);
2378 }
Chris Lattnerac609682007-08-28 06:15:15 +00002379
Chris Lattnere00b18c2007-08-28 18:24:31 +00002380 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00002381 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00002382}
2383
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002384Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2385 ExprTy *expr) {
2386 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2387
Chris Lattner8e25d862008-03-16 00:16:02 +00002388 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002389}
2390
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002391Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00002392 SourceLocation LBrace,
2393 SourceLocation RBrace,
2394 const char *Lang,
2395 unsigned StrSize,
2396 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002397 LinkageSpecDecl::LanguageIDs Language;
2398 Decl *dcl = static_cast<Decl *>(D);
2399 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2400 Language = LinkageSpecDecl::lang_c;
2401 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2402 Language = LinkageSpecDecl::lang_cxx;
2403 else {
2404 Diag(Loc, diag::err_bad_language);
2405 return 0;
2406 }
2407
2408 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00002409 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002410}