blob: c5050d201b1b4fe27ad1926e67a0009d0d15e411 [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"
Eli Friedman02c22ce2008-05-20 13:48:25 +000027#include "clang/AST/ExprCXX.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000028// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner33aad6e2008-02-06 00:51:33 +000029#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000030#include "clang/Lex/HeaderSearch.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000031#include "llvm/ADT/SmallString.h"
Chris Lattner4b009652007-07-25 00:24:17 +000032#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian67907bd2007-10-05 18:00:57 +000033#include "llvm/ADT/DenseSet.h"
Chris Lattner4b009652007-07-25 00:24:17 +000034using namespace clang;
35
Steve Naroff6384a012008-04-02 14:35:35 +000036Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
37 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
38
Douglas Gregor1d661552008-04-13 21:07:44 +000039 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
40 isa<ObjCInterfaceDecl>(IIDecl) ||
41 isa<TagDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000042 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000043 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000044}
45
Chris Lattneref87a202008-04-22 18:39:57 +000046void Sema::PushDeclContext(DeclContext *DC) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +000047 assert( ( (isa<ObjCMethodDecl>(DC) && isa<TranslationUnitDecl>(CurContext))
Chris Lattneref87a202008-04-22 18:39:57 +000048 || DC->getParent() == CurContext ) &&
Chris Lattnerf3874bc2008-04-06 04:47:34 +000049 "The next DeclContext should be directly contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000050 CurContext = DC;
Chris Lattnereee57c02008-04-04 06:12:32 +000051}
52
Chris Lattnerf3874bc2008-04-06 04:47:34 +000053void Sema::PopDeclContext() {
54 assert(CurContext && "DeclContext imbalance!");
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000055 // If CurContext is a ObjC method, getParent() will return NULL.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +000056 CurContext = isa<ObjCMethodDecl>(CurContext)
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000057 ? Context.getTranslationUnitDecl()
58 : CurContext->getParent();
Chris Lattnereee57c02008-04-04 06:12:32 +000059}
60
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000061/// Add this decl to the scope shadowed decl chains.
62void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000063 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000064
65 // C++ [basic.scope]p4:
66 // -- exactly one declaration shall declare a class name or
67 // enumeration name that is not a typedef name and the other
68 // declarations shall all refer to the same object or
69 // enumerator, or all refer to functions and function templates;
70 // in this case the class name or enumeration name is hidden.
71 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
72 // We are pushing the name of a tag (enum or class).
73 IdentifierResolver::ctx_iterator
74 CIT = IdResolver.ctx_begin(TD->getIdentifier(), TD->getDeclContext());
75 if (CIT != IdResolver.ctx_end(TD->getIdentifier()) &&
76 IdResolver.isDeclInScope(*CIT, TD->getDeclContext(), S)) {
77 // There is already a declaration with the same name in the same
78 // scope. It must be found before we find the new declaration,
79 // so swap the order on the shadowed declaration chain.
80
81 IdResolver.AddShadowedDecl(TD, *CIT);
82 return;
83 }
84 }
85
86 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000087}
88
Steve Naroff9637a9b2007-10-09 22:01:59 +000089void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000090 if (S->decl_empty()) return;
91 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000092
93 // We only want to remove the decls from the identifier decl chains for local
94 // scopes, when inside a function/method.
95 if (S->getFnParent() == 0)
96 return;
Chris Lattnera7549902007-08-26 06:24:45 +000097
Chris Lattner4b009652007-07-25 00:24:17 +000098 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
99 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000100 Decl *TmpD = static_cast<Decl*>(*I);
101 assert(TmpD && "This decl didn't get pushed??");
102 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
103 assert(D && "This decl isn't a ScopedDecl?");
104
Chris Lattner4b009652007-07-25 00:24:17 +0000105 IdentifierInfo *II = D->getIdentifier();
106 if (!II) continue;
107
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000108 // Unlink this decl from the identifier.
109 IdResolver.RemoveDecl(D);
110
Chris Lattner4b009652007-07-25 00:24:17 +0000111 // This will have to be revisited for C++: there we want to nest stuff in
112 // namespace decls etc. Even for C, we might want a top-level translation
113 // unit decl or something.
114 if (!CurFunctionDecl)
115 continue;
116
117 // Chain this decl to the containing function, it now owns the memory for
118 // the decl.
119 D->setNext(CurFunctionDecl->getDeclChain());
120 CurFunctionDecl->setDeclChain(D);
121 }
122}
123
Steve Naroffe57c21a2008-04-01 23:04:06 +0000124/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
125/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000126ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000127 // The third "scope" argument is 0 since we aren't enabling lazy built-in
128 // creation from this context.
129 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000130
Steve Naroff6384a012008-04-02 14:35:35 +0000131 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000132}
133
Steve Naroffe57c21a2008-04-01 23:04:06 +0000134/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000135/// namespace.
Steve Naroff6384a012008-04-02 14:35:35 +0000136Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
137 Scope *S, bool enableLazyBuiltinCreation) {
Chris Lattner4b009652007-07-25 00:24:17 +0000138 if (II == 0) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000139 unsigned NS = NSI;
140 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
141 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000142
Chris Lattner4b009652007-07-25 00:24:17 +0000143 // Scan up the scope chain looking for a decl that matches this identifier
144 // that is in the appropriate namespace. This search should not take long, as
145 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000146 for (IdentifierResolver::iterator
147 I = IdResolver.begin(II, CurContext), E = IdResolver.end(II); I != E; ++I)
148 if ((*I)->getIdentifierNamespace() & NS)
149 return *I;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000150
Chris Lattner4b009652007-07-25 00:24:17 +0000151 // If we didn't find a use of this identifier, and if the identifier
152 // corresponds to a compiler builtin, create the decl object for the builtin
153 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1d661552008-04-13 21:07:44 +0000154 if (NS & Decl::IDNS_Ordinary) {
Steve Naroff6384a012008-04-02 14:35:35 +0000155 if (enableLazyBuiltinCreation) {
156 // If this is a builtin on this (or all) targets, create the decl.
157 if (unsigned BuiltinID = II->getBuiltinID())
158 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
159 }
Steve Naroffe57c21a2008-04-01 23:04:06 +0000160 if (getLangOptions().ObjC1) {
161 // @interface and @compatibility_alias introduce typedef-like names.
162 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000163 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000164 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000165 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
166 if (IDI != ObjCInterfaceDecls.end())
167 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000168 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
169 if (I != ObjCAliasDecls.end())
170 return I->second->getClassInterface();
171 }
Chris Lattner4b009652007-07-25 00:24:17 +0000172 }
173 return 0;
174}
175
Chris Lattnera9c87f22008-05-05 22:18:14 +0000176void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000177 if (!Context.getBuiltinVaListType().isNull())
178 return;
179
180 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000181 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000182 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000183 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
184}
185
Chris Lattner4b009652007-07-25 00:24:17 +0000186/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
187/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000188ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
189 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000190 Builtin::ID BID = (Builtin::ID)bid;
191
Anders Carlsson36760332007-10-15 20:28:48 +0000192 if (BID == Builtin::BI__builtin_va_start ||
Chris Lattnera9c87f22008-05-05 22:18:14 +0000193 BID == Builtin::BI__builtin_va_copy ||
194 BID == Builtin::BI__builtin_va_end)
Anders Carlsson36760332007-10-15 20:28:48 +0000195 InitBuiltinVaListType();
196
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000197 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000198 FunctionDecl *New = FunctionDecl::Create(Context,
199 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000200 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000201 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000202
Chris Lattnera9c87f22008-05-05 22:18:14 +0000203 // Create Decl objects for each parameter, adding them to the
204 // FunctionDecl.
205 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
206 llvm::SmallVector<ParmVarDecl*, 16> Params;
207 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
208 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
209 FT->getArgType(i), VarDecl::None, 0,
210 0));
211 New->setParams(&Params[0], Params.size());
212 }
213
214
215
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000216 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000217 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000218 return New;
219}
220
221/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
222/// and scope as a previous declaration 'Old'. Figure out how to resolve this
223/// situation, merging decls or emitting diagnostics as appropriate.
224///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000225TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000226 // Verify the old decl was also a typedef.
227 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
228 if (!Old) {
229 Diag(New->getLocation(), diag::err_redefinition_different_kind,
230 New->getName());
231 Diag(OldD->getLocation(), diag::err_previous_definition);
232 return New;
233 }
234
Steve Naroffae84af82007-10-31 18:42:27 +0000235 // Allow multiple definitions for ObjC built-in typedefs.
236 // FIXME: Verify the underlying types are equivalent!
Ted Kremenek42730c52008-01-07 19:49:32 +0000237 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroffae84af82007-10-31 18:42:27 +0000238 return Old;
Steve Naroffa9eae582008-01-30 23:46:05 +0000239
240 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
241 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
242 // *either* declaration is in a system header. The code below implements
243 // this adhoc compatibility rule. FIXME: The following code will not
244 // work properly when compiling ".i" files (containing preprocessed output).
245 SourceManager &SrcMgr = Context.getSourceManager();
246 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
247 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
248 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
249 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
250 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
251
Steve Naroff1997d2c2008-03-26 21:27:00 +0000252 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
253 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
254 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroff73a07032008-02-07 03:50:06 +0000255 getLangOptions().Microsoft)
Steve Naroffa9eae582008-01-30 23:46:05 +0000256 return New;
Steve Naroff1997d2c2008-03-26 21:27:00 +0000257
Chris Lattner4b009652007-07-25 00:24:17 +0000258 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
259 // TODO: This is totally simplistic. It should handle merging functions
260 // together etc, merging extern int X; int X; ...
Ted Kremenek64845ce2008-05-23 21:28:18 +0000261 Diag(New->getLocation(), diag::err_redefinition, New->getName());
262 Diag(Old->getLocation(), diag::err_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000263 return New;
264}
265
Chris Lattner402b3372008-03-03 03:28:21 +0000266/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
267static bool DeclHasAttr(const Decl *decl, const Attr *target) {
268 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
269 if (attr->getKind() == target->getKind())
270 return true;
271
272 return false;
273}
274
275/// MergeAttributes - append attributes from the Old decl to the New one.
276static void MergeAttributes(Decl *New, Decl *Old) {
277 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
278
Chris Lattner402b3372008-03-03 03:28:21 +0000279 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 }
Nuno Lopes77654342008-06-01 22:53:53 +0000290
291 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000292}
293
Chris Lattner3e254fb2008-04-08 04:40:51 +0000294/// MergeFunctionDecl - We just parsed a function 'New' from
295/// declarator D which has the same name and scope as a previous
296/// declaration 'Old'. Figure out how to resolve this situation,
297/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor42214c52008-04-21 02:02:58 +0000298/// Redeclaration will be set true if thisNew is a redeclaration OldD.
299FunctionDecl *
300Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
301 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000302 // Verify the old decl was also a function.
303 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
304 if (!Old) {
305 Diag(New->getLocation(), diag::err_redefinition_different_kind,
306 New->getName());
307 Diag(OldD->getLocation(), diag::err_previous_definition);
308 return New;
309 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000310
Chris Lattner42a21742008-04-06 23:10:54 +0000311 QualType OldQType = Context.getCanonicalType(Old->getType());
312 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000313
Chris Lattner3e254fb2008-04-08 04:40:51 +0000314 // C++ [dcl.fct]p3:
315 // All declarations for a function shall agree exactly in both the
316 // return type and the parameter-type-list.
Douglas Gregor42214c52008-04-21 02:02:58 +0000317 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
318 MergeAttributes(New, Old);
319 Redeclaration = true;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000320 return MergeCXXFunctionDecl(New, Old);
Douglas Gregor42214c52008-04-21 02:02:58 +0000321 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000322
323 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000324 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000325 if (!getLangOptions().CPlusPlus &&
326 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000327 MergeAttributes(New, Old);
328 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000329 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000330 }
Chris Lattner1470b072007-11-06 06:07:26 +0000331
Steve Naroff6c9e7922008-01-16 15:01:34 +0000332 // A function that has already been declared has been redeclared or defined
333 // with a different type- show appropriate diagnostic
Steve Naroff9104f3c2008-04-04 14:32:09 +0000334 diag::kind PrevDiag;
Douglas Gregor42214c52008-04-21 02:02:58 +0000335 if (Old->isThisDeclarationADefinition())
Steve Naroff9104f3c2008-04-04 14:32:09 +0000336 PrevDiag = diag::err_previous_definition;
337 else if (Old->isImplicit())
338 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000339 else
Steve Naroff9104f3c2008-04-04 14:32:09 +0000340 PrevDiag = diag::err_previous_declaration;
Steve Naroff6c9e7922008-01-16 15:01:34 +0000341
Chris Lattner4b009652007-07-25 00:24:17 +0000342 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
343 // TODO: This is totally simplistic. It should handle merging functions
344 // together etc, merging extern int X; int X; ...
Steve Naroff6c9e7922008-01-16 15:01:34 +0000345 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
346 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000347 return New;
348}
349
Chris Lattnerf9167d12007-11-06 04:28:31 +0000350/// equivalentArrayTypes - Used to determine whether two array types are
351/// equivalent.
352/// We need to check this explicitly as an incomplete array definition is
353/// considered a VariableArrayType, so will not match a complete array
354/// definition that would be otherwise equivalent.
355static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
356 const ArrayType *NewAT = NewQType->getAsArrayType();
357 const ArrayType *OldAT = OldQType->getAsArrayType();
358
359 if (!NewAT || !OldAT)
360 return false;
361
362 // If either (or both) array types in incomplete we need to strip off the
363 // outer VariableArrayType. Once the outer VAT is removed the remaining
364 // types must be identical if the array types are to be considered
365 // equivalent.
366 // eg. int[][1] and int[1][1] become
367 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
368 // removing the outermost VAT gives
369 // CAT(1, int) and CAT(1, int)
370 // which are equal, therefore the array types are equivalent.
Eli Friedmane0079792008-02-15 12:53:51 +0000371 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerf9167d12007-11-06 04:28:31 +0000372 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
373 return false;
Eli Friedmand32157f2008-01-29 07:51:12 +0000374 NewQType = NewAT->getElementType().getCanonicalType();
375 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerf9167d12007-11-06 04:28:31 +0000376 }
377
378 return NewQType == OldQType;
379}
380
Chris Lattner4b009652007-07-25 00:24:17 +0000381/// MergeVarDecl - We just parsed a variable 'New' which has the same name
382/// and scope as a previous declaration 'Old'. Figure out how to resolve this
383/// situation, merging decls or emitting diagnostics as appropriate.
384///
385/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
386/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
387///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000388VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000389 // Verify the old decl was also a variable.
390 VarDecl *Old = dyn_cast<VarDecl>(OldD);
391 if (!Old) {
392 Diag(New->getLocation(), diag::err_redefinition_different_kind,
393 New->getName());
394 Diag(OldD->getLocation(), diag::err_previous_definition);
395 return New;
396 }
Chris Lattner402b3372008-03-03 03:28:21 +0000397
398 MergeAttributes(New, Old);
399
Chris Lattner4b009652007-07-25 00:24:17 +0000400 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000401 QualType OldCType = Context.getCanonicalType(Old->getType());
402 QualType NewCType = Context.getCanonicalType(New->getType());
403 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000404 Diag(New->getLocation(), diag::err_redefinition, New->getName());
405 Diag(Old->getLocation(), diag::err_previous_definition);
406 return New;
407 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000408 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
409 if (New->getStorageClass() == VarDecl::Static &&
410 (Old->getStorageClass() == VarDecl::None ||
411 Old->getStorageClass() == VarDecl::Extern)) {
412 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
413 Diag(Old->getLocation(), diag::err_previous_definition);
414 return New;
415 }
416 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
417 if (New->getStorageClass() != VarDecl::Static &&
418 Old->getStorageClass() == VarDecl::Static) {
419 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
420 Diag(Old->getLocation(), diag::err_previous_definition);
421 return New;
422 }
423 // We've verified the types match, now handle "tentative" definitions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000424 if (Old->isFileVarDecl() && New->isFileVarDecl()) {
Steve Naroffb00247f2008-01-30 00:44:01 +0000425 // Handle C "tentative" external object definitions (C99 6.9.2).
426 bool OldIsTentative = false;
427 bool NewIsTentative = false;
428
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000429 if (!Old->getInit() &&
430 (Old->getStorageClass() == VarDecl::None ||
431 Old->getStorageClass() == VarDecl::Static))
Steve Naroffb00247f2008-01-30 00:44:01 +0000432 OldIsTentative = true;
433
434 // FIXME: this check doesn't work (since the initializer hasn't been
435 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
436 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
437 // thrown out the old decl.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000438 if (!New->getInit() &&
439 (New->getStorageClass() == VarDecl::None ||
440 New->getStorageClass() == VarDecl::Static))
Steve Naroffb00247f2008-01-30 00:44:01 +0000441 ; // change to NewIsTentative = true; once the code is moved.
442
443 if (NewIsTentative || OldIsTentative)
444 return New;
445 }
Steve Naroff89301de2008-05-12 22:36:43 +0000446 // Handle __private_extern__ just like extern.
Steve Naroffb00247f2008-01-30 00:44:01 +0000447 if (Old->getStorageClass() != VarDecl::Extern &&
Steve Naroff89301de2008-05-12 22:36:43 +0000448 Old->getStorageClass() != VarDecl::PrivateExtern &&
449 New->getStorageClass() != VarDecl::Extern &&
450 New->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner4b009652007-07-25 00:24:17 +0000451 Diag(New->getLocation(), diag::err_redefinition, New->getName());
452 Diag(Old->getLocation(), diag::err_previous_definition);
453 }
454 return New;
455}
456
Chris Lattner3e254fb2008-04-08 04:40:51 +0000457/// CheckParmsForFunctionDef - Check that the parameters of the given
458/// function are appropriate for the definition of a function. This
459/// takes care of any checks that cannot be performed on the
460/// declaration itself, e.g., that the types of each of the function
461/// parameters are complete.
462bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
463 bool HasInvalidParm = false;
464 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
465 ParmVarDecl *Param = FD->getParamDecl(p);
466
467 // C99 6.7.5.3p4: the parameters in a parameter type list in a
468 // function declarator that is part of a function definition of
469 // that function shall not have incomplete type.
470 if (Param->getType()->isIncompleteType() &&
471 !Param->isInvalidDecl()) {
472 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
473 Param->getType().getAsString());
474 Param->setInvalidDecl();
475 HasInvalidParm = true;
476 }
477 }
478
479 return HasInvalidParm;
480}
481
482/// CreateImplicitParameter - Creates an implicit function parameter
483/// in the scope S and with the given type. This routine is used, for
484/// example, to create the implicit "self" parameter in an Objective-C
485/// method.
486ParmVarDecl *
487Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
488 SourceLocation IdLoc, QualType Type) {
489 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
490 VarDecl::None, 0, 0);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000491 if (Id)
492 PushOnScopeChains(New, S);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000493
494 return New;
495}
496
Chris Lattner4b009652007-07-25 00:24:17 +0000497/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
498/// no declarator (e.g. "struct foo;") is parsed.
499Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
500 // TODO: emit error on 'int;' or 'const enum foo;'.
501 // TODO: emit error on 'typedef int;'
502 // if (!DS.isMissingDeclaratorOk()) Diag(...);
503
Steve Naroffedafc0b2007-11-17 21:37:36 +0000504 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000505}
506
Steve Narofff0b23542008-01-10 22:15:12 +0000507bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000508 // Get the type before calling CheckSingleAssignmentConstraints(), since
509 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000510 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000511
Chris Lattner005ed752008-01-04 18:04:52 +0000512 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
513 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
514 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000515}
516
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000517bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Narofff0b23542008-01-10 22:15:12 +0000518 QualType ElementType) {
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000519 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Narofff0b23542008-01-10 22:15:12 +0000520 if (CheckSingleInitializer(expr, ElementType))
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000521 return true; // types weren't compatible.
522
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000523 if (savExpr != expr) // The type was promoted, update initializer list.
524 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000525 return false;
526}
527
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000528bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedman8ff07782008-02-15 18:16:39 +0000529 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000530 // C99 6.7.8p14. We have an array of character type with unknown size
531 // being initialized to a string literal.
532 llvm::APSInt ConstVal(32);
533 ConstVal = strLiteral->getByteLength() + 1;
534 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000535 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000536 ArrayType::Normal, 0);
537 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
538 // C99 6.7.8p14. We have an array of character type with known size.
539 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
540 Diag(strLiteral->getSourceRange().getBegin(),
541 diag::warn_initializer_string_for_char_array_too_long,
542 strLiteral->getSourceRange());
543 } else {
544 assert(0 && "HandleStringLiteralInit(): Invalid array type");
545 }
546 // Set type from "char *" to "constant array of char".
547 strLiteral->setType(DeclT);
548 // For now, we always return false (meaning success).
549 return false;
550}
551
552StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000553 const ArrayType *AT = DeclType->getAsArrayType();
Steve Narofff3cb5142008-01-25 00:51:06 +0000554 if (AT && AT->getElementType()->isCharType()) {
555 return dyn_cast<StringLiteral>(Init);
556 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000557 return 0;
558}
559
Steve Narofff3cb5142008-01-25 00:51:06 +0000560// CheckInitializerListTypes - Checks the types of elements of an initializer
561// list. This function is recursive: it calls itself to initialize subelements
562// of aggregate types. Note that the topLevel parameter essentially refers to
563// whether this expression "owns" the initializer list passed in, or if this
564// initialization is taking elements out of a parent initializer. Each
565// call to this function adds zero or more to startIndex, reports any errors,
566// and returns true if it found any inconsistent types.
567bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
568 bool topLevel, unsigned& startIndex) {
Steve Naroffcb69fb72007-12-10 22:44:33 +0000569 bool hadError = false;
Steve Narofff3cb5142008-01-25 00:51:06 +0000570
571 if (DeclType->isScalarType()) {
572 // The simplest case: initializing a single scalar
573 if (topLevel) {
574 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
575 IList->getSourceRange());
576 }
577 if (startIndex < IList->getNumInits()) {
578 Expr* expr = IList->getInit(startIndex);
579 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
580 // FIXME: Should an error be reported here instead?
581 unsigned newIndex = 0;
582 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
583 } else {
584 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
585 }
586 ++startIndex;
587 }
588 // FIXME: Should an error be reported for empty initializer list + scalar?
589 } else if (DeclType->isVectorType()) {
590 if (startIndex < IList->getNumInits()) {
591 const VectorType *VT = DeclType->getAsVectorType();
592 int maxElements = VT->getNumElements();
593 QualType elementType = VT->getElementType();
594
595 for (int i = 0; i < maxElements; ++i) {
596 // Don't attempt to go past the end of the init list
597 if (startIndex >= IList->getNumInits())
598 break;
599 Expr* expr = IList->getInit(startIndex);
600 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
601 unsigned newIndex = 0;
602 hadError |= CheckInitializerListTypes(SubInitList, elementType,
603 true, newIndex);
604 ++startIndex;
605 } else {
606 hadError |= CheckInitializerListTypes(IList, elementType,
607 false, startIndex);
608 }
609 }
610 }
611 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
612 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroffedce4ec2008-01-28 02:00:41 +0000613 if (startIndex < IList->getNumInits() && !topLevel &&
614 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
615 DeclType)) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000616 // We found a compatible struct; per the standard, this initializes the
617 // struct. (The C standard technically says that this only applies for
618 // initializers for declarations with automatic scope; however, this
619 // construct is unambiguous anyway because a struct cannot contain
620 // a type compatible with itself. We'll output an error when we check
621 // if the initializer is constant.)
622 // FIXME: Is a call to CheckSingleInitializer required here?
623 ++startIndex;
624 } else {
625 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffee467032008-02-11 00:06:17 +0000626
Steve Naroff576df292008-02-11 21:52:37 +0000627 // If the record is invalid, some of it's members are invalid. To avoid
628 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffee467032008-02-11 00:06:17 +0000629 if (structDecl->isInvalidDecl())
630 return true;
631
Steve Narofff3cb5142008-01-25 00:51:06 +0000632 // If structDecl is a forward declaration, this loop won't do anything;
633 // That's okay, because an error should get printed out elsewhere. It
634 // might be worthwhile to skip over the rest of the initializer, though.
635 int numMembers = structDecl->getNumMembers() -
636 structDecl->hasFlexibleArrayMember();
637 for (int i = 0; i < numMembers; i++) {
638 // Don't attempt to go past the end of the init list
639 if (startIndex >= IList->getNumInits())
640 break;
641 FieldDecl * curField = structDecl->getMember(i);
642 if (!curField->getIdentifier()) {
643 // Don't initialize unnamed fields, e.g. "int : 20;"
644 continue;
645 }
646 QualType fieldType = curField->getType();
647 Expr* expr = IList->getInit(startIndex);
648 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
649 unsigned newStart = 0;
650 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
651 true, newStart);
652 ++startIndex;
653 } else {
654 hadError |= CheckInitializerListTypes(IList, fieldType,
655 false, startIndex);
656 }
657 if (DeclType->isUnionType())
658 break;
659 }
660 // FIXME: Implement flexible array initialization GCC extension (it's a
661 // really messy extension to implement, unfortunately...the necessary
662 // information isn't actually even here!)
663 }
664 } else if (DeclType->isArrayType()) {
665 // Check for the special-case of initializing an array with a string.
666 if (startIndex < IList->getNumInits()) {
667 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
668 DeclType)) {
669 CheckStringLiteralInit(lit, DeclType);
670 ++startIndex;
671 if (topLevel && startIndex < IList->getNumInits()) {
672 // We have leftover initializers; warn
673 Diag(IList->getInit(startIndex)->getLocStart(),
674 diag::err_excess_initializers_in_char_array_initializer,
675 IList->getInit(startIndex)->getSourceRange());
676 }
677 return false;
678 }
679 }
680 int maxElements;
Eli Friedman8ff07782008-02-15 18:16:39 +0000681 if (DeclType->isIncompleteArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000682 // FIXME: use a proper constant
683 maxElements = 0x7FFFFFFF;
Chris Lattnerb9716a62008-02-20 23:17:35 +0000684 } else if (const VariableArrayType *VAT =
685 DeclType->getAsVariableArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000686 // Check for VLAs; in standard C it would be possible to check this
687 // earlier, but I don't know where clang accepts VLAs (gcc accepts
688 // them in all sorts of strange places).
Eli Friedman8ff07782008-02-15 18:16:39 +0000689 Diag(VAT->getSizeExpr()->getLocStart(),
690 diag::err_variable_object_no_init,
691 VAT->getSizeExpr()->getSourceRange());
692 hadError = true;
693 maxElements = 0x7FFFFFFF;
Steve Narofff3cb5142008-01-25 00:51:06 +0000694 } else {
695 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
696 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
697 }
698 QualType elementType = DeclType->getAsArrayType()->getElementType();
699 int numElements = 0;
700 for (int i = 0; i < maxElements; ++i, ++numElements) {
701 // Don't attempt to go past the end of the init list
702 if (startIndex >= IList->getNumInits())
703 break;
704 Expr* expr = IList->getInit(startIndex);
705 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
706 unsigned newIndex = 0;
707 hadError |= CheckInitializerListTypes(SubInitList, elementType,
708 true, newIndex);
709 ++startIndex;
710 } else {
711 hadError |= CheckInitializerListTypes(IList, elementType,
712 false, startIndex);
713 }
714 }
Eli Friedmane0079792008-02-15 12:53:51 +0000715 if (DeclType->isIncompleteArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000716 // If this is an incomplete array type, the actual type needs to
717 // be calculated here
718 if (numElements == 0) {
719 // Sizing an array implicitly to zero is not allowed
720 // (It could in theory be allowed, but it doesn't really matter.)
721 Diag(IList->getLocStart(),
722 diag::err_at_least_one_initializer_needed_to_size_array);
723 hadError = true;
724 } else {
725 llvm::APSInt ConstVal(32);
726 ConstVal = numElements;
727 DeclType = Context.getConstantArrayType(elementType, ConstVal,
728 ArrayType::Normal, 0);
729 }
730 }
731 } else {
732 assert(0 && "Aggregate that isn't a function or array?!");
733 }
734 } else {
735 // In C, all types are either scalars or aggregates, but
736 // additional handling is needed here for C++ (and possibly others?).
737 assert(0 && "Unsupported initializer type");
738 }
739
740 // If this init list is a base list, we set the type; an initializer doesn't
741 // fundamentally have a type, but this makes the ASTs a bit easier to read
742 if (topLevel)
743 IList->setType(DeclType);
744
745 if (topLevel && startIndex < IList->getNumInits()) {
746 // We have leftover initializers; warn
747 Diag(IList->getInit(startIndex)->getLocStart(),
748 diag::warn_excess_initializers,
749 IList->getInit(startIndex)->getSourceRange());
750 }
751 return hadError;
752}
753
754bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroff8e9337f2008-01-21 23:53:58 +0000755 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
756 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedman8ff07782008-02-15 18:16:39 +0000757 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroff8e9337f2008-01-21 23:53:58 +0000758 return Diag(VAT->getSizeExpr()->getLocStart(),
759 diag::err_variable_object_no_init,
760 VAT->getSizeExpr()->getSourceRange());
761
Steve Naroffcb69fb72007-12-10 22:44:33 +0000762 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
763 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000764 // FIXME: Handle wide strings
765 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
766 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000767
768 if (DeclType->isArrayType())
769 return Diag(Init->getLocStart(),
770 diag::err_array_init_list_required,
771 Init->getSourceRange());
772
Steve Narofff0b23542008-01-10 22:15:12 +0000773 return CheckSingleInitializer(Init, DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000774 }
Eli Friedman0fecfde2008-05-19 20:29:35 +0000775#if 0
Steve Narofff3cb5142008-01-25 00:51:06 +0000776 unsigned newIndex = 0;
777 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000778#else
779 InitListChecker CheckInitList(this, InitList, DeclType);
780 return CheckInitList.HadError();
781#endif
Steve Naroffe14e5542007-09-02 02:04:30 +0000782}
783
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000784Sema::DeclTy *
Steve Naroff0acc9c92007-09-15 18:49:24 +0000785Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000786 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000787 IdentifierInfo *II = D.getIdentifier();
788
789 // All of these full declarators require an identifier. If it doesn't have
790 // one, the ParsedFreeStandingDeclSpec action should be used.
791 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000792 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000793 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000794 D.getDeclSpec().getSourceRange(), D.getSourceRange());
795 return 0;
796 }
797
Chris Lattnera7549902007-08-26 06:24:45 +0000798 // The scope passed in may not be a decl scope. Zip up the scope tree until
799 // we find one that is.
800 while ((S->getFlags() & Scope::DeclScope) == 0)
801 S = S->getParent();
802
Chris Lattner4b009652007-07-25 00:24:17 +0000803 // See if this is a redefinition of a variable in the same scope.
Steve Naroff6384a012008-04-02 14:35:35 +0000804 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000805 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000806 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000807
808 // In C++, the previous declaration we find might be a tag type
809 // (class or enum). In this case, the new declaration will hide the
810 // tag type.
811 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
812 PrevDecl = 0;
813
Chris Lattner82bb4792007-11-14 06:34:38 +0000814 QualType R = GetTypeForDeclarator(D, S);
815 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
816
Chris Lattner4b009652007-07-25 00:24:17 +0000817 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000818 // Check that there are no default arguments (C++ only).
819 if (getLangOptions().CPlusPlus)
820 CheckExtraCXXDefaultArguments(D);
821
Chris Lattner82bb4792007-11-14 06:34:38 +0000822 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000823 if (!NewTD) return 0;
824
825 // Handle attributes prior to checking for duplicates in MergeVarDecl
826 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
827 D.getAttributes());
Steve Narofff8a09432008-01-09 23:34:55 +0000828 // Merge the decl with the existing one if appropriate. If the decl is
829 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000830 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000831 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
832 if (NewTD == 0) return 0;
833 }
834 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000835 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000836 // C99 6.7.7p2: If a typedef name specifies a variably modified type
837 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000838 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
839 // FIXME: Diagnostic needs to be fixed.
840 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff5eb879b2007-08-31 17:20:07 +0000841 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000842 }
843 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000844 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000845 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000846 switch (D.getDeclSpec().getStorageClassSpec()) {
847 default: assert(0 && "Unknown storage class!");
848 case DeclSpec::SCS_auto:
849 case DeclSpec::SCS_register:
850 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
851 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000852 InvalidDecl = true;
853 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000854 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
855 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
856 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000857 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000858 }
859
Chris Lattner4c7802b2008-03-15 21:24:04 +0000860 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattnereee57c02008-04-04 06:12:32 +0000861 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
862 D.getIdentifierLoc(),
Chris Lattner4c7802b2008-03-15 21:24:04 +0000863 II, R, SC, isInline,
864 LastDeclarator);
Ted Kremenek117f1862008-02-27 22:18:07 +0000865 // Handle attributes.
Ted Kremenek117f1862008-02-27 22:18:07 +0000866 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
867 D.getAttributes());
Chris Lattner3e254fb2008-04-08 04:40:51 +0000868
869 // Copy the parameter declarations from the declarator D to
870 // the function declaration NewFD, if they are available.
871 if (D.getNumTypeObjects() > 0 &&
872 D.getTypeObject(0).Fun.hasPrototype) {
873 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
874
875 // Create Decl objects for each parameter, adding them to the
876 // FunctionDecl.
877 llvm::SmallVector<ParmVarDecl*, 16> Params;
878
879 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
880 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +0000881 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +0000882 // We let through "const void" here because Sema::GetTypeForDeclarator
883 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000884 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
885 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +0000886 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
887 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +0000888 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
889
Chris Lattnerda7b5f02008-04-10 02:26:16 +0000890 // In C++, the empty parameter-type-list must be spelled "void"; a
891 // typedef of void is not permitted.
892 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +0000893 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +0000894 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
895 }
896
Chris Lattner3e254fb2008-04-08 04:40:51 +0000897 } else {
898 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
899 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
900 }
901
902 NewFD->setParams(&Params[0], Params.size());
903 }
904
Steve Narofff8a09432008-01-09 23:34:55 +0000905 // Merge the decl with the existing one if appropriate. Since C functions
906 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000907 if (PrevDecl &&
908 (!getLangOptions().CPlusPlus ||
909 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000910 bool Redeclaration = false;
911 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Chris Lattner4b009652007-07-25 00:24:17 +0000912 if (NewFD == 0) return 0;
Douglas Gregor42214c52008-04-21 02:02:58 +0000913 if (Redeclaration) {
Eli Friedmand2701812008-05-27 05:07:37 +0000914 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregor42214c52008-04-21 02:02:58 +0000915 }
Chris Lattner4b009652007-07-25 00:24:17 +0000916 }
917 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000918
919 // In C++, check default arguments now that we have merged decls.
920 if (getLangOptions().CPlusPlus)
921 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +0000922 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000923 // Check that there are no default arguments (C++ only).
924 if (getLangOptions().CPlusPlus)
925 CheckExtraCXXDefaultArguments(D);
926
Ted Kremenek42730c52008-01-07 19:49:32 +0000927 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000928 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
929 D.getIdentifier()->getName());
930 InvalidDecl = true;
931 }
Chris Lattner4b009652007-07-25 00:24:17 +0000932
933 VarDecl *NewVD;
934 VarDecl::StorageClass SC;
935 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +0000936 default: assert(0 && "Unknown storage class!");
937 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
938 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
939 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
940 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
941 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
942 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000943 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000944 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000945 // C99 6.9p2: The storage-class specifiers auto and register shall not
946 // appear in the declaration specifiers in an external declaration.
947 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
948 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
949 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000950 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000951 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000952 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
953 II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000954 } else {
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000955 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
956 II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000957 }
Chris Lattner4b009652007-07-25 00:24:17 +0000958 // Handle attributes prior to checking for duplicates in MergeVarDecl
959 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
960 D.getAttributes());
Nate Begemanea583262008-03-14 18:07:10 +0000961
962 // Emit an error if an address space was applied to decl with local storage.
963 // This includes arrays of objects with address space qualifiers, but not
964 // automatic variables that point to other address spaces.
965 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +0000966 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
967 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
968 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +0000969 }
Steve Narofff8a09432008-01-09 23:34:55 +0000970 // Merge the decl with the existing one if appropriate. If the decl is
971 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000972 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000973 NewVD = MergeVarDecl(NewVD, PrevDecl);
974 if (NewVD == 0) return 0;
975 }
Chris Lattner4b009652007-07-25 00:24:17 +0000976 New = NewVD;
977 }
978
979 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000980 if (II)
981 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000982 // If any semantic error occurred, mark the decl as invalid.
983 if (D.getInvalidType() || InvalidDecl)
984 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000985
986 return New;
987}
988
Eli Friedman02c22ce2008-05-20 13:48:25 +0000989bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
990 switch (Init->getStmtClass()) {
991 default:
992 Diag(Init->getExprLoc(),
993 diag::err_init_element_not_constant, Init->getSourceRange());
994 return true;
995 case Expr::ParenExprClass: {
996 const ParenExpr* PE = cast<ParenExpr>(Init);
997 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
998 }
999 case Expr::CompoundLiteralExprClass:
1000 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1001 case Expr::DeclRefExprClass: {
1002 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001003 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1004 if (VD->hasGlobalStorage())
1005 return false;
1006 Diag(Init->getExprLoc(),
1007 diag::err_init_element_not_constant, Init->getSourceRange());
1008 return true;
1009 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001010 if (isa<FunctionDecl>(D))
1011 return false;
1012 Diag(Init->getExprLoc(),
1013 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Narofff0b23542008-01-10 22:15:12 +00001014 return true;
1015 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001016 case Expr::MemberExprClass: {
1017 const MemberExpr *M = cast<MemberExpr>(Init);
1018 if (M->isArrow())
1019 return CheckAddressConstantExpression(M->getBase());
1020 return CheckAddressConstantExpressionLValue(M->getBase());
1021 }
1022 case Expr::ArraySubscriptExprClass: {
1023 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1024 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1025 return CheckAddressConstantExpression(ASE->getBase()) ||
1026 CheckArithmeticConstantExpression(ASE->getIdx());
1027 }
1028 case Expr::StringLiteralClass:
1029 case Expr::PreDefinedExprClass:
1030 return false;
1031 case Expr::UnaryOperatorClass: {
1032 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1033
1034 // C99 6.6p9
1035 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001036 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001037
1038 Diag(Init->getExprLoc(),
1039 diag::err_init_element_not_constant, Init->getSourceRange());
1040 return true;
1041 }
1042 }
1043}
1044
1045bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1046 switch (Init->getStmtClass()) {
1047 default:
1048 Diag(Init->getExprLoc(),
1049 diag::err_init_element_not_constant, Init->getSourceRange());
1050 return true;
1051 case Expr::ParenExprClass: {
1052 const ParenExpr* PE = cast<ParenExpr>(Init);
1053 return CheckAddressConstantExpression(PE->getSubExpr());
1054 }
1055 case Expr::StringLiteralClass:
1056 case Expr::ObjCStringLiteralClass:
1057 return false;
1058 case Expr::CallExprClass: {
1059 const CallExpr *CE = cast<CallExpr>(Init);
1060 if (CE->isBuiltinConstantExpr())
1061 return false;
1062 Diag(Init->getExprLoc(),
1063 diag::err_init_element_not_constant, Init->getSourceRange());
1064 return true;
1065 }
1066 case Expr::UnaryOperatorClass: {
1067 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1068
1069 // C99 6.6p9
1070 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1071 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1072
1073 if (Exp->getOpcode() == UnaryOperator::Extension)
1074 return CheckAddressConstantExpression(Exp->getSubExpr());
1075
1076 Diag(Init->getExprLoc(),
1077 diag::err_init_element_not_constant, Init->getSourceRange());
1078 return true;
1079 }
1080 case Expr::BinaryOperatorClass: {
1081 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1082 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1083
1084 Expr *PExp = Exp->getLHS();
1085 Expr *IExp = Exp->getRHS();
1086 if (IExp->getType()->isPointerType())
1087 std::swap(PExp, IExp);
1088
1089 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1090 return CheckAddressConstantExpression(PExp) ||
1091 CheckArithmeticConstantExpression(IExp);
1092 }
1093 case Expr::ImplicitCastExprClass: {
1094 const Expr* SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
1095
1096 // Check for implicit promotion
1097 if (SubExpr->getType()->isFunctionType() ||
1098 SubExpr->getType()->isArrayType())
1099 return CheckAddressConstantExpressionLValue(SubExpr);
1100
1101 // Check for pointer->pointer cast
1102 if (SubExpr->getType()->isPointerType())
1103 return CheckAddressConstantExpression(SubExpr);
1104
1105 if (SubExpr->getType()->isArithmeticType())
1106 return CheckArithmeticConstantExpression(SubExpr);
1107
1108 Diag(Init->getExprLoc(),
1109 diag::err_init_element_not_constant, Init->getSourceRange());
1110 return true;
1111 }
1112 case Expr::CastExprClass: {
1113 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
1114
1115 // Check for pointer->pointer cast
1116 if (SubExpr->getType()->isPointerType())
1117 return CheckAddressConstantExpression(SubExpr);
1118
1119 // FIXME: Should we pedwarn for (int*)(0+0)?
1120 if (SubExpr->getType()->isArithmeticType())
1121 return CheckArithmeticConstantExpression(SubExpr);
1122
1123 Diag(Init->getExprLoc(),
1124 diag::err_init_element_not_constant, Init->getSourceRange());
1125 return true;
1126 }
1127 case Expr::ConditionalOperatorClass: {
1128 // FIXME: Should we pedwarn here?
1129 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1130 if (!Exp->getCond()->getType()->isArithmeticType()) {
1131 Diag(Init->getExprLoc(),
1132 diag::err_init_element_not_constant, Init->getSourceRange());
1133 return true;
1134 }
1135 if (CheckArithmeticConstantExpression(Exp->getCond()))
1136 return true;
1137 if (Exp->getLHS() &&
1138 CheckAddressConstantExpression(Exp->getLHS()))
1139 return true;
1140 return CheckAddressConstantExpression(Exp->getRHS());
1141 }
1142 case Expr::AddrLabelExprClass:
1143 return false;
1144 }
1145}
1146
1147bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1148 switch (Init->getStmtClass()) {
1149 default:
1150 Diag(Init->getExprLoc(),
1151 diag::err_init_element_not_constant, Init->getSourceRange());
1152 return true;
1153 case Expr::ParenExprClass: {
1154 const ParenExpr* PE = cast<ParenExpr>(Init);
1155 return CheckArithmeticConstantExpression(PE->getSubExpr());
1156 }
1157 case Expr::FloatingLiteralClass:
1158 case Expr::IntegerLiteralClass:
1159 case Expr::CharacterLiteralClass:
1160 case Expr::ImaginaryLiteralClass:
1161 case Expr::TypesCompatibleExprClass:
1162 case Expr::CXXBoolLiteralExprClass:
1163 return false;
1164 case Expr::CallExprClass: {
1165 const CallExpr *CE = cast<CallExpr>(Init);
1166 if (CE->isBuiltinConstantExpr())
1167 return false;
1168 Diag(Init->getExprLoc(),
1169 diag::err_init_element_not_constant, Init->getSourceRange());
1170 return true;
1171 }
1172 case Expr::DeclRefExprClass: {
1173 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1174 if (isa<EnumConstantDecl>(D))
1175 return false;
1176 Diag(Init->getExprLoc(),
1177 diag::err_init_element_not_constant, Init->getSourceRange());
1178 return true;
1179 }
1180 case Expr::CompoundLiteralExprClass:
1181 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1182 // but vectors are allowed to be magic.
1183 if (Init->getType()->isVectorType())
1184 return false;
1185 Diag(Init->getExprLoc(),
1186 diag::err_init_element_not_constant, Init->getSourceRange());
1187 return true;
1188 case Expr::UnaryOperatorClass: {
1189 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1190
1191 switch (Exp->getOpcode()) {
1192 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1193 // See C99 6.6p3.
1194 default:
1195 Diag(Init->getExprLoc(),
1196 diag::err_init_element_not_constant, Init->getSourceRange());
1197 return true;
1198 case UnaryOperator::SizeOf:
1199 case UnaryOperator::AlignOf:
1200 case UnaryOperator::OffsetOf:
1201 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1202 // See C99 6.5.3.4p2 and 6.6p3.
1203 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1204 return false;
1205 Diag(Init->getExprLoc(),
1206 diag::err_init_element_not_constant, Init->getSourceRange());
1207 return true;
1208 case UnaryOperator::Extension:
1209 case UnaryOperator::LNot:
1210 case UnaryOperator::Plus:
1211 case UnaryOperator::Minus:
1212 case UnaryOperator::Not:
1213 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1214 }
1215 }
1216 case Expr::SizeOfAlignOfTypeExprClass: {
1217 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1218 // Special check for void types, which are allowed as an extension
1219 if (Exp->getArgumentType()->isVoidType())
1220 return false;
1221 // alignof always evaluates to a constant.
1222 // FIXME: is sizeof(int[3.0]) a constant expression?
1223 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1224 Diag(Init->getExprLoc(),
1225 diag::err_init_element_not_constant, Init->getSourceRange());
1226 return true;
1227 }
1228 return false;
1229 }
1230 case Expr::BinaryOperatorClass: {
1231 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1232
1233 if (Exp->getLHS()->getType()->isArithmeticType() &&
1234 Exp->getRHS()->getType()->isArithmeticType()) {
1235 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1236 CheckArithmeticConstantExpression(Exp->getRHS());
1237 }
1238
1239 Diag(Init->getExprLoc(),
1240 diag::err_init_element_not_constant, Init->getSourceRange());
1241 return true;
1242 }
1243 case Expr::ImplicitCastExprClass:
1244 case Expr::CastExprClass: {
1245 const Expr *SubExpr;
1246 if (const CastExpr *C = dyn_cast<CastExpr>(Init)) {
1247 SubExpr = C->getSubExpr();
1248 } else {
1249 SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
1250 }
1251
1252 if (SubExpr->getType()->isArithmeticType())
1253 return CheckArithmeticConstantExpression(SubExpr);
1254
1255 Diag(Init->getExprLoc(),
1256 diag::err_init_element_not_constant, Init->getSourceRange());
1257 return true;
1258 }
1259 case Expr::ConditionalOperatorClass: {
1260 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1261 if (CheckArithmeticConstantExpression(Exp->getCond()))
1262 return true;
1263 if (Exp->getLHS() &&
1264 CheckArithmeticConstantExpression(Exp->getLHS()))
1265 return true;
1266 return CheckArithmeticConstantExpression(Exp->getRHS());
1267 }
1268 }
1269}
1270
1271bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
1272 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1273 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1274 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1275
1276 if (Init->getType()->isReferenceType()) {
1277 // FIXME: Work out how the heck reference types work
1278 return false;
1279#if 0
1280 // A reference is constant if the address of the expression
1281 // is constant
1282 // We look through initlists here to simplify
1283 // CheckAddressConstantExpressionLValue.
1284 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1285 assert(Exp->getNumInits() > 0 &&
1286 "Refernce initializer cannot be empty");
1287 Init = Exp->getInit(0);
1288 }
1289 return CheckAddressConstantExpressionLValue(Init);
1290#endif
1291 }
1292
1293 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1294 unsigned numInits = Exp->getNumInits();
1295 for (unsigned i = 0; i < numInits; i++) {
1296 // FIXME: Need to get the type of the declaration for C++,
1297 // because it could be a reference?
1298 if (CheckForConstantInitializer(Exp->getInit(i),
1299 Exp->getInit(i)->getType()))
1300 return true;
1301 }
1302 return false;
1303 }
1304
1305 if (Init->isNullPointerConstant(Context))
1306 return false;
1307 if (Init->getType()->isArithmeticType()) {
Eli Friedman25086f02008-05-30 18:14:48 +00001308 QualType InitTy = Init->getType().getCanonicalType().getUnqualifiedType();
1309 if (InitTy == Context.BoolTy) {
1310 // Special handling for pointers implicitly cast to bool;
1311 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1312 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1313 Expr* SubE = ICE->getSubExpr();
1314 if (SubE->getType()->isPointerType() ||
1315 SubE->getType()->isArrayType() ||
1316 SubE->getType()->isFunctionType()) {
1317 return CheckAddressConstantExpression(Init);
1318 }
1319 }
1320 } else if (InitTy->isIntegralType()) {
1321 Expr* SubE = 0;
1322 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init))
1323 SubE = ICE->getSubExpr();
1324 else if (CastExpr* CE = dyn_cast<CastExpr>(Init))
1325 SubE = CE->getSubExpr();
1326 // Special check for pointer cast to int; we allow as an extension
1327 // an address constant cast to an integer if the integer
1328 // is of an appropriate width (this sort of code is apparently used
1329 // in some places).
1330 // FIXME: Add pedwarn?
1331 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1332 if (SubE && (SubE->getType()->isPointerType() ||
1333 SubE->getType()->isArrayType() ||
1334 SubE->getType()->isFunctionType())) {
1335 unsigned IntWidth = Context.getTypeSize(Init->getType());
1336 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1337 if (IntWidth >= PointerWidth)
1338 return CheckAddressConstantExpression(Init);
1339 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001340 }
1341
1342 return CheckArithmeticConstantExpression(Init);
1343 }
1344
1345 if (Init->getType()->isPointerType())
1346 return CheckAddressConstantExpression(Init);
1347
Eli Friedman25086f02008-05-30 18:14:48 +00001348 // An array type at the top level that isn't an init-list must
1349 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00001350 if (Init->getType()->isArrayType())
1351 return false;
1352
1353 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1354 Init->getSourceRange());
1355 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00001356}
1357
Steve Naroff6a0e2092007-09-12 14:07:44 +00001358void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001359 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001360 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001361 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00001362
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001363 // If there is no declaration, there was an error parsing it. Just ignore
1364 // the initializer.
1365 if (RealDecl == 0) {
1366 delete Init;
1367 return;
1368 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001369
Steve Naroff420d0f52007-09-12 20:13:48 +00001370 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1371 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00001372 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1373 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00001374 RealDecl->setInvalidDecl();
1375 return;
1376 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001377 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00001378 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00001379 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001380 if (VDecl->isBlockVarDecl()) {
1381 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001382 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00001383 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001384 VDecl->setInvalidDecl();
1385 } else if (!VDecl->isInvalidDecl()) {
Steve Narofff3cb5142008-01-25 00:51:06 +00001386 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001387 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001388 if (SC == VarDecl::Static) // C99 6.7.8p4.
1389 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001390 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001391 } else if (VDecl->isFileVarDecl()) {
1392 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00001393 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001394 if (!VDecl->isInvalidDecl())
Steve Narofff3cb5142008-01-25 00:51:06 +00001395 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001396 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001397
1398 // C99 6.7.8p4. All file scoped initializers need to be constant.
1399 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001400 }
1401 // If the type changed, it means we had an incomplete type that was
1402 // completed by the initializer. For example:
1403 // int ary[] = { 1, 3, 5 };
1404 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00001405 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001406 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00001407 Init->setType(DclT);
1408 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001409
1410 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00001411 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001412 return;
1413}
1414
Chris Lattner4b009652007-07-25 00:24:17 +00001415/// The declarators are chained together backwards, reverse the list.
1416Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1417 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001418 Decl *GroupDecl = static_cast<Decl*>(group);
1419 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00001420 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00001421
1422 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1423 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001424 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00001425 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001426 else { // reverse the list.
1427 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001428 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001429 Group->setNextDeclarator(NewGroup);
1430 NewGroup = Group;
1431 Group = Next;
1432 }
1433 }
1434 // Perform semantic analysis that depends on having fully processed both
1435 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001436 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00001437 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1438 if (!IDecl)
1439 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001440 QualType T = IDecl->getType();
1441
1442 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1443 // static storage duration, it shall not have a variable length array.
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001444 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1445 IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman70f414d2008-02-15 19:53:52 +00001446 if (T->getAsVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001447 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1448 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001449 }
1450 }
1451 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1452 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001453 if (IDecl->isBlockVarDecl() &&
1454 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001455 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +00001456 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1457 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001458 IDecl->setInvalidDecl();
1459 }
1460 }
1461 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1462 // object that has file scope without an initializer, and without a
1463 // storage-class specifier or with the storage-class specifier "static",
1464 // constitutes a tentative definition. Note: A tentative definition with
1465 // external linkage is valid (C99 6.2.2p5).
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001466 if (IDecl && !IDecl->getInit() &&
1467 (IDecl->getStorageClass() == VarDecl::Static ||
1468 IDecl->getStorageClass() == VarDecl::None)) {
Eli Friedmane0079792008-02-15 12:53:51 +00001469 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00001470 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1471 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001472 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00001473 // C99 6.9.2p3: If the declaration of an identifier for an object is
1474 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1475 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +00001476 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1477 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001478 IDecl->setInvalidDecl();
1479 }
1480 }
Chris Lattner4b009652007-07-25 00:24:17 +00001481 }
1482 return NewGroup;
1483}
Steve Naroff91b03f72007-08-28 03:03:08 +00001484
Chris Lattner3e254fb2008-04-08 04:40:51 +00001485/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1486/// to introduce parameters into function prototype scope.
1487Sema::DeclTy *
1488Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1489 DeclSpec &DS = D.getDeclSpec();
1490
1491 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1492 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1493 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1494 Diag(DS.getStorageClassSpecLoc(),
1495 diag::err_invalid_storage_class_in_func_decl);
1496 DS.ClearStorageClassSpecs();
1497 }
1498 if (DS.isThreadSpecified()) {
1499 Diag(DS.getThreadSpecLoc(),
1500 diag::err_invalid_storage_class_in_func_decl);
1501 DS.ClearStorageClassSpecs();
1502 }
1503
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001504 // Check that there are no default arguments inside the type of this
1505 // parameter (C++ only).
1506 if (getLangOptions().CPlusPlus)
1507 CheckExtraCXXDefaultArguments(D);
1508
Chris Lattner3e254fb2008-04-08 04:40:51 +00001509 // In this context, we *do not* check D.getInvalidType(). If the declarator
1510 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1511 // though it will not reflect the user specified type.
1512 QualType parmDeclType = GetTypeForDeclarator(D, S);
1513
1514 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1515
Chris Lattner4b009652007-07-25 00:24:17 +00001516 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1517 // Can this happen for params? We already checked that they don't conflict
1518 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001519 IdentifierInfo *II = D.getIdentifier();
1520 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1521 if (S->isDeclScope(PrevDecl)) {
1522 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1523 dyn_cast<NamedDecl>(PrevDecl)->getName());
1524
1525 // Recover by removing the name
1526 II = 0;
1527 D.SetIdentifier(0, D.getIdentifierLoc());
1528 }
Chris Lattner4b009652007-07-25 00:24:17 +00001529 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00001530
1531 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1532 // Doing the promotion here has a win and a loss. The win is the type for
1533 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1534 // code generator). The loss is the orginal type isn't preserved. For example:
1535 //
1536 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1537 // int blockvardecl[5];
1538 // sizeof(parmvardecl); // size == 4
1539 // sizeof(blockvardecl); // size == 20
1540 // }
1541 //
1542 // For expressions, all implicit conversions are captured using the
1543 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1544 //
1545 // FIXME: If a source translation tool needs to see the original type, then
1546 // we need to consider storing both types (in ParmVarDecl)...
1547 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00001548 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00001549 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00001550 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00001551 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00001552 parmDeclType = Context.getPointerType(parmDeclType);
1553
Chris Lattner3e254fb2008-04-08 04:40:51 +00001554 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1555 D.getIdentifierLoc(), II,
1556 parmDeclType, VarDecl::None,
1557 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00001558
Chris Lattner3e254fb2008-04-08 04:40:51 +00001559 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00001560 New->setInvalidDecl();
1561
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001562 if (II)
1563 PushOnScopeChains(New, S);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00001564
Nate Begemanc5b66682008-05-09 16:56:01 +00001565 HandleDeclAttributes(New, D.getDeclSpec().getAttributes(),
1566 D.getAttributes());
Chris Lattner4b009652007-07-25 00:24:17 +00001567 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001568
Chris Lattner4b009652007-07-25 00:24:17 +00001569}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001570
Chris Lattnerea148702007-10-09 17:14:05 +00001571Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +00001572 assert(CurFunctionDecl == 0 && "Function parsing confused");
1573 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1574 "Not a function declarator!");
1575 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001576
Chris Lattner4b009652007-07-25 00:24:17 +00001577 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1578 // for a K&R function.
1579 if (!FTI.hasPrototype) {
1580 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001581 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001582 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1583 FTI.ArgInfo[i].Ident->getName());
1584 // Implicitly declare the argument as type 'int' for lack of a better
1585 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001586 DeclSpec DS;
1587 const char* PrevSpec; // unused
1588 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1589 PrevSpec);
1590 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1591 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1592 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00001593 }
1594 }
Chris Lattnerec9361f2008-02-17 19:31:09 +00001595
Chris Lattner4b009652007-07-25 00:24:17 +00001596 // Since this is a function definition, act as though we have information
1597 // about the arguments.
Chris Lattnerec9361f2008-02-17 19:31:09 +00001598 if (FTI.NumArgs)
1599 FTI.hasPrototype = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001600 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001601 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00001602 }
1603
1604 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001605
1606 // See if this is a redefinition.
Steve Naroffe57c21a2008-04-01 23:04:06 +00001607 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroff6384a012008-04-02 14:35:35 +00001608 GlobalScope);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001609 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1610 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1611 const FunctionDecl *Definition;
1612 if (FD->getBody(Definition)) {
1613 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1614 D.getIdentifier()->getName());
1615 Diag(Definition->getLocation(), diag::err_previous_definition);
1616 }
Steve Naroff1d5bd642008-01-14 20:51:29 +00001617 }
1618 }
Steve Naroff4a712442008-02-12 01:09:36 +00001619 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattner2d2216b2008-02-16 01:20:36 +00001620 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattner4b009652007-07-25 00:24:17 +00001621 CurFunctionDecl = FD;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001622 PushDeclContext(FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001623
1624 // Check the validity of our function parameters
1625 CheckParmsForFunctionDef(FD);
1626
1627 // Introduce our parameters into the function scope
1628 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1629 ParmVarDecl *Param = FD->getParamDecl(p);
1630 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001631 if (Param->getIdentifier())
1632 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001633 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001634
Chris Lattner4b009652007-07-25 00:24:17 +00001635 return FD;
1636}
1637
Steve Naroff99ee4302007-11-11 23:20:51 +00001638Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1639 Decl *dcl = static_cast<Decl *>(D);
1640 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1641 FD->setBody((Stmt*)Body);
1642 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff8ba51142007-12-13 18:18:56 +00001643 CurFunctionDecl = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001644 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001645 MD->setBody((Stmt*)Body);
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001646 CurMethodDecl = 0;
Steve Naroff8ba51142007-12-13 18:18:56 +00001647 }
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001648 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00001649 // Verify and clean out per-function state.
1650
1651 // Check goto/label use.
1652 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1653 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1654 // Verify that we have no forward references left. If so, there was a goto
1655 // or address of a label taken, but no definition of it. Label fwd
1656 // definitions are indicated with a null substmt.
1657 if (I->second->getSubStmt() == 0) {
1658 LabelStmt *L = I->second;
1659 // Emit error.
1660 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1661
1662 // At this point, we have gotos that use the bogus label. Stitch it into
1663 // the function body so that they aren't leaked and that the AST is well
1664 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00001665 if (Body) {
1666 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1667 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1668 } else {
1669 // The whole function wasn't parsed correctly, just delete this.
1670 delete L;
1671 }
Chris Lattner4b009652007-07-25 00:24:17 +00001672 }
1673 }
1674 LabelMap.clear();
1675
Steve Naroff99ee4302007-11-11 23:20:51 +00001676 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001677}
1678
Chris Lattner4b009652007-07-25 00:24:17 +00001679/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1680/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001681ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1682 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001683 // Extension in C99. Legal in C90, but warn about it.
1684 if (getLangOptions().C99)
Chris Lattner4b009652007-07-25 00:24:17 +00001685 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001686 else
Chris Lattner4b009652007-07-25 00:24:17 +00001687 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1688
1689 // FIXME: handle stuff like:
1690 // void foo() { extern float X(); }
1691 // void bar() { X(); } <-- implicit decl for X in another scope.
1692
1693 // Set a Declarator for the implicit definition: int foo();
1694 const char *Dummy;
1695 DeclSpec DS;
1696 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1697 Error = Error; // Silence warning.
1698 assert(!Error && "Error setting up implicit decl!");
1699 Declarator D(DS, Declarator::BlockContext);
1700 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1701 D.SetIdentifier(&II, Loc);
1702
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001703 // Insert this function into translation-unit scope.
1704
1705 DeclContext *PrevDC = CurContext;
1706 CurContext = Context.getTranslationUnitDecl();
1707
Steve Naroff9104f3c2008-04-04 14:32:09 +00001708 FunctionDecl *FD =
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001709 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00001710 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001711
1712 CurContext = PrevDC;
1713
Steve Naroff9104f3c2008-04-04 14:32:09 +00001714 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00001715}
1716
1717
Chris Lattner82bb4792007-11-14 06:34:38 +00001718TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00001719 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00001720 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001721 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00001722
1723 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00001724 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1725 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00001726 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00001727 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001728 if (D.getInvalidType())
1729 NewTD->setInvalidDecl();
1730 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00001731}
1732
Steve Naroff0acc9c92007-09-15 18:49:24 +00001733/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001734/// former case, Name will be non-null. In the later case, Name will be null.
1735/// TagType indicates what kind of tag this is. TK indicates whether this is a
1736/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001737Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001738 SourceLocation KWLoc, IdentifierInfo *Name,
1739 SourceLocation NameLoc, AttributeList *Attr) {
1740 // If this is a use of an existing tag, it must have a name.
1741 assert((Name != 0 || TK == TK_Definition) &&
1742 "Nameless record must be a definition!");
1743
1744 Decl::Kind Kind;
1745 switch (TagType) {
1746 default: assert(0 && "Unknown tag type!");
1747 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1748 case DeclSpec::TST_union: Kind = Decl::Union; break;
Chris Lattner2e78db32008-04-13 18:59:07 +00001749 case DeclSpec::TST_class: Kind = Decl::Class; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001750 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1751 }
1752
1753 // If this is a named struct, check to see if there was a previous forward
1754 // declaration or definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001755 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1756 if (ScopedDecl *PrevDecl =
1757 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Chris Lattner4b009652007-07-25 00:24:17 +00001758
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001759 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1760 "unexpected Decl type");
1761 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1762 // If this is a use of a previous tag, or if the tag is already declared in
1763 // the same scope (so that the definition/declaration completes or
1764 // rementions the tag), reuse the decl.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001765 if (TK == TK_Reference ||
1766 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001767 // Make sure that this wasn't declared as an enum and now used as a struct
1768 // or something similar.
1769 if (PrevDecl->getKind() != Kind) {
1770 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1771 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1772 }
1773
1774 // If this is a use or a forward declaration, we're good.
1775 if (TK != TK_Definition)
1776 return PrevDecl;
Chris Lattner4b009652007-07-25 00:24:17 +00001777
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001778 // Diagnose attempts to redefine a tag.
1779 if (PrevTagDecl->isDefinition()) {
1780 Diag(NameLoc, diag::err_redefinition, Name->getName());
1781 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1782 // If this is a redefinition, recover by making this struct be
1783 // anonymous, which will make any later references get the previous
1784 // definition.
1785 Name = 0;
1786 } else {
1787 // Okay, this is definition of a previously declared or referenced tag.
1788 // Move the location of the decl to be the definition site.
1789 PrevDecl->setLocation(NameLoc);
1790 return PrevDecl;
1791 }
Chris Lattner4b009652007-07-25 00:24:17 +00001792 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001793 // If we get here, this is a definition of a new struct type in a nested
1794 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1795 // type.
1796 } else {
1797 // The tag name clashes with a namespace name, issue an error and recover
1798 // by making this tag be anonymous.
1799 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1800 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1801 Name = 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001802 }
Chris Lattner4b009652007-07-25 00:24:17 +00001803 }
1804
1805 // If there is an identifier, use the location of the identifier as the
1806 // location of the decl, otherwise use the location of the struct/union
1807 // keyword.
1808 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1809
1810 // Otherwise, if this is the first time we've seen this tag, create the decl.
1811 TagDecl *New;
1812 switch (Kind) {
1813 default: assert(0 && "Unknown tag kind!");
1814 case Decl::Enum:
1815 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1816 // enum X { A, B, C } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00001817 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001818 // If this is an undefined enum, warn.
1819 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1820 break;
1821 case Decl::Union:
1822 case Decl::Struct:
1823 case Decl::Class:
1824 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1825 // struct X { int A; } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00001826 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001827 break;
1828 }
1829
1830 // If this has an identifier, add it to the scope stack.
1831 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001832 // The scope passed in may not be a decl scope. Zip up the scope tree until
1833 // we find one that is.
1834 while ((S->getFlags() & Scope::DeclScope) == 0)
1835 S = S->getParent();
1836
1837 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001838 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00001839 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00001840
Anders Carlsson136cdc32008-02-16 00:29:18 +00001841 HandleDeclAttributes(New, Attr, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001842 return New;
1843}
1844
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001845static bool CalcFakeICEVal(const Expr* Expr,
1846 llvm::APSInt& Result,
1847 ASTContext& Context) {
1848 // Calculate the value of an expression that has a calculatable
1849 // value, but isn't an ICE. Currently, this only supports
1850 // a very narrow set of extensions, but it can be expanded if needed.
1851 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Expr))
1852 return CalcFakeICEVal(PE->getSubExpr(), Result, Context);
1853
1854 if (const CastExpr *CE = dyn_cast<CastExpr>(Expr)) {
1855 QualType CETy = CE->getType();
1856 if ((CETy->isIntegralType() && !CETy->isBooleanType()) ||
1857 CETy->isPointerType()) {
1858 if (CalcFakeICEVal(CE->getSubExpr(), Result, Context)) {
1859 Result.extOrTrunc(Context.getTypeSize(CETy));
1860 // FIXME: This assumes pointers are signed.
1861 Result.setIsSigned(CETy->isSignedIntegerType() ||
1862 CETy->isPointerType());
1863 return true;
1864 }
1865 }
1866 }
1867
1868 if (Expr->getType()->isIntegralType())
1869 return Expr->isIntegerConstantExpr(Result, Context);
1870
1871 return false;
1872}
1873
1874QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1875 // This method tries to turn a variable array into a constant
1876 // array even when the size isn't an ICE. This is necessary
1877 // for compatibility with code that depends on gcc's buggy
1878 // constant expression folding, like struct {char x[(int)(char*)2];}
1879 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
1880 llvm::APSInt Result(32);
1881 if (VLATy->getSizeExpr() &&
1882 CalcFakeICEVal(VLATy->getSizeExpr(), Result, Context) &&
1883 Result > llvm::APSInt(Result.getBitWidth(), Result.isUnsigned())) {
1884 return Context.getConstantArrayType(VLATy->getElementType(),
1885 Result, ArrayType::Normal, 0);
1886 }
1887 }
1888 return QualType();
1889}
1890
Steve Naroff0acc9c92007-09-15 18:49:24 +00001891/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001892/// to create a FieldDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001893Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner4b009652007-07-25 00:24:17 +00001894 SourceLocation DeclStart,
1895 Declarator &D, ExprTy *BitfieldWidth) {
1896 IdentifierInfo *II = D.getIdentifier();
1897 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001898 SourceLocation Loc = DeclStart;
1899 if (II) Loc = D.getIdentifierLoc();
1900
1901 // FIXME: Unnamed fields can be handled in various different ways, for
1902 // example, unnamed unions inject all members into the struct namespace!
1903
1904
1905 if (BitWidth) {
1906 // TODO: Validate.
1907 //printf("WARNING: BITFIELDS IGNORED!\n");
1908
1909 // 6.7.2.1p3
1910 // 6.7.2.1p4
1911
1912 } else {
1913 // Not a bitfield.
1914
1915 // validate II.
1916
1917 }
1918
1919 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001920 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1921 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001922
Chris Lattner4b009652007-07-25 00:24:17 +00001923 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1924 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00001925 if (T->isVariablyModifiedType()) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001926 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
1927 if (!FixedTy.isNull()) {
1928 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
1929 T = FixedTy;
1930 } else {
1931 // FIXME: This diagnostic needs work
1932 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1933 InvalidDecl = true;
1934 }
Chris Lattner4b009652007-07-25 00:24:17 +00001935 }
Chris Lattner4b009652007-07-25 00:24:17 +00001936 // FIXME: Chain fielddecls together.
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001937 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff75494892007-09-11 21:17:26 +00001938
Anders Carlsson136cdc32008-02-16 00:29:18 +00001939 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1940 D.getAttributes());
1941
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001942 if (D.getInvalidType() || InvalidDecl)
1943 NewFD->setInvalidDecl();
1944 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001945}
1946
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001947/// TranslateIvarVisibility - Translate visibility from a token ID to an
1948/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00001949static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001950TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00001951 switch (ivarVisibility) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001952 case tok::objc_private: return ObjCIvarDecl::Private;
1953 case tok::objc_public: return ObjCIvarDecl::Public;
1954 case tok::objc_protected: return ObjCIvarDecl::Protected;
1955 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001956 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00001957 }
1958}
1959
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001960/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1961/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001962Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001963 SourceLocation DeclStart,
1964 Declarator &D, ExprTy *BitfieldWidth,
1965 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001966 IdentifierInfo *II = D.getIdentifier();
1967 Expr *BitWidth = (Expr*)BitfieldWidth;
1968 SourceLocation Loc = DeclStart;
1969 if (II) Loc = D.getIdentifierLoc();
1970
1971 // FIXME: Unnamed fields can be handled in various different ways, for
1972 // example, unnamed unions inject all members into the struct namespace!
1973
1974
1975 if (BitWidth) {
1976 // TODO: Validate.
1977 //printf("WARNING: BITFIELDS IGNORED!\n");
1978
1979 // 6.7.2.1p3
1980 // 6.7.2.1p4
1981
1982 } else {
1983 // Not a bitfield.
1984
1985 // validate II.
1986
1987 }
1988
1989 QualType T = GetTypeForDeclarator(D, S);
1990 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1991 bool InvalidDecl = false;
1992
1993 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1994 // than a variably modified type.
1995 if (T->isVariablyModifiedType()) {
1996 // FIXME: This diagnostic needs work
1997 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1998 InvalidDecl = true;
1999 }
2000
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002001 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002002
2003 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
2004 D.getAttributes());
2005
2006 if (D.getInvalidType() || InvalidDecl)
2007 NewID->setInvalidDecl();
2008 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002009 if (Visibility != tok::objc_not_keyword)
2010 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002011 return NewID;
2012}
2013
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00002014void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002015 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00002016 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002017 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002018 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2019 assert(EnclosingDecl && "missing record or interface decl");
2020 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2021
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002022 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002023 // Diagnose code like:
2024 // struct S { struct S {} X; };
2025 // We discover this when we complete the outer S. Reject and ignore the
2026 // outer S.
2027 Diag(Record->getLocation(), diag::err_nested_redefinition,
2028 Record->getKindName());
2029 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002030 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002031 return;
2032 }
Chris Lattner4b009652007-07-25 00:24:17 +00002033 // Verify that all the fields are okay.
2034 unsigned NumNamedMembers = 0;
2035 llvm::SmallVector<FieldDecl*, 32> RecFields;
2036 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00002037
Chris Lattner4b009652007-07-25 00:24:17 +00002038 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002039
Steve Naroff9bb759f2007-09-14 22:20:54 +00002040 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2041 assert(FD && "missing field decl");
2042
2043 // Remember all fields.
2044 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00002045
2046 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00002047 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00002048
Chris Lattner4b009652007-07-25 00:24:17 +00002049 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00002050 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002051 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00002052 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002053 FD->setInvalidDecl();
2054 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002055 continue;
2056 }
Chris Lattner4b009652007-07-25 00:24:17 +00002057 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2058 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002059 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002060 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002061 FD->setInvalidDecl();
2062 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002063 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002064 }
Chris Lattner4b009652007-07-25 00:24:17 +00002065 if (i != NumFields-1 || // ... that the last member ...
2066 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00002067 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00002068 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002069 FD->setInvalidDecl();
2070 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002071 continue;
2072 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002073 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00002074 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2075 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002076 FD->setInvalidDecl();
2077 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002078 continue;
2079 }
Chris Lattner4b009652007-07-25 00:24:17 +00002080 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002081 if (Record)
2082 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002083 }
Chris Lattner4b009652007-07-25 00:24:17 +00002084 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2085 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00002086 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002087 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2088 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002089 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner4b009652007-07-25 00:24:17 +00002090 Record->setHasFlexibleArrayMember(true);
2091 } else {
2092 // If this is a struct/class and this is not the last element, reject
2093 // it. Note that GCC supports variable sized arrays in the middle of
2094 // structures.
2095 if (i != NumFields-1) {
2096 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2097 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002098 FD->setInvalidDecl();
2099 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002100 continue;
2101 }
Chris Lattner4b009652007-07-25 00:24:17 +00002102 // We support flexible arrays at the end of structs in other structs
2103 // as an extension.
2104 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2105 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002106 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002107 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002108 }
2109 }
2110 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002111 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00002112 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002113 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2114 FD->getName());
2115 FD->setInvalidDecl();
2116 EnclosingDecl->setInvalidDecl();
2117 continue;
2118 }
Chris Lattner4b009652007-07-25 00:24:17 +00002119 // Keep track of the number of named members.
2120 if (IdentifierInfo *II = FD->getIdentifier()) {
2121 // Detect duplicate member names.
2122 if (!FieldIDs.insert(II)) {
2123 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2124 // Find the previous decl.
2125 SourceLocation PrevLoc;
2126 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2127 assert(i != e && "Didn't find previous def!");
2128 if (RecFields[i]->getIdentifier() == II) {
2129 PrevLoc = RecFields[i]->getLocation();
2130 break;
2131 }
2132 }
2133 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002134 FD->setInvalidDecl();
2135 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002136 continue;
2137 }
2138 ++NumNamedMembers;
2139 }
Chris Lattner4b009652007-07-25 00:24:17 +00002140 }
2141
Chris Lattner4b009652007-07-25 00:24:17 +00002142 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00002143 if (Record) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002144 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattner33aad6e2008-02-06 00:51:33 +00002145 Consumer.HandleTagDeclDefinition(Record);
2146 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00002147 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2148 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2149 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2150 else if (ObjCImplementationDecl *IMPDecl =
2151 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002152 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2153 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00002154 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00002155 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00002156 }
Chris Lattner4b009652007-07-25 00:24:17 +00002157}
2158
Steve Naroff0acc9c92007-09-15 18:49:24 +00002159Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00002160 DeclTy *lastEnumConst,
2161 SourceLocation IdLoc, IdentifierInfo *Id,
2162 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00002163 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002164 EnumConstantDecl *LastEnumConst =
2165 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2166 Expr *Val = static_cast<Expr*>(val);
2167
Chris Lattnera7549902007-08-26 06:24:45 +00002168 // The scope passed in may not be a decl scope. Zip up the scope tree until
2169 // we find one that is.
2170 while ((S->getFlags() & Scope::DeclScope) == 0)
2171 S = S->getParent();
2172
Chris Lattner4b009652007-07-25 00:24:17 +00002173 // Verify that there isn't already something declared with this name in this
2174 // scope.
Steve Naroff6384a012008-04-02 14:35:35 +00002175 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00002176 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002177 if (isa<EnumConstantDecl>(PrevDecl))
2178 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2179 else
2180 Diag(IdLoc, diag::err_redefinition, Id->getName());
2181 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002182 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00002183 return 0;
2184 }
2185 }
2186
2187 llvm::APSInt EnumVal(32);
2188 QualType EltTy;
2189 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00002190 // Make sure to promote the operand type to int.
2191 UsualUnaryConversions(Val);
2192
Chris Lattner4b009652007-07-25 00:24:17 +00002193 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2194 SourceLocation ExpLoc;
2195 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
2196 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2197 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002198 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00002199 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00002200 } else {
2201 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002202 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00002203 }
2204
2205 if (!Val) {
2206 if (LastEnumConst) {
2207 // Assign the last value + 1.
2208 EnumVal = LastEnumConst->getInitVal();
2209 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00002210
2211 // Check for overflow on increment.
2212 if (EnumVal < LastEnumConst->getInitVal())
2213 Diag(IdLoc, diag::warn_enum_value_overflow);
2214
Chris Lattnere7f53a42007-08-27 17:37:24 +00002215 EltTy = LastEnumConst->getType();
2216 } else {
2217 // First value, set to zero.
2218 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002219 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00002220 }
Chris Lattner4b009652007-07-25 00:24:17 +00002221 }
2222
Chris Lattnere4650482008-03-15 06:12:44 +00002223 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00002224 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2225 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00002226 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00002227
2228 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002229 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002230 return New;
2231}
2232
Steve Naroff0acc9c92007-09-15 18:49:24 +00002233void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00002234 DeclTy **Elements, unsigned NumElements) {
2235 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
2236 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
2237
Chris Lattner435c3fd2007-08-28 05:10:31 +00002238 // TODO: If the result value doesn't fit in an int, it must be a long or long
2239 // long value. ISO C does not support this, but GCC does as an extension,
2240 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002241 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00002242
Chris Lattner206754a2007-08-28 06:15:15 +00002243 // Verify that all the values are okay, compute the size of the values, and
2244 // reverse the list.
2245 unsigned NumNegativeBits = 0;
2246 unsigned NumPositiveBits = 0;
2247
2248 // Keep track of whether all elements have type int.
2249 bool AllElementsInt = true;
2250
Chris Lattner4b009652007-07-25 00:24:17 +00002251 EnumConstantDecl *EltList = 0;
2252 for (unsigned i = 0; i != NumElements; ++i) {
2253 EnumConstantDecl *ECD =
2254 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2255 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002256
2257 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002258 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002259 assert(InitVal.getBitWidth() >= IntWidth &&
2260 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00002261 if (InitVal.getBitWidth() > IntWidth) {
2262 llvm::APSInt V(InitVal);
2263 V.trunc(IntWidth);
2264 V.extend(InitVal.getBitWidth());
2265 if (V != InitVal)
2266 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
2267 InitVal.toString());
2268 }
Chris Lattner206754a2007-08-28 06:15:15 +00002269
2270 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002271 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00002272 NumPositiveBits = std::max(NumPositiveBits,
2273 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00002274 else
Chris Lattneraff63f02008-01-14 21:47:29 +00002275 NumNegativeBits = std::max(NumNegativeBits,
2276 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00002277
Chris Lattner206754a2007-08-28 06:15:15 +00002278 // Keep track of whether every enum element has type int (very commmon).
2279 if (AllElementsInt)
2280 AllElementsInt = ECD->getType() == Context.IntTy;
2281
Chris Lattner4b009652007-07-25 00:24:17 +00002282 ECD->setNextDeclarator(EltList);
2283 EltList = ECD;
2284 }
2285
Chris Lattner206754a2007-08-28 06:15:15 +00002286 // Figure out the type that should be used for this enum.
2287 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2288 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002289 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00002290
2291 if (NumNegativeBits) {
2292 // If there is a negative value, figure out the smallest integer type (of
2293 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002294 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002295 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002296 BestWidth = IntWidth;
2297 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002298 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002299
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002300 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002301 BestType = Context.LongTy;
2302 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002303 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002304
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002305 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002306 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2307 BestType = Context.LongLongTy;
2308 }
2309 }
2310 } else {
2311 // If there is no negative value, figure out which of uint, ulong, ulonglong
2312 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002313 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002314 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002315 BestWidth = IntWidth;
2316 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00002317 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00002318 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002319 } else {
2320 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002321 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00002322 "How could an initializer get larger than ULL?");
2323 BestType = Context.UnsignedLongLongTy;
2324 }
2325 }
2326
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002327 // Loop over all of the enumerator constants, changing their types to match
2328 // the type of the enum if needed.
2329 for (unsigned i = 0; i != NumElements; ++i) {
2330 EnumConstantDecl *ECD =
2331 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2332 if (!ECD) continue; // Already issued a diagnostic.
2333
2334 // Standard C says the enumerators have int type, but we allow, as an
2335 // extension, the enumerators to be larger than int size. If each
2336 // enumerator value fits in an int, type it as an int, otherwise type it the
2337 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2338 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002339 if (ECD->getType() == Context.IntTy) {
2340 // Make sure the init value is signed.
2341 llvm::APSInt IV = ECD->getInitVal();
2342 IV.setIsSigned(true);
2343 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002344 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002345 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002346
2347 // Determine whether the value fits into an int.
2348 llvm::APSInt InitVal = ECD->getInitVal();
2349 bool FitsInInt;
2350 if (InitVal.isUnsigned() || !InitVal.isNegative())
2351 FitsInInt = InitVal.getActiveBits() < IntWidth;
2352 else
2353 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2354
2355 // If it fits into an integer type, force it. Otherwise force it to match
2356 // the enum decl type.
2357 QualType NewTy;
2358 unsigned NewWidth;
2359 bool NewSign;
2360 if (FitsInInt) {
2361 NewTy = Context.IntTy;
2362 NewWidth = IntWidth;
2363 NewSign = true;
2364 } else if (ECD->getType() == BestType) {
2365 // Already the right type!
2366 continue;
2367 } else {
2368 NewTy = BestType;
2369 NewWidth = BestWidth;
2370 NewSign = BestType->isSignedIntegerType();
2371 }
2372
2373 // Adjust the APSInt value.
2374 InitVal.extOrTrunc(NewWidth);
2375 InitVal.setIsSigned(NewSign);
2376 ECD->setInitVal(InitVal);
2377
2378 // Adjust the Expr initializer and type.
2379 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2380 ECD->setType(NewTy);
2381 }
Chris Lattner206754a2007-08-28 06:15:15 +00002382
Chris Lattner90a018d2007-08-28 18:24:31 +00002383 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002384 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00002385}
2386
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002387Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2388 ExprTy *expr) {
2389 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2390
Chris Lattner81db64a2008-03-16 00:16:02 +00002391 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002392}
2393
Chris Lattner806a5f52008-01-12 07:05:38 +00002394Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00002395 SourceLocation LBrace,
2396 SourceLocation RBrace,
2397 const char *Lang,
2398 unsigned StrSize,
2399 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00002400 LinkageSpecDecl::LanguageIDs Language;
2401 Decl *dcl = static_cast<Decl *>(D);
2402 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2403 Language = LinkageSpecDecl::lang_c;
2404 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2405 Language = LinkageSpecDecl::lang_cxx;
2406 else {
2407 Diag(Loc, diag::err_bad_language);
2408 return 0;
2409 }
2410
2411 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00002412 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00002413}
2414
Chris Lattner49d15cb2008-02-21 00:48:22 +00002415void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson28e34e32007-12-19 06:16:30 +00002416
Chris Lattner49d15cb2008-02-21 00:48:22 +00002417 switch (Attr->getKind()) {
Chris Lattnerb9716a62008-02-20 23:17:35 +00002418 case AttributeList::AT_vector_size:
Chris Lattner4b009652007-07-25 00:24:17 +00002419 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner49d15cb2008-02-21 00:48:22 +00002420 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00002421 if (!newType.isNull()) // install the new vector type into the decl
2422 vDecl->setType(newType);
2423 }
2424 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2425 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00002426 Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00002427 if (!newType.isNull()) // install the new vector type into the decl
2428 tDecl->setUnderlyingType(newType);
2429 }
Chris Lattnerb9716a62008-02-20 23:17:35 +00002430 break;
Nate Begemanaf6ed502008-04-18 23:10:10 +00002431 case AttributeList::AT_ext_vector_type:
Steve Naroff82113e32007-07-29 16:33:31 +00002432 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Nate Begemanaf6ed502008-04-18 23:10:10 +00002433 HandleExtVectorTypeAttribute(tDecl, Attr);
Steve Naroff82113e32007-07-29 16:33:31 +00002434 else
Chris Lattner49d15cb2008-02-21 00:48:22 +00002435 Diag(Attr->getLoc(),
Nate Begemanaf6ed502008-04-18 23:10:10 +00002436 diag::err_typecheck_ext_vector_not_typedef);
Chris Lattnerb9716a62008-02-20 23:17:35 +00002437 break;
2438 case AttributeList::AT_address_space:
Christopher Lamb2a72bb32008-02-04 02:31:56 +00002439 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2440 QualType newType = HandleAddressSpaceTypeAttribute(
2441 tDecl->getUnderlyingType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00002442 Attr);
2443 tDecl->setUnderlyingType(newType);
Christopher Lamb2a72bb32008-02-04 02:31:56 +00002444 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2445 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00002446 Attr);
2447 // install the new addr spaced type into the decl
2448 vDecl->setType(newType);
Christopher Lamb2a72bb32008-02-04 02:31:56 +00002449 }
Chris Lattnerb9716a62008-02-20 23:17:35 +00002450 break;
Eli Friedman86ad5222008-05-27 03:33:27 +00002451 case AttributeList::AT_mode:
2452 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2453 QualType newType = HandleModeTypeAttribute(tDecl->getUnderlyingType(),
2454 Attr);
2455 tDecl->setUnderlyingType(newType);
2456 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2457 QualType newType = HandleModeTypeAttribute(vDecl->getType(), Attr);
2458 vDecl->setType(newType);
2459 }
2460 // FIXME: Diagnostic?
2461 break;
Chris Lattneree4c3bf2008-02-29 16:48:43 +00002462 case AttributeList::AT_deprecated:
Chris Lattner402b3372008-03-03 03:28:21 +00002463 HandleDeprecatedAttribute(New, Attr);
2464 break;
2465 case AttributeList::AT_visibility:
2466 HandleVisibilityAttribute(New, Attr);
2467 break;
2468 case AttributeList::AT_weak:
2469 HandleWeakAttribute(New, Attr);
2470 break;
2471 case AttributeList::AT_dllimport:
2472 HandleDLLImportAttribute(New, Attr);
2473 break;
2474 case AttributeList::AT_dllexport:
2475 HandleDLLExportAttribute(New, Attr);
2476 break;
2477 case AttributeList::AT_nothrow:
2478 HandleNothrowAttribute(New, Attr);
Chris Lattneree4c3bf2008-02-29 16:48:43 +00002479 break;
Nate Begemand75d28b2008-03-07 20:04:22 +00002480 case AttributeList::AT_stdcall:
2481 HandleStdCallAttribute(New, Attr);
2482 break;
2483 case AttributeList::AT_fastcall:
2484 HandleFastCallAttribute(New, Attr);
2485 break;
Chris Lattnerb9716a62008-02-20 23:17:35 +00002486 case AttributeList::AT_aligned:
Chris Lattner49d15cb2008-02-21 00:48:22 +00002487 HandleAlignedAttribute(New, Attr);
Chris Lattnerb9716a62008-02-20 23:17:35 +00002488 break;
2489 case AttributeList::AT_packed:
Chris Lattner49d15cb2008-02-21 00:48:22 +00002490 HandlePackedAttribute(New, Attr);
Chris Lattnerb9716a62008-02-20 23:17:35 +00002491 break;
Nate Begeman754d3fc2008-02-21 19:30:49 +00002492 case AttributeList::AT_annotate:
2493 HandleAnnotateAttribute(New, Attr);
2494 break;
Ted Kremenek13bfae62008-02-27 20:43:06 +00002495 case AttributeList::AT_noreturn:
2496 HandleNoReturnAttribute(New, Attr);
2497 break;
Chris Lattner402b3372008-03-03 03:28:21 +00002498 case AttributeList::AT_format:
2499 HandleFormatAttribute(New, Attr);
2500 break;
Nuno Lopes463ec842008-04-25 09:32:00 +00002501 case AttributeList::AT_transparent_union:
2502 HandleTransparentUnionAttribute(New, Attr);
2503 break;
Chris Lattnerb9716a62008-02-20 23:17:35 +00002504 default:
Chris Lattneree4c3bf2008-02-29 16:48:43 +00002505#if 0
2506 // TODO: when we have the full set of attributes, warn about unknown ones.
2507 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
2508 Attr->getName()->getName());
2509#endif
Chris Lattnerb9716a62008-02-20 23:17:35 +00002510 break;
2511 }
Chris Lattner4b009652007-07-25 00:24:17 +00002512}
2513
2514void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2515 AttributeList *declarator_postfix) {
2516 while (declspec_prefix) {
2517 HandleDeclAttribute(New, declspec_prefix);
2518 declspec_prefix = declspec_prefix->getNext();
2519 }
2520 while (declarator_postfix) {
2521 HandleDeclAttribute(New, declarator_postfix);
2522 declarator_postfix = declarator_postfix->getNext();
2523 }
2524}
2525
Nate Begemanaf6ed502008-04-18 23:10:10 +00002526void Sema::HandleExtVectorTypeAttribute(TypedefDecl *tDecl,
Steve Naroff82113e32007-07-29 16:33:31 +00002527 AttributeList *rawAttr) {
2528 QualType curType = tDecl->getUnderlyingType();
Anders Carlssonc8b44122007-12-19 07:19:40 +00002529 // check the attribute arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002530 if (rawAttr->getNumArgs() != 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00002531 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Chris Lattner4b009652007-07-25 00:24:17 +00002532 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00002533 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002534 }
2535 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2536 llvm::APSInt vecSize(32);
2537 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00002538 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Nate Begemanaf6ed502008-04-18 23:10:10 +00002539 "ext_vector_type", sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00002540 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002541 }
2542 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2543 // in conjunction with complex types (pointers, arrays, functions, etc.).
2544 Type *canonType = curType.getCanonicalType().getTypePtr();
2545 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner9384f502008-02-20 23:25:22 +00002546 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Chris Lattner4b009652007-07-25 00:24:17 +00002547 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00002548 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002549 }
2550 // unlike gcc's vector_size attribute, the size is specified as the
2551 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00002552 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00002553
2554 if (vectorSize == 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00002555 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Chris Lattner4b009652007-07-25 00:24:17 +00002556 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00002557 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002558 }
Steve Naroff82113e32007-07-29 16:33:31 +00002559 // Instantiate/Install the vector type, the number of elements is > 0.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002560 tDecl->setUnderlyingType(Context.getExtVectorType(curType, vectorSize));
Steve Naroff82113e32007-07-29 16:33:31 +00002561 // Remember this typedef decl, we will need it later for diagnostics.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002562 ExtVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002563}
2564
2565QualType Sema::HandleVectorTypeAttribute(QualType curType,
2566 AttributeList *rawAttr) {
2567 // check the attribute arugments.
2568 if (rawAttr->getNumArgs() != 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00002569 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Chris Lattner4b009652007-07-25 00:24:17 +00002570 std::string("1"));
2571 return QualType();
2572 }
2573 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2574 llvm::APSInt vecSize(32);
2575 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00002576 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson7dce0292008-02-16 19:51:27 +00002577 "vector_size", sizeExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002578 return QualType();
2579 }
2580 // navigate to the base type - we need to provide for vector pointers,
2581 // vector arrays, and functions returning vectors.
2582 Type *canonType = curType.getCanonicalType().getTypePtr();
2583
2584 if (canonType->isPointerType() || canonType->isArrayType() ||
2585 canonType->isFunctionType()) {
Chris Lattner5b5e1982007-12-19 05:38:06 +00002586 assert(0 && "HandleVector(): Complex type construction unimplemented");
Chris Lattner4b009652007-07-25 00:24:17 +00002587 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2588 do {
2589 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2590 canonType = PT->getPointeeType().getTypePtr();
2591 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2592 canonType = AT->getElementType().getTypePtr();
2593 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2594 canonType = FT->getResultType().getTypePtr();
2595 } while (canonType->isPointerType() || canonType->isArrayType() ||
2596 canonType->isFunctionType());
2597 */
2598 }
2599 // the base type must be integer or float.
2600 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner9384f502008-02-20 23:25:22 +00002601 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Chris Lattner4b009652007-07-25 00:24:17 +00002602 curType.getCanonicalType().getAsString());
2603 return QualType();
2604 }
Chris Lattner8cd0e932008-03-05 18:54:05 +00002605 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Chris Lattner4b009652007-07-25 00:24:17 +00002606 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00002607 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00002608
2609 // the vector size needs to be an integral multiple of the type size.
2610 if (vectorSize % typeSize) {
Chris Lattner9384f502008-02-20 23:25:22 +00002611 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Chris Lattner4b009652007-07-25 00:24:17 +00002612 sizeExpr->getSourceRange());
2613 return QualType();
2614 }
2615 if (vectorSize == 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00002616 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Chris Lattner4b009652007-07-25 00:24:17 +00002617 sizeExpr->getSourceRange());
2618 return QualType();
2619 }
Nate Begeman754d3fc2008-02-21 19:30:49 +00002620 // Instantiate the vector type, the number of elements is > 0, and not
2621 // required to be a power of 2, unlike GCC.
Chris Lattner4b009652007-07-25 00:24:17 +00002622 return Context.getVectorType(curType, vectorSize/typeSize);
2623}
2624
Chris Lattner9384f502008-02-20 23:25:22 +00002625void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlsson136cdc32008-02-16 00:29:18 +00002626 // check the attribute arguments.
2627 if (rawAttr->getNumArgs() > 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00002628 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson136cdc32008-02-16 00:29:18 +00002629 std::string("0"));
2630 return;
2631 }
2632
2633 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2634 TD->addAttr(new PackedAttr);
2635 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2636 // If the alignment is less than or equal to 8 bits, the packed attribute
2637 // has no effect.
Chris Lattner8bb7dd52008-05-09 05:34:49 +00002638 if (!FD->getType()->isIncompleteType() &&
2639 Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner9384f502008-02-20 23:25:22 +00002640 Diag(rawAttr->getLoc(),
Anders Carlsson136cdc32008-02-16 00:29:18 +00002641 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner9384f502008-02-20 23:25:22 +00002642 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlsson136cdc32008-02-16 00:29:18 +00002643 else
Anders Carlssonca133d92008-02-16 00:39:40 +00002644 FD->addAttr(new PackedAttr);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002645 } else
Chris Lattner9384f502008-02-20 23:25:22 +00002646 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2647 rawAttr->getName()->getName());
Anders Carlsson136cdc32008-02-16 00:29:18 +00002648}
Nate Begeman754d3fc2008-02-21 19:30:49 +00002649
Ted Kremenek13bfae62008-02-27 20:43:06 +00002650void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2651 // check the attribute arguments.
2652 if (rawAttr->getNumArgs() != 0) {
2653 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2654 std::string("0"));
2655 return;
2656 }
2657
Ted Kremenek40b95e52008-03-03 16:52:27 +00002658 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2659
2660 if (!Fn) {
2661 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2662 "noreturn", "function");
2663 return;
2664 }
2665
Ted Kremenek13bfae62008-02-27 20:43:06 +00002666 d->addAttr(new NoReturnAttr());
2667}
2668
Chris Lattner402b3372008-03-03 03:28:21 +00002669void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2670 // check the attribute arguments.
2671 if (rawAttr->getNumArgs() != 0) {
2672 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2673 std::string("0"));
2674 return;
2675 }
2676
2677 d->addAttr(new DeprecatedAttr());
2678}
2679
2680void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2681 // check the attribute arguments.
Chris Lattnere9d83be2008-03-04 18:08:48 +00002682 if (rawAttr->getNumArgs() != 1) {
Chris Lattner402b3372008-03-03 03:28:21 +00002683 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2684 std::string("1"));
2685 return;
2686 }
2687
Chris Lattnere9d83be2008-03-04 18:08:48 +00002688 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2689 Arg = Arg->IgnoreParenCasts();
2690 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2691
2692 if (Str == 0 || Str->isWide()) {
Chris Lattner402b3372008-03-03 03:28:21 +00002693 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattnere9d83be2008-03-04 18:08:48 +00002694 "visibility", std::string("1"));
Chris Lattner402b3372008-03-03 03:28:21 +00002695 return;
2696 }
2697
Chris Lattnere9d83be2008-03-04 18:08:48 +00002698 const char *TypeStr = Str->getStrData();
2699 unsigned TypeLen = Str->getByteLength();
Dan Gohman4751a3a2008-05-22 00:50:06 +00002700 VisibilityAttr::VisibilityTypes type;
Chris Lattner402b3372008-03-03 03:28:21 +00002701
Chris Lattnere9d83be2008-03-04 18:08:48 +00002702 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Dan Gohman4751a3a2008-05-22 00:50:06 +00002703 type = VisibilityAttr::DefaultVisibility;
Chris Lattnere9d83be2008-03-04 18:08:48 +00002704 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Dan Gohman4751a3a2008-05-22 00:50:06 +00002705 type = VisibilityAttr::HiddenVisibility;
Chris Lattnere9d83be2008-03-04 18:08:48 +00002706 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Dan Gohman4751a3a2008-05-22 00:50:06 +00002707 type = VisibilityAttr::HiddenVisibility; // FIXME
Chris Lattnere9d83be2008-03-04 18:08:48 +00002708 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Dan Gohman4751a3a2008-05-22 00:50:06 +00002709 type = VisibilityAttr::ProtectedVisibility;
Chris Lattner402b3372008-03-03 03:28:21 +00002710 else {
2711 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattnere9d83be2008-03-04 18:08:48 +00002712 "visibility", TypeStr);
Chris Lattner402b3372008-03-03 03:28:21 +00002713 return;
2714 }
2715
2716 d->addAttr(new VisibilityAttr(type));
2717}
2718
2719void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2720 // check the attribute arguments.
2721 if (rawAttr->getNumArgs() != 0) {
2722 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2723 std::string("0"));
2724 return;
2725 }
2726
2727 d->addAttr(new WeakAttr());
2728}
2729
2730void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2731 // check the attribute arguments.
2732 if (rawAttr->getNumArgs() != 0) {
2733 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2734 std::string("0"));
2735 return;
2736 }
2737
2738 d->addAttr(new DLLImportAttr());
2739}
2740
2741void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2742 // check the attribute arguments.
2743 if (rawAttr->getNumArgs() != 0) {
2744 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2745 std::string("0"));
2746 return;
2747 }
2748
2749 d->addAttr(new DLLExportAttr());
2750}
2751
Nate Begemand75d28b2008-03-07 20:04:22 +00002752void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2753 // check the attribute arguments.
2754 if (rawAttr->getNumArgs() != 0) {
2755 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2756 std::string("0"));
2757 return;
2758 }
2759
2760 d->addAttr(new StdCallAttr());
2761}
2762
2763void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2764 // check the attribute arguments.
2765 if (rawAttr->getNumArgs() != 0) {
2766 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2767 std::string("0"));
2768 return;
2769 }
2770
2771 d->addAttr(new FastCallAttr());
2772}
2773
Chris Lattner402b3372008-03-03 03:28:21 +00002774void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2775 // check the attribute arguments.
2776 if (rawAttr->getNumArgs() != 0) {
2777 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2778 std::string("0"));
2779 return;
2780 }
2781
2782 d->addAttr(new NoThrowAttr());
2783}
2784
Nuno Lopes02564e52008-03-25 23:01:48 +00002785static const FunctionTypeProto *getFunctionProto(Decl *d) {
Nuno Lopesc3cf4502008-04-18 22:43:39 +00002786 QualType Ty;
Nuno Lopes02564e52008-03-25 23:01:48 +00002787
Nuno Lopesc3cf4502008-04-18 22:43:39 +00002788 if (ValueDecl *decl = dyn_cast<ValueDecl>(d))
2789 Ty = decl->getType();
2790 else if (FieldDecl *decl = dyn_cast<FieldDecl>(d))
2791 Ty = decl->getType();
Ted Kremenek1e0fb9b2008-05-09 17:36:24 +00002792 else if (TypedefDecl* decl = dyn_cast<TypedefDecl>(d))
2793 Ty = decl->getUnderlyingType();
Nuno Lopesc3cf4502008-04-18 22:43:39 +00002794 else
2795 return 0;
Nuno Lopes02564e52008-03-25 23:01:48 +00002796
2797 if (Ty->isFunctionPointerType()) {
2798 const PointerType *PtrTy = Ty->getAsPointerType();
2799 Ty = PtrTy->getPointeeType();
2800 }
2801
2802 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2803 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2804
2805 return 0;
2806}
2807
Ted Kremenek9df18da2008-05-08 19:43:35 +00002808static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
2809 if (!T->isPointerType())
2810 return false;
2811
2812 T = T->getAsPointerType()->getPointeeType().getCanonicalType();
2813 ObjCInterfaceType* ClsT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
2814
2815 if (!ClsT)
2816 return false;
2817
2818 IdentifierInfo* ClsName = ClsT->getDecl()->getIdentifier();
2819
2820 // FIXME: Should we walk the chain of classes?
2821 return ClsName == &Ctx.Idents.get("NSString") ||
2822 ClsName == &Ctx.Idents.get("NSMutableString");
2823}
Nuno Lopes02564e52008-03-25 23:01:48 +00002824
Ted Kremeneke5769412008-03-07 18:43:49 +00002825/// Handle __attribute__((format(type,idx,firstarg))) attributes
2826/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattner402b3372008-03-03 03:28:21 +00002827void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2828
2829 if (!rawAttr->getParameterName()) {
2830 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2831 "format", std::string("1"));
2832 return;
2833 }
2834
2835 if (rawAttr->getNumArgs() != 2) {
2836 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2837 std::string("3"));
2838 return;
2839 }
2840
Nuno Lopes02564e52008-03-25 23:01:48 +00002841 // GCC ignores the format attribute on K&R style function
2842 // prototypes, so we ignore it as well
2843 const FunctionTypeProto *proto = getFunctionProto(d);
2844
2845 if (!proto) {
Chris Lattner402b3372008-03-03 03:28:21 +00002846 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2847 "format", "function");
2848 return;
2849 }
2850
2851 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremeneke5769412008-03-07 18:43:49 +00002852 // this is needed in order to be compatible with GCC
Chris Lattner402b3372008-03-03 03:28:21 +00002853 // the index must start in 1 and the limit is numargs+1
Nuno Lopes02564e52008-03-25 23:01:48 +00002854 unsigned NumArgs = proto->getNumArgs();
Ted Kremeneke5769412008-03-07 18:43:49 +00002855 unsigned FirstIdx = 1;
Chris Lattner402b3372008-03-03 03:28:21 +00002856
2857 const char *Format = rawAttr->getParameterName()->getName();
2858 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2859
2860 // Normalize the argument, __foo__ becomes foo.
2861 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2862 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2863 Format += 2;
2864 FormatLen -= 4;
2865 }
2866
Ted Kremenek9df18da2008-05-08 19:43:35 +00002867 bool Supported = false;
2868 bool is_NSString = false;
2869 bool is_strftime = false;
2870
2871 switch (FormatLen) {
2872 default: break;
2873 case 5:
2874 Supported = !memcmp(Format, "scanf", 5);
2875 break;
2876 case 6:
2877 Supported = !memcmp(Format, "printf", 6);
2878 break;
2879 case 7:
2880 Supported = !memcmp(Format, "strfmon", 7);
2881 break;
2882 case 8:
2883 Supported = (is_strftime = !memcmp(Format, "strftime", 8)) ||
2884 (is_NSString = !memcmp(Format, "NSString", 8));
2885 break;
2886 }
2887
2888 if (!Supported) {
Chris Lattner402b3372008-03-03 03:28:21 +00002889 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2890 "format", rawAttr->getParameterName()->getName());
2891 return;
2892 }
2893
Ted Kremeneke5769412008-03-07 18:43:49 +00002894 // checks for the 2nd argument
Chris Lattner402b3372008-03-03 03:28:21 +00002895 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremeneke5769412008-03-07 18:43:49 +00002896 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattner402b3372008-03-03 03:28:21 +00002897 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2898 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2899 "format", std::string("2"), IdxExpr->getSourceRange());
2900 return;
2901 }
2902
Ted Kremeneke5769412008-03-07 18:43:49 +00002903 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattner402b3372008-03-03 03:28:21 +00002904 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2905 "format", std::string("2"), IdxExpr->getSourceRange());
2906 return;
2907 }
2908
Ted Kremenek9df18da2008-05-08 19:43:35 +00002909 // FIXME: Do we need to bounds check?
2910 unsigned ArgIdx = Idx.getZExtValue() - 1;
2911
Ted Kremeneke5769412008-03-07 18:43:49 +00002912 // make sure the format string is really a string
Ted Kremenek9df18da2008-05-08 19:43:35 +00002913 QualType Ty = proto->getArgType(ArgIdx);
2914
2915 if (is_NSString) {
2916 // FIXME: do we need to check if the type is NSString*? What are
2917 // the semantics?
2918 if (!isNSStringType(Ty, Context)) {
2919 // FIXME: Should highlight the actual expression that has the
2920 // wrong type.
2921 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_NSString,
2922 IdxExpr->getSourceRange());
2923 return;
2924 }
2925 }
2926 else if (!Ty->isPointerType() ||
Ted Kremeneke5769412008-03-07 18:43:49 +00002927 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
Ted Kremenek9df18da2008-05-08 19:43:35 +00002928 // FIXME: Should highlight the actual expression that has the
2929 // wrong type.
Ted Kremeneke5769412008-03-07 18:43:49 +00002930 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2931 IdxExpr->getSourceRange());
2932 return;
2933 }
2934
Ted Kremeneke5769412008-03-07 18:43:49 +00002935 // check the 3rd argument
Chris Lattner402b3372008-03-03 03:28:21 +00002936 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremeneke5769412008-03-07 18:43:49 +00002937 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattner402b3372008-03-03 03:28:21 +00002938 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2939 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2940 "format", std::string("3"), FirstArgExpr->getSourceRange());
2941 return;
2942 }
2943
Ted Kremeneke5769412008-03-07 18:43:49 +00002944 // check if the function is variadic if the 3rd argument non-zero
2945 if (FirstArg != 0) {
2946 if (proto->isVariadic()) {
2947 ++NumArgs; // +1 for ...
2948 } else {
2949 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2950 return;
2951 }
2952 }
2953
2954 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2955 // the input is just the current time + the format string
Ted Kremenek9df18da2008-05-08 19:43:35 +00002956 if (is_strftime) {
Ted Kremeneke5769412008-03-07 18:43:49 +00002957 if (FirstArg != 0) {
Chris Lattner402b3372008-03-03 03:28:21 +00002958 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2959 FirstArgExpr->getSourceRange());
2960 return;
2961 }
Ted Kremeneke5769412008-03-07 18:43:49 +00002962 // if 0 it disables parameter checking (to use with e.g. va_list)
2963 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattner402b3372008-03-03 03:28:21 +00002964 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2965 "format", std::string("3"), FirstArgExpr->getSourceRange());
2966 return;
2967 }
2968
2969 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2970 Idx.getZExtValue(), FirstArg.getZExtValue()));
2971}
2972
Nuno Lopes463ec842008-04-25 09:32:00 +00002973void Sema::HandleTransparentUnionAttribute(Decl *d, AttributeList *rawAttr) {
2974 // check the attribute arguments.
2975 if (rawAttr->getNumArgs() != 0) {
2976 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2977 std::string("0"));
2978 return;
2979 }
2980
2981 TypeDecl *decl = dyn_cast<TypeDecl>(d);
2982
2983 if (!decl || !Context.getTypeDeclType(decl)->isUnionType()) {
2984 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2985 "transparent_union", "union");
2986 return;
2987 }
2988
Chris Lattner46f83552008-04-30 16:04:01 +00002989 //QualType QTy = Context.getTypeDeclType(decl);
2990 //const RecordType *Ty = QTy->getAsUnionType();
Nuno Lopes463ec842008-04-25 09:32:00 +00002991
2992// FIXME
2993// Ty->addAttr(new TransparentUnionAttr());
2994}
2995
Nate Begeman754d3fc2008-02-21 19:30:49 +00002996void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2997 // check the attribute arguments.
2998 if (rawAttr->getNumArgs() != 1) {
2999 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
3000 std::string("1"));
3001 return;
3002 }
3003 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
3004 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlsson136cdc32008-02-16 00:29:18 +00003005
Nate Begeman754d3fc2008-02-21 19:30:49 +00003006 // Make sure that there is a string literal as the annotation's single
3007 // argument.
3008 if (!SE) {
3009 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
3010 return;
3011 }
3012 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
3013 SE->getByteLength())));
3014}
3015
Anders Carlssonc8b44122007-12-19 07:19:40 +00003016void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
3017{
3018 // check the attribute arguments.
Eli Friedman74820702008-01-30 17:38:42 +00003019 if (rawAttr->getNumArgs() > 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00003020 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonc8b44122007-12-19 07:19:40 +00003021 std::string("1"));
3022 return;
3023 }
Eli Friedman74820702008-01-30 17:38:42 +00003024
Anders Carlsson7dce0292008-02-16 19:51:27 +00003025 unsigned Align = 0;
3026
3027 if (rawAttr->getNumArgs() == 0) {
3028 // FIXME: This should be the target specific maximum alignment.
3029 // (For now we just use 128 bits which is the maximum on X86.
3030 Align = 128;
Eli Friedman74820702008-01-30 17:38:42 +00003031 return;
Anders Carlsson7dce0292008-02-16 19:51:27 +00003032 } else {
3033 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
3034 llvm::APSInt alignment(32);
3035 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00003036 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson7dce0292008-02-16 19:51:27 +00003037 "aligned", alignmentExpr->getSourceRange());
3038 return;
3039 }
3040
3041 Align = alignment.getZExtValue() * 8;
3042 }
Eli Friedman74820702008-01-30 17:38:42 +00003043
Anders Carlsson7dce0292008-02-16 19:51:27 +00003044 d->addAttr(new AlignedAttr(Align));
Anders Carlssonc8b44122007-12-19 07:19:40 +00003045}