blob: f583ad1606a3ed0a8cd8fdb76c4d5527aa1a495e [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
Anders Carlssonf78915f2008-02-15 07:04:12 +000017#include "clang/AST/Attr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +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"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Basic/SourceManager.h"
27// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000028#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000029#include "clang/Lex/HeaderSearch.h"
Steve Naroff563477d2007-09-18 23:55:05 +000030#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000032#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
34
Steve Naroffb327ce02008-04-02 14:35:35 +000035Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
36 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
37
Douglas Gregor2ce52f32008-04-13 21:07:44 +000038 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
39 isa<ObjCInterfaceDecl>(IIDecl) ||
40 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000041 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000042 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000043}
44
Chris Lattner9fdf9c62008-04-22 18:39:57 +000045void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000046 assert( ( (isa<ObjCMethodDecl>(DC) && isa<TranslationUnitDecl>(CurContext))
Chris Lattner9fdf9c62008-04-22 18:39:57 +000047 || DC->getParent() == CurContext ) &&
Chris Lattnerb048c982008-04-06 04:47:34 +000048 "The next DeclContext should be directly contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000049 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000050}
51
Chris Lattnerb048c982008-04-06 04:47:34 +000052void Sema::PopDeclContext() {
53 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000054 // If CurContext is a ObjC method, getParent() will return NULL.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000055 CurContext = isa<ObjCMethodDecl>(CurContext)
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000056 ? Context.getTranslationUnitDecl()
57 : CurContext->getParent();
Chris Lattner0ed844b2008-04-04 06:12:32 +000058}
59
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000060/// Add this decl to the scope shadowed decl chains.
61void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
62 IdResolver.AddDecl(D, S);
63 S->AddDecl(D);
64}
65
Steve Naroffb216c882007-10-09 22:01:59 +000066void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000067 if (S->decl_empty()) return;
68 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
69
Reid Spencer5f016e22007-07-11 17:01:13 +000070 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
71 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000072 Decl *TmpD = static_cast<Decl*>(*I);
73 assert(TmpD && "This decl didn't get pushed??");
74 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
75 assert(D && "This decl isn't a ScopedDecl?");
76
Reid Spencer5f016e22007-07-11 17:01:13 +000077 IdentifierInfo *II = D->getIdentifier();
78 if (!II) continue;
79
Chris Lattner7f925cc2008-04-11 07:00:53 +000080 // Unlink this decl from the identifier.
81 IdResolver.RemoveDecl(D);
82
Reid Spencer5f016e22007-07-11 17:01:13 +000083 // This will have to be revisited for C++: there we want to nest stuff in
84 // namespace decls etc. Even for C, we might want a top-level translation
85 // unit decl or something.
86 if (!CurFunctionDecl)
87 continue;
88
89 // Chain this decl to the containing function, it now owns the memory for
90 // the decl.
91 D->setNext(CurFunctionDecl->getDeclChain());
92 CurFunctionDecl->setDeclChain(D);
93 }
94}
95
Steve Naroffe8043c32008-04-01 23:04:06 +000096/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
97/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +000098ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +000099 // The third "scope" argument is 0 since we aren't enabling lazy built-in
100 // creation from this context.
101 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000102
Steve Naroffb327ce02008-04-02 14:35:35 +0000103 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000104}
105
Steve Naroffe8043c32008-04-01 23:04:06 +0000106/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000107/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000108Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
109 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000110 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000111 unsigned NS = NSI;
112 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
113 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000114
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 // Scan up the scope chain looking for a decl that matches this identifier
116 // that is in the appropriate namespace. This search should not take long, as
117 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Chris Lattner7f925cc2008-04-11 07:00:53 +0000118 NamedDecl *ND = IdResolver.Lookup(II, NS);
119 if (ND) return ND;
120
Reid Spencer5f016e22007-07-11 17:01:13 +0000121 // If we didn't find a use of this identifier, and if the identifier
122 // corresponds to a compiler builtin, create the decl object for the builtin
123 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000124 if (NS & Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000125 if (enableLazyBuiltinCreation) {
126 // If this is a builtin on this (or all) targets, create the decl.
127 if (unsigned BuiltinID = II->getBuiltinID())
128 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
129 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000130 if (getLangOptions().ObjC1) {
131 // @interface and @compatibility_alias introduce typedef-like names.
132 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000133 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000134 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000135 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
136 if (IDI != ObjCInterfaceDecls.end())
137 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000138 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
139 if (I != ObjCAliasDecls.end())
140 return I->second->getClassInterface();
141 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 }
143 return 0;
144}
145
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000146void Sema::InitBuiltinVaListType()
147{
148 if (!Context.getBuiltinVaListType().isNull())
149 return;
150
151 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000152 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000153 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000154 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
155}
156
Reid Spencer5f016e22007-07-11 17:01:13 +0000157/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
158/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000159ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
160 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000161 Builtin::ID BID = (Builtin::ID)bid;
162
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000163 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson793680e2007-10-12 23:56:29 +0000164 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000165 BID == Builtin::BI__builtin_va_end)
166 InitBuiltinVaListType();
167
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000168 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000169 FunctionDecl *New = FunctionDecl::Create(Context,
170 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000171 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000172 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000173
Chris Lattner7f925cc2008-04-11 07:00:53 +0000174 // TUScope is the translation-unit scope to insert this function into.
175 TUScope->AddDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +0000176
177 // Add this decl to the end of the identifier info.
Chris Lattner7f925cc2008-04-11 07:00:53 +0000178 IdResolver.AddGlobalDecl(New);
179
Reid Spencer5f016e22007-07-11 17:01:13 +0000180 return New;
181}
182
183/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
184/// and scope as a previous declaration 'Old'. Figure out how to resolve this
185/// situation, merging decls or emitting diagnostics as appropriate.
186///
Steve Naroffe8043c32008-04-01 23:04:06 +0000187TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000188 // Verify the old decl was also a typedef.
189 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
190 if (!Old) {
191 Diag(New->getLocation(), diag::err_redefinition_different_kind,
192 New->getName());
193 Diag(OldD->getLocation(), diag::err_previous_definition);
194 return New;
195 }
196
Steve Naroff8ee529b2007-10-31 18:42:27 +0000197 // Allow multiple definitions for ObjC built-in typedefs.
198 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000199 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000200 return Old;
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000201
202 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
203 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
204 // *either* declaration is in a system header. The code below implements
205 // this adhoc compatibility rule. FIXME: The following code will not
206 // work properly when compiling ".i" files (containing preprocessed output).
207 SourceManager &SrcMgr = Context.getSourceManager();
208 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
209 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
210 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
211 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
212 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
213
Steve Naroffc5e2f342008-03-26 21:27:00 +0000214 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
215 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
216 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroffd62701b2008-02-07 03:50:06 +0000217 getLangOptions().Microsoft)
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000218 return New;
Steve Naroffc5e2f342008-03-26 21:27:00 +0000219
Reid Spencer5f016e22007-07-11 17:01:13 +0000220 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
221 // TODO: This is totally simplistic. It should handle merging functions
222 // together etc, merging extern int X; int X; ...
223 Diag(New->getLocation(), diag::err_redefinition, New->getName());
224 Diag(Old->getLocation(), diag::err_previous_definition);
225 return New;
226}
227
Chris Lattnerddee4232008-03-03 03:28:21 +0000228/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
229static bool DeclHasAttr(const Decl *decl, const Attr *target) {
230 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
231 if (attr->getKind() == target->getKind())
232 return true;
233
234 return false;
235}
236
237/// MergeAttributes - append attributes from the Old decl to the New one.
238static void MergeAttributes(Decl *New, Decl *Old) {
239 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
240
241// FIXME: fix this code to cleanup the Old attrs correctly
242 while (attr) {
243 tmp = attr;
244 attr = attr->getNext();
245
246 if (!DeclHasAttr(New, tmp)) {
247 New->addAttr(tmp);
248 } else {
249 tmp->setNext(0);
250 delete(tmp);
251 }
252 }
253}
254
Chris Lattner04421082008-04-08 04:40:51 +0000255/// MergeFunctionDecl - We just parsed a function 'New' from
256/// declarator D which has the same name and scope as a previous
257/// declaration 'Old'. Figure out how to resolve this situation,
258/// merging decls or emitting diagnostics as appropriate.
Douglas Gregorf0097952008-04-21 02:02:58 +0000259/// Redeclaration will be set true if thisNew is a redeclaration OldD.
260FunctionDecl *
261Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
262 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000263 // Verify the old decl was also a function.
264 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
265 if (!Old) {
266 Diag(New->getLocation(), diag::err_redefinition_different_kind,
267 New->getName());
268 Diag(OldD->getLocation(), diag::err_previous_definition);
269 return New;
270 }
Chris Lattner04421082008-04-08 04:40:51 +0000271
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000272 QualType OldQType = Context.getCanonicalType(Old->getType());
273 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000274
Chris Lattner04421082008-04-08 04:40:51 +0000275 // C++ [dcl.fct]p3:
276 // All declarations for a function shall agree exactly in both the
277 // return type and the parameter-type-list.
Douglas Gregorf0097952008-04-21 02:02:58 +0000278 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
279 MergeAttributes(New, Old);
280 Redeclaration = true;
Chris Lattner04421082008-04-08 04:40:51 +0000281 return MergeCXXFunctionDecl(New, Old);
Douglas Gregorf0097952008-04-21 02:02:58 +0000282 }
Chris Lattner04421082008-04-08 04:40:51 +0000283
284 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000285 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000286 if (!getLangOptions().CPlusPlus &&
287 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000288 MergeAttributes(New, Old);
289 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000290 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000291 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000292
Steve Naroff837618c2008-01-16 15:01:34 +0000293 // A function that has already been declared has been redeclared or defined
294 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000295 diag::kind PrevDiag;
Douglas Gregorf0097952008-04-21 02:02:58 +0000296 if (Old->isThisDeclarationADefinition())
Steve Naroffe2ef8152008-04-04 14:32:09 +0000297 PrevDiag = diag::err_previous_definition;
298 else if (Old->isImplicit())
299 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000300 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000301 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000302
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
304 // TODO: This is totally simplistic. It should handle merging functions
305 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000306 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
307 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 return New;
309}
310
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000311/// equivalentArrayTypes - Used to determine whether two array types are
312/// equivalent.
313/// We need to check this explicitly as an incomplete array definition is
314/// considered a VariableArrayType, so will not match a complete array
315/// definition that would be otherwise equivalent.
316static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
317 const ArrayType *NewAT = NewQType->getAsArrayType();
318 const ArrayType *OldAT = OldQType->getAsArrayType();
319
320 if (!NewAT || !OldAT)
321 return false;
322
323 // If either (or both) array types in incomplete we need to strip off the
324 // outer VariableArrayType. Once the outer VAT is removed the remaining
325 // types must be identical if the array types are to be considered
326 // equivalent.
327 // eg. int[][1] and int[1][1] become
328 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
329 // removing the outermost VAT gives
330 // CAT(1, int) and CAT(1, int)
331 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000332 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000333 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
334 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000335 NewQType = NewAT->getElementType().getCanonicalType();
336 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000337 }
338
339 return NewQType == OldQType;
340}
341
Reid Spencer5f016e22007-07-11 17:01:13 +0000342/// MergeVarDecl - We just parsed a variable 'New' which has the same name
343/// and scope as a previous declaration 'Old'. Figure out how to resolve this
344/// situation, merging decls or emitting diagnostics as appropriate.
345///
346/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
347/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
348///
Steve Naroffe8043c32008-04-01 23:04:06 +0000349VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 // Verify the old decl was also a variable.
351 VarDecl *Old = dyn_cast<VarDecl>(OldD);
352 if (!Old) {
353 Diag(New->getLocation(), diag::err_redefinition_different_kind,
354 New->getName());
355 Diag(OldD->getLocation(), diag::err_previous_definition);
356 return New;
357 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000358
359 MergeAttributes(New, Old);
360
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000362 QualType OldCType = Context.getCanonicalType(Old->getType());
363 QualType NewCType = Context.getCanonicalType(New->getType());
364 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000365 Diag(New->getLocation(), diag::err_redefinition, New->getName());
366 Diag(Old->getLocation(), diag::err_previous_definition);
367 return New;
368 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000369 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
370 if (New->getStorageClass() == VarDecl::Static &&
371 (Old->getStorageClass() == VarDecl::None ||
372 Old->getStorageClass() == VarDecl::Extern)) {
373 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
374 Diag(Old->getLocation(), diag::err_previous_definition);
375 return New;
376 }
377 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
378 if (New->getStorageClass() != VarDecl::Static &&
379 Old->getStorageClass() == VarDecl::Static) {
380 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
381 Diag(Old->getLocation(), diag::err_previous_definition);
382 return New;
383 }
384 // We've verified the types match, now handle "tentative" definitions.
Steve Naroff248a7532008-04-15 22:42:06 +0000385 if (Old->isFileVarDecl() && New->isFileVarDecl()) {
Steve Naroffb7b032e2008-01-30 00:44:01 +0000386 // Handle C "tentative" external object definitions (C99 6.9.2).
387 bool OldIsTentative = false;
388 bool NewIsTentative = false;
389
Steve Naroff248a7532008-04-15 22:42:06 +0000390 if (!Old->getInit() &&
391 (Old->getStorageClass() == VarDecl::None ||
392 Old->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000393 OldIsTentative = true;
394
395 // FIXME: this check doesn't work (since the initializer hasn't been
396 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
397 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
398 // thrown out the old decl.
Steve Naroff248a7532008-04-15 22:42:06 +0000399 if (!New->getInit() &&
400 (New->getStorageClass() == VarDecl::None ||
401 New->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000402 ; // change to NewIsTentative = true; once the code is moved.
403
404 if (NewIsTentative || OldIsTentative)
405 return New;
406 }
407 if (Old->getStorageClass() != VarDecl::Extern &&
408 New->getStorageClass() != VarDecl::Extern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 Diag(New->getLocation(), diag::err_redefinition, New->getName());
410 Diag(Old->getLocation(), diag::err_previous_definition);
411 }
412 return New;
413}
414
Chris Lattner04421082008-04-08 04:40:51 +0000415/// CheckParmsForFunctionDef - Check that the parameters of the given
416/// function are appropriate for the definition of a function. This
417/// takes care of any checks that cannot be performed on the
418/// declaration itself, e.g., that the types of each of the function
419/// parameters are complete.
420bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
421 bool HasInvalidParm = false;
422 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
423 ParmVarDecl *Param = FD->getParamDecl(p);
424
425 // C99 6.7.5.3p4: the parameters in a parameter type list in a
426 // function declarator that is part of a function definition of
427 // that function shall not have incomplete type.
428 if (Param->getType()->isIncompleteType() &&
429 !Param->isInvalidDecl()) {
430 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
431 Param->getType().getAsString());
432 Param->setInvalidDecl();
433 HasInvalidParm = true;
434 }
435 }
436
437 return HasInvalidParm;
438}
439
440/// CreateImplicitParameter - Creates an implicit function parameter
441/// in the scope S and with the given type. This routine is used, for
442/// example, to create the implicit "self" parameter in an Objective-C
443/// method.
444ParmVarDecl *
445Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
446 SourceLocation IdLoc, QualType Type) {
447 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
448 VarDecl::None, 0, 0);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000449 if (Id)
450 PushOnScopeChains(New, S);
Chris Lattner04421082008-04-08 04:40:51 +0000451
452 return New;
453}
454
Reid Spencer5f016e22007-07-11 17:01:13 +0000455/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
456/// no declarator (e.g. "struct foo;") is parsed.
457Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
458 // TODO: emit error on 'int;' or 'const enum foo;'.
459 // TODO: emit error on 'typedef int;'
460 // if (!DS.isMissingDeclaratorOk()) Diag(...);
461
Steve Naroff92199282007-11-17 21:37:36 +0000462 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000463}
464
Steve Naroffd0091aa2008-01-10 22:15:12 +0000465bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000466 // Get the type before calling CheckSingleAssignmentConstraints(), since
467 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000468 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000469
Chris Lattner5cf216b2008-01-04 18:04:52 +0000470 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
471 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
472 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000473}
474
Steve Naroff9e8925e2007-09-04 14:36:54 +0000475bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000476 QualType ElementType) {
Chris Lattner33b7b062007-12-11 23:15:04 +0000477 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffd0091aa2008-01-10 22:15:12 +0000478 if (CheckSingleInitializer(expr, ElementType))
Chris Lattner33b7b062007-12-11 23:15:04 +0000479 return true; // types weren't compatible.
480
Steve Naroff9e8925e2007-09-04 14:36:54 +0000481 if (savExpr != expr) // The type was promoted, update initializer list.
482 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000483 return false;
484}
485
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000486bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000487 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000488 // C99 6.7.8p14. We have an array of character type with unknown size
489 // being initialized to a string literal.
490 llvm::APSInt ConstVal(32);
491 ConstVal = strLiteral->getByteLength() + 1;
492 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000493 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000494 ArrayType::Normal, 0);
495 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
496 // C99 6.7.8p14. We have an array of character type with known size.
497 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
498 Diag(strLiteral->getSourceRange().getBegin(),
499 diag::warn_initializer_string_for_char_array_too_long,
500 strLiteral->getSourceRange());
501 } else {
502 assert(0 && "HandleStringLiteralInit(): Invalid array type");
503 }
504 // Set type from "char *" to "constant array of char".
505 strLiteral->setType(DeclT);
506 // For now, we always return false (meaning success).
507 return false;
508}
509
510StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000511 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000512 if (AT && AT->getElementType()->isCharType()) {
513 return dyn_cast<StringLiteral>(Init);
514 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000515 return 0;
516}
517
Steve Naroffa9960332008-01-25 00:51:06 +0000518// CheckInitializerListTypes - Checks the types of elements of an initializer
519// list. This function is recursive: it calls itself to initialize subelements
520// of aggregate types. Note that the topLevel parameter essentially refers to
521// whether this expression "owns" the initializer list passed in, or if this
522// initialization is taking elements out of a parent initializer. Each
523// call to this function adds zero or more to startIndex, reports any errors,
524// and returns true if it found any inconsistent types.
525bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
526 bool topLevel, unsigned& startIndex) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000527 bool hadError = false;
Steve Naroffa9960332008-01-25 00:51:06 +0000528
529 if (DeclType->isScalarType()) {
530 // The simplest case: initializing a single scalar
531 if (topLevel) {
532 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
533 IList->getSourceRange());
534 }
535 if (startIndex < IList->getNumInits()) {
536 Expr* expr = IList->getInit(startIndex);
537 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
538 // FIXME: Should an error be reported here instead?
539 unsigned newIndex = 0;
540 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
541 } else {
542 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
543 }
544 ++startIndex;
545 }
546 // FIXME: Should an error be reported for empty initializer list + scalar?
547 } else if (DeclType->isVectorType()) {
548 if (startIndex < IList->getNumInits()) {
549 const VectorType *VT = DeclType->getAsVectorType();
550 int maxElements = VT->getNumElements();
551 QualType elementType = VT->getElementType();
552
553 for (int i = 0; i < maxElements; ++i) {
554 // Don't attempt to go past the end of the init list
555 if (startIndex >= IList->getNumInits())
556 break;
557 Expr* expr = IList->getInit(startIndex);
558 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
559 unsigned newIndex = 0;
560 hadError |= CheckInitializerListTypes(SubInitList, elementType,
561 true, newIndex);
562 ++startIndex;
563 } else {
564 hadError |= CheckInitializerListTypes(IList, elementType,
565 false, startIndex);
566 }
567 }
568 }
569 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
570 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroff578edc62008-01-28 02:00:41 +0000571 if (startIndex < IList->getNumInits() && !topLevel &&
572 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
573 DeclType)) {
Steve Naroffa9960332008-01-25 00:51:06 +0000574 // We found a compatible struct; per the standard, this initializes the
575 // struct. (The C standard technically says that this only applies for
576 // initializers for declarations with automatic scope; however, this
577 // construct is unambiguous anyway because a struct cannot contain
578 // a type compatible with itself. We'll output an error when we check
579 // if the initializer is constant.)
580 // FIXME: Is a call to CheckSingleInitializer required here?
581 ++startIndex;
582 } else {
583 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffb43eaa52008-02-11 00:06:17 +0000584
Steve Naroff406db932008-02-11 21:52:37 +0000585 // If the record is invalid, some of it's members are invalid. To avoid
586 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffb43eaa52008-02-11 00:06:17 +0000587 if (structDecl->isInvalidDecl())
588 return true;
589
Steve Naroffa9960332008-01-25 00:51:06 +0000590 // If structDecl is a forward declaration, this loop won't do anything;
591 // That's okay, because an error should get printed out elsewhere. It
592 // might be worthwhile to skip over the rest of the initializer, though.
593 int numMembers = structDecl->getNumMembers() -
594 structDecl->hasFlexibleArrayMember();
595 for (int i = 0; i < numMembers; i++) {
596 // Don't attempt to go past the end of the init list
597 if (startIndex >= IList->getNumInits())
598 break;
599 FieldDecl * curField = structDecl->getMember(i);
600 if (!curField->getIdentifier()) {
601 // Don't initialize unnamed fields, e.g. "int : 20;"
602 continue;
603 }
604 QualType fieldType = curField->getType();
605 Expr* expr = IList->getInit(startIndex);
606 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
607 unsigned newStart = 0;
608 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
609 true, newStart);
610 ++startIndex;
611 } else {
612 hadError |= CheckInitializerListTypes(IList, fieldType,
613 false, startIndex);
614 }
615 if (DeclType->isUnionType())
616 break;
617 }
618 // FIXME: Implement flexible array initialization GCC extension (it's a
619 // really messy extension to implement, unfortunately...the necessary
620 // information isn't actually even here!)
621 }
622 } else if (DeclType->isArrayType()) {
623 // Check for the special-case of initializing an array with a string.
624 if (startIndex < IList->getNumInits()) {
625 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
626 DeclType)) {
627 CheckStringLiteralInit(lit, DeclType);
628 ++startIndex;
629 if (topLevel && startIndex < IList->getNumInits()) {
630 // We have leftover initializers; warn
631 Diag(IList->getInit(startIndex)->getLocStart(),
632 diag::err_excess_initializers_in_char_array_initializer,
633 IList->getInit(startIndex)->getSourceRange());
634 }
635 return false;
636 }
637 }
638 int maxElements;
Eli Friedmanc5773c42008-02-15 18:16:39 +0000639 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000640 // FIXME: use a proper constant
641 maxElements = 0x7FFFFFFF;
Chris Lattner212839c2008-02-20 23:17:35 +0000642 } else if (const VariableArrayType *VAT =
643 DeclType->getAsVariableArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000644 // Check for VLAs; in standard C it would be possible to check this
645 // earlier, but I don't know where clang accepts VLAs (gcc accepts
646 // them in all sorts of strange places).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000647 Diag(VAT->getSizeExpr()->getLocStart(),
648 diag::err_variable_object_no_init,
649 VAT->getSizeExpr()->getSourceRange());
650 hadError = true;
651 maxElements = 0x7FFFFFFF;
Steve Naroffa9960332008-01-25 00:51:06 +0000652 } else {
653 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
654 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
655 }
656 QualType elementType = DeclType->getAsArrayType()->getElementType();
657 int numElements = 0;
658 for (int i = 0; i < maxElements; ++i, ++numElements) {
659 // Don't attempt to go past the end of the init list
660 if (startIndex >= IList->getNumInits())
661 break;
662 Expr* expr = IList->getInit(startIndex);
663 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
664 unsigned newIndex = 0;
665 hadError |= CheckInitializerListTypes(SubInitList, elementType,
666 true, newIndex);
667 ++startIndex;
668 } else {
669 hadError |= CheckInitializerListTypes(IList, elementType,
670 false, startIndex);
671 }
672 }
Eli Friedman9db13972008-02-15 12:53:51 +0000673 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000674 // If this is an incomplete array type, the actual type needs to
675 // be calculated here
676 if (numElements == 0) {
677 // Sizing an array implicitly to zero is not allowed
678 // (It could in theory be allowed, but it doesn't really matter.)
679 Diag(IList->getLocStart(),
680 diag::err_at_least_one_initializer_needed_to_size_array);
681 hadError = true;
682 } else {
683 llvm::APSInt ConstVal(32);
684 ConstVal = numElements;
685 DeclType = Context.getConstantArrayType(elementType, ConstVal,
686 ArrayType::Normal, 0);
687 }
688 }
689 } else {
690 assert(0 && "Aggregate that isn't a function or array?!");
691 }
692 } else {
693 // In C, all types are either scalars or aggregates, but
694 // additional handling is needed here for C++ (and possibly others?).
695 assert(0 && "Unsupported initializer type");
696 }
697
698 // If this init list is a base list, we set the type; an initializer doesn't
699 // fundamentally have a type, but this makes the ASTs a bit easier to read
700 if (topLevel)
701 IList->setType(DeclType);
702
703 if (topLevel && startIndex < IList->getNumInits()) {
704 // We have leftover initializers; warn
705 Diag(IList->getInit(startIndex)->getLocStart(),
706 diag::warn_excess_initializers,
707 IList->getInit(startIndex)->getSourceRange());
708 }
709 return hadError;
710}
711
712bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000713 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
714 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000715 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000716 return Diag(VAT->getSizeExpr()->getLocStart(),
717 diag::err_variable_object_no_init,
718 VAT->getSizeExpr()->getSourceRange());
719
Steve Naroff2fdc3742007-12-10 22:44:33 +0000720 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
721 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000722 // FIXME: Handle wide strings
723 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
724 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000725
726 if (DeclType->isArrayType())
727 return Diag(Init->getLocStart(),
728 diag::err_array_init_list_required,
729 Init->getSourceRange());
730
Steve Naroffd0091aa2008-01-10 22:15:12 +0000731 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000732 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000733#if 1
Steve Naroffa9960332008-01-25 00:51:06 +0000734 unsigned newIndex = 0;
735 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000736#else
737 InitListChecker CheckInitList(this, InitList, DeclType);
738 return CheckInitList.HadError();
739#endif
Steve Narofff0090632007-09-02 02:04:30 +0000740}
741
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000742Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000743Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000744 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 IdentifierInfo *II = D.getIdentifier();
746
Chris Lattnere80a59c2007-07-25 00:24:17 +0000747 // All of these full declarators require an identifier. If it doesn't have
748 // one, the ParsedFreeStandingDeclSpec action should be used.
749 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000750 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000751 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000752 D.getDeclSpec().getSourceRange(), D.getSourceRange());
753 return 0;
754 }
755
Chris Lattner31e05722007-08-26 06:24:45 +0000756 // The scope passed in may not be a decl scope. Zip up the scope tree until
757 // we find one that is.
758 while ((S->getFlags() & Scope::DeclScope) == 0)
759 S = S->getParent();
760
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000762 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000763 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000764 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000765
766 // In C++, the previous declaration we find might be a tag type
767 // (class or enum). In this case, the new declaration will hide the
768 // tag type.
769 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
770 PrevDecl = 0;
771
Chris Lattner41af0932007-11-14 06:34:38 +0000772 QualType R = GetTypeForDeclarator(D, S);
773 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
774
Reid Spencer5f016e22007-07-11 17:01:13 +0000775 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner41af0932007-11-14 06:34:38 +0000776 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000777 if (!NewTD) return 0;
778
779 // Handle attributes prior to checking for duplicates in MergeVarDecl
780 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
781 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000782 // Merge the decl with the existing one if appropriate. If the decl is
783 // in an outer scope, it isn't the same thing.
784 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000785 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
786 if (NewTD == 0) return 0;
787 }
788 New = NewTD;
789 if (S->getParent() == 0) {
790 // C99 6.7.7p2: If a typedef name specifies a variably modified type
791 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000792 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
793 // FIXME: Diagnostic needs to be fixed.
794 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000795 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000796 }
797 }
Chris Lattner41af0932007-11-14 06:34:38 +0000798 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000799 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000800 switch (D.getDeclSpec().getStorageClassSpec()) {
801 default: assert(0 && "Unknown storage class!");
802 case DeclSpec::SCS_auto:
803 case DeclSpec::SCS_register:
804 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
805 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000806 InvalidDecl = true;
807 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000808 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
809 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
810 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000811 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000812 }
813
Chris Lattnera98e58d2008-03-15 21:24:04 +0000814 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattner0ed844b2008-04-04 06:12:32 +0000815 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
816 D.getIdentifierLoc(),
Chris Lattnera98e58d2008-03-15 21:24:04 +0000817 II, R, SC, isInline,
818 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000819 // Handle attributes.
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000820 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
821 D.getAttributes());
Chris Lattner04421082008-04-08 04:40:51 +0000822
823 // Copy the parameter declarations from the declarator D to
824 // the function declaration NewFD, if they are available.
825 if (D.getNumTypeObjects() > 0 &&
826 D.getTypeObject(0).Fun.hasPrototype) {
827 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
828
829 // Create Decl objects for each parameter, adding them to the
830 // FunctionDecl.
831 llvm::SmallVector<ParmVarDecl*, 16> Params;
832
833 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
834 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000835 // single void argument.
Chris Lattner04421082008-04-08 04:40:51 +0000836 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
837 FTI.ArgInfo[0].Param &&
838 !((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
839 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
840 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000841 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
842
Chris Lattnerdef026a2008-04-10 02:26:16 +0000843 // In C++, the empty parameter-type-list must be spelled "void"; a
844 // typedef of void is not permitted.
845 if (getLangOptions().CPlusPlus &&
Chris Lattner8123a952008-04-10 02:22:51 +0000846 Param->getType() != Context.VoidTy) {
847 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
848 }
849
Chris Lattner04421082008-04-08 04:40:51 +0000850 } else {
851 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
852 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
853 }
854
855 NewFD->setParams(&Params[0], Params.size());
856 }
857
Steve Naroffffce4d52008-01-09 23:34:55 +0000858 // Merge the decl with the existing one if appropriate. Since C functions
859 // are in a flat namespace, make sure we consider decls in outer scopes.
Reid Spencer5f016e22007-07-11 17:01:13 +0000860 if (PrevDecl) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000861 bool Redeclaration = false;
862 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +0000863 if (NewFD == 0) return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +0000864 if (Redeclaration) {
865 // Note that the new declaration is a redeclaration of the
866 // older declaration. Then return the older declaration: the
867 // new one is only kept within the set of previous
868 // declarations for this function.
869 FunctionDecl *OldFD = (FunctionDecl *)PrevDecl;
870 OldFD->AddRedeclaration(NewFD);
871 return OldFD;
872 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000873 }
874 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000875
876 // In C++, check default arguments now that we have merged decls.
877 if (getLangOptions().CPlusPlus)
878 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000879 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000880 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000881 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
882 D.getIdentifier()->getName());
883 InvalidDecl = true;
884 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000885
886 VarDecl *NewVD;
887 VarDecl::StorageClass SC;
888 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000889 default: assert(0 && "Unknown storage class!");
890 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
891 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
892 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
893 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
894 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
895 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000896 }
897 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000898 // C99 6.9p2: The storage-class specifiers auto and register shall not
899 // appear in the declaration specifiers in an external declaration.
900 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
901 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
902 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000903 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000904 }
Steve Naroff248a7532008-04-15 22:42:06 +0000905 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
906 II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000907 } else {
Steve Naroff248a7532008-04-15 22:42:06 +0000908 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
909 II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000910 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000911 // Handle attributes prior to checking for duplicates in MergeVarDecl
912 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
913 D.getAttributes());
Nate Begemanc8e89a82008-03-14 18:07:10 +0000914
915 // Emit an error if an address space was applied to decl with local storage.
916 // This includes arrays of objects with address space qualifiers, but not
917 // automatic variables that point to other address spaces.
918 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000919 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
920 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
921 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000922 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000923 // Merge the decl with the existing one if appropriate. If the decl is
924 // in an outer scope, it isn't the same thing.
925 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 NewVD = MergeVarDecl(NewVD, PrevDecl);
927 if (NewVD == 0) return 0;
928 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000929 New = NewVD;
930 }
931
932 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000933 if (II)
934 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000935 // If any semantic error occurred, mark the decl as invalid.
936 if (D.getInvalidType() || InvalidDecl)
937 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000938
939 return New;
940}
941
Steve Naroffd0091aa2008-01-10 22:15:12 +0000942bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
943 SourceLocation loc;
944 // FIXME: Remove the isReference check and handle assignment to a reference.
945 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
946 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
947 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
948 return true;
949 }
950 return false;
951}
952
Steve Naroffbb204692007-09-12 14:07:44 +0000953void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000954 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000955 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000956 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000957
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000958 // If there is no declaration, there was an error parsing it. Just ignore
959 // the initializer.
960 if (RealDecl == 0) {
961 delete Init;
962 return;
963 }
Steve Naroffbb204692007-09-12 14:07:44 +0000964
Steve Naroff410e3e22007-09-12 20:13:48 +0000965 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
966 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000967 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
968 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000969 RealDecl->setInvalidDecl();
970 return;
971 }
Steve Naroffbb204692007-09-12 14:07:44 +0000972 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +0000973 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000974 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +0000975 if (VDecl->isBlockVarDecl()) {
976 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +0000977 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000978 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +0000979 VDecl->setInvalidDecl();
980 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000981 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +0000982 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000983 if (SC == VarDecl::Static) // C99 6.7.8p4.
984 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000985 }
Steve Naroff248a7532008-04-15 22:42:06 +0000986 } else if (VDecl->isFileVarDecl()) {
987 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000988 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +0000989 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +0000990 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +0000991 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000992
993 // C99 6.7.8p4. All file scoped initializers need to be constant.
994 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000995 }
996 // If the type changed, it means we had an incomplete type that was
997 // completed by the initializer. For example:
998 // int ary[] = { 1, 3, 5 };
999 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001000 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001001 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001002 Init->setType(DclT);
1003 }
Steve Naroffbb204692007-09-12 14:07:44 +00001004
1005 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001006 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001007 return;
1008}
1009
Reid Spencer5f016e22007-07-11 17:01:13 +00001010/// The declarators are chained together backwards, reverse the list.
1011Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1012 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001013 Decl *GroupDecl = static_cast<Decl*>(group);
1014 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001015 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001016
1017 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1018 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001019 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001020 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001021 else { // reverse the list.
1022 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001023 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001024 Group->setNextDeclarator(NewGroup);
1025 NewGroup = Group;
1026 Group = Next;
1027 }
1028 }
1029 // Perform semantic analysis that depends on having fully processed both
1030 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001031 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001032 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1033 if (!IDecl)
1034 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001035 QualType T = IDecl->getType();
1036
1037 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1038 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001039 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1040 IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +00001041 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001042 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1043 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001044 }
1045 }
1046 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1047 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001048 if (IDecl->isBlockVarDecl() &&
1049 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001050 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001051 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1052 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001053 IDecl->setInvalidDecl();
1054 }
1055 }
1056 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1057 // object that has file scope without an initializer, and without a
1058 // storage-class specifier or with the storage-class specifier "static",
1059 // constitutes a tentative definition. Note: A tentative definition with
1060 // external linkage is valid (C99 6.2.2p5).
Steve Naroff248a7532008-04-15 22:42:06 +00001061 if (IDecl && !IDecl->getInit() &&
1062 (IDecl->getStorageClass() == VarDecl::Static ||
1063 IDecl->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001064 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001065 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1066 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001067 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001068 // C99 6.9.2p3: If the declaration of an identifier for an object is
1069 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1070 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001071 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1072 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001073 IDecl->setInvalidDecl();
1074 }
1075 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001076 }
1077 return NewGroup;
1078}
Steve Naroffe1223f72007-08-28 03:03:08 +00001079
Chris Lattner04421082008-04-08 04:40:51 +00001080/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1081/// to introduce parameters into function prototype scope.
1082Sema::DeclTy *
1083Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1084 DeclSpec &DS = D.getDeclSpec();
1085
1086 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1087 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1088 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1089 Diag(DS.getStorageClassSpecLoc(),
1090 diag::err_invalid_storage_class_in_func_decl);
1091 DS.ClearStorageClassSpecs();
1092 }
1093 if (DS.isThreadSpecified()) {
1094 Diag(DS.getThreadSpecLoc(),
1095 diag::err_invalid_storage_class_in_func_decl);
1096 DS.ClearStorageClassSpecs();
1097 }
1098
1099
1100 // In this context, we *do not* check D.getInvalidType(). If the declarator
1101 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1102 // though it will not reflect the user specified type.
1103 QualType parmDeclType = GetTypeForDeclarator(D, S);
1104
1105 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1106
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1108 // Can this happen for params? We already checked that they don't conflict
1109 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001110 IdentifierInfo *II = D.getIdentifier();
1111 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1112 if (S->isDeclScope(PrevDecl)) {
1113 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1114 dyn_cast<NamedDecl>(PrevDecl)->getName());
1115
1116 // Recover by removing the name
1117 II = 0;
1118 D.SetIdentifier(0, D.getIdentifierLoc());
1119 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001120 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001121
1122 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1123 // Doing the promotion here has a win and a loss. The win is the type for
1124 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1125 // code generator). The loss is the orginal type isn't preserved. For example:
1126 //
1127 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1128 // int blockvardecl[5];
1129 // sizeof(parmvardecl); // size == 4
1130 // sizeof(blockvardecl); // size == 20
1131 // }
1132 //
1133 // For expressions, all implicit conversions are captured using the
1134 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1135 //
1136 // FIXME: If a source translation tool needs to see the original type, then
1137 // we need to consider storing both types (in ParmVarDecl)...
1138 //
Chris Lattnere6327742008-04-02 05:18:44 +00001139 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001140 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001141 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001142 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001143 parmDeclType = Context.getPointerType(parmDeclType);
1144
Chris Lattner04421082008-04-08 04:40:51 +00001145 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1146 D.getIdentifierLoc(), II,
1147 parmDeclType, VarDecl::None,
1148 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001149
Chris Lattner04421082008-04-08 04:40:51 +00001150 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001151 New->setInvalidDecl();
1152
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001153 if (II)
1154 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001155
Chris Lattner04421082008-04-08 04:40:51 +00001156 HandleDeclAttributes(New, D.getAttributes(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001157 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001158
Reid Spencer5f016e22007-07-11 17:01:13 +00001159}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001160
Chris Lattnerb652cea2007-10-09 17:14:05 +00001161Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 assert(CurFunctionDecl == 0 && "Function parsing confused");
1163 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1164 "Not a function declarator!");
1165 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001166
Reid Spencer5f016e22007-07-11 17:01:13 +00001167 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1168 // for a K&R function.
1169 if (!FTI.hasPrototype) {
1170 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001171 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001172 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1173 FTI.ArgInfo[i].Ident->getName());
1174 // Implicitly declare the argument as type 'int' for lack of a better
1175 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001176 DeclSpec DS;
1177 const char* PrevSpec; // unused
1178 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1179 PrevSpec);
1180 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1181 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1182 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001183 }
1184 }
Chris Lattner52804082008-02-17 19:31:09 +00001185
Reid Spencer5f016e22007-07-11 17:01:13 +00001186 // Since this is a function definition, act as though we have information
1187 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001188 if (FTI.NumArgs)
1189 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001191 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001192 }
1193
1194 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001195
1196 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001197 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001198 GlobalScope);
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001199 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001200 const FunctionDecl *Definition;
1201 if (FD->getBody(Definition)) {
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001202 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1203 D.getIdentifier()->getName());
Douglas Gregorf0097952008-04-21 02:02:58 +00001204 Diag(Definition->getLocation(), diag::err_previous_definition);
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001205 }
1206 }
Steve Narofffabbc342008-02-12 01:09:36 +00001207 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001208 FunctionDecl *FD = cast<FunctionDecl>(decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001209 CurFunctionDecl = FD;
Chris Lattnerb048c982008-04-06 04:47:34 +00001210 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001211
1212 // Check the validity of our function parameters
1213 CheckParmsForFunctionDef(FD);
1214
1215 // Introduce our parameters into the function scope
1216 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1217 ParmVarDecl *Param = FD->getParamDecl(p);
1218 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001219 if (Param->getIdentifier())
1220 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001221 }
Chris Lattner04421082008-04-08 04:40:51 +00001222
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 return FD;
1224}
1225
Steve Naroffd6d054d2007-11-11 23:20:51 +00001226Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1227 Decl *dcl = static_cast<Decl *>(D);
1228 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1229 FD->setBody((Stmt*)Body);
1230 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001231 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001232 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001233 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001234 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001235 }
Chris Lattnerb048c982008-04-06 04:47:34 +00001236 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001237 // Verify and clean out per-function state.
1238
1239 // Check goto/label use.
1240 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1241 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1242 // Verify that we have no forward references left. If so, there was a goto
1243 // or address of a label taken, but no definition of it. Label fwd
1244 // definitions are indicated with a null substmt.
1245 if (I->second->getSubStmt() == 0) {
1246 LabelStmt *L = I->second;
1247 // Emit error.
1248 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1249
1250 // At this point, we have gotos that use the bogus label. Stitch it into
1251 // the function body so that they aren't leaked and that the AST is well
1252 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001253 if (Body) {
1254 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1255 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1256 } else {
1257 // The whole function wasn't parsed correctly, just delete this.
1258 delete L;
1259 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001260 }
1261 }
1262 LabelMap.clear();
1263
Steve Naroffd6d054d2007-11-11 23:20:51 +00001264 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001265}
1266
Reid Spencer5f016e22007-07-11 17:01:13 +00001267/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1268/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001269ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1270 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001271 // Extension in C99. Legal in C90, but warn about it.
1272 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001274 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1276
1277 // FIXME: handle stuff like:
1278 // void foo() { extern float X(); }
1279 // void bar() { X(); } <-- implicit decl for X in another scope.
1280
1281 // Set a Declarator for the implicit definition: int foo();
1282 const char *Dummy;
1283 DeclSpec DS;
1284 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1285 Error = Error; // Silence warning.
1286 assert(!Error && "Error setting up implicit decl!");
1287 Declarator D(DS, Declarator::BlockContext);
1288 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1289 D.SetIdentifier(&II, Loc);
1290
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001291 // Insert this function into translation-unit scope.
1292
1293 DeclContext *PrevDC = CurContext;
1294 CurContext = Context.getTranslationUnitDecl();
1295
Steve Naroffe2ef8152008-04-04 14:32:09 +00001296 FunctionDecl *FD =
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001297 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001298 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001299
1300 CurContext = PrevDC;
1301
Steve Naroffe2ef8152008-04-04 14:32:09 +00001302 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001303}
1304
1305
Chris Lattner41af0932007-11-14 06:34:38 +00001306TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001307 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001308 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001309 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001310
1311 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001312 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1313 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001314 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001315 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001316 if (D.getInvalidType())
1317 NewTD->setInvalidDecl();
1318 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001319}
1320
Steve Naroff08d92e42007-09-15 18:49:24 +00001321/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001322/// former case, Name will be non-null. In the later case, Name will be null.
1323/// TagType indicates what kind of tag this is. TK indicates whether this is a
1324/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001325Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001326 SourceLocation KWLoc, IdentifierInfo *Name,
1327 SourceLocation NameLoc, AttributeList *Attr) {
1328 // If this is a use of an existing tag, it must have a name.
1329 assert((Name != 0 || TK == TK_Definition) &&
1330 "Nameless record must be a definition!");
1331
1332 Decl::Kind Kind;
1333 switch (TagType) {
1334 default: assert(0 && "Unknown tag type!");
1335 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1336 case DeclSpec::TST_union: Kind = Decl::Union; break;
Chris Lattner99dc9142008-04-13 18:59:07 +00001337 case DeclSpec::TST_class: Kind = Decl::Class; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1339 }
1340
1341 // If this is a named struct, check to see if there was a previous forward
1342 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001343 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1344 if (ScopedDecl *PrevDecl =
1345 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001346
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001347 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1348 "unexpected Decl type");
1349 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1350 // If this is a use of a previous tag, or if the tag is already declared in
1351 // the same scope (so that the definition/declaration completes or
1352 // rementions the tag), reuse the decl.
1353 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1354 // Make sure that this wasn't declared as an enum and now used as a struct
1355 // or something similar.
1356 if (PrevDecl->getKind() != Kind) {
1357 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1358 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1359 }
1360
1361 // If this is a use or a forward declaration, we're good.
1362 if (TK != TK_Definition)
1363 return PrevDecl;
Reid Spencer5f016e22007-07-11 17:01:13 +00001364
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001365 // Diagnose attempts to redefine a tag.
1366 if (PrevTagDecl->isDefinition()) {
1367 Diag(NameLoc, diag::err_redefinition, Name->getName());
1368 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1369 // If this is a redefinition, recover by making this struct be
1370 // anonymous, which will make any later references get the previous
1371 // definition.
1372 Name = 0;
1373 } else {
1374 // Okay, this is definition of a previously declared or referenced tag.
1375 // Move the location of the decl to be the definition site.
1376 PrevDecl->setLocation(NameLoc);
1377 return PrevDecl;
1378 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001379 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001380 // If we get here, this is a definition of a new struct type in a nested
1381 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1382 // type.
1383 } else {
1384 // The tag name clashes with a namespace name, issue an error and recover
1385 // by making this tag be anonymous.
1386 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1387 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1388 Name = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 }
1391
1392 // If there is an identifier, use the location of the identifier as the
1393 // location of the decl, otherwise use the location of the struct/union
1394 // keyword.
1395 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1396
1397 // Otherwise, if this is the first time we've seen this tag, create the decl.
1398 TagDecl *New;
1399 switch (Kind) {
1400 default: assert(0 && "Unknown tag kind!");
1401 case Decl::Enum:
1402 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1403 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001404 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001405 // If this is an undefined enum, warn.
1406 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1407 break;
1408 case Decl::Union:
1409 case Decl::Struct:
1410 case Decl::Class:
1411 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1412 // struct X { int A; } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001413 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001414 break;
1415 }
1416
1417 // If this has an identifier, add it to the scope stack.
1418 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001419 // The scope passed in may not be a decl scope. Zip up the scope tree until
1420 // we find one that is.
1421 while ((S->getFlags() & Scope::DeclScope) == 0)
1422 S = S->getParent();
1423
1424 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001425 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001427
Anders Carlssonad148062008-02-16 00:29:18 +00001428 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 return New;
1430}
1431
Steve Naroff08d92e42007-09-15 18:49:24 +00001432/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001433/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001434Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001435 SourceLocation DeclStart,
1436 Declarator &D, ExprTy *BitfieldWidth) {
1437 IdentifierInfo *II = D.getIdentifier();
1438 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001439 SourceLocation Loc = DeclStart;
1440 if (II) Loc = D.getIdentifierLoc();
1441
1442 // FIXME: Unnamed fields can be handled in various different ways, for
1443 // example, unnamed unions inject all members into the struct namespace!
1444
1445
1446 if (BitWidth) {
1447 // TODO: Validate.
1448 //printf("WARNING: BITFIELDS IGNORED!\n");
1449
1450 // 6.7.2.1p3
1451 // 6.7.2.1p4
1452
1453 } else {
1454 // Not a bitfield.
1455
1456 // validate II.
1457
1458 }
1459
1460 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001461 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1462 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001463
Reid Spencer5f016e22007-07-11 17:01:13 +00001464 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1465 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001466 if (T->isVariablyModifiedType()) {
1467 // FIXME: This diagnostic needs work
1468 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroffd7444aa2007-08-31 17:20:07 +00001469 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001470 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001471 // FIXME: Chain fielddecls together.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001472 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00001473
Anders Carlssonad148062008-02-16 00:29:18 +00001474 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1475 D.getAttributes());
1476
Steve Naroff5912a352007-08-28 20:14:24 +00001477 if (D.getInvalidType() || InvalidDecl)
1478 NewFD->setInvalidDecl();
1479 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001480}
1481
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001482/// TranslateIvarVisibility - Translate visibility from a token ID to an
1483/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001484static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001485TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001486 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001487 case tok::objc_private: return ObjCIvarDecl::Private;
1488 case tok::objc_public: return ObjCIvarDecl::Public;
1489 case tok::objc_protected: return ObjCIvarDecl::Protected;
1490 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001491 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001492 }
1493}
1494
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001495/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1496/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001497Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001498 SourceLocation DeclStart,
1499 Declarator &D, ExprTy *BitfieldWidth,
1500 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001501 IdentifierInfo *II = D.getIdentifier();
1502 Expr *BitWidth = (Expr*)BitfieldWidth;
1503 SourceLocation Loc = DeclStart;
1504 if (II) Loc = D.getIdentifierLoc();
1505
1506 // FIXME: Unnamed fields can be handled in various different ways, for
1507 // example, unnamed unions inject all members into the struct namespace!
1508
1509
1510 if (BitWidth) {
1511 // TODO: Validate.
1512 //printf("WARNING: BITFIELDS IGNORED!\n");
1513
1514 // 6.7.2.1p3
1515 // 6.7.2.1p4
1516
1517 } else {
1518 // Not a bitfield.
1519
1520 // validate II.
1521
1522 }
1523
1524 QualType T = GetTypeForDeclarator(D, S);
1525 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1526 bool InvalidDecl = false;
1527
1528 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1529 // than a variably modified type.
1530 if (T->isVariablyModifiedType()) {
1531 // FIXME: This diagnostic needs work
1532 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1533 InvalidDecl = true;
1534 }
1535
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001536 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001537
1538 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1539 D.getAttributes());
1540
1541 if (D.getInvalidType() || InvalidDecl)
1542 NewID->setInvalidDecl();
1543 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001544 if (Visibility != tok::objc_not_keyword)
1545 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001546 return NewID;
1547}
1548
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001549void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001550 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001551 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001552 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00001553 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1554 assert(EnclosingDecl && "missing record or interface decl");
1555 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1556
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001557 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 // Diagnose code like:
1559 // struct S { struct S {} X; };
1560 // We discover this when we complete the outer S. Reject and ignore the
1561 // outer S.
1562 Diag(Record->getLocation(), diag::err_nested_redefinition,
1563 Record->getKindName());
1564 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001565 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 return;
1567 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001568 // Verify that all the fields are okay.
1569 unsigned NumNamedMembers = 0;
1570 llvm::SmallVector<FieldDecl*, 32> RecFields;
1571 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001572
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001574
Steve Naroff74216642007-09-14 22:20:54 +00001575 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1576 assert(FD && "missing field decl");
1577
1578 // Remember all fields.
1579 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001580
1581 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001582 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00001583
Reid Spencer5f016e22007-07-11 17:01:13 +00001584 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001585 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001586 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001588 FD->setInvalidDecl();
1589 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001590 continue;
1591 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1593 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001594 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001595 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001596 FD->setInvalidDecl();
1597 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001598 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001599 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 if (i != NumFields-1 || // ... that the last member ...
1601 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001602 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001603 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001604 FD->setInvalidDecl();
1605 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 continue;
1607 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001608 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1610 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001611 FD->setInvalidDecl();
1612 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001613 continue;
1614 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001615 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001616 if (Record)
1617 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001619 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1620 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001621 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001622 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1623 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001624 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001625 Record->setHasFlexibleArrayMember(true);
1626 } else {
1627 // If this is a struct/class and this is not the last element, reject
1628 // it. Note that GCC supports variable sized arrays in the middle of
1629 // structures.
1630 if (i != NumFields-1) {
1631 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1632 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001633 FD->setInvalidDecl();
1634 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 continue;
1636 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001637 // We support flexible arrays at the end of structs in other structs
1638 // as an extension.
1639 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1640 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001641 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001642 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 }
1644 }
1645 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001646 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001647 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001648 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1649 FD->getName());
1650 FD->setInvalidDecl();
1651 EnclosingDecl->setInvalidDecl();
1652 continue;
1653 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001654 // Keep track of the number of named members.
1655 if (IdentifierInfo *II = FD->getIdentifier()) {
1656 // Detect duplicate member names.
1657 if (!FieldIDs.insert(II)) {
1658 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1659 // Find the previous decl.
1660 SourceLocation PrevLoc;
1661 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1662 assert(i != e && "Didn't find previous def!");
1663 if (RecFields[i]->getIdentifier() == II) {
1664 PrevLoc = RecFields[i]->getLocation();
1665 break;
1666 }
1667 }
1668 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001669 FD->setInvalidDecl();
1670 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001671 continue;
1672 }
1673 ++NumNamedMembers;
1674 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 }
1676
Reid Spencer5f016e22007-07-11 17:01:13 +00001677 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00001678 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001679 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00001680 Consumer.HandleTagDeclDefinition(Record);
1681 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00001682 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1683 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1684 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1685 else if (ObjCImplementationDecl *IMPDecl =
1686 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001687 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1688 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001689 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001690 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001691 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001692}
1693
Steve Naroff08d92e42007-09-15 18:49:24 +00001694Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001695 DeclTy *lastEnumConst,
1696 SourceLocation IdLoc, IdentifierInfo *Id,
1697 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00001698 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00001699 EnumConstantDecl *LastEnumConst =
1700 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1701 Expr *Val = static_cast<Expr*>(val);
1702
Chris Lattner31e05722007-08-26 06:24:45 +00001703 // The scope passed in may not be a decl scope. Zip up the scope tree until
1704 // we find one that is.
1705 while ((S->getFlags() & Scope::DeclScope) == 0)
1706 S = S->getParent();
1707
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 // Verify that there isn't already something declared with this name in this
1709 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00001710 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 if (S->isDeclScope(PrevDecl)) {
1712 if (isa<EnumConstantDecl>(PrevDecl))
1713 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1714 else
1715 Diag(IdLoc, diag::err_redefinition, Id->getName());
1716 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00001717 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 return 0;
1719 }
1720 }
1721
1722 llvm::APSInt EnumVal(32);
1723 QualType EltTy;
1724 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001725 // Make sure to promote the operand type to int.
1726 UsualUnaryConversions(Val);
1727
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1729 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001730 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001731 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1732 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00001733 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001734 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001735 } else {
1736 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001737 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001738 }
1739
1740 if (!Val) {
1741 if (LastEnumConst) {
1742 // Assign the last value + 1.
1743 EnumVal = LastEnumConst->getInitVal();
1744 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001745
1746 // Check for overflow on increment.
1747 if (EnumVal < LastEnumConst->getInitVal())
1748 Diag(IdLoc, diag::warn_enum_value_overflow);
1749
Chris Lattnerb7416f92007-08-27 17:37:24 +00001750 EltTy = LastEnumConst->getType();
1751 } else {
1752 // First value, set to zero.
1753 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001754 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001755 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001756 }
1757
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001758 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00001759 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
1760 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001761 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00001762
1763 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001764 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001765 return New;
1766}
1767
Steve Naroff08d92e42007-09-15 18:49:24 +00001768void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 DeclTy **Elements, unsigned NumElements) {
1770 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1771 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1772
Chris Lattnere37f0be2007-08-28 05:10:31 +00001773 // TODO: If the result value doesn't fit in an int, it must be a long or long
1774 // long value. ISO C does not support this, but GCC does as an extension,
1775 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00001776 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00001777
Chris Lattnerac609682007-08-28 06:15:15 +00001778 // Verify that all the values are okay, compute the size of the values, and
1779 // reverse the list.
1780 unsigned NumNegativeBits = 0;
1781 unsigned NumPositiveBits = 0;
1782
1783 // Keep track of whether all elements have type int.
1784 bool AllElementsInt = true;
1785
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 EnumConstantDecl *EltList = 0;
1787 for (unsigned i = 0; i != NumElements; ++i) {
1788 EnumConstantDecl *ECD =
1789 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1790 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001791
1792 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00001793 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00001794 assert(InitVal.getBitWidth() >= IntWidth &&
1795 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00001796 if (InitVal.getBitWidth() > IntWidth) {
1797 llvm::APSInt V(InitVal);
1798 V.trunc(IntWidth);
1799 V.extend(InitVal.getBitWidth());
1800 if (V != InitVal)
1801 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1802 InitVal.toString());
1803 }
Chris Lattnerac609682007-08-28 06:15:15 +00001804
1805 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00001806 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00001807 NumPositiveBits = std::max(NumPositiveBits,
1808 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00001809 else
Chris Lattner21dd8212008-01-14 21:47:29 +00001810 NumNegativeBits = std::max(NumNegativeBits,
1811 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001812
Chris Lattnerac609682007-08-28 06:15:15 +00001813 // Keep track of whether every enum element has type int (very commmon).
1814 if (AllElementsInt)
1815 AllElementsInt = ECD->getType() == Context.IntTy;
1816
Reid Spencer5f016e22007-07-11 17:01:13 +00001817 ECD->setNextDeclarator(EltList);
1818 EltList = ECD;
1819 }
1820
Chris Lattnerac609682007-08-28 06:15:15 +00001821 // Figure out the type that should be used for this enum.
1822 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1823 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001824 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001825
1826 if (NumNegativeBits) {
1827 // If there is a negative value, figure out the smallest integer type (of
1828 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001829 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001830 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001831 BestWidth = IntWidth;
1832 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00001833 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001834
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001835 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001836 BestType = Context.LongTy;
1837 else {
Chris Lattner98be4942008-03-05 18:54:05 +00001838 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001839
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001840 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001841 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1842 BestType = Context.LongLongTy;
1843 }
1844 }
1845 } else {
1846 // If there is no negative value, figure out which of uint, ulong, ulonglong
1847 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001848 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001849 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001850 BestWidth = IntWidth;
1851 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00001852 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00001853 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001854 } else {
1855 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001856 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001857 "How could an initializer get larger than ULL?");
1858 BestType = Context.UnsignedLongLongTy;
1859 }
1860 }
1861
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001862 // Loop over all of the enumerator constants, changing their types to match
1863 // the type of the enum if needed.
1864 for (unsigned i = 0; i != NumElements; ++i) {
1865 EnumConstantDecl *ECD =
1866 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1867 if (!ECD) continue; // Already issued a diagnostic.
1868
1869 // Standard C says the enumerators have int type, but we allow, as an
1870 // extension, the enumerators to be larger than int size. If each
1871 // enumerator value fits in an int, type it as an int, otherwise type it the
1872 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1873 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00001874 if (ECD->getType() == Context.IntTy) {
1875 // Make sure the init value is signed.
1876 llvm::APSInt IV = ECD->getInitVal();
1877 IV.setIsSigned(true);
1878 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001879 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00001880 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001881
1882 // Determine whether the value fits into an int.
1883 llvm::APSInt InitVal = ECD->getInitVal();
1884 bool FitsInInt;
1885 if (InitVal.isUnsigned() || !InitVal.isNegative())
1886 FitsInInt = InitVal.getActiveBits() < IntWidth;
1887 else
1888 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1889
1890 // If it fits into an integer type, force it. Otherwise force it to match
1891 // the enum decl type.
1892 QualType NewTy;
1893 unsigned NewWidth;
1894 bool NewSign;
1895 if (FitsInInt) {
1896 NewTy = Context.IntTy;
1897 NewWidth = IntWidth;
1898 NewSign = true;
1899 } else if (ECD->getType() == BestType) {
1900 // Already the right type!
1901 continue;
1902 } else {
1903 NewTy = BestType;
1904 NewWidth = BestWidth;
1905 NewSign = BestType->isSignedIntegerType();
1906 }
1907
1908 // Adjust the APSInt value.
1909 InitVal.extOrTrunc(NewWidth);
1910 InitVal.setIsSigned(NewSign);
1911 ECD->setInitVal(InitVal);
1912
1913 // Adjust the Expr initializer and type.
1914 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1915 ECD->setType(NewTy);
1916 }
Chris Lattnerac609682007-08-28 06:15:15 +00001917
Chris Lattnere00b18c2007-08-28 18:24:31 +00001918 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00001919 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00001920}
1921
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001922Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1923 ExprTy *expr) {
1924 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1925
Chris Lattner8e25d862008-03-16 00:16:02 +00001926 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001927}
1928
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001929Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00001930 SourceLocation LBrace,
1931 SourceLocation RBrace,
1932 const char *Lang,
1933 unsigned StrSize,
1934 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001935 LinkageSpecDecl::LanguageIDs Language;
1936 Decl *dcl = static_cast<Decl *>(D);
1937 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1938 Language = LinkageSpecDecl::lang_c;
1939 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1940 Language = LinkageSpecDecl::lang_cxx;
1941 else {
1942 Diag(Loc, diag::err_bad_language);
1943 return 0;
1944 }
1945
1946 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00001947 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001948}
1949
Chris Lattner74788ba2008-02-21 00:48:22 +00001950void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00001951
Chris Lattner74788ba2008-02-21 00:48:22 +00001952 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00001953 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00001954 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00001955 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001956 if (!newType.isNull()) // install the new vector type into the decl
1957 vDecl->setType(newType);
1958 }
1959 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1960 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001961 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001962 if (!newType.isNull()) // install the new vector type into the decl
1963 tDecl->setUnderlyingType(newType);
1964 }
Chris Lattner212839c2008-02-20 23:17:35 +00001965 break;
Nate Begeman213541a2008-04-18 23:10:10 +00001966 case AttributeList::AT_ext_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00001967 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Nate Begeman213541a2008-04-18 23:10:10 +00001968 HandleExtVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00001969 else
Chris Lattner74788ba2008-02-21 00:48:22 +00001970 Diag(Attr->getLoc(),
Nate Begeman213541a2008-04-18 23:10:10 +00001971 diag::err_typecheck_ext_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00001972 break;
1973 case AttributeList::AT_address_space:
Christopher Lambebb97e92008-02-04 02:31:56 +00001974 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1975 QualType newType = HandleAddressSpaceTypeAttribute(
1976 tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001977 Attr);
1978 tDecl->setUnderlyingType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001979 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1980 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001981 Attr);
1982 // install the new addr spaced type into the decl
1983 vDecl->setType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001984 }
Chris Lattner212839c2008-02-20 23:17:35 +00001985 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00001986 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00001987 HandleDeprecatedAttribute(New, Attr);
1988 break;
1989 case AttributeList::AT_visibility:
1990 HandleVisibilityAttribute(New, Attr);
1991 break;
1992 case AttributeList::AT_weak:
1993 HandleWeakAttribute(New, Attr);
1994 break;
1995 case AttributeList::AT_dllimport:
1996 HandleDLLImportAttribute(New, Attr);
1997 break;
1998 case AttributeList::AT_dllexport:
1999 HandleDLLExportAttribute(New, Attr);
2000 break;
2001 case AttributeList::AT_nothrow:
2002 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00002003 break;
Nate Begeman440b4562008-03-07 20:04:22 +00002004 case AttributeList::AT_stdcall:
2005 HandleStdCallAttribute(New, Attr);
2006 break;
2007 case AttributeList::AT_fastcall:
2008 HandleFastCallAttribute(New, Attr);
2009 break;
Chris Lattner212839c2008-02-20 23:17:35 +00002010 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00002011 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00002012 break;
2013 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00002014 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00002015 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00002016 case AttributeList::AT_annotate:
2017 HandleAnnotateAttribute(New, Attr);
2018 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00002019 case AttributeList::AT_noreturn:
2020 HandleNoReturnAttribute(New, Attr);
2021 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00002022 case AttributeList::AT_format:
2023 HandleFormatAttribute(New, Attr);
2024 break;
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002025 case AttributeList::AT_transparent_union:
2026 HandleTransparentUnionAttribute(New, Attr);
2027 break;
Chris Lattner212839c2008-02-20 23:17:35 +00002028 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00002029#if 0
2030 // TODO: when we have the full set of attributes, warn about unknown ones.
2031 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
2032 Attr->getName()->getName());
2033#endif
Chris Lattner212839c2008-02-20 23:17:35 +00002034 break;
2035 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002036}
2037
2038void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2039 AttributeList *declarator_postfix) {
2040 while (declspec_prefix) {
2041 HandleDeclAttribute(New, declspec_prefix);
2042 declspec_prefix = declspec_prefix->getNext();
2043 }
2044 while (declarator_postfix) {
2045 HandleDeclAttribute(New, declarator_postfix);
2046 declarator_postfix = declarator_postfix->getNext();
2047 }
2048}
2049
Nate Begeman213541a2008-04-18 23:10:10 +00002050void Sema::HandleExtVectorTypeAttribute(TypedefDecl *tDecl,
Steve Naroffbea0b342007-07-29 16:33:31 +00002051 AttributeList *rawAttr) {
2052 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00002053 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00002054 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002055 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00002056 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002057 return;
Steve Naroff73322922007-07-18 18:00:27 +00002058 }
2059 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2060 llvm::APSInt vecSize(32);
2061 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002062 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Nate Begeman213541a2008-04-18 23:10:10 +00002063 "ext_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002064 return;
Steve Naroff73322922007-07-18 18:00:27 +00002065 }
2066 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2067 // in conjunction with complex types (pointers, arrays, functions, etc.).
2068 Type *canonType = curType.getCanonicalType().getTypePtr();
2069 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002070 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00002071 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002072 return;
Steve Naroff73322922007-07-18 18:00:27 +00002073 }
2074 // unlike gcc's vector_size attribute, the size is specified as the
2075 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002076 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002077
2078 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002079 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00002080 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002081 return;
Steve Naroff73322922007-07-18 18:00:27 +00002082 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002083 // Instantiate/Install the vector type, the number of elements is > 0.
Nate Begeman213541a2008-04-18 23:10:10 +00002084 tDecl->setUnderlyingType(Context.getExtVectorType(curType, vectorSize));
Steve Naroffbea0b342007-07-29 16:33:31 +00002085 // Remember this typedef decl, we will need it later for diagnostics.
Nate Begeman213541a2008-04-18 23:10:10 +00002086 ExtVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002087}
2088
Reid Spencer5f016e22007-07-11 17:01:13 +00002089QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002090 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002091 // check the attribute arugments.
2092 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002093 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00002094 std::string("1"));
2095 return QualType();
2096 }
2097 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2098 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002099 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002100 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002101 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002102 return QualType();
2103 }
2104 // navigate to the base type - we need to provide for vector pointers,
2105 // vector arrays, and functions returning vectors.
2106 Type *canonType = curType.getCanonicalType().getTypePtr();
2107
Steve Naroff73322922007-07-18 18:00:27 +00002108 if (canonType->isPointerType() || canonType->isArrayType() ||
2109 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00002110 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00002111 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2112 do {
2113 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2114 canonType = PT->getPointeeType().getTypePtr();
2115 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2116 canonType = AT->getElementType().getTypePtr();
2117 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2118 canonType = FT->getResultType().getTypePtr();
2119 } while (canonType->isPointerType() || canonType->isArrayType() ||
2120 canonType->isFunctionType());
2121 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002122 }
2123 // the base type must be integer or float.
2124 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002125 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00002126 curType.getCanonicalType().getAsString());
2127 return QualType();
2128 }
Chris Lattner98be4942008-03-05 18:54:05 +00002129 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Reid Spencer5f016e22007-07-11 17:01:13 +00002130 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002131 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002132
2133 // the vector size needs to be an integral multiple of the type size.
2134 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00002135 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002136 sizeExpr->getSourceRange());
2137 return QualType();
2138 }
2139 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002140 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002141 sizeExpr->getSourceRange());
2142 return QualType();
2143 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00002144 // Instantiate the vector type, the number of elements is > 0, and not
2145 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00002146 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002147}
2148
Chris Lattner2070d802008-02-20 23:25:22 +00002149void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00002150 // check the attribute arguments.
2151 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002152 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00002153 std::string("0"));
2154 return;
2155 }
2156
2157 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2158 TD->addAttr(new PackedAttr);
2159 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2160 // If the alignment is less than or equal to 8 bits, the packed attribute
2161 // has no effect.
Chris Lattner98be4942008-03-05 18:54:05 +00002162 if (Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00002163 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00002164 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00002165 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00002166 else
Anders Carlsson425a6092008-02-16 00:39:40 +00002167 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00002168 } else
Chris Lattner2070d802008-02-20 23:25:22 +00002169 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2170 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00002171}
Nate Begemanc398f0b2008-02-21 19:30:49 +00002172
Ted Kremenekaecb3832008-02-27 20:43:06 +00002173void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2174 // check the attribute arguments.
2175 if (rawAttr->getNumArgs() != 0) {
2176 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2177 std::string("0"));
2178 return;
2179 }
2180
Ted Kremenek3465fb32008-03-03 16:52:27 +00002181 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2182
2183 if (!Fn) {
2184 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2185 "noreturn", "function");
2186 return;
2187 }
2188
Ted Kremenekaecb3832008-02-27 20:43:06 +00002189 d->addAttr(new NoReturnAttr());
2190}
2191
Chris Lattnerddee4232008-03-03 03:28:21 +00002192void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2193 // check the attribute arguments.
2194 if (rawAttr->getNumArgs() != 0) {
2195 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2196 std::string("0"));
2197 return;
2198 }
2199
2200 d->addAttr(new DeprecatedAttr());
2201}
2202
2203void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2204 // check the attribute arguments.
Chris Lattner7b937ae2008-03-04 18:08:48 +00002205 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002206 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2207 std::string("1"));
2208 return;
2209 }
2210
Chris Lattner7b937ae2008-03-04 18:08:48 +00002211 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2212 Arg = Arg->IgnoreParenCasts();
2213 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2214
2215 if (Str == 0 || Str->isWide()) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002216 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002217 "visibility", std::string("1"));
Chris Lattnerddee4232008-03-03 03:28:21 +00002218 return;
2219 }
2220
Chris Lattner7b937ae2008-03-04 18:08:48 +00002221 const char *TypeStr = Str->getStrData();
2222 unsigned TypeLen = Str->getByteLength();
Chris Lattnerddee4232008-03-03 03:28:21 +00002223 llvm::GlobalValue::VisibilityTypes type;
2224
Chris Lattner7b937ae2008-03-04 18:08:48 +00002225 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Chris Lattnerddee4232008-03-03 03:28:21 +00002226 type = llvm::GlobalValue::DefaultVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002227 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Chris Lattnerddee4232008-03-03 03:28:21 +00002228 type = llvm::GlobalValue::HiddenVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002229 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Chris Lattnerddee4232008-03-03 03:28:21 +00002230 type = llvm::GlobalValue::HiddenVisibility; // FIXME
Chris Lattner7b937ae2008-03-04 18:08:48 +00002231 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Chris Lattnerddee4232008-03-03 03:28:21 +00002232 type = llvm::GlobalValue::ProtectedVisibility;
2233 else {
2234 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002235 "visibility", TypeStr);
Chris Lattnerddee4232008-03-03 03:28:21 +00002236 return;
2237 }
2238
2239 d->addAttr(new VisibilityAttr(type));
2240}
2241
2242void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2243 // check the attribute arguments.
2244 if (rawAttr->getNumArgs() != 0) {
2245 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2246 std::string("0"));
2247 return;
2248 }
2249
2250 d->addAttr(new WeakAttr());
2251}
2252
2253void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2254 // check the attribute arguments.
2255 if (rawAttr->getNumArgs() != 0) {
2256 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2257 std::string("0"));
2258 return;
2259 }
2260
2261 d->addAttr(new DLLImportAttr());
2262}
2263
2264void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2265 // check the attribute arguments.
2266 if (rawAttr->getNumArgs() != 0) {
2267 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2268 std::string("0"));
2269 return;
2270 }
2271
2272 d->addAttr(new DLLExportAttr());
2273}
2274
Nate Begeman440b4562008-03-07 20:04:22 +00002275void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2276 // check the attribute arguments.
2277 if (rawAttr->getNumArgs() != 0) {
2278 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2279 std::string("0"));
2280 return;
2281 }
2282
2283 d->addAttr(new StdCallAttr());
2284}
2285
2286void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2287 // check the attribute arguments.
2288 if (rawAttr->getNumArgs() != 0) {
2289 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2290 std::string("0"));
2291 return;
2292 }
2293
2294 d->addAttr(new FastCallAttr());
2295}
2296
Chris Lattnerddee4232008-03-03 03:28:21 +00002297void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2298 // check the attribute arguments.
2299 if (rawAttr->getNumArgs() != 0) {
2300 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2301 std::string("0"));
2302 return;
2303 }
2304
2305 d->addAttr(new NoThrowAttr());
2306}
2307
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002308static const FunctionTypeProto *getFunctionProto(Decl *d) {
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002309 QualType Ty;
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002310
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002311 if (ValueDecl *decl = dyn_cast<ValueDecl>(d))
2312 Ty = decl->getType();
2313 else if (FieldDecl *decl = dyn_cast<FieldDecl>(d))
2314 Ty = decl->getType();
2315 else
2316 return 0;
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002317
2318 if (Ty->isFunctionPointerType()) {
2319 const PointerType *PtrTy = Ty->getAsPointerType();
2320 Ty = PtrTy->getPointeeType();
2321 }
2322
2323 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2324 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2325
2326 return 0;
2327}
2328
2329
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002330/// Handle __attribute__((format(type,idx,firstarg))) attributes
2331/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattnerddee4232008-03-03 03:28:21 +00002332void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2333
2334 if (!rawAttr->getParameterName()) {
2335 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2336 "format", std::string("1"));
2337 return;
2338 }
2339
2340 if (rawAttr->getNumArgs() != 2) {
2341 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2342 std::string("3"));
2343 return;
2344 }
2345
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002346 // GCC ignores the format attribute on K&R style function
2347 // prototypes, so we ignore it as well
2348 const FunctionTypeProto *proto = getFunctionProto(d);
2349
2350 if (!proto) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002351 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2352 "format", "function");
2353 return;
2354 }
2355
2356 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002357 // this is needed in order to be compatible with GCC
Chris Lattnerddee4232008-03-03 03:28:21 +00002358 // the index must start in 1 and the limit is numargs+1
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002359 unsigned NumArgs = proto->getNumArgs();
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002360 unsigned FirstIdx = 1;
Chris Lattnerddee4232008-03-03 03:28:21 +00002361
2362 const char *Format = rawAttr->getParameterName()->getName();
2363 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2364
2365 // Normalize the argument, __foo__ becomes foo.
2366 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2367 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2368 Format += 2;
2369 FormatLen -= 4;
2370 }
2371
2372 if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2373 || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2374 || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2375 || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2376 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2377 "format", rawAttr->getParameterName()->getName());
2378 return;
2379 }
2380
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002381 // checks for the 2nd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002382 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002383 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002384 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2385 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2386 "format", std::string("2"), IdxExpr->getSourceRange());
2387 return;
2388 }
2389
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002390 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002391 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2392 "format", std::string("2"), IdxExpr->getSourceRange());
2393 return;
2394 }
2395
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002396 // make sure the format string is really a string
2397 QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2398 if (!Ty->isPointerType() ||
2399 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2400 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2401 IdxExpr->getSourceRange());
2402 return;
2403 }
2404
2405
2406 // check the 3rd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002407 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002408 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002409 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2410 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2411 "format", std::string("3"), FirstArgExpr->getSourceRange());
2412 return;
2413 }
2414
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002415 // check if the function is variadic if the 3rd argument non-zero
2416 if (FirstArg != 0) {
2417 if (proto->isVariadic()) {
2418 ++NumArgs; // +1 for ...
2419 } else {
2420 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2421 return;
2422 }
2423 }
2424
2425 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2426 // the input is just the current time + the format string
Chris Lattnerddee4232008-03-03 03:28:21 +00002427 if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002428 if (FirstArg != 0) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002429 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2430 FirstArgExpr->getSourceRange());
2431 return;
2432 }
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002433 // if 0 it disables parameter checking (to use with e.g. va_list)
2434 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002435 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2436 "format", std::string("3"), FirstArgExpr->getSourceRange());
2437 return;
2438 }
2439
2440 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2441 Idx.getZExtValue(), FirstArg.getZExtValue()));
2442}
2443
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002444void Sema::HandleTransparentUnionAttribute(Decl *d, AttributeList *rawAttr) {
2445 // check the attribute arguments.
2446 if (rawAttr->getNumArgs() != 0) {
2447 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2448 std::string("0"));
2449 return;
2450 }
2451
2452 TypeDecl *decl = dyn_cast<TypeDecl>(d);
2453
2454 if (!decl || !Context.getTypeDeclType(decl)->isUnionType()) {
2455 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2456 "transparent_union", "union");
2457 return;
2458 }
2459
Chris Lattner22624942008-04-30 16:04:01 +00002460 //QualType QTy = Context.getTypeDeclType(decl);
2461 //const RecordType *Ty = QTy->getAsUnionType();
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002462
2463// FIXME
2464// Ty->addAttr(new TransparentUnionAttr());
2465}
2466
Nate Begemanc398f0b2008-02-21 19:30:49 +00002467void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2468 // check the attribute arguments.
2469 if (rawAttr->getNumArgs() != 1) {
2470 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2471 std::string("1"));
2472 return;
2473 }
2474 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2475 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002476
Nate Begemanc398f0b2008-02-21 19:30:49 +00002477 // Make sure that there is a string literal as the annotation's single
2478 // argument.
2479 if (!SE) {
2480 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2481 return;
2482 }
2483 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2484 SE->getByteLength())));
2485}
2486
Anders Carlsson78aaae92007-12-19 07:19:40 +00002487void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2488{
2489 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002490 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002491 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002492 std::string("1"));
2493 return;
2494 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002495
Anders Carlsson042c4e72008-02-16 19:51:27 +00002496 unsigned Align = 0;
2497
2498 if (rawAttr->getNumArgs() == 0) {
2499 // FIXME: This should be the target specific maximum alignment.
2500 // (For now we just use 128 bits which is the maximum on X86.
2501 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002502 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002503 } else {
2504 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2505 llvm::APSInt alignment(32);
2506 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002507 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002508 "aligned", alignmentExpr->getSourceRange());
2509 return;
2510 }
2511
2512 Align = alignment.getZExtValue() * 8;
2513 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002514
Anders Carlsson042c4e72008-02-16 19:51:27 +00002515 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002516}