blob: 26fbafdd408987ddbd6484550e04768399de785d [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
Anders Carlsson3f70c542008-02-15 07:04:12 +000017#include "clang/AST/Attr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "clang/AST/Builtins.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/Type.h"
22#include "clang/Parse/DeclSpec.h"
23#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Basic/SourceManager.h"
27// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner33aad6e2008-02-06 00:51:33 +000028#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000029#include "clang/Lex/HeaderSearch.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000030#include "llvm/ADT/SmallString.h"
Chris Lattner4b009652007-07-25 00:24:17 +000031#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian67907bd2007-10-05 18:00:57 +000032#include "llvm/ADT/DenseSet.h"
Chris Lattner4b009652007-07-25 00:24:17 +000033using namespace clang;
34
Steve Naroff6384a012008-04-02 14:35:35 +000035Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
36 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
37
Douglas Gregor1d661552008-04-13 21:07:44 +000038 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
39 isa<ObjCInterfaceDecl>(IIDecl) ||
40 isa<TagDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000041 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000042 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000043}
44
Chris Lattneref87a202008-04-22 18:39:57 +000045void Sema::PushDeclContext(DeclContext *DC) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +000046 assert( ( (isa<ObjCMethodDecl>(DC) && isa<TranslationUnitDecl>(CurContext))
Chris Lattneref87a202008-04-22 18:39:57 +000047 || DC->getParent() == CurContext ) &&
Chris Lattnerf3874bc2008-04-06 04:47:34 +000048 "The next DeclContext should be directly contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000049 CurContext = DC;
Chris Lattnereee57c02008-04-04 06:12:32 +000050}
51
Chris Lattnerf3874bc2008-04-06 04:47:34 +000052void Sema::PopDeclContext() {
53 assert(CurContext && "DeclContext imbalance!");
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000054 // If CurContext is a ObjC method, getParent() will return NULL.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +000055 CurContext = isa<ObjCMethodDecl>(CurContext)
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000056 ? Context.getTranslationUnitDecl()
57 : CurContext->getParent();
Chris Lattnereee57c02008-04-04 06:12:32 +000058}
59
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000060/// Add this decl to the scope shadowed decl chains.
61void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000062 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000063
64 // C++ [basic.scope]p4:
65 // -- exactly one declaration shall declare a class name or
66 // enumeration name that is not a typedef name and the other
67 // declarations shall all refer to the same object or
68 // enumerator, or all refer to functions and function templates;
69 // in this case the class name or enumeration name is hidden.
70 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
71 // We are pushing the name of a tag (enum or class).
72 IdentifierResolver::ctx_iterator
73 CIT = IdResolver.ctx_begin(TD->getIdentifier(), TD->getDeclContext());
74 if (CIT != IdResolver.ctx_end(TD->getIdentifier()) &&
75 IdResolver.isDeclInScope(*CIT, TD->getDeclContext(), S)) {
76 // There is already a declaration with the same name in the same
77 // scope. It must be found before we find the new declaration,
78 // so swap the order on the shadowed declaration chain.
79
80 IdResolver.AddShadowedDecl(TD, *CIT);
81 return;
82 }
83 }
84
85 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000086}
87
Steve Naroff9637a9b2007-10-09 22:01:59 +000088void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000089 if (S->decl_empty()) return;
90 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000091
92 // We only want to remove the decls from the identifier decl chains for local
93 // scopes, when inside a function/method.
94 if (S->getFnParent() == 0)
95 return;
Chris Lattnera7549902007-08-26 06:24:45 +000096
Chris Lattner4b009652007-07-25 00:24:17 +000097 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
98 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +000099 Decl *TmpD = static_cast<Decl*>(*I);
100 assert(TmpD && "This decl didn't get pushed??");
101 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
102 assert(D && "This decl isn't a ScopedDecl?");
103
Chris Lattner4b009652007-07-25 00:24:17 +0000104 IdentifierInfo *II = D->getIdentifier();
105 if (!II) continue;
106
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000107 // Unlink this decl from the identifier.
108 IdResolver.RemoveDecl(D);
109
Chris Lattner4b009652007-07-25 00:24:17 +0000110 // This will have to be revisited for C++: there we want to nest stuff in
111 // namespace decls etc. Even for C, we might want a top-level translation
112 // unit decl or something.
113 if (!CurFunctionDecl)
114 continue;
115
116 // Chain this decl to the containing function, it now owns the memory for
117 // the decl.
118 D->setNext(CurFunctionDecl->getDeclChain());
119 CurFunctionDecl->setDeclChain(D);
120 }
121}
122
Steve Naroffe57c21a2008-04-01 23:04:06 +0000123/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
124/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000125ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000126 // The third "scope" argument is 0 since we aren't enabling lazy built-in
127 // creation from this context.
128 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000129
Steve Naroff6384a012008-04-02 14:35:35 +0000130 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000131}
132
Steve Naroffe57c21a2008-04-01 23:04:06 +0000133/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000134/// namespace.
Steve Naroff6384a012008-04-02 14:35:35 +0000135Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
136 Scope *S, bool enableLazyBuiltinCreation) {
Chris Lattner4b009652007-07-25 00:24:17 +0000137 if (II == 0) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000138 unsigned NS = NSI;
139 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
140 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000141
Chris Lattner4b009652007-07-25 00:24:17 +0000142 // Scan up the scope chain looking for a decl that matches this identifier
143 // that is in the appropriate namespace. This search should not take long, as
144 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000145 for (IdentifierResolver::iterator
146 I = IdResolver.begin(II, CurContext), E = IdResolver.end(II); I != E; ++I)
147 if ((*I)->getIdentifierNamespace() & NS)
148 return *I;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000149
Chris Lattner4b009652007-07-25 00:24:17 +0000150 // If we didn't find a use of this identifier, and if the identifier
151 // corresponds to a compiler builtin, create the decl object for the builtin
152 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1d661552008-04-13 21:07:44 +0000153 if (NS & Decl::IDNS_Ordinary) {
Steve Naroff6384a012008-04-02 14:35:35 +0000154 if (enableLazyBuiltinCreation) {
155 // If this is a builtin on this (or all) targets, create the decl.
156 if (unsigned BuiltinID = II->getBuiltinID())
157 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
158 }
Steve Naroffe57c21a2008-04-01 23:04:06 +0000159 if (getLangOptions().ObjC1) {
160 // @interface and @compatibility_alias introduce typedef-like names.
161 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000162 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000163 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000164 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
165 if (IDI != ObjCInterfaceDecls.end())
166 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000167 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
168 if (I != ObjCAliasDecls.end())
169 return I->second->getClassInterface();
170 }
Chris Lattner4b009652007-07-25 00:24:17 +0000171 }
172 return 0;
173}
174
Chris Lattnera9c87f22008-05-05 22:18:14 +0000175void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000176 if (!Context.getBuiltinVaListType().isNull())
177 return;
178
179 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000180 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000181 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000182 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
183}
184
Chris Lattner4b009652007-07-25 00:24:17 +0000185/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
186/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000187ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
188 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000189 Builtin::ID BID = (Builtin::ID)bid;
190
Anders Carlsson36760332007-10-15 20:28:48 +0000191 if (BID == Builtin::BI__builtin_va_start ||
Chris Lattnera9c87f22008-05-05 22:18:14 +0000192 BID == Builtin::BI__builtin_va_copy ||
193 BID == Builtin::BI__builtin_va_end)
Anders Carlsson36760332007-10-15 20:28:48 +0000194 InitBuiltinVaListType();
195
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000196 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000197 FunctionDecl *New = FunctionDecl::Create(Context,
198 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000199 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000200 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000201
Chris Lattnera9c87f22008-05-05 22:18:14 +0000202 // Create Decl objects for each parameter, adding them to the
203 // FunctionDecl.
204 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
205 llvm::SmallVector<ParmVarDecl*, 16> Params;
206 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
207 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
208 FT->getArgType(i), VarDecl::None, 0,
209 0));
210 New->setParams(&Params[0], Params.size());
211 }
212
213
214
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000215 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000216 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000217 return New;
218}
219
220/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
221/// and scope as a previous declaration 'Old'. Figure out how to resolve this
222/// situation, merging decls or emitting diagnostics as appropriate.
223///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000224TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000225 // Verify the old decl was also a typedef.
226 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
227 if (!Old) {
228 Diag(New->getLocation(), diag::err_redefinition_different_kind,
229 New->getName());
230 Diag(OldD->getLocation(), diag::err_previous_definition);
231 return New;
232 }
233
Steve Naroffae84af82007-10-31 18:42:27 +0000234 // Allow multiple definitions for ObjC built-in typedefs.
235 // FIXME: Verify the underlying types are equivalent!
Ted Kremenek42730c52008-01-07 19:49:32 +0000236 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroffae84af82007-10-31 18:42:27 +0000237 return Old;
Steve Naroffa9eae582008-01-30 23:46:05 +0000238
239 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
240 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
241 // *either* declaration is in a system header. The code below implements
242 // this adhoc compatibility rule. FIXME: The following code will not
243 // work properly when compiling ".i" files (containing preprocessed output).
244 SourceManager &SrcMgr = Context.getSourceManager();
245 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
246 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
247 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
248 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
249 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
250
Steve Naroff1997d2c2008-03-26 21:27:00 +0000251 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
252 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
253 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroff73a07032008-02-07 03:50:06 +0000254 getLangOptions().Microsoft)
Steve Naroffa9eae582008-01-30 23:46:05 +0000255 return New;
Steve Naroff1997d2c2008-03-26 21:27:00 +0000256
Chris Lattner4b009652007-07-25 00:24:17 +0000257 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
258 // TODO: This is totally simplistic. It should handle merging functions
259 // together etc, merging extern int X; int X; ...
260 Diag(New->getLocation(), diag::err_redefinition, New->getName());
261 Diag(Old->getLocation(), diag::err_previous_definition);
262 return New;
263}
264
Chris Lattner402b3372008-03-03 03:28:21 +0000265/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
266static bool DeclHasAttr(const Decl *decl, const Attr *target) {
267 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
268 if (attr->getKind() == target->getKind())
269 return true;
270
271 return false;
272}
273
274/// MergeAttributes - append attributes from the Old decl to the New one.
275static void MergeAttributes(Decl *New, Decl *Old) {
276 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
277
278// FIXME: fix this code to cleanup the Old attrs correctly
279 while (attr) {
280 tmp = attr;
281 attr = attr->getNext();
282
283 if (!DeclHasAttr(New, tmp)) {
284 New->addAttr(tmp);
285 } else {
286 tmp->setNext(0);
287 delete(tmp);
288 }
289 }
290}
291
Chris Lattner3e254fb2008-04-08 04:40:51 +0000292/// MergeFunctionDecl - We just parsed a function 'New' from
293/// declarator D which has the same name and scope as a previous
294/// declaration 'Old'. Figure out how to resolve this situation,
295/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor42214c52008-04-21 02:02:58 +0000296/// Redeclaration will be set true if thisNew is a redeclaration OldD.
297FunctionDecl *
298Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
299 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000300 // Verify the old decl was also a function.
301 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
302 if (!Old) {
303 Diag(New->getLocation(), diag::err_redefinition_different_kind,
304 New->getName());
305 Diag(OldD->getLocation(), diag::err_previous_definition);
306 return New;
307 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000308
Chris Lattner42a21742008-04-06 23:10:54 +0000309 QualType OldQType = Context.getCanonicalType(Old->getType());
310 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000311
Chris Lattner3e254fb2008-04-08 04:40:51 +0000312 // C++ [dcl.fct]p3:
313 // All declarations for a function shall agree exactly in both the
314 // return type and the parameter-type-list.
Douglas Gregor42214c52008-04-21 02:02:58 +0000315 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
316 MergeAttributes(New, Old);
317 Redeclaration = true;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000318 return MergeCXXFunctionDecl(New, Old);
Douglas Gregor42214c52008-04-21 02:02:58 +0000319 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000320
321 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000322 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000323 if (!getLangOptions().CPlusPlus &&
324 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000325 MergeAttributes(New, Old);
326 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000327 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000328 }
Chris Lattner1470b072007-11-06 06:07:26 +0000329
Steve Naroff6c9e7922008-01-16 15:01:34 +0000330 // A function that has already been declared has been redeclared or defined
331 // with a different type- show appropriate diagnostic
Steve Naroff9104f3c2008-04-04 14:32:09 +0000332 diag::kind PrevDiag;
Douglas Gregor42214c52008-04-21 02:02:58 +0000333 if (Old->isThisDeclarationADefinition())
Steve Naroff9104f3c2008-04-04 14:32:09 +0000334 PrevDiag = diag::err_previous_definition;
335 else if (Old->isImplicit())
336 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000337 else
Steve Naroff9104f3c2008-04-04 14:32:09 +0000338 PrevDiag = diag::err_previous_declaration;
Steve Naroff6c9e7922008-01-16 15:01:34 +0000339
Chris Lattner4b009652007-07-25 00:24:17 +0000340 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
341 // TODO: This is totally simplistic. It should handle merging functions
342 // together etc, merging extern int X; int X; ...
Steve Naroff6c9e7922008-01-16 15:01:34 +0000343 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
344 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000345 return New;
346}
347
Chris Lattnerf9167d12007-11-06 04:28:31 +0000348/// equivalentArrayTypes - Used to determine whether two array types are
349/// equivalent.
350/// We need to check this explicitly as an incomplete array definition is
351/// considered a VariableArrayType, so will not match a complete array
352/// definition that would be otherwise equivalent.
353static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
354 const ArrayType *NewAT = NewQType->getAsArrayType();
355 const ArrayType *OldAT = OldQType->getAsArrayType();
356
357 if (!NewAT || !OldAT)
358 return false;
359
360 // If either (or both) array types in incomplete we need to strip off the
361 // outer VariableArrayType. Once the outer VAT is removed the remaining
362 // types must be identical if the array types are to be considered
363 // equivalent.
364 // eg. int[][1] and int[1][1] become
365 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
366 // removing the outermost VAT gives
367 // CAT(1, int) and CAT(1, int)
368 // which are equal, therefore the array types are equivalent.
Eli Friedmane0079792008-02-15 12:53:51 +0000369 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerf9167d12007-11-06 04:28:31 +0000370 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
371 return false;
Eli Friedmand32157f2008-01-29 07:51:12 +0000372 NewQType = NewAT->getElementType().getCanonicalType();
373 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerf9167d12007-11-06 04:28:31 +0000374 }
375
376 return NewQType == OldQType;
377}
378
Chris Lattner4b009652007-07-25 00:24:17 +0000379/// MergeVarDecl - We just parsed a variable 'New' which has the same name
380/// and scope as a previous declaration 'Old'. Figure out how to resolve this
381/// situation, merging decls or emitting diagnostics as appropriate.
382///
383/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
384/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
385///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000386VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000387 // Verify the old decl was also a variable.
388 VarDecl *Old = dyn_cast<VarDecl>(OldD);
389 if (!Old) {
390 Diag(New->getLocation(), diag::err_redefinition_different_kind,
391 New->getName());
392 Diag(OldD->getLocation(), diag::err_previous_definition);
393 return New;
394 }
Chris Lattner402b3372008-03-03 03:28:21 +0000395
396 MergeAttributes(New, Old);
397
Chris Lattner4b009652007-07-25 00:24:17 +0000398 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000399 QualType OldCType = Context.getCanonicalType(Old->getType());
400 QualType NewCType = Context.getCanonicalType(New->getType());
401 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000402 Diag(New->getLocation(), diag::err_redefinition, New->getName());
403 Diag(Old->getLocation(), diag::err_previous_definition);
404 return New;
405 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000406 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
407 if (New->getStorageClass() == VarDecl::Static &&
408 (Old->getStorageClass() == VarDecl::None ||
409 Old->getStorageClass() == VarDecl::Extern)) {
410 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
411 Diag(Old->getLocation(), diag::err_previous_definition);
412 return New;
413 }
414 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
415 if (New->getStorageClass() != VarDecl::Static &&
416 Old->getStorageClass() == VarDecl::Static) {
417 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
418 Diag(Old->getLocation(), diag::err_previous_definition);
419 return New;
420 }
421 // We've verified the types match, now handle "tentative" definitions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000422 if (Old->isFileVarDecl() && New->isFileVarDecl()) {
Steve Naroffb00247f2008-01-30 00:44:01 +0000423 // Handle C "tentative" external object definitions (C99 6.9.2).
424 bool OldIsTentative = false;
425 bool NewIsTentative = false;
426
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000427 if (!Old->getInit() &&
428 (Old->getStorageClass() == VarDecl::None ||
429 Old->getStorageClass() == VarDecl::Static))
Steve Naroffb00247f2008-01-30 00:44:01 +0000430 OldIsTentative = true;
431
432 // FIXME: this check doesn't work (since the initializer hasn't been
433 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
434 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
435 // thrown out the old decl.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000436 if (!New->getInit() &&
437 (New->getStorageClass() == VarDecl::None ||
438 New->getStorageClass() == VarDecl::Static))
Steve Naroffb00247f2008-01-30 00:44:01 +0000439 ; // change to NewIsTentative = true; once the code is moved.
440
441 if (NewIsTentative || OldIsTentative)
442 return New;
443 }
Steve Naroff89301de2008-05-12 22:36:43 +0000444 // Handle __private_extern__ just like extern.
Steve Naroffb00247f2008-01-30 00:44:01 +0000445 if (Old->getStorageClass() != VarDecl::Extern &&
Steve Naroff89301de2008-05-12 22:36:43 +0000446 Old->getStorageClass() != VarDecl::PrivateExtern &&
447 New->getStorageClass() != VarDecl::Extern &&
448 New->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner4b009652007-07-25 00:24:17 +0000449 Diag(New->getLocation(), diag::err_redefinition, New->getName());
450 Diag(Old->getLocation(), diag::err_previous_definition);
451 }
452 return New;
453}
454
Chris Lattner3e254fb2008-04-08 04:40:51 +0000455/// CheckParmsForFunctionDef - Check that the parameters of the given
456/// function are appropriate for the definition of a function. This
457/// takes care of any checks that cannot be performed on the
458/// declaration itself, e.g., that the types of each of the function
459/// parameters are complete.
460bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
461 bool HasInvalidParm = false;
462 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
463 ParmVarDecl *Param = FD->getParamDecl(p);
464
465 // C99 6.7.5.3p4: the parameters in a parameter type list in a
466 // function declarator that is part of a function definition of
467 // that function shall not have incomplete type.
468 if (Param->getType()->isIncompleteType() &&
469 !Param->isInvalidDecl()) {
470 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
471 Param->getType().getAsString());
472 Param->setInvalidDecl();
473 HasInvalidParm = true;
474 }
475 }
476
477 return HasInvalidParm;
478}
479
480/// CreateImplicitParameter - Creates an implicit function parameter
481/// in the scope S and with the given type. This routine is used, for
482/// example, to create the implicit "self" parameter in an Objective-C
483/// method.
484ParmVarDecl *
485Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
486 SourceLocation IdLoc, QualType Type) {
487 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
488 VarDecl::None, 0, 0);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000489 if (Id)
490 PushOnScopeChains(New, S);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000491
492 return New;
493}
494
Chris Lattner4b009652007-07-25 00:24:17 +0000495/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
496/// no declarator (e.g. "struct foo;") is parsed.
497Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
498 // TODO: emit error on 'int;' or 'const enum foo;'.
499 // TODO: emit error on 'typedef int;'
500 // if (!DS.isMissingDeclaratorOk()) Diag(...);
501
Steve Naroffedafc0b2007-11-17 21:37:36 +0000502 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000503}
504
Steve Narofff0b23542008-01-10 22:15:12 +0000505bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000506 // Get the type before calling CheckSingleAssignmentConstraints(), since
507 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000508 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000509
Chris Lattner005ed752008-01-04 18:04:52 +0000510 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
511 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
512 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000513}
514
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000515bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Narofff0b23542008-01-10 22:15:12 +0000516 QualType ElementType) {
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000517 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Narofff0b23542008-01-10 22:15:12 +0000518 if (CheckSingleInitializer(expr, ElementType))
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000519 return true; // types weren't compatible.
520
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000521 if (savExpr != expr) // The type was promoted, update initializer list.
522 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000523 return false;
524}
525
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000526bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedman8ff07782008-02-15 18:16:39 +0000527 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000528 // C99 6.7.8p14. We have an array of character type with unknown size
529 // being initialized to a string literal.
530 llvm::APSInt ConstVal(32);
531 ConstVal = strLiteral->getByteLength() + 1;
532 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000533 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000534 ArrayType::Normal, 0);
535 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
536 // C99 6.7.8p14. We have an array of character type with known size.
537 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
538 Diag(strLiteral->getSourceRange().getBegin(),
539 diag::warn_initializer_string_for_char_array_too_long,
540 strLiteral->getSourceRange());
541 } else {
542 assert(0 && "HandleStringLiteralInit(): Invalid array type");
543 }
544 // Set type from "char *" to "constant array of char".
545 strLiteral->setType(DeclT);
546 // For now, we always return false (meaning success).
547 return false;
548}
549
550StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000551 const ArrayType *AT = DeclType->getAsArrayType();
Steve Narofff3cb5142008-01-25 00:51:06 +0000552 if (AT && AT->getElementType()->isCharType()) {
553 return dyn_cast<StringLiteral>(Init);
554 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000555 return 0;
556}
557
Steve Narofff3cb5142008-01-25 00:51:06 +0000558// CheckInitializerListTypes - Checks the types of elements of an initializer
559// list. This function is recursive: it calls itself to initialize subelements
560// of aggregate types. Note that the topLevel parameter essentially refers to
561// whether this expression "owns" the initializer list passed in, or if this
562// initialization is taking elements out of a parent initializer. Each
563// call to this function adds zero or more to startIndex, reports any errors,
564// and returns true if it found any inconsistent types.
565bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
566 bool topLevel, unsigned& startIndex) {
Steve Naroffcb69fb72007-12-10 22:44:33 +0000567 bool hadError = false;
Steve Narofff3cb5142008-01-25 00:51:06 +0000568
569 if (DeclType->isScalarType()) {
570 // The simplest case: initializing a single scalar
571 if (topLevel) {
572 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
573 IList->getSourceRange());
574 }
575 if (startIndex < IList->getNumInits()) {
576 Expr* expr = IList->getInit(startIndex);
577 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
578 // FIXME: Should an error be reported here instead?
579 unsigned newIndex = 0;
580 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
581 } else {
582 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
583 }
584 ++startIndex;
585 }
586 // FIXME: Should an error be reported for empty initializer list + scalar?
587 } else if (DeclType->isVectorType()) {
588 if (startIndex < IList->getNumInits()) {
589 const VectorType *VT = DeclType->getAsVectorType();
590 int maxElements = VT->getNumElements();
591 QualType elementType = VT->getElementType();
592
593 for (int i = 0; i < maxElements; ++i) {
594 // Don't attempt to go past the end of the init list
595 if (startIndex >= IList->getNumInits())
596 break;
597 Expr* expr = IList->getInit(startIndex);
598 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
599 unsigned newIndex = 0;
600 hadError |= CheckInitializerListTypes(SubInitList, elementType,
601 true, newIndex);
602 ++startIndex;
603 } else {
604 hadError |= CheckInitializerListTypes(IList, elementType,
605 false, startIndex);
606 }
607 }
608 }
609 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
610 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroffedce4ec2008-01-28 02:00:41 +0000611 if (startIndex < IList->getNumInits() && !topLevel &&
612 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
613 DeclType)) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000614 // We found a compatible struct; per the standard, this initializes the
615 // struct. (The C standard technically says that this only applies for
616 // initializers for declarations with automatic scope; however, this
617 // construct is unambiguous anyway because a struct cannot contain
618 // a type compatible with itself. We'll output an error when we check
619 // if the initializer is constant.)
620 // FIXME: Is a call to CheckSingleInitializer required here?
621 ++startIndex;
622 } else {
623 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffee467032008-02-11 00:06:17 +0000624
Steve Naroff576df292008-02-11 21:52:37 +0000625 // If the record is invalid, some of it's members are invalid. To avoid
626 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffee467032008-02-11 00:06:17 +0000627 if (structDecl->isInvalidDecl())
628 return true;
629
Steve Narofff3cb5142008-01-25 00:51:06 +0000630 // If structDecl is a forward declaration, this loop won't do anything;
631 // That's okay, because an error should get printed out elsewhere. It
632 // might be worthwhile to skip over the rest of the initializer, though.
633 int numMembers = structDecl->getNumMembers() -
634 structDecl->hasFlexibleArrayMember();
635 for (int i = 0; i < numMembers; i++) {
636 // Don't attempt to go past the end of the init list
637 if (startIndex >= IList->getNumInits())
638 break;
639 FieldDecl * curField = structDecl->getMember(i);
640 if (!curField->getIdentifier()) {
641 // Don't initialize unnamed fields, e.g. "int : 20;"
642 continue;
643 }
644 QualType fieldType = curField->getType();
645 Expr* expr = IList->getInit(startIndex);
646 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
647 unsigned newStart = 0;
648 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
649 true, newStart);
650 ++startIndex;
651 } else {
652 hadError |= CheckInitializerListTypes(IList, fieldType,
653 false, startIndex);
654 }
655 if (DeclType->isUnionType())
656 break;
657 }
658 // FIXME: Implement flexible array initialization GCC extension (it's a
659 // really messy extension to implement, unfortunately...the necessary
660 // information isn't actually even here!)
661 }
662 } else if (DeclType->isArrayType()) {
663 // Check for the special-case of initializing an array with a string.
664 if (startIndex < IList->getNumInits()) {
665 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
666 DeclType)) {
667 CheckStringLiteralInit(lit, DeclType);
668 ++startIndex;
669 if (topLevel && startIndex < IList->getNumInits()) {
670 // We have leftover initializers; warn
671 Diag(IList->getInit(startIndex)->getLocStart(),
672 diag::err_excess_initializers_in_char_array_initializer,
673 IList->getInit(startIndex)->getSourceRange());
674 }
675 return false;
676 }
677 }
678 int maxElements;
Eli Friedman8ff07782008-02-15 18:16:39 +0000679 if (DeclType->isIncompleteArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000680 // FIXME: use a proper constant
681 maxElements = 0x7FFFFFFF;
Chris Lattnerb9716a62008-02-20 23:17:35 +0000682 } else if (const VariableArrayType *VAT =
683 DeclType->getAsVariableArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000684 // Check for VLAs; in standard C it would be possible to check this
685 // earlier, but I don't know where clang accepts VLAs (gcc accepts
686 // them in all sorts of strange places).
Eli Friedman8ff07782008-02-15 18:16:39 +0000687 Diag(VAT->getSizeExpr()->getLocStart(),
688 diag::err_variable_object_no_init,
689 VAT->getSizeExpr()->getSourceRange());
690 hadError = true;
691 maxElements = 0x7FFFFFFF;
Steve Narofff3cb5142008-01-25 00:51:06 +0000692 } else {
693 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
694 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
695 }
696 QualType elementType = DeclType->getAsArrayType()->getElementType();
697 int numElements = 0;
698 for (int i = 0; i < maxElements; ++i, ++numElements) {
699 // Don't attempt to go past the end of the init list
700 if (startIndex >= IList->getNumInits())
701 break;
702 Expr* expr = IList->getInit(startIndex);
703 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
704 unsigned newIndex = 0;
705 hadError |= CheckInitializerListTypes(SubInitList, elementType,
706 true, newIndex);
707 ++startIndex;
708 } else {
709 hadError |= CheckInitializerListTypes(IList, elementType,
710 false, startIndex);
711 }
712 }
Eli Friedmane0079792008-02-15 12:53:51 +0000713 if (DeclType->isIncompleteArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000714 // If this is an incomplete array type, the actual type needs to
715 // be calculated here
716 if (numElements == 0) {
717 // Sizing an array implicitly to zero is not allowed
718 // (It could in theory be allowed, but it doesn't really matter.)
719 Diag(IList->getLocStart(),
720 diag::err_at_least_one_initializer_needed_to_size_array);
721 hadError = true;
722 } else {
723 llvm::APSInt ConstVal(32);
724 ConstVal = numElements;
725 DeclType = Context.getConstantArrayType(elementType, ConstVal,
726 ArrayType::Normal, 0);
727 }
728 }
729 } else {
730 assert(0 && "Aggregate that isn't a function or array?!");
731 }
732 } else {
733 // In C, all types are either scalars or aggregates, but
734 // additional handling is needed here for C++ (and possibly others?).
735 assert(0 && "Unsupported initializer type");
736 }
737
738 // If this init list is a base list, we set the type; an initializer doesn't
739 // fundamentally have a type, but this makes the ASTs a bit easier to read
740 if (topLevel)
741 IList->setType(DeclType);
742
743 if (topLevel && startIndex < IList->getNumInits()) {
744 // We have leftover initializers; warn
745 Diag(IList->getInit(startIndex)->getLocStart(),
746 diag::warn_excess_initializers,
747 IList->getInit(startIndex)->getSourceRange());
748 }
749 return hadError;
750}
751
752bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroff8e9337f2008-01-21 23:53:58 +0000753 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
754 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedman8ff07782008-02-15 18:16:39 +0000755 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroff8e9337f2008-01-21 23:53:58 +0000756 return Diag(VAT->getSizeExpr()->getLocStart(),
757 diag::err_variable_object_no_init,
758 VAT->getSizeExpr()->getSourceRange());
759
Steve Naroffcb69fb72007-12-10 22:44:33 +0000760 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
761 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000762 // FIXME: Handle wide strings
763 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
764 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000765
766 if (DeclType->isArrayType())
767 return Diag(Init->getLocStart(),
768 diag::err_array_init_list_required,
769 Init->getSourceRange());
770
Steve Narofff0b23542008-01-10 22:15:12 +0000771 return CheckSingleInitializer(Init, DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000772 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000773#if 1
Steve Narofff3cb5142008-01-25 00:51:06 +0000774 unsigned newIndex = 0;
775 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000776#else
777 InitListChecker CheckInitList(this, InitList, DeclType);
778 return CheckInitList.HadError();
779#endif
Steve Naroffe14e5542007-09-02 02:04:30 +0000780}
781
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000782Sema::DeclTy *
Steve Naroff0acc9c92007-09-15 18:49:24 +0000783Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000784 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000785 IdentifierInfo *II = D.getIdentifier();
786
787 // All of these full declarators require an identifier. If it doesn't have
788 // one, the ParsedFreeStandingDeclSpec action should be used.
789 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000790 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000791 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000792 D.getDeclSpec().getSourceRange(), D.getSourceRange());
793 return 0;
794 }
795
Chris Lattnera7549902007-08-26 06:24:45 +0000796 // The scope passed in may not be a decl scope. Zip up the scope tree until
797 // we find one that is.
798 while ((S->getFlags() & Scope::DeclScope) == 0)
799 S = S->getParent();
800
Chris Lattner4b009652007-07-25 00:24:17 +0000801 // See if this is a redefinition of a variable in the same scope.
Steve Naroff6384a012008-04-02 14:35:35 +0000802 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000803 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000804 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000805
806 // In C++, the previous declaration we find might be a tag type
807 // (class or enum). In this case, the new declaration will hide the
808 // tag type.
809 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
810 PrevDecl = 0;
811
Chris Lattner82bb4792007-11-14 06:34:38 +0000812 QualType R = GetTypeForDeclarator(D, S);
813 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
814
Chris Lattner4b009652007-07-25 00:24:17 +0000815 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000816 // Check that there are no default arguments (C++ only).
817 if (getLangOptions().CPlusPlus)
818 CheckExtraCXXDefaultArguments(D);
819
Chris Lattner82bb4792007-11-14 06:34:38 +0000820 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000821 if (!NewTD) return 0;
822
823 // Handle attributes prior to checking for duplicates in MergeVarDecl
824 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
825 D.getAttributes());
Steve Narofff8a09432008-01-09 23:34:55 +0000826 // Merge the decl with the existing one if appropriate. If the decl is
827 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000828 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000829 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
830 if (NewTD == 0) return 0;
831 }
832 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000833 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000834 // C99 6.7.7p2: If a typedef name specifies a variably modified type
835 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000836 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
837 // FIXME: Diagnostic needs to be fixed.
838 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff5eb879b2007-08-31 17:20:07 +0000839 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000840 }
841 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000842 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000843 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000844 switch (D.getDeclSpec().getStorageClassSpec()) {
845 default: assert(0 && "Unknown storage class!");
846 case DeclSpec::SCS_auto:
847 case DeclSpec::SCS_register:
848 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
849 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000850 InvalidDecl = true;
851 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000852 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
853 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
854 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000855 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000856 }
857
Chris Lattner4c7802b2008-03-15 21:24:04 +0000858 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattnereee57c02008-04-04 06:12:32 +0000859 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
860 D.getIdentifierLoc(),
Chris Lattner4c7802b2008-03-15 21:24:04 +0000861 II, R, SC, isInline,
862 LastDeclarator);
Ted Kremenek117f1862008-02-27 22:18:07 +0000863 // Handle attributes.
Ted Kremenek117f1862008-02-27 22:18:07 +0000864 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
865 D.getAttributes());
Chris Lattner3e254fb2008-04-08 04:40:51 +0000866
867 // Copy the parameter declarations from the declarator D to
868 // the function declaration NewFD, if they are available.
869 if (D.getNumTypeObjects() > 0 &&
870 D.getTypeObject(0).Fun.hasPrototype) {
871 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
872
873 // Create Decl objects for each parameter, adding them to the
874 // FunctionDecl.
875 llvm::SmallVector<ParmVarDecl*, 16> Params;
876
877 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
878 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +0000879 // single void argument.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000880 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
881 FTI.ArgInfo[0].Param &&
882 !((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
883 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
884 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +0000885 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
886
Chris Lattnerda7b5f02008-04-10 02:26:16 +0000887 // In C++, the empty parameter-type-list must be spelled "void"; a
888 // typedef of void is not permitted.
889 if (getLangOptions().CPlusPlus &&
Chris Lattner97316c02008-04-10 02:22:51 +0000890 Param->getType() != Context.VoidTy) {
891 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
892 }
893
Chris Lattner3e254fb2008-04-08 04:40:51 +0000894 } else {
895 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
896 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
897 }
898
899 NewFD->setParams(&Params[0], Params.size());
900 }
901
Steve Narofff8a09432008-01-09 23:34:55 +0000902 // Merge the decl with the existing one if appropriate. Since C functions
903 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000904 if (PrevDecl &&
905 (!getLangOptions().CPlusPlus ||
906 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000907 bool Redeclaration = false;
908 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Chris Lattner4b009652007-07-25 00:24:17 +0000909 if (NewFD == 0) return 0;
Douglas Gregor42214c52008-04-21 02:02:58 +0000910 if (Redeclaration) {
911 // Note that the new declaration is a redeclaration of the
912 // older declaration. Then return the older declaration: the
913 // new one is only kept within the set of previous
914 // declarations for this function.
915 FunctionDecl *OldFD = (FunctionDecl *)PrevDecl;
916 OldFD->AddRedeclaration(NewFD);
917 return OldFD;
918 }
Chris Lattner4b009652007-07-25 00:24:17 +0000919 }
920 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000921
922 // In C++, check default arguments now that we have merged decls.
923 if (getLangOptions().CPlusPlus)
924 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +0000925 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000926 // Check that there are no default arguments (C++ only).
927 if (getLangOptions().CPlusPlus)
928 CheckExtraCXXDefaultArguments(D);
929
Ted Kremenek42730c52008-01-07 19:49:32 +0000930 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000931 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
932 D.getIdentifier()->getName());
933 InvalidDecl = true;
934 }
Chris Lattner4b009652007-07-25 00:24:17 +0000935
936 VarDecl *NewVD;
937 VarDecl::StorageClass SC;
938 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +0000939 default: assert(0 && "Unknown storage class!");
940 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
941 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
942 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
943 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
944 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
945 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000946 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000947 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000948 // C99 6.9p2: The storage-class specifiers auto and register shall not
949 // appear in the declaration specifiers in an external declaration.
950 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
951 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
952 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000953 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000954 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000955 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
956 II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000957 } else {
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000958 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
959 II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000960 }
Chris Lattner4b009652007-07-25 00:24:17 +0000961 // Handle attributes prior to checking for duplicates in MergeVarDecl
962 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
963 D.getAttributes());
Nate Begemanea583262008-03-14 18:07:10 +0000964
965 // Emit an error if an address space was applied to decl with local storage.
966 // This includes arrays of objects with address space qualifiers, but not
967 // automatic variables that point to other address spaces.
968 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +0000969 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
970 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
971 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +0000972 }
Steve Narofff8a09432008-01-09 23:34:55 +0000973 // Merge the decl with the existing one if appropriate. If the decl is
974 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000975 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000976 NewVD = MergeVarDecl(NewVD, PrevDecl);
977 if (NewVD == 0) return 0;
978 }
Chris Lattner4b009652007-07-25 00:24:17 +0000979 New = NewVD;
980 }
981
982 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000983 if (II)
984 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000985 // If any semantic error occurred, mark the decl as invalid.
986 if (D.getInvalidType() || InvalidDecl)
987 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000988
989 return New;
990}
991
Steve Narofff0b23542008-01-10 22:15:12 +0000992bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
993 SourceLocation loc;
994 // FIXME: Remove the isReference check and handle assignment to a reference.
995 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
996 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
997 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
998 return true;
999 }
1000 return false;
1001}
1002
Steve Naroff6a0e2092007-09-12 14:07:44 +00001003void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001004 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001005 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001006 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00001007
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001008 // If there is no declaration, there was an error parsing it. Just ignore
1009 // the initializer.
1010 if (RealDecl == 0) {
1011 delete Init;
1012 return;
1013 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001014
Steve Naroff420d0f52007-09-12 20:13:48 +00001015 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1016 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00001017 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1018 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00001019 RealDecl->setInvalidDecl();
1020 return;
1021 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001022 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00001023 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00001024 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001025 if (VDecl->isBlockVarDecl()) {
1026 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001027 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00001028 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001029 VDecl->setInvalidDecl();
1030 } else if (!VDecl->isInvalidDecl()) {
Steve Narofff3cb5142008-01-25 00:51:06 +00001031 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001032 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001033 if (SC == VarDecl::Static) // C99 6.7.8p4.
1034 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001035 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001036 } else if (VDecl->isFileVarDecl()) {
1037 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00001038 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001039 if (!VDecl->isInvalidDecl())
Steve Narofff3cb5142008-01-25 00:51:06 +00001040 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001041 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001042
1043 // C99 6.7.8p4. All file scoped initializers need to be constant.
1044 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001045 }
1046 // If the type changed, it means we had an incomplete type that was
1047 // completed by the initializer. For example:
1048 // int ary[] = { 1, 3, 5 };
1049 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00001050 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001051 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00001052 Init->setType(DclT);
1053 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001054
1055 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00001056 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001057 return;
1058}
1059
Chris Lattner4b009652007-07-25 00:24:17 +00001060/// The declarators are chained together backwards, reverse the list.
1061Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1062 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001063 Decl *GroupDecl = static_cast<Decl*>(group);
1064 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00001065 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00001066
1067 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1068 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001069 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00001070 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001071 else { // reverse the list.
1072 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001073 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001074 Group->setNextDeclarator(NewGroup);
1075 NewGroup = Group;
1076 Group = Next;
1077 }
1078 }
1079 // Perform semantic analysis that depends on having fully processed both
1080 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001081 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00001082 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1083 if (!IDecl)
1084 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001085 QualType T = IDecl->getType();
1086
1087 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1088 // static storage duration, it shall not have a variable length array.
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001089 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1090 IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman70f414d2008-02-15 19:53:52 +00001091 if (T->getAsVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001092 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1093 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001094 }
1095 }
1096 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1097 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001098 if (IDecl->isBlockVarDecl() &&
1099 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001100 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +00001101 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1102 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001103 IDecl->setInvalidDecl();
1104 }
1105 }
1106 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1107 // object that has file scope without an initializer, and without a
1108 // storage-class specifier or with the storage-class specifier "static",
1109 // constitutes a tentative definition. Note: A tentative definition with
1110 // external linkage is valid (C99 6.2.2p5).
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001111 if (IDecl && !IDecl->getInit() &&
1112 (IDecl->getStorageClass() == VarDecl::Static ||
1113 IDecl->getStorageClass() == VarDecl::None)) {
Eli Friedmane0079792008-02-15 12:53:51 +00001114 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00001115 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1116 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001117 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00001118 // C99 6.9.2p3: If the declaration of an identifier for an object is
1119 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1120 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +00001121 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1122 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001123 IDecl->setInvalidDecl();
1124 }
1125 }
Chris Lattner4b009652007-07-25 00:24:17 +00001126 }
1127 return NewGroup;
1128}
Steve Naroff91b03f72007-08-28 03:03:08 +00001129
Chris Lattner3e254fb2008-04-08 04:40:51 +00001130/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1131/// to introduce parameters into function prototype scope.
1132Sema::DeclTy *
1133Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1134 DeclSpec &DS = D.getDeclSpec();
1135
1136 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1137 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1138 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1139 Diag(DS.getStorageClassSpecLoc(),
1140 diag::err_invalid_storage_class_in_func_decl);
1141 DS.ClearStorageClassSpecs();
1142 }
1143 if (DS.isThreadSpecified()) {
1144 Diag(DS.getThreadSpecLoc(),
1145 diag::err_invalid_storage_class_in_func_decl);
1146 DS.ClearStorageClassSpecs();
1147 }
1148
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001149 // Check that there are no default arguments inside the type of this
1150 // parameter (C++ only).
1151 if (getLangOptions().CPlusPlus)
1152 CheckExtraCXXDefaultArguments(D);
1153
Chris Lattner3e254fb2008-04-08 04:40:51 +00001154 // In this context, we *do not* check D.getInvalidType(). If the declarator
1155 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1156 // though it will not reflect the user specified type.
1157 QualType parmDeclType = GetTypeForDeclarator(D, S);
1158
1159 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1160
Chris Lattner4b009652007-07-25 00:24:17 +00001161 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1162 // Can this happen for params? We already checked that they don't conflict
1163 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001164 IdentifierInfo *II = D.getIdentifier();
1165 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1166 if (S->isDeclScope(PrevDecl)) {
1167 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1168 dyn_cast<NamedDecl>(PrevDecl)->getName());
1169
1170 // Recover by removing the name
1171 II = 0;
1172 D.SetIdentifier(0, D.getIdentifierLoc());
1173 }
Chris Lattner4b009652007-07-25 00:24:17 +00001174 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00001175
1176 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1177 // Doing the promotion here has a win and a loss. The win is the type for
1178 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1179 // code generator). The loss is the orginal type isn't preserved. For example:
1180 //
1181 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1182 // int blockvardecl[5];
1183 // sizeof(parmvardecl); // size == 4
1184 // sizeof(blockvardecl); // size == 20
1185 // }
1186 //
1187 // For expressions, all implicit conversions are captured using the
1188 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1189 //
1190 // FIXME: If a source translation tool needs to see the original type, then
1191 // we need to consider storing both types (in ParmVarDecl)...
1192 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00001193 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00001194 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00001195 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00001196 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00001197 parmDeclType = Context.getPointerType(parmDeclType);
1198
Chris Lattner3e254fb2008-04-08 04:40:51 +00001199 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1200 D.getIdentifierLoc(), II,
1201 parmDeclType, VarDecl::None,
1202 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00001203
Chris Lattner3e254fb2008-04-08 04:40:51 +00001204 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00001205 New->setInvalidDecl();
1206
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001207 if (II)
1208 PushOnScopeChains(New, S);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00001209
Nate Begemanc5b66682008-05-09 16:56:01 +00001210 HandleDeclAttributes(New, D.getDeclSpec().getAttributes(),
1211 D.getAttributes());
Chris Lattner4b009652007-07-25 00:24:17 +00001212 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001213
Chris Lattner4b009652007-07-25 00:24:17 +00001214}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001215
Chris Lattnerea148702007-10-09 17:14:05 +00001216Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +00001217 assert(CurFunctionDecl == 0 && "Function parsing confused");
1218 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1219 "Not a function declarator!");
1220 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001221
Chris Lattner4b009652007-07-25 00:24:17 +00001222 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1223 // for a K&R function.
1224 if (!FTI.hasPrototype) {
1225 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001226 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001227 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1228 FTI.ArgInfo[i].Ident->getName());
1229 // Implicitly declare the argument as type 'int' for lack of a better
1230 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001231 DeclSpec DS;
1232 const char* PrevSpec; // unused
1233 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1234 PrevSpec);
1235 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1236 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1237 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00001238 }
1239 }
Chris Lattnerec9361f2008-02-17 19:31:09 +00001240
Chris Lattner4b009652007-07-25 00:24:17 +00001241 // Since this is a function definition, act as though we have information
1242 // about the arguments.
Chris Lattnerec9361f2008-02-17 19:31:09 +00001243 if (FTI.NumArgs)
1244 FTI.hasPrototype = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001245 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001246 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00001247 }
1248
1249 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001250
1251 // See if this is a redefinition.
Steve Naroffe57c21a2008-04-01 23:04:06 +00001252 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroff6384a012008-04-02 14:35:35 +00001253 GlobalScope);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001254 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1255 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1256 const FunctionDecl *Definition;
1257 if (FD->getBody(Definition)) {
1258 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1259 D.getIdentifier()->getName());
1260 Diag(Definition->getLocation(), diag::err_previous_definition);
1261 }
Steve Naroff1d5bd642008-01-14 20:51:29 +00001262 }
1263 }
Steve Naroff4a712442008-02-12 01:09:36 +00001264 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattner2d2216b2008-02-16 01:20:36 +00001265 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattner4b009652007-07-25 00:24:17 +00001266 CurFunctionDecl = FD;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001267 PushDeclContext(FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001268
1269 // Check the validity of our function parameters
1270 CheckParmsForFunctionDef(FD);
1271
1272 // Introduce our parameters into the function scope
1273 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1274 ParmVarDecl *Param = FD->getParamDecl(p);
1275 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001276 if (Param->getIdentifier())
1277 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001278 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001279
Chris Lattner4b009652007-07-25 00:24:17 +00001280 return FD;
1281}
1282
Steve Naroff99ee4302007-11-11 23:20:51 +00001283Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1284 Decl *dcl = static_cast<Decl *>(D);
1285 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1286 FD->setBody((Stmt*)Body);
1287 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff8ba51142007-12-13 18:18:56 +00001288 CurFunctionDecl = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001289 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001290 MD->setBody((Stmt*)Body);
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001291 CurMethodDecl = 0;
Steve Naroff8ba51142007-12-13 18:18:56 +00001292 }
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001293 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00001294 // Verify and clean out per-function state.
1295
1296 // Check goto/label use.
1297 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1298 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1299 // Verify that we have no forward references left. If so, there was a goto
1300 // or address of a label taken, but no definition of it. Label fwd
1301 // definitions are indicated with a null substmt.
1302 if (I->second->getSubStmt() == 0) {
1303 LabelStmt *L = I->second;
1304 // Emit error.
1305 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1306
1307 // At this point, we have gotos that use the bogus label. Stitch it into
1308 // the function body so that they aren't leaked and that the AST is well
1309 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00001310 if (Body) {
1311 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1312 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1313 } else {
1314 // The whole function wasn't parsed correctly, just delete this.
1315 delete L;
1316 }
Chris Lattner4b009652007-07-25 00:24:17 +00001317 }
1318 }
1319 LabelMap.clear();
1320
Steve Naroff99ee4302007-11-11 23:20:51 +00001321 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001322}
1323
Chris Lattner4b009652007-07-25 00:24:17 +00001324/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1325/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001326ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1327 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001328 // Extension in C99. Legal in C90, but warn about it.
1329 if (getLangOptions().C99)
Chris Lattner4b009652007-07-25 00:24:17 +00001330 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001331 else
Chris Lattner4b009652007-07-25 00:24:17 +00001332 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1333
1334 // FIXME: handle stuff like:
1335 // void foo() { extern float X(); }
1336 // void bar() { X(); } <-- implicit decl for X in another scope.
1337
1338 // Set a Declarator for the implicit definition: int foo();
1339 const char *Dummy;
1340 DeclSpec DS;
1341 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1342 Error = Error; // Silence warning.
1343 assert(!Error && "Error setting up implicit decl!");
1344 Declarator D(DS, Declarator::BlockContext);
1345 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1346 D.SetIdentifier(&II, Loc);
1347
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001348 // Insert this function into translation-unit scope.
1349
1350 DeclContext *PrevDC = CurContext;
1351 CurContext = Context.getTranslationUnitDecl();
1352
Steve Naroff9104f3c2008-04-04 14:32:09 +00001353 FunctionDecl *FD =
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001354 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00001355 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001356
1357 CurContext = PrevDC;
1358
Steve Naroff9104f3c2008-04-04 14:32:09 +00001359 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00001360}
1361
1362
Chris Lattner82bb4792007-11-14 06:34:38 +00001363TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00001364 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00001365 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001366 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00001367
1368 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00001369 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1370 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00001371 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00001372 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001373 if (D.getInvalidType())
1374 NewTD->setInvalidDecl();
1375 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00001376}
1377
Steve Naroff0acc9c92007-09-15 18:49:24 +00001378/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001379/// former case, Name will be non-null. In the later case, Name will be null.
1380/// TagType indicates what kind of tag this is. TK indicates whether this is a
1381/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001382Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001383 SourceLocation KWLoc, IdentifierInfo *Name,
1384 SourceLocation NameLoc, AttributeList *Attr) {
1385 // If this is a use of an existing tag, it must have a name.
1386 assert((Name != 0 || TK == TK_Definition) &&
1387 "Nameless record must be a definition!");
1388
1389 Decl::Kind Kind;
1390 switch (TagType) {
1391 default: assert(0 && "Unknown tag type!");
1392 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1393 case DeclSpec::TST_union: Kind = Decl::Union; break;
Chris Lattner2e78db32008-04-13 18:59:07 +00001394 case DeclSpec::TST_class: Kind = Decl::Class; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001395 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1396 }
1397
1398 // If this is a named struct, check to see if there was a previous forward
1399 // declaration or definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001400 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1401 if (ScopedDecl *PrevDecl =
1402 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Chris Lattner4b009652007-07-25 00:24:17 +00001403
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001404 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1405 "unexpected Decl type");
1406 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1407 // If this is a use of a previous tag, or if the tag is already declared in
1408 // the same scope (so that the definition/declaration completes or
1409 // rementions the tag), reuse the decl.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001410 if (TK == TK_Reference ||
1411 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001412 // Make sure that this wasn't declared as an enum and now used as a struct
1413 // or something similar.
1414 if (PrevDecl->getKind() != Kind) {
1415 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1416 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1417 }
1418
1419 // If this is a use or a forward declaration, we're good.
1420 if (TK != TK_Definition)
1421 return PrevDecl;
Chris Lattner4b009652007-07-25 00:24:17 +00001422
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001423 // Diagnose attempts to redefine a tag.
1424 if (PrevTagDecl->isDefinition()) {
1425 Diag(NameLoc, diag::err_redefinition, Name->getName());
1426 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1427 // If this is a redefinition, recover by making this struct be
1428 // anonymous, which will make any later references get the previous
1429 // definition.
1430 Name = 0;
1431 } else {
1432 // Okay, this is definition of a previously declared or referenced tag.
1433 // Move the location of the decl to be the definition site.
1434 PrevDecl->setLocation(NameLoc);
1435 return PrevDecl;
1436 }
Chris Lattner4b009652007-07-25 00:24:17 +00001437 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001438 // If we get here, this is a definition of a new struct type in a nested
1439 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1440 // type.
1441 } else {
1442 // The tag name clashes with a namespace name, issue an error and recover
1443 // by making this tag be anonymous.
1444 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1445 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1446 Name = 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001447 }
Chris Lattner4b009652007-07-25 00:24:17 +00001448 }
1449
1450 // If there is an identifier, use the location of the identifier as the
1451 // location of the decl, otherwise use the location of the struct/union
1452 // keyword.
1453 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1454
1455 // Otherwise, if this is the first time we've seen this tag, create the decl.
1456 TagDecl *New;
1457 switch (Kind) {
1458 default: assert(0 && "Unknown tag kind!");
1459 case Decl::Enum:
1460 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1461 // enum X { A, B, C } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00001462 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001463 // If this is an undefined enum, warn.
1464 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1465 break;
1466 case Decl::Union:
1467 case Decl::Struct:
1468 case Decl::Class:
1469 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1470 // struct X { int A; } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00001471 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001472 break;
1473 }
1474
1475 // If this has an identifier, add it to the scope stack.
1476 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001477 // The scope passed in may not be a decl scope. Zip up the scope tree until
1478 // we find one that is.
1479 while ((S->getFlags() & Scope::DeclScope) == 0)
1480 S = S->getParent();
1481
1482 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001483 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00001484 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00001485
Anders Carlsson136cdc32008-02-16 00:29:18 +00001486 HandleDeclAttributes(New, Attr, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001487 return New;
1488}
1489
Steve Naroff0acc9c92007-09-15 18:49:24 +00001490/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001491/// to create a FieldDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001492Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner4b009652007-07-25 00:24:17 +00001493 SourceLocation DeclStart,
1494 Declarator &D, ExprTy *BitfieldWidth) {
1495 IdentifierInfo *II = D.getIdentifier();
1496 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001497 SourceLocation Loc = DeclStart;
1498 if (II) Loc = D.getIdentifierLoc();
1499
1500 // FIXME: Unnamed fields can be handled in various different ways, for
1501 // example, unnamed unions inject all members into the struct namespace!
1502
1503
1504 if (BitWidth) {
1505 // TODO: Validate.
1506 //printf("WARNING: BITFIELDS IGNORED!\n");
1507
1508 // 6.7.2.1p3
1509 // 6.7.2.1p4
1510
1511 } else {
1512 // Not a bitfield.
1513
1514 // validate II.
1515
1516 }
1517
1518 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001519 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1520 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001521
Chris Lattner4b009652007-07-25 00:24:17 +00001522 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1523 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00001524 if (T->isVariablyModifiedType()) {
1525 // FIXME: This diagnostic needs work
1526 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroff5eb879b2007-08-31 17:20:07 +00001527 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001528 }
Chris Lattner4b009652007-07-25 00:24:17 +00001529 // FIXME: Chain fielddecls together.
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001530 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff75494892007-09-11 21:17:26 +00001531
Anders Carlsson136cdc32008-02-16 00:29:18 +00001532 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1533 D.getAttributes());
1534
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001535 if (D.getInvalidType() || InvalidDecl)
1536 NewFD->setInvalidDecl();
1537 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001538}
1539
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001540/// TranslateIvarVisibility - Translate visibility from a token ID to an
1541/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00001542static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001543TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00001544 switch (ivarVisibility) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001545 case tok::objc_private: return ObjCIvarDecl::Private;
1546 case tok::objc_public: return ObjCIvarDecl::Public;
1547 case tok::objc_protected: return ObjCIvarDecl::Protected;
1548 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001549 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00001550 }
1551}
1552
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001553/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1554/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001555Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001556 SourceLocation DeclStart,
1557 Declarator &D, ExprTy *BitfieldWidth,
1558 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001559 IdentifierInfo *II = D.getIdentifier();
1560 Expr *BitWidth = (Expr*)BitfieldWidth;
1561 SourceLocation Loc = DeclStart;
1562 if (II) Loc = D.getIdentifierLoc();
1563
1564 // FIXME: Unnamed fields can be handled in various different ways, for
1565 // example, unnamed unions inject all members into the struct namespace!
1566
1567
1568 if (BitWidth) {
1569 // TODO: Validate.
1570 //printf("WARNING: BITFIELDS IGNORED!\n");
1571
1572 // 6.7.2.1p3
1573 // 6.7.2.1p4
1574
1575 } else {
1576 // Not a bitfield.
1577
1578 // validate II.
1579
1580 }
1581
1582 QualType T = GetTypeForDeclarator(D, S);
1583 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1584 bool InvalidDecl = false;
1585
1586 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1587 // than a variably modified type.
1588 if (T->isVariablyModifiedType()) {
1589 // FIXME: This diagnostic needs work
1590 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1591 InvalidDecl = true;
1592 }
1593
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001594 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001595
1596 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1597 D.getAttributes());
1598
1599 if (D.getInvalidType() || InvalidDecl)
1600 NewID->setInvalidDecl();
1601 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001602 if (Visibility != tok::objc_not_keyword)
1603 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001604 return NewID;
1605}
1606
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00001607void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001608 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001609 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001610 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001611 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1612 assert(EnclosingDecl && "missing record or interface decl");
1613 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1614
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001615 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001616 // Diagnose code like:
1617 // struct S { struct S {} X; };
1618 // We discover this when we complete the outer S. Reject and ignore the
1619 // outer S.
1620 Diag(Record->getLocation(), diag::err_nested_redefinition,
1621 Record->getKindName());
1622 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001623 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001624 return;
1625 }
Chris Lattner4b009652007-07-25 00:24:17 +00001626 // Verify that all the fields are okay.
1627 unsigned NumNamedMembers = 0;
1628 llvm::SmallVector<FieldDecl*, 32> RecFields;
1629 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00001630
Chris Lattner4b009652007-07-25 00:24:17 +00001631 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001632
Steve Naroff9bb759f2007-09-14 22:20:54 +00001633 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1634 assert(FD && "missing field decl");
1635
1636 // Remember all fields.
1637 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00001638
1639 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001640 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00001641
Chris Lattner4b009652007-07-25 00:24:17 +00001642 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001643 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001644 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00001645 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001646 FD->setInvalidDecl();
1647 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001648 continue;
1649 }
Chris Lattner4b009652007-07-25 00:24:17 +00001650 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1651 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001652 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001653 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001654 FD->setInvalidDecl();
1655 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001656 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001657 }
Chris Lattner4b009652007-07-25 00:24:17 +00001658 if (i != NumFields-1 || // ... that the last member ...
1659 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001660 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001661 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001662 FD->setInvalidDecl();
1663 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001664 continue;
1665 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001666 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00001667 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1668 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001669 FD->setInvalidDecl();
1670 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001671 continue;
1672 }
Chris Lattner4b009652007-07-25 00:24:17 +00001673 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001674 if (Record)
1675 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001676 }
Chris Lattner4b009652007-07-25 00:24:17 +00001677 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1678 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001679 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001680 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1681 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001682 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner4b009652007-07-25 00:24:17 +00001683 Record->setHasFlexibleArrayMember(true);
1684 } else {
1685 // If this is a struct/class and this is not the last element, reject
1686 // it. Note that GCC supports variable sized arrays in the middle of
1687 // structures.
1688 if (i != NumFields-1) {
1689 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1690 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001691 FD->setInvalidDecl();
1692 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001693 continue;
1694 }
Chris Lattner4b009652007-07-25 00:24:17 +00001695 // We support flexible arrays at the end of structs in other structs
1696 // as an extension.
1697 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1698 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001699 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001700 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001701 }
1702 }
1703 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001704 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00001705 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001706 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1707 FD->getName());
1708 FD->setInvalidDecl();
1709 EnclosingDecl->setInvalidDecl();
1710 continue;
1711 }
Chris Lattner4b009652007-07-25 00:24:17 +00001712 // Keep track of the number of named members.
1713 if (IdentifierInfo *II = FD->getIdentifier()) {
1714 // Detect duplicate member names.
1715 if (!FieldIDs.insert(II)) {
1716 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1717 // Find the previous decl.
1718 SourceLocation PrevLoc;
1719 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1720 assert(i != e && "Didn't find previous def!");
1721 if (RecFields[i]->getIdentifier() == II) {
1722 PrevLoc = RecFields[i]->getLocation();
1723 break;
1724 }
1725 }
1726 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001727 FD->setInvalidDecl();
1728 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001729 continue;
1730 }
1731 ++NumNamedMembers;
1732 }
Chris Lattner4b009652007-07-25 00:24:17 +00001733 }
1734
Chris Lattner4b009652007-07-25 00:24:17 +00001735 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00001736 if (Record) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001737 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattner33aad6e2008-02-06 00:51:33 +00001738 Consumer.HandleTagDeclDefinition(Record);
1739 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00001740 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1741 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1742 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1743 else if (ObjCImplementationDecl *IMPDecl =
1744 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001745 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1746 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00001747 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001748 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001749 }
Chris Lattner4b009652007-07-25 00:24:17 +00001750}
1751
Steve Naroff0acc9c92007-09-15 18:49:24 +00001752Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001753 DeclTy *lastEnumConst,
1754 SourceLocation IdLoc, IdentifierInfo *Id,
1755 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00001756 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00001757 EnumConstantDecl *LastEnumConst =
1758 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1759 Expr *Val = static_cast<Expr*>(val);
1760
Chris Lattnera7549902007-08-26 06:24:45 +00001761 // The scope passed in may not be a decl scope. Zip up the scope tree until
1762 // we find one that is.
1763 while ((S->getFlags() & Scope::DeclScope) == 0)
1764 S = S->getParent();
1765
Chris Lattner4b009652007-07-25 00:24:17 +00001766 // Verify that there isn't already something declared with this name in this
1767 // scope.
Steve Naroff6384a012008-04-02 14:35:35 +00001768 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001769 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001770 if (isa<EnumConstantDecl>(PrevDecl))
1771 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1772 else
1773 Diag(IdLoc, diag::err_redefinition, Id->getName());
1774 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001775 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00001776 return 0;
1777 }
1778 }
1779
1780 llvm::APSInt EnumVal(32);
1781 QualType EltTy;
1782 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001783 // Make sure to promote the operand type to int.
1784 UsualUnaryConversions(Val);
1785
Chris Lattner4b009652007-07-25 00:24:17 +00001786 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1787 SourceLocation ExpLoc;
1788 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1789 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1790 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001791 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001792 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001793 } else {
1794 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001795 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001796 }
1797
1798 if (!Val) {
1799 if (LastEnumConst) {
1800 // Assign the last value + 1.
1801 EnumVal = LastEnumConst->getInitVal();
1802 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001803
1804 // Check for overflow on increment.
1805 if (EnumVal < LastEnumConst->getInitVal())
1806 Diag(IdLoc, diag::warn_enum_value_overflow);
1807
Chris Lattnere7f53a42007-08-27 17:37:24 +00001808 EltTy = LastEnumConst->getType();
1809 } else {
1810 // First value, set to zero.
1811 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00001812 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001813 }
Chris Lattner4b009652007-07-25 00:24:17 +00001814 }
1815
Chris Lattnere4650482008-03-15 06:12:44 +00001816 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00001817 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
1818 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00001819 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00001820
1821 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001822 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00001823 return New;
1824}
1825
Steve Naroff0acc9c92007-09-15 18:49:24 +00001826void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00001827 DeclTy **Elements, unsigned NumElements) {
1828 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1829 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1830
Chris Lattner435c3fd2007-08-28 05:10:31 +00001831 // TODO: If the result value doesn't fit in an int, it must be a long or long
1832 // long value. ISO C does not support this, but GCC does as an extension,
1833 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001834 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00001835
Chris Lattner206754a2007-08-28 06:15:15 +00001836 // Verify that all the values are okay, compute the size of the values, and
1837 // reverse the list.
1838 unsigned NumNegativeBits = 0;
1839 unsigned NumPositiveBits = 0;
1840
1841 // Keep track of whether all elements have type int.
1842 bool AllElementsInt = true;
1843
Chris Lattner4b009652007-07-25 00:24:17 +00001844 EnumConstantDecl *EltList = 0;
1845 for (unsigned i = 0; i != NumElements; ++i) {
1846 EnumConstantDecl *ECD =
1847 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1848 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001849
1850 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001851 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001852 assert(InitVal.getBitWidth() >= IntWidth &&
1853 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00001854 if (InitVal.getBitWidth() > IntWidth) {
1855 llvm::APSInt V(InitVal);
1856 V.trunc(IntWidth);
1857 V.extend(InitVal.getBitWidth());
1858 if (V != InitVal)
1859 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1860 InitVal.toString());
1861 }
Chris Lattner206754a2007-08-28 06:15:15 +00001862
1863 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001864 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00001865 NumPositiveBits = std::max(NumPositiveBits,
1866 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00001867 else
Chris Lattneraff63f02008-01-14 21:47:29 +00001868 NumNegativeBits = std::max(NumNegativeBits,
1869 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001870
Chris Lattner206754a2007-08-28 06:15:15 +00001871 // Keep track of whether every enum element has type int (very commmon).
1872 if (AllElementsInt)
1873 AllElementsInt = ECD->getType() == Context.IntTy;
1874
Chris Lattner4b009652007-07-25 00:24:17 +00001875 ECD->setNextDeclarator(EltList);
1876 EltList = ECD;
1877 }
1878
Chris Lattner206754a2007-08-28 06:15:15 +00001879 // Figure out the type that should be used for this enum.
1880 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1881 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001882 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001883
1884 if (NumNegativeBits) {
1885 // If there is a negative value, figure out the smallest integer type (of
1886 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001887 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001888 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001889 BestWidth = IntWidth;
1890 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001891 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001892
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001893 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001894 BestType = Context.LongTy;
1895 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001896 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001897
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001898 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001899 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1900 BestType = Context.LongLongTy;
1901 }
1902 }
1903 } else {
1904 // If there is no negative value, figure out which of uint, ulong, ulonglong
1905 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001906 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001907 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001908 BestWidth = IntWidth;
1909 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00001910 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00001911 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00001912 } else {
1913 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001914 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001915 "How could an initializer get larger than ULL?");
1916 BestType = Context.UnsignedLongLongTy;
1917 }
1918 }
1919
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001920 // Loop over all of the enumerator constants, changing their types to match
1921 // the type of the enum if needed.
1922 for (unsigned i = 0; i != NumElements; ++i) {
1923 EnumConstantDecl *ECD =
1924 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1925 if (!ECD) continue; // Already issued a diagnostic.
1926
1927 // Standard C says the enumerators have int type, but we allow, as an
1928 // extension, the enumerators to be larger than int size. If each
1929 // enumerator value fits in an int, type it as an int, otherwise type it the
1930 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1931 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001932 if (ECD->getType() == Context.IntTy) {
1933 // Make sure the init value is signed.
1934 llvm::APSInt IV = ECD->getInitVal();
1935 IV.setIsSigned(true);
1936 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001937 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001938 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001939
1940 // Determine whether the value fits into an int.
1941 llvm::APSInt InitVal = ECD->getInitVal();
1942 bool FitsInInt;
1943 if (InitVal.isUnsigned() || !InitVal.isNegative())
1944 FitsInInt = InitVal.getActiveBits() < IntWidth;
1945 else
1946 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1947
1948 // If it fits into an integer type, force it. Otherwise force it to match
1949 // the enum decl type.
1950 QualType NewTy;
1951 unsigned NewWidth;
1952 bool NewSign;
1953 if (FitsInInt) {
1954 NewTy = Context.IntTy;
1955 NewWidth = IntWidth;
1956 NewSign = true;
1957 } else if (ECD->getType() == BestType) {
1958 // Already the right type!
1959 continue;
1960 } else {
1961 NewTy = BestType;
1962 NewWidth = BestWidth;
1963 NewSign = BestType->isSignedIntegerType();
1964 }
1965
1966 // Adjust the APSInt value.
1967 InitVal.extOrTrunc(NewWidth);
1968 InitVal.setIsSigned(NewSign);
1969 ECD->setInitVal(InitVal);
1970
1971 // Adjust the Expr initializer and type.
1972 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1973 ECD->setType(NewTy);
1974 }
Chris Lattner206754a2007-08-28 06:15:15 +00001975
Chris Lattner90a018d2007-08-28 18:24:31 +00001976 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00001977 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00001978}
1979
Anders Carlsson4f7f4412008-02-08 00:33:21 +00001980Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1981 ExprTy *expr) {
1982 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1983
Chris Lattner81db64a2008-03-16 00:16:02 +00001984 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00001985}
1986
Chris Lattner806a5f52008-01-12 07:05:38 +00001987Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00001988 SourceLocation LBrace,
1989 SourceLocation RBrace,
1990 const char *Lang,
1991 unsigned StrSize,
1992 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00001993 LinkageSpecDecl::LanguageIDs Language;
1994 Decl *dcl = static_cast<Decl *>(D);
1995 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1996 Language = LinkageSpecDecl::lang_c;
1997 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1998 Language = LinkageSpecDecl::lang_cxx;
1999 else {
2000 Diag(Loc, diag::err_bad_language);
2001 return 0;
2002 }
2003
2004 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00002005 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00002006}
2007
Chris Lattner49d15cb2008-02-21 00:48:22 +00002008void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson28e34e32007-12-19 06:16:30 +00002009
Chris Lattner49d15cb2008-02-21 00:48:22 +00002010 switch (Attr->getKind()) {
Chris Lattnerb9716a62008-02-20 23:17:35 +00002011 case AttributeList::AT_vector_size:
Chris Lattner4b009652007-07-25 00:24:17 +00002012 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner49d15cb2008-02-21 00:48:22 +00002013 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00002014 if (!newType.isNull()) // install the new vector type into the decl
2015 vDecl->setType(newType);
2016 }
2017 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2018 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00002019 Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00002020 if (!newType.isNull()) // install the new vector type into the decl
2021 tDecl->setUnderlyingType(newType);
2022 }
Chris Lattnerb9716a62008-02-20 23:17:35 +00002023 break;
Nate Begemanaf6ed502008-04-18 23:10:10 +00002024 case AttributeList::AT_ext_vector_type:
Steve Naroff82113e32007-07-29 16:33:31 +00002025 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Nate Begemanaf6ed502008-04-18 23:10:10 +00002026 HandleExtVectorTypeAttribute(tDecl, Attr);
Steve Naroff82113e32007-07-29 16:33:31 +00002027 else
Chris Lattner49d15cb2008-02-21 00:48:22 +00002028 Diag(Attr->getLoc(),
Nate Begemanaf6ed502008-04-18 23:10:10 +00002029 diag::err_typecheck_ext_vector_not_typedef);
Chris Lattnerb9716a62008-02-20 23:17:35 +00002030 break;
2031 case AttributeList::AT_address_space:
Christopher Lamb2a72bb32008-02-04 02:31:56 +00002032 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2033 QualType newType = HandleAddressSpaceTypeAttribute(
2034 tDecl->getUnderlyingType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00002035 Attr);
2036 tDecl->setUnderlyingType(newType);
Christopher Lamb2a72bb32008-02-04 02:31:56 +00002037 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2038 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00002039 Attr);
2040 // install the new addr spaced type into the decl
2041 vDecl->setType(newType);
Christopher Lamb2a72bb32008-02-04 02:31:56 +00002042 }
Chris Lattnerb9716a62008-02-20 23:17:35 +00002043 break;
Chris Lattneree4c3bf2008-02-29 16:48:43 +00002044 case AttributeList::AT_deprecated:
Chris Lattner402b3372008-03-03 03:28:21 +00002045 HandleDeprecatedAttribute(New, Attr);
2046 break;
2047 case AttributeList::AT_visibility:
2048 HandleVisibilityAttribute(New, Attr);
2049 break;
2050 case AttributeList::AT_weak:
2051 HandleWeakAttribute(New, Attr);
2052 break;
2053 case AttributeList::AT_dllimport:
2054 HandleDLLImportAttribute(New, Attr);
2055 break;
2056 case AttributeList::AT_dllexport:
2057 HandleDLLExportAttribute(New, Attr);
2058 break;
2059 case AttributeList::AT_nothrow:
2060 HandleNothrowAttribute(New, Attr);
Chris Lattneree4c3bf2008-02-29 16:48:43 +00002061 break;
Nate Begemand75d28b2008-03-07 20:04:22 +00002062 case AttributeList::AT_stdcall:
2063 HandleStdCallAttribute(New, Attr);
2064 break;
2065 case AttributeList::AT_fastcall:
2066 HandleFastCallAttribute(New, Attr);
2067 break;
Chris Lattnerb9716a62008-02-20 23:17:35 +00002068 case AttributeList::AT_aligned:
Chris Lattner49d15cb2008-02-21 00:48:22 +00002069 HandleAlignedAttribute(New, Attr);
Chris Lattnerb9716a62008-02-20 23:17:35 +00002070 break;
2071 case AttributeList::AT_packed:
Chris Lattner49d15cb2008-02-21 00:48:22 +00002072 HandlePackedAttribute(New, Attr);
Chris Lattnerb9716a62008-02-20 23:17:35 +00002073 break;
Nate Begeman754d3fc2008-02-21 19:30:49 +00002074 case AttributeList::AT_annotate:
2075 HandleAnnotateAttribute(New, Attr);
2076 break;
Ted Kremenek13bfae62008-02-27 20:43:06 +00002077 case AttributeList::AT_noreturn:
2078 HandleNoReturnAttribute(New, Attr);
2079 break;
Chris Lattner402b3372008-03-03 03:28:21 +00002080 case AttributeList::AT_format:
2081 HandleFormatAttribute(New, Attr);
2082 break;
Nuno Lopes463ec842008-04-25 09:32:00 +00002083 case AttributeList::AT_transparent_union:
2084 HandleTransparentUnionAttribute(New, Attr);
2085 break;
Chris Lattnerb9716a62008-02-20 23:17:35 +00002086 default:
Chris Lattneree4c3bf2008-02-29 16:48:43 +00002087#if 0
2088 // TODO: when we have the full set of attributes, warn about unknown ones.
2089 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
2090 Attr->getName()->getName());
2091#endif
Chris Lattnerb9716a62008-02-20 23:17:35 +00002092 break;
2093 }
Chris Lattner4b009652007-07-25 00:24:17 +00002094}
2095
2096void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2097 AttributeList *declarator_postfix) {
2098 while (declspec_prefix) {
2099 HandleDeclAttribute(New, declspec_prefix);
2100 declspec_prefix = declspec_prefix->getNext();
2101 }
2102 while (declarator_postfix) {
2103 HandleDeclAttribute(New, declarator_postfix);
2104 declarator_postfix = declarator_postfix->getNext();
2105 }
2106}
2107
Nate Begemanaf6ed502008-04-18 23:10:10 +00002108void Sema::HandleExtVectorTypeAttribute(TypedefDecl *tDecl,
Steve Naroff82113e32007-07-29 16:33:31 +00002109 AttributeList *rawAttr) {
2110 QualType curType = tDecl->getUnderlyingType();
Anders Carlssonc8b44122007-12-19 07:19:40 +00002111 // check the attribute arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002112 if (rawAttr->getNumArgs() != 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00002113 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Chris Lattner4b009652007-07-25 00:24:17 +00002114 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00002115 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002116 }
2117 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2118 llvm::APSInt vecSize(32);
2119 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00002120 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Nate Begemanaf6ed502008-04-18 23:10:10 +00002121 "ext_vector_type", sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00002122 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002123 }
2124 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2125 // in conjunction with complex types (pointers, arrays, functions, etc.).
2126 Type *canonType = curType.getCanonicalType().getTypePtr();
2127 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner9384f502008-02-20 23:25:22 +00002128 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Chris Lattner4b009652007-07-25 00:24:17 +00002129 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00002130 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002131 }
2132 // unlike gcc's vector_size attribute, the size is specified as the
2133 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00002134 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00002135
2136 if (vectorSize == 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00002137 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Chris Lattner4b009652007-07-25 00:24:17 +00002138 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00002139 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002140 }
Steve Naroff82113e32007-07-29 16:33:31 +00002141 // Instantiate/Install the vector type, the number of elements is > 0.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002142 tDecl->setUnderlyingType(Context.getExtVectorType(curType, vectorSize));
Steve Naroff82113e32007-07-29 16:33:31 +00002143 // Remember this typedef decl, we will need it later for diagnostics.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002144 ExtVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002145}
2146
2147QualType Sema::HandleVectorTypeAttribute(QualType curType,
2148 AttributeList *rawAttr) {
2149 // check the attribute arugments.
2150 if (rawAttr->getNumArgs() != 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00002151 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Chris Lattner4b009652007-07-25 00:24:17 +00002152 std::string("1"));
2153 return QualType();
2154 }
2155 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2156 llvm::APSInt vecSize(32);
2157 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00002158 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson7dce0292008-02-16 19:51:27 +00002159 "vector_size", sizeExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002160 return QualType();
2161 }
2162 // navigate to the base type - we need to provide for vector pointers,
2163 // vector arrays, and functions returning vectors.
2164 Type *canonType = curType.getCanonicalType().getTypePtr();
2165
2166 if (canonType->isPointerType() || canonType->isArrayType() ||
2167 canonType->isFunctionType()) {
Chris Lattner5b5e1982007-12-19 05:38:06 +00002168 assert(0 && "HandleVector(): Complex type construction unimplemented");
Chris Lattner4b009652007-07-25 00:24:17 +00002169 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2170 do {
2171 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2172 canonType = PT->getPointeeType().getTypePtr();
2173 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2174 canonType = AT->getElementType().getTypePtr();
2175 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2176 canonType = FT->getResultType().getTypePtr();
2177 } while (canonType->isPointerType() || canonType->isArrayType() ||
2178 canonType->isFunctionType());
2179 */
2180 }
2181 // the base type must be integer or float.
2182 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner9384f502008-02-20 23:25:22 +00002183 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Chris Lattner4b009652007-07-25 00:24:17 +00002184 curType.getCanonicalType().getAsString());
2185 return QualType();
2186 }
Chris Lattner8cd0e932008-03-05 18:54:05 +00002187 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Chris Lattner4b009652007-07-25 00:24:17 +00002188 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00002189 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00002190
2191 // the vector size needs to be an integral multiple of the type size.
2192 if (vectorSize % typeSize) {
Chris Lattner9384f502008-02-20 23:25:22 +00002193 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Chris Lattner4b009652007-07-25 00:24:17 +00002194 sizeExpr->getSourceRange());
2195 return QualType();
2196 }
2197 if (vectorSize == 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00002198 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Chris Lattner4b009652007-07-25 00:24:17 +00002199 sizeExpr->getSourceRange());
2200 return QualType();
2201 }
Nate Begeman754d3fc2008-02-21 19:30:49 +00002202 // Instantiate the vector type, the number of elements is > 0, and not
2203 // required to be a power of 2, unlike GCC.
Chris Lattner4b009652007-07-25 00:24:17 +00002204 return Context.getVectorType(curType, vectorSize/typeSize);
2205}
2206
Chris Lattner9384f502008-02-20 23:25:22 +00002207void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlsson136cdc32008-02-16 00:29:18 +00002208 // check the attribute arguments.
2209 if (rawAttr->getNumArgs() > 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00002210 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson136cdc32008-02-16 00:29:18 +00002211 std::string("0"));
2212 return;
2213 }
2214
2215 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2216 TD->addAttr(new PackedAttr);
2217 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2218 // If the alignment is less than or equal to 8 bits, the packed attribute
2219 // has no effect.
Chris Lattner8bb7dd52008-05-09 05:34:49 +00002220 if (!FD->getType()->isIncompleteType() &&
2221 Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner9384f502008-02-20 23:25:22 +00002222 Diag(rawAttr->getLoc(),
Anders Carlsson136cdc32008-02-16 00:29:18 +00002223 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner9384f502008-02-20 23:25:22 +00002224 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlsson136cdc32008-02-16 00:29:18 +00002225 else
Anders Carlssonca133d92008-02-16 00:39:40 +00002226 FD->addAttr(new PackedAttr);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002227 } else
Chris Lattner9384f502008-02-20 23:25:22 +00002228 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2229 rawAttr->getName()->getName());
Anders Carlsson136cdc32008-02-16 00:29:18 +00002230}
Nate Begeman754d3fc2008-02-21 19:30:49 +00002231
Ted Kremenek13bfae62008-02-27 20:43:06 +00002232void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2233 // check the attribute arguments.
2234 if (rawAttr->getNumArgs() != 0) {
2235 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2236 std::string("0"));
2237 return;
2238 }
2239
Ted Kremenek40b95e52008-03-03 16:52:27 +00002240 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2241
2242 if (!Fn) {
2243 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2244 "noreturn", "function");
2245 return;
2246 }
2247
Ted Kremenek13bfae62008-02-27 20:43:06 +00002248 d->addAttr(new NoReturnAttr());
2249}
2250
Chris Lattner402b3372008-03-03 03:28:21 +00002251void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2252 // check the attribute arguments.
2253 if (rawAttr->getNumArgs() != 0) {
2254 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2255 std::string("0"));
2256 return;
2257 }
2258
2259 d->addAttr(new DeprecatedAttr());
2260}
2261
2262void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2263 // check the attribute arguments.
Chris Lattnere9d83be2008-03-04 18:08:48 +00002264 if (rawAttr->getNumArgs() != 1) {
Chris Lattner402b3372008-03-03 03:28:21 +00002265 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2266 std::string("1"));
2267 return;
2268 }
2269
Chris Lattnere9d83be2008-03-04 18:08:48 +00002270 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2271 Arg = Arg->IgnoreParenCasts();
2272 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2273
2274 if (Str == 0 || Str->isWide()) {
Chris Lattner402b3372008-03-03 03:28:21 +00002275 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattnere9d83be2008-03-04 18:08:48 +00002276 "visibility", std::string("1"));
Chris Lattner402b3372008-03-03 03:28:21 +00002277 return;
2278 }
2279
Chris Lattnere9d83be2008-03-04 18:08:48 +00002280 const char *TypeStr = Str->getStrData();
2281 unsigned TypeLen = Str->getByteLength();
Chris Lattner402b3372008-03-03 03:28:21 +00002282 llvm::GlobalValue::VisibilityTypes type;
2283
Chris Lattnere9d83be2008-03-04 18:08:48 +00002284 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Chris Lattner402b3372008-03-03 03:28:21 +00002285 type = llvm::GlobalValue::DefaultVisibility;
Chris Lattnere9d83be2008-03-04 18:08:48 +00002286 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Chris Lattner402b3372008-03-03 03:28:21 +00002287 type = llvm::GlobalValue::HiddenVisibility;
Chris Lattnere9d83be2008-03-04 18:08:48 +00002288 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Chris Lattner402b3372008-03-03 03:28:21 +00002289 type = llvm::GlobalValue::HiddenVisibility; // FIXME
Chris Lattnere9d83be2008-03-04 18:08:48 +00002290 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Chris Lattner402b3372008-03-03 03:28:21 +00002291 type = llvm::GlobalValue::ProtectedVisibility;
2292 else {
2293 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattnere9d83be2008-03-04 18:08:48 +00002294 "visibility", TypeStr);
Chris Lattner402b3372008-03-03 03:28:21 +00002295 return;
2296 }
2297
2298 d->addAttr(new VisibilityAttr(type));
2299}
2300
2301void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2302 // check the attribute arguments.
2303 if (rawAttr->getNumArgs() != 0) {
2304 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2305 std::string("0"));
2306 return;
2307 }
2308
2309 d->addAttr(new WeakAttr());
2310}
2311
2312void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2313 // check the attribute arguments.
2314 if (rawAttr->getNumArgs() != 0) {
2315 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2316 std::string("0"));
2317 return;
2318 }
2319
2320 d->addAttr(new DLLImportAttr());
2321}
2322
2323void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2324 // check the attribute arguments.
2325 if (rawAttr->getNumArgs() != 0) {
2326 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2327 std::string("0"));
2328 return;
2329 }
2330
2331 d->addAttr(new DLLExportAttr());
2332}
2333
Nate Begemand75d28b2008-03-07 20:04:22 +00002334void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2335 // check the attribute arguments.
2336 if (rawAttr->getNumArgs() != 0) {
2337 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2338 std::string("0"));
2339 return;
2340 }
2341
2342 d->addAttr(new StdCallAttr());
2343}
2344
2345void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2346 // check the attribute arguments.
2347 if (rawAttr->getNumArgs() != 0) {
2348 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2349 std::string("0"));
2350 return;
2351 }
2352
2353 d->addAttr(new FastCallAttr());
2354}
2355
Chris Lattner402b3372008-03-03 03:28:21 +00002356void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2357 // check the attribute arguments.
2358 if (rawAttr->getNumArgs() != 0) {
2359 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2360 std::string("0"));
2361 return;
2362 }
2363
2364 d->addAttr(new NoThrowAttr());
2365}
2366
Nuno Lopes02564e52008-03-25 23:01:48 +00002367static const FunctionTypeProto *getFunctionProto(Decl *d) {
Nuno Lopesc3cf4502008-04-18 22:43:39 +00002368 QualType Ty;
Nuno Lopes02564e52008-03-25 23:01:48 +00002369
Nuno Lopesc3cf4502008-04-18 22:43:39 +00002370 if (ValueDecl *decl = dyn_cast<ValueDecl>(d))
2371 Ty = decl->getType();
2372 else if (FieldDecl *decl = dyn_cast<FieldDecl>(d))
2373 Ty = decl->getType();
Ted Kremenek1e0fb9b2008-05-09 17:36:24 +00002374 else if (TypedefDecl* decl = dyn_cast<TypedefDecl>(d))
2375 Ty = decl->getUnderlyingType();
Nuno Lopesc3cf4502008-04-18 22:43:39 +00002376 else
2377 return 0;
Nuno Lopes02564e52008-03-25 23:01:48 +00002378
2379 if (Ty->isFunctionPointerType()) {
2380 const PointerType *PtrTy = Ty->getAsPointerType();
2381 Ty = PtrTy->getPointeeType();
2382 }
2383
2384 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2385 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2386
2387 return 0;
2388}
2389
Ted Kremenek9df18da2008-05-08 19:43:35 +00002390static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
2391 if (!T->isPointerType())
2392 return false;
2393
2394 T = T->getAsPointerType()->getPointeeType().getCanonicalType();
2395 ObjCInterfaceType* ClsT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
2396
2397 if (!ClsT)
2398 return false;
2399
2400 IdentifierInfo* ClsName = ClsT->getDecl()->getIdentifier();
2401
2402 // FIXME: Should we walk the chain of classes?
2403 return ClsName == &Ctx.Idents.get("NSString") ||
2404 ClsName == &Ctx.Idents.get("NSMutableString");
2405}
Nuno Lopes02564e52008-03-25 23:01:48 +00002406
Ted Kremeneke5769412008-03-07 18:43:49 +00002407/// Handle __attribute__((format(type,idx,firstarg))) attributes
2408/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattner402b3372008-03-03 03:28:21 +00002409void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2410
2411 if (!rawAttr->getParameterName()) {
2412 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2413 "format", std::string("1"));
2414 return;
2415 }
2416
2417 if (rawAttr->getNumArgs() != 2) {
2418 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2419 std::string("3"));
2420 return;
2421 }
2422
Nuno Lopes02564e52008-03-25 23:01:48 +00002423 // GCC ignores the format attribute on K&R style function
2424 // prototypes, so we ignore it as well
2425 const FunctionTypeProto *proto = getFunctionProto(d);
2426
2427 if (!proto) {
Chris Lattner402b3372008-03-03 03:28:21 +00002428 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2429 "format", "function");
2430 return;
2431 }
2432
2433 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremeneke5769412008-03-07 18:43:49 +00002434 // this is needed in order to be compatible with GCC
Chris Lattner402b3372008-03-03 03:28:21 +00002435 // the index must start in 1 and the limit is numargs+1
Nuno Lopes02564e52008-03-25 23:01:48 +00002436 unsigned NumArgs = proto->getNumArgs();
Ted Kremeneke5769412008-03-07 18:43:49 +00002437 unsigned FirstIdx = 1;
Chris Lattner402b3372008-03-03 03:28:21 +00002438
2439 const char *Format = rawAttr->getParameterName()->getName();
2440 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2441
2442 // Normalize the argument, __foo__ becomes foo.
2443 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2444 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2445 Format += 2;
2446 FormatLen -= 4;
2447 }
2448
Ted Kremenek9df18da2008-05-08 19:43:35 +00002449 bool Supported = false;
2450 bool is_NSString = false;
2451 bool is_strftime = false;
2452
2453 switch (FormatLen) {
2454 default: break;
2455 case 5:
2456 Supported = !memcmp(Format, "scanf", 5);
2457 break;
2458 case 6:
2459 Supported = !memcmp(Format, "printf", 6);
2460 break;
2461 case 7:
2462 Supported = !memcmp(Format, "strfmon", 7);
2463 break;
2464 case 8:
2465 Supported = (is_strftime = !memcmp(Format, "strftime", 8)) ||
2466 (is_NSString = !memcmp(Format, "NSString", 8));
2467 break;
2468 }
2469
2470 if (!Supported) {
Chris Lattner402b3372008-03-03 03:28:21 +00002471 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2472 "format", rawAttr->getParameterName()->getName());
2473 return;
2474 }
2475
Ted Kremeneke5769412008-03-07 18:43:49 +00002476 // checks for the 2nd argument
Chris Lattner402b3372008-03-03 03:28:21 +00002477 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremeneke5769412008-03-07 18:43:49 +00002478 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattner402b3372008-03-03 03:28:21 +00002479 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2480 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2481 "format", std::string("2"), IdxExpr->getSourceRange());
2482 return;
2483 }
2484
Ted Kremeneke5769412008-03-07 18:43:49 +00002485 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattner402b3372008-03-03 03:28:21 +00002486 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2487 "format", std::string("2"), IdxExpr->getSourceRange());
2488 return;
2489 }
2490
Ted Kremenek9df18da2008-05-08 19:43:35 +00002491 // FIXME: Do we need to bounds check?
2492 unsigned ArgIdx = Idx.getZExtValue() - 1;
2493
Ted Kremeneke5769412008-03-07 18:43:49 +00002494 // make sure the format string is really a string
Ted Kremenek9df18da2008-05-08 19:43:35 +00002495 QualType Ty = proto->getArgType(ArgIdx);
2496
2497 if (is_NSString) {
2498 // FIXME: do we need to check if the type is NSString*? What are
2499 // the semantics?
2500 if (!isNSStringType(Ty, Context)) {
2501 // FIXME: Should highlight the actual expression that has the
2502 // wrong type.
2503 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_NSString,
2504 IdxExpr->getSourceRange());
2505 return;
2506 }
2507 }
2508 else if (!Ty->isPointerType() ||
Ted Kremeneke5769412008-03-07 18:43:49 +00002509 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
Ted Kremenek9df18da2008-05-08 19:43:35 +00002510 // FIXME: Should highlight the actual expression that has the
2511 // wrong type.
Ted Kremeneke5769412008-03-07 18:43:49 +00002512 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2513 IdxExpr->getSourceRange());
2514 return;
2515 }
2516
Ted Kremeneke5769412008-03-07 18:43:49 +00002517 // check the 3rd argument
Chris Lattner402b3372008-03-03 03:28:21 +00002518 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremeneke5769412008-03-07 18:43:49 +00002519 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattner402b3372008-03-03 03:28:21 +00002520 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2521 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2522 "format", std::string("3"), FirstArgExpr->getSourceRange());
2523 return;
2524 }
2525
Ted Kremeneke5769412008-03-07 18:43:49 +00002526 // check if the function is variadic if the 3rd argument non-zero
2527 if (FirstArg != 0) {
2528 if (proto->isVariadic()) {
2529 ++NumArgs; // +1 for ...
2530 } else {
2531 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2532 return;
2533 }
2534 }
2535
2536 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2537 // the input is just the current time + the format string
Ted Kremenek9df18da2008-05-08 19:43:35 +00002538 if (is_strftime) {
Ted Kremeneke5769412008-03-07 18:43:49 +00002539 if (FirstArg != 0) {
Chris Lattner402b3372008-03-03 03:28:21 +00002540 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2541 FirstArgExpr->getSourceRange());
2542 return;
2543 }
Ted Kremeneke5769412008-03-07 18:43:49 +00002544 // if 0 it disables parameter checking (to use with e.g. va_list)
2545 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattner402b3372008-03-03 03:28:21 +00002546 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2547 "format", std::string("3"), FirstArgExpr->getSourceRange());
2548 return;
2549 }
2550
2551 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2552 Idx.getZExtValue(), FirstArg.getZExtValue()));
2553}
2554
Nuno Lopes463ec842008-04-25 09:32:00 +00002555void Sema::HandleTransparentUnionAttribute(Decl *d, AttributeList *rawAttr) {
2556 // check the attribute arguments.
2557 if (rawAttr->getNumArgs() != 0) {
2558 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2559 std::string("0"));
2560 return;
2561 }
2562
2563 TypeDecl *decl = dyn_cast<TypeDecl>(d);
2564
2565 if (!decl || !Context.getTypeDeclType(decl)->isUnionType()) {
2566 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2567 "transparent_union", "union");
2568 return;
2569 }
2570
Chris Lattner46f83552008-04-30 16:04:01 +00002571 //QualType QTy = Context.getTypeDeclType(decl);
2572 //const RecordType *Ty = QTy->getAsUnionType();
Nuno Lopes463ec842008-04-25 09:32:00 +00002573
2574// FIXME
2575// Ty->addAttr(new TransparentUnionAttr());
2576}
2577
Nate Begeman754d3fc2008-02-21 19:30:49 +00002578void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2579 // check the attribute arguments.
2580 if (rawAttr->getNumArgs() != 1) {
2581 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2582 std::string("1"));
2583 return;
2584 }
2585 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2586 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002587
Nate Begeman754d3fc2008-02-21 19:30:49 +00002588 // Make sure that there is a string literal as the annotation's single
2589 // argument.
2590 if (!SE) {
2591 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2592 return;
2593 }
2594 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2595 SE->getByteLength())));
2596}
2597
Anders Carlssonc8b44122007-12-19 07:19:40 +00002598void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2599{
2600 // check the attribute arguments.
Eli Friedman74820702008-01-30 17:38:42 +00002601 if (rawAttr->getNumArgs() > 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00002602 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonc8b44122007-12-19 07:19:40 +00002603 std::string("1"));
2604 return;
2605 }
Eli Friedman74820702008-01-30 17:38:42 +00002606
Anders Carlsson7dce0292008-02-16 19:51:27 +00002607 unsigned Align = 0;
2608
2609 if (rawAttr->getNumArgs() == 0) {
2610 // FIXME: This should be the target specific maximum alignment.
2611 // (For now we just use 128 bits which is the maximum on X86.
2612 Align = 128;
Eli Friedman74820702008-01-30 17:38:42 +00002613 return;
Anders Carlsson7dce0292008-02-16 19:51:27 +00002614 } else {
2615 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2616 llvm::APSInt alignment(32);
2617 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00002618 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson7dce0292008-02-16 19:51:27 +00002619 "aligned", alignmentExpr->getSourceRange());
2620 return;
2621 }
2622
2623 Align = alignment.getZExtValue() * 8;
2624 }
Eli Friedman74820702008-01-30 17:38:42 +00002625
Anders Carlsson7dce0292008-02-16 19:51:27 +00002626 d->addAttr(new AlignedAttr(Align));
Anders Carlssonc8b44122007-12-19 07:19:40 +00002627}