blob: 5451ec27c05386ce37b91d1f0908d9b12a331d6e [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
38 if (IIDecl && (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000039 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000040 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000041}
42
Chris Lattnerb048c982008-04-06 04:47:34 +000043void Sema::PushDeclContext(DeclContext *CD) {
Chris Lattner0ed844b2008-04-04 06:12:32 +000044 assert(CD->getParent() == CurContext &&
Chris Lattnerb048c982008-04-06 04:47:34 +000045 "The next DeclContext should be directly contained in the current one.");
Chris Lattner0ed844b2008-04-04 06:12:32 +000046 CurContext = CD;
47}
48
Chris Lattnerb048c982008-04-06 04:47:34 +000049void Sema::PopDeclContext() {
50 assert(CurContext && "DeclContext imbalance!");
Chris Lattner0ed844b2008-04-04 06:12:32 +000051 CurContext = CurContext->getParent();
52}
53
Steve Naroffb216c882007-10-09 22:01:59 +000054void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000055 if (S->decl_empty()) return;
56 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
57
Reid Spencer5f016e22007-07-11 17:01:13 +000058 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
59 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000060 Decl *TmpD = static_cast<Decl*>(*I);
61 assert(TmpD && "This decl didn't get pushed??");
62 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
63 assert(D && "This decl isn't a ScopedDecl?");
64
Reid Spencer5f016e22007-07-11 17:01:13 +000065 IdentifierInfo *II = D->getIdentifier();
66 if (!II) continue;
67
68 // Unlink this decl from the identifier. Because the scope contains decls
69 // in an unordered collection, and because we have multiple identifier
70 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
71 if (II->getFETokenInfo<Decl>() == D) {
72 // Normal case, no multiple decls in different namespaces.
73 II->setFETokenInfo(D->getNext());
74 } else {
75 // Scan ahead. There are only three namespaces in C, so this loop can
76 // never execute more than 3 times.
Steve Naroffc752d042007-09-13 18:10:37 +000077 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +000078 while (SomeDecl->getNext() != D) {
79 SomeDecl = SomeDecl->getNext();
80 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
81 }
82 SomeDecl->setNext(D->getNext());
83 }
84
85 // This will have to be revisited for C++: there we want to nest stuff in
86 // namespace decls etc. Even for C, we might want a top-level translation
87 // unit decl or something.
88 if (!CurFunctionDecl)
89 continue;
90
91 // Chain this decl to the containing function, it now owns the memory for
92 // the decl.
93 D->setNext(CurFunctionDecl->getDeclChain());
94 CurFunctionDecl->setDeclChain(D);
95 }
96}
97
Steve Naroffe8043c32008-04-01 23:04:06 +000098/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
99/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000100ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000101 // The third "scope" argument is 0 since we aren't enabling lazy built-in
102 // creation from this context.
103 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000104
Steve Naroffb327ce02008-04-02 14:35:35 +0000105 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000106}
107
Steve Naroffe8043c32008-04-01 23:04:06 +0000108/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000109/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000110Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
111 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000112 if (II == 0) return 0;
113 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
114
115 // 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.
Steve Naroffc752d042007-09-13 18:10:37 +0000118 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 if (D->getIdentifierNamespace() == NS)
120 return D;
121
122 // If we didn't find a use of this identifier, and if the identifier
123 // corresponds to a compiler builtin, create the decl object for the builtin
124 // now, injecting it into translation unit scope, and return it.
125 if (NS == Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000126 if (enableLazyBuiltinCreation) {
127 // If this is a builtin on this (or all) targets, create the decl.
128 if (unsigned BuiltinID = II->getBuiltinID())
129 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
130 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000131 if (getLangOptions().ObjC1) {
132 // @interface and @compatibility_alias introduce typedef-like names.
133 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000134 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000135 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000136 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
137 if (IDI != ObjCInterfaceDecls.end())
138 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000139 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
140 if (I != ObjCAliasDecls.end())
141 return I->second->getClassInterface();
142 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 }
144 return 0;
145}
146
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000147void Sema::InitBuiltinVaListType()
148{
149 if (!Context.getBuiltinVaListType().isNull())
150 return;
151
152 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000153 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000154 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000155 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
156}
157
Reid Spencer5f016e22007-07-11 17:01:13 +0000158/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
159/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000160ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
161 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000162 Builtin::ID BID = (Builtin::ID)bid;
163
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000164 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson793680e2007-10-12 23:56:29 +0000165 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000166 BID == Builtin::BI__builtin_va_end)
167 InitBuiltinVaListType();
168
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000169 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000170 FunctionDecl *New = FunctionDecl::Create(Context, CurContext,
171 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000172 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000173
174 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000175 if (Scope *FnS = S->getFnParent())
176 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000177 while (S->getParent())
178 S = S->getParent();
179 S->AddDecl(New);
180
181 // Add this decl to the end of the identifier info.
Steve Naroffc752d042007-09-13 18:10:37 +0000182 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 // Scan until we find the last (outermost) decl in the id chain.
184 while (LastDecl->getNext())
185 LastDecl = LastDecl->getNext();
186 // Insert before (outside) it.
187 LastDecl->setNext(New);
188 } else {
189 II->setFETokenInfo(New);
190 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 return New;
192}
193
194/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
195/// and scope as a previous declaration 'Old'. Figure out how to resolve this
196/// situation, merging decls or emitting diagnostics as appropriate.
197///
Steve Naroffe8043c32008-04-01 23:04:06 +0000198TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000199 // Verify the old decl was also a typedef.
200 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
201 if (!Old) {
202 Diag(New->getLocation(), diag::err_redefinition_different_kind,
203 New->getName());
204 Diag(OldD->getLocation(), diag::err_previous_definition);
205 return New;
206 }
207
Steve Naroff8ee529b2007-10-31 18:42:27 +0000208 // Allow multiple definitions for ObjC built-in typedefs.
209 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000210 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000211 return Old;
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000212
213 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
214 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
215 // *either* declaration is in a system header. The code below implements
216 // this adhoc compatibility rule. FIXME: The following code will not
217 // work properly when compiling ".i" files (containing preprocessed output).
218 SourceManager &SrcMgr = Context.getSourceManager();
219 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
220 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
221 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
222 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
223 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
224
Steve Naroffc5e2f342008-03-26 21:27:00 +0000225 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
226 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
227 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroffd62701b2008-02-07 03:50:06 +0000228 getLangOptions().Microsoft)
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000229 return New;
Steve Naroffc5e2f342008-03-26 21:27:00 +0000230
Reid Spencer5f016e22007-07-11 17:01:13 +0000231 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
232 // TODO: This is totally simplistic. It should handle merging functions
233 // together etc, merging extern int X; int X; ...
234 Diag(New->getLocation(), diag::err_redefinition, New->getName());
235 Diag(Old->getLocation(), diag::err_previous_definition);
236 return New;
237}
238
Chris Lattnerddee4232008-03-03 03:28:21 +0000239/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
240static bool DeclHasAttr(const Decl *decl, const Attr *target) {
241 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
242 if (attr->getKind() == target->getKind())
243 return true;
244
245 return false;
246}
247
248/// MergeAttributes - append attributes from the Old decl to the New one.
249static void MergeAttributes(Decl *New, Decl *Old) {
250 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
251
252// FIXME: fix this code to cleanup the Old attrs correctly
253 while (attr) {
254 tmp = attr;
255 attr = attr->getNext();
256
257 if (!DeclHasAttr(New, tmp)) {
258 New->addAttr(tmp);
259 } else {
260 tmp->setNext(0);
261 delete(tmp);
262 }
263 }
264}
265
Chris Lattner04421082008-04-08 04:40:51 +0000266/// MergeFunctionDecl - We just parsed a function 'New' from
267/// declarator D which has the same name and scope as a previous
268/// declaration 'Old'. Figure out how to resolve this situation,
269/// merging decls or emitting diagnostics as appropriate.
Reid Spencer5f016e22007-07-11 17:01:13 +0000270///
Steve Naroffe8043c32008-04-01 23:04:06 +0000271FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 // Verify the old decl was also a function.
273 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
274 if (!Old) {
275 Diag(New->getLocation(), diag::err_redefinition_different_kind,
276 New->getName());
277 Diag(OldD->getLocation(), diag::err_previous_definition);
278 return New;
279 }
Chris Lattner04421082008-04-08 04:40:51 +0000280
Chris Lattnerddee4232008-03-03 03:28:21 +0000281 MergeAttributes(New, Old);
282
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000283 QualType OldQType = Context.getCanonicalType(Old->getType());
284 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000285
Chris Lattner04421082008-04-08 04:40:51 +0000286 // C++ [dcl.fct]p3:
287 // All declarations for a function shall agree exactly in both the
288 // return type and the parameter-type-list.
289 if (getLangOptions().CPlusPlus && OldQType == NewQType)
290 return MergeCXXFunctionDecl(New, Old);
291
292 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000293 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000294 if (!getLangOptions().CPlusPlus &&
295 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000296 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000297 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000298
Steve Naroff837618c2008-01-16 15:01:34 +0000299 // A function that has already been declared has been redeclared or defined
300 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000301 diag::kind PrevDiag;
302 if (Old->getBody())
303 PrevDiag = diag::err_previous_definition;
304 else if (Old->isImplicit())
305 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000306 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000307 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000308
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
310 // TODO: This is totally simplistic. It should handle merging functions
311 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000312 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
313 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000314 return New;
315}
316
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000317/// equivalentArrayTypes - Used to determine whether two array types are
318/// equivalent.
319/// We need to check this explicitly as an incomplete array definition is
320/// considered a VariableArrayType, so will not match a complete array
321/// definition that would be otherwise equivalent.
322static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
323 const ArrayType *NewAT = NewQType->getAsArrayType();
324 const ArrayType *OldAT = OldQType->getAsArrayType();
325
326 if (!NewAT || !OldAT)
327 return false;
328
329 // If either (or both) array types in incomplete we need to strip off the
330 // outer VariableArrayType. Once the outer VAT is removed the remaining
331 // types must be identical if the array types are to be considered
332 // equivalent.
333 // eg. int[][1] and int[1][1] become
334 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
335 // removing the outermost VAT gives
336 // CAT(1, int) and CAT(1, int)
337 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000338 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000339 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
340 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000341 NewQType = NewAT->getElementType().getCanonicalType();
342 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000343 }
344
345 return NewQType == OldQType;
346}
347
Reid Spencer5f016e22007-07-11 17:01:13 +0000348/// MergeVarDecl - We just parsed a variable 'New' which has the same name
349/// and scope as a previous declaration 'Old'. Figure out how to resolve this
350/// situation, merging decls or emitting diagnostics as appropriate.
351///
352/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
353/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
354///
Steve Naroffe8043c32008-04-01 23:04:06 +0000355VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 // Verify the old decl was also a variable.
357 VarDecl *Old = dyn_cast<VarDecl>(OldD);
358 if (!Old) {
359 Diag(New->getLocation(), diag::err_redefinition_different_kind,
360 New->getName());
361 Diag(OldD->getLocation(), diag::err_previous_definition);
362 return New;
363 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000364
365 MergeAttributes(New, Old);
366
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000368 QualType OldCType = Context.getCanonicalType(Old->getType());
369 QualType NewCType = Context.getCanonicalType(New->getType());
370 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 Diag(New->getLocation(), diag::err_redefinition, New->getName());
372 Diag(Old->getLocation(), diag::err_previous_definition);
373 return New;
374 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000375 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
376 if (New->getStorageClass() == VarDecl::Static &&
377 (Old->getStorageClass() == VarDecl::None ||
378 Old->getStorageClass() == VarDecl::Extern)) {
379 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
380 Diag(Old->getLocation(), diag::err_previous_definition);
381 return New;
382 }
383 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
384 if (New->getStorageClass() != VarDecl::Static &&
385 Old->getStorageClass() == VarDecl::Static) {
386 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
387 Diag(Old->getLocation(), diag::err_previous_definition);
388 return New;
389 }
390 // We've verified the types match, now handle "tentative" definitions.
391 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
392 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
393
394 if (OldFSDecl && NewFSDecl) {
395 // Handle C "tentative" external object definitions (C99 6.9.2).
396 bool OldIsTentative = false;
397 bool NewIsTentative = false;
398
399 if (!OldFSDecl->getInit() &&
400 (OldFSDecl->getStorageClass() == VarDecl::None ||
401 OldFSDecl->getStorageClass() == VarDecl::Static))
402 OldIsTentative = true;
403
404 // FIXME: this check doesn't work (since the initializer hasn't been
405 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
406 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
407 // thrown out the old decl.
408 if (!NewFSDecl->getInit() &&
409 (NewFSDecl->getStorageClass() == VarDecl::None ||
410 NewFSDecl->getStorageClass() == VarDecl::Static))
411 ; // change to NewIsTentative = true; once the code is moved.
412
413 if (NewIsTentative || OldIsTentative)
414 return New;
415 }
416 if (Old->getStorageClass() != VarDecl::Extern &&
417 New->getStorageClass() != VarDecl::Extern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000418 Diag(New->getLocation(), diag::err_redefinition, New->getName());
419 Diag(Old->getLocation(), diag::err_previous_definition);
420 }
421 return New;
422}
423
Chris Lattner04421082008-04-08 04:40:51 +0000424/// CheckParmsForFunctionDef - Check that the parameters of the given
425/// function are appropriate for the definition of a function. This
426/// takes care of any checks that cannot be performed on the
427/// declaration itself, e.g., that the types of each of the function
428/// parameters are complete.
429bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
430 bool HasInvalidParm = false;
431 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
432 ParmVarDecl *Param = FD->getParamDecl(p);
433
434 // C99 6.7.5.3p4: the parameters in a parameter type list in a
435 // function declarator that is part of a function definition of
436 // that function shall not have incomplete type.
437 if (Param->getType()->isIncompleteType() &&
438 !Param->isInvalidDecl()) {
439 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
440 Param->getType().getAsString());
441 Param->setInvalidDecl();
442 HasInvalidParm = true;
443 }
444 }
445
446 return HasInvalidParm;
447}
448
449/// CreateImplicitParameter - Creates an implicit function parameter
450/// in the scope S and with the given type. This routine is used, for
451/// example, to create the implicit "self" parameter in an Objective-C
452/// method.
453ParmVarDecl *
454Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
455 SourceLocation IdLoc, QualType Type) {
456 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
457 VarDecl::None, 0, 0);
458 if (Id) {
459 New->setNext(Id->getFETokenInfo<ScopedDecl>());
460 Id->setFETokenInfo(New);
461 S->AddDecl(New);
462 }
463
464 return New;
465}
466
Reid Spencer5f016e22007-07-11 17:01:13 +0000467/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
468/// no declarator (e.g. "struct foo;") is parsed.
469Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
470 // TODO: emit error on 'int;' or 'const enum foo;'.
471 // TODO: emit error on 'typedef int;'
472 // if (!DS.isMissingDeclaratorOk()) Diag(...);
473
Steve Naroff92199282007-11-17 21:37:36 +0000474 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000475}
476
Steve Naroffd0091aa2008-01-10 22:15:12 +0000477bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000478 // Get the type before calling CheckSingleAssignmentConstraints(), since
479 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000480 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000481
Chris Lattner5cf216b2008-01-04 18:04:52 +0000482 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
483 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
484 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000485}
486
Steve Naroff9e8925e2007-09-04 14:36:54 +0000487bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000488 QualType ElementType) {
Chris Lattner33b7b062007-12-11 23:15:04 +0000489 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffd0091aa2008-01-10 22:15:12 +0000490 if (CheckSingleInitializer(expr, ElementType))
Chris Lattner33b7b062007-12-11 23:15:04 +0000491 return true; // types weren't compatible.
492
Steve Naroff9e8925e2007-09-04 14:36:54 +0000493 if (savExpr != expr) // The type was promoted, update initializer list.
494 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000495 return false;
496}
497
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000498bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000499 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000500 // C99 6.7.8p14. We have an array of character type with unknown size
501 // being initialized to a string literal.
502 llvm::APSInt ConstVal(32);
503 ConstVal = strLiteral->getByteLength() + 1;
504 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000505 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000506 ArrayType::Normal, 0);
507 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
508 // C99 6.7.8p14. We have an array of character type with known size.
509 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
510 Diag(strLiteral->getSourceRange().getBegin(),
511 diag::warn_initializer_string_for_char_array_too_long,
512 strLiteral->getSourceRange());
513 } else {
514 assert(0 && "HandleStringLiteralInit(): Invalid array type");
515 }
516 // Set type from "char *" to "constant array of char".
517 strLiteral->setType(DeclT);
518 // For now, we always return false (meaning success).
519 return false;
520}
521
522StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000523 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000524 if (AT && AT->getElementType()->isCharType()) {
525 return dyn_cast<StringLiteral>(Init);
526 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000527 return 0;
528}
529
Steve Naroffa9960332008-01-25 00:51:06 +0000530// CheckInitializerListTypes - Checks the types of elements of an initializer
531// list. This function is recursive: it calls itself to initialize subelements
532// of aggregate types. Note that the topLevel parameter essentially refers to
533// whether this expression "owns" the initializer list passed in, or if this
534// initialization is taking elements out of a parent initializer. Each
535// call to this function adds zero or more to startIndex, reports any errors,
536// and returns true if it found any inconsistent types.
537bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
538 bool topLevel, unsigned& startIndex) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000539 bool hadError = false;
Steve Naroffa9960332008-01-25 00:51:06 +0000540
541 if (DeclType->isScalarType()) {
542 // The simplest case: initializing a single scalar
543 if (topLevel) {
544 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
545 IList->getSourceRange());
546 }
547 if (startIndex < IList->getNumInits()) {
548 Expr* expr = IList->getInit(startIndex);
549 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
550 // FIXME: Should an error be reported here instead?
551 unsigned newIndex = 0;
552 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
553 } else {
554 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
555 }
556 ++startIndex;
557 }
558 // FIXME: Should an error be reported for empty initializer list + scalar?
559 } else if (DeclType->isVectorType()) {
560 if (startIndex < IList->getNumInits()) {
561 const VectorType *VT = DeclType->getAsVectorType();
562 int maxElements = VT->getNumElements();
563 QualType elementType = VT->getElementType();
564
565 for (int i = 0; i < maxElements; ++i) {
566 // Don't attempt to go past the end of the init list
567 if (startIndex >= IList->getNumInits())
568 break;
569 Expr* expr = IList->getInit(startIndex);
570 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
571 unsigned newIndex = 0;
572 hadError |= CheckInitializerListTypes(SubInitList, elementType,
573 true, newIndex);
574 ++startIndex;
575 } else {
576 hadError |= CheckInitializerListTypes(IList, elementType,
577 false, startIndex);
578 }
579 }
580 }
581 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
582 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroff578edc62008-01-28 02:00:41 +0000583 if (startIndex < IList->getNumInits() && !topLevel &&
584 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
585 DeclType)) {
Steve Naroffa9960332008-01-25 00:51:06 +0000586 // We found a compatible struct; per the standard, this initializes the
587 // struct. (The C standard technically says that this only applies for
588 // initializers for declarations with automatic scope; however, this
589 // construct is unambiguous anyway because a struct cannot contain
590 // a type compatible with itself. We'll output an error when we check
591 // if the initializer is constant.)
592 // FIXME: Is a call to CheckSingleInitializer required here?
593 ++startIndex;
594 } else {
595 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffb43eaa52008-02-11 00:06:17 +0000596
Steve Naroff406db932008-02-11 21:52:37 +0000597 // If the record is invalid, some of it's members are invalid. To avoid
598 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffb43eaa52008-02-11 00:06:17 +0000599 if (structDecl->isInvalidDecl())
600 return true;
601
Steve Naroffa9960332008-01-25 00:51:06 +0000602 // If structDecl is a forward declaration, this loop won't do anything;
603 // That's okay, because an error should get printed out elsewhere. It
604 // might be worthwhile to skip over the rest of the initializer, though.
605 int numMembers = structDecl->getNumMembers() -
606 structDecl->hasFlexibleArrayMember();
607 for (int i = 0; i < numMembers; i++) {
608 // Don't attempt to go past the end of the init list
609 if (startIndex >= IList->getNumInits())
610 break;
611 FieldDecl * curField = structDecl->getMember(i);
612 if (!curField->getIdentifier()) {
613 // Don't initialize unnamed fields, e.g. "int : 20;"
614 continue;
615 }
616 QualType fieldType = curField->getType();
617 Expr* expr = IList->getInit(startIndex);
618 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
619 unsigned newStart = 0;
620 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
621 true, newStart);
622 ++startIndex;
623 } else {
624 hadError |= CheckInitializerListTypes(IList, fieldType,
625 false, startIndex);
626 }
627 if (DeclType->isUnionType())
628 break;
629 }
630 // FIXME: Implement flexible array initialization GCC extension (it's a
631 // really messy extension to implement, unfortunately...the necessary
632 // information isn't actually even here!)
633 }
634 } else if (DeclType->isArrayType()) {
635 // Check for the special-case of initializing an array with a string.
636 if (startIndex < IList->getNumInits()) {
637 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
638 DeclType)) {
639 CheckStringLiteralInit(lit, DeclType);
640 ++startIndex;
641 if (topLevel && startIndex < IList->getNumInits()) {
642 // We have leftover initializers; warn
643 Diag(IList->getInit(startIndex)->getLocStart(),
644 diag::err_excess_initializers_in_char_array_initializer,
645 IList->getInit(startIndex)->getSourceRange());
646 }
647 return false;
648 }
649 }
650 int maxElements;
Eli Friedmanc5773c42008-02-15 18:16:39 +0000651 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000652 // FIXME: use a proper constant
653 maxElements = 0x7FFFFFFF;
Chris Lattner212839c2008-02-20 23:17:35 +0000654 } else if (const VariableArrayType *VAT =
655 DeclType->getAsVariableArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000656 // Check for VLAs; in standard C it would be possible to check this
657 // earlier, but I don't know where clang accepts VLAs (gcc accepts
658 // them in all sorts of strange places).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000659 Diag(VAT->getSizeExpr()->getLocStart(),
660 diag::err_variable_object_no_init,
661 VAT->getSizeExpr()->getSourceRange());
662 hadError = true;
663 maxElements = 0x7FFFFFFF;
Steve Naroffa9960332008-01-25 00:51:06 +0000664 } else {
665 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
666 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
667 }
668 QualType elementType = DeclType->getAsArrayType()->getElementType();
669 int numElements = 0;
670 for (int i = 0; i < maxElements; ++i, ++numElements) {
671 // Don't attempt to go past the end of the init list
672 if (startIndex >= IList->getNumInits())
673 break;
674 Expr* expr = IList->getInit(startIndex);
675 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
676 unsigned newIndex = 0;
677 hadError |= CheckInitializerListTypes(SubInitList, elementType,
678 true, newIndex);
679 ++startIndex;
680 } else {
681 hadError |= CheckInitializerListTypes(IList, elementType,
682 false, startIndex);
683 }
684 }
Eli Friedman9db13972008-02-15 12:53:51 +0000685 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000686 // If this is an incomplete array type, the actual type needs to
687 // be calculated here
688 if (numElements == 0) {
689 // Sizing an array implicitly to zero is not allowed
690 // (It could in theory be allowed, but it doesn't really matter.)
691 Diag(IList->getLocStart(),
692 diag::err_at_least_one_initializer_needed_to_size_array);
693 hadError = true;
694 } else {
695 llvm::APSInt ConstVal(32);
696 ConstVal = numElements;
697 DeclType = Context.getConstantArrayType(elementType, ConstVal,
698 ArrayType::Normal, 0);
699 }
700 }
701 } else {
702 assert(0 && "Aggregate that isn't a function or array?!");
703 }
704 } else {
705 // In C, all types are either scalars or aggregates, but
706 // additional handling is needed here for C++ (and possibly others?).
707 assert(0 && "Unsupported initializer type");
708 }
709
710 // If this init list is a base list, we set the type; an initializer doesn't
711 // fundamentally have a type, but this makes the ASTs a bit easier to read
712 if (topLevel)
713 IList->setType(DeclType);
714
715 if (topLevel && startIndex < IList->getNumInits()) {
716 // We have leftover initializers; warn
717 Diag(IList->getInit(startIndex)->getLocStart(),
718 diag::warn_excess_initializers,
719 IList->getInit(startIndex)->getSourceRange());
720 }
721 return hadError;
722}
723
724bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000725 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
726 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000727 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000728 return Diag(VAT->getSizeExpr()->getLocStart(),
729 diag::err_variable_object_no_init,
730 VAT->getSizeExpr()->getSourceRange());
731
Steve Naroff2fdc3742007-12-10 22:44:33 +0000732 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
733 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000734 // FIXME: Handle wide strings
735 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
736 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000737
738 if (DeclType->isArrayType())
739 return Diag(Init->getLocStart(),
740 diag::err_array_init_list_required,
741 Init->getSourceRange());
742
Steve Naroffd0091aa2008-01-10 22:15:12 +0000743 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000744 }
Steve Naroffa9960332008-01-25 00:51:06 +0000745 unsigned newIndex = 0;
746 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Narofff0090632007-09-02 02:04:30 +0000747}
748
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000749Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000750Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000751 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000752 IdentifierInfo *II = D.getIdentifier();
753
Chris Lattnere80a59c2007-07-25 00:24:17 +0000754 // All of these full declarators require an identifier. If it doesn't have
755 // one, the ParsedFreeStandingDeclSpec action should be used.
756 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000757 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000758 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000759 D.getDeclSpec().getSourceRange(), D.getSourceRange());
760 return 0;
761 }
762
Chris Lattner31e05722007-08-26 06:24:45 +0000763 // The scope passed in may not be a decl scope. Zip up the scope tree until
764 // we find one that is.
765 while ((S->getFlags() & Scope::DeclScope) == 0)
766 S = S->getParent();
767
Reid Spencer5f016e22007-07-11 17:01:13 +0000768 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000769 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000770 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000771 bool InvalidDecl = false;
772
Chris Lattner41af0932007-11-14 06:34:38 +0000773 QualType R = GetTypeForDeclarator(D, S);
774 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
775
Reid Spencer5f016e22007-07-11 17:01:13 +0000776 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner41af0932007-11-14 06:34:38 +0000777 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000778 if (!NewTD) return 0;
779
780 // Handle attributes prior to checking for duplicates in MergeVarDecl
781 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
782 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000783 // Merge the decl with the existing one if appropriate. If the decl is
784 // in an outer scope, it isn't the same thing.
785 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
787 if (NewTD == 0) return 0;
788 }
789 New = NewTD;
790 if (S->getParent() == 0) {
791 // C99 6.7.7p2: If a typedef name specifies a variably modified type
792 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000793 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
794 // FIXME: Diagnostic needs to be fixed.
795 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000796 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000797 }
798 }
Chris Lattner41af0932007-11-14 06:34:38 +0000799 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000800 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000801 switch (D.getDeclSpec().getStorageClassSpec()) {
802 default: assert(0 && "Unknown storage class!");
803 case DeclSpec::SCS_auto:
804 case DeclSpec::SCS_register:
805 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
806 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000807 InvalidDecl = true;
808 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000809 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
810 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
811 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000812 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000813 }
814
Chris Lattnera98e58d2008-03-15 21:24:04 +0000815 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattner0ed844b2008-04-04 06:12:32 +0000816 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
817 D.getIdentifierLoc(),
Chris Lattnera98e58d2008-03-15 21:24:04 +0000818 II, R, SC, isInline,
819 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000820 // Handle attributes.
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000821 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
822 D.getAttributes());
Chris Lattner04421082008-04-08 04:40:51 +0000823
824 // Copy the parameter declarations from the declarator D to
825 // the function declaration NewFD, if they are available.
826 if (D.getNumTypeObjects() > 0 &&
827 D.getTypeObject(0).Fun.hasPrototype) {
828 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
829
830 // Create Decl objects for each parameter, adding them to the
831 // FunctionDecl.
832 llvm::SmallVector<ParmVarDecl*, 16> Params;
833
834 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
835 // function that takes no arguments, not a function that takes a
836 // single void argument. FIXME: Is this really the right place
837 // to check for this? C++ says that the parameter list (void) is
838 // the same as an empty parameter list, whereas the parameter
839 // list (T) (with T typedef'd to void) is not. For C++, this
840 // should be handled in the parser. Check C89 and C99 standards
841 // to see what the correct behavior is.
842 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
843 FTI.ArgInfo[0].Param &&
844 !((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
845 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
846 // empty arg list, don't push any params.
847 } else {
848 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
849 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
850 }
851
852 NewFD->setParams(&Params[0], Params.size());
853 }
854
Steve Naroffffce4d52008-01-09 23:34:55 +0000855 // Merge the decl with the existing one if appropriate. Since C functions
856 // are in a flat namespace, make sure we consider decls in outer scopes.
Reid Spencer5f016e22007-07-11 17:01:13 +0000857 if (PrevDecl) {
858 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
859 if (NewFD == 0) return 0;
860 }
861 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000862
863 // In C++, check default arguments now that we have merged decls.
864 if (getLangOptions().CPlusPlus)
865 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000866 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000867 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000868 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
869 D.getIdentifier()->getName());
870 InvalidDecl = true;
871 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000872
873 VarDecl *NewVD;
874 VarDecl::StorageClass SC;
875 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000876 default: assert(0 && "Unknown storage class!");
877 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
878 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
879 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
880 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
881 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
882 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000883 }
884 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000885 // C99 6.9p2: The storage-class specifiers auto and register shall not
886 // appear in the declaration specifiers in an external declaration.
887 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
888 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
889 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000890 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000891 }
Chris Lattner0ed844b2008-04-04 06:12:32 +0000892 NewVD = FileVarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
893 II, R, SC,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000894 LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000895 } else {
Chris Lattner0ed844b2008-04-04 06:12:32 +0000896 NewVD = BlockVarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
897 II, R, SC,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000898 LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000899 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000900 // Handle attributes prior to checking for duplicates in MergeVarDecl
901 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
902 D.getAttributes());
Nate Begemanc8e89a82008-03-14 18:07:10 +0000903
904 // Emit an error if an address space was applied to decl with local storage.
905 // This includes arrays of objects with address space qualifiers, but not
906 // automatic variables that point to other address spaces.
907 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000908 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
909 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
910 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000911 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000912 // Merge the decl with the existing one if appropriate. If the decl is
913 // in an outer scope, it isn't the same thing.
914 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000915 NewVD = MergeVarDecl(NewVD, PrevDecl);
916 if (NewVD == 0) return 0;
917 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000918 New = NewVD;
919 }
920
921 // If this has an identifier, add it to the scope stack.
922 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000923 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000924 II->setFETokenInfo(New);
925 S->AddDecl(New);
926 }
Steve Naroff5912a352007-08-28 20:14:24 +0000927 // If any semantic error occurred, mark the decl as invalid.
928 if (D.getInvalidType() || InvalidDecl)
929 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000930
931 return New;
932}
933
Steve Naroffd0091aa2008-01-10 22:15:12 +0000934bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
935 SourceLocation loc;
936 // FIXME: Remove the isReference check and handle assignment to a reference.
937 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
938 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
939 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
940 return true;
941 }
942 return false;
943}
944
Steve Naroffbb204692007-09-12 14:07:44 +0000945void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000946 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000947 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000948 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000949
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000950 // If there is no declaration, there was an error parsing it. Just ignore
951 // the initializer.
952 if (RealDecl == 0) {
953 delete Init;
954 return;
955 }
Steve Naroffbb204692007-09-12 14:07:44 +0000956
Steve Naroff410e3e22007-09-12 20:13:48 +0000957 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
958 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000959 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
960 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000961 RealDecl->setInvalidDecl();
962 return;
963 }
Steve Naroffbb204692007-09-12 14:07:44 +0000964 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +0000965 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000966 QualType DclT = VDecl->getType(), SavT = DclT;
967 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000968 VarDecl::StorageClass SC = BVD->getStorageClass();
969 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000970 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000971 BVD->setInvalidDecl();
972 } else if (!BVD->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000973 if (CheckInitializerTypes(Init, DclT))
974 BVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000975 if (SC == VarDecl::Static) // C99 6.7.8p4.
976 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000977 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000978 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000979 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000980 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000981 if (!FVD->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +0000982 if (CheckInitializerTypes(Init, DclT))
983 FVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000984
985 // C99 6.7.8p4. All file scoped initializers need to be constant.
986 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000987 }
988 // If the type changed, it means we had an incomplete type that was
989 // completed by the initializer. For example:
990 // int ary[] = { 1, 3, 5 };
991 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +0000992 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000993 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +0000994 Init->setType(DclT);
995 }
Steve Naroffbb204692007-09-12 14:07:44 +0000996
997 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000998 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000999 return;
1000}
1001
Reid Spencer5f016e22007-07-11 17:01:13 +00001002/// The declarators are chained together backwards, reverse the list.
1003Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1004 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001005 Decl *GroupDecl = static_cast<Decl*>(group);
1006 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001007 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001008
1009 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1010 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001011 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001012 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001013 else { // reverse the list.
1014 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001015 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001016 Group->setNextDeclarator(NewGroup);
1017 NewGroup = Group;
1018 Group = Next;
1019 }
1020 }
1021 // Perform semantic analysis that depends on having fully processed both
1022 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001023 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001024 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1025 if (!IDecl)
1026 continue;
1027 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
1028 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
1029 QualType T = IDecl->getType();
1030
1031 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1032 // static storage duration, it shall not have a variable length array.
1033 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +00001034 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001035 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1036 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001037 }
1038 }
1039 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1040 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
1041 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001042 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001043 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1044 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001045 IDecl->setInvalidDecl();
1046 }
1047 }
1048 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1049 // object that has file scope without an initializer, and without a
1050 // storage-class specifier or with the storage-class specifier "static",
1051 // constitutes a tentative definition. Note: A tentative definition with
1052 // external linkage is valid (C99 6.2.2p5).
Steve Naroffd3cd1e52008-01-18 00:39:39 +00001053 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
1054 FVD->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001055 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001056 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1057 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001058 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001059 // C99 6.9.2p3: If the declaration of an identifier for an object is
1060 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1061 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001062 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1063 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001064 IDecl->setInvalidDecl();
1065 }
1066 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001067 }
1068 return NewGroup;
1069}
Steve Naroffe1223f72007-08-28 03:03:08 +00001070
Chris Lattner04421082008-04-08 04:40:51 +00001071/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1072/// to introduce parameters into function prototype scope.
1073Sema::DeclTy *
1074Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1075 DeclSpec &DS = D.getDeclSpec();
1076
1077 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1078 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1079 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1080 Diag(DS.getStorageClassSpecLoc(),
1081 diag::err_invalid_storage_class_in_func_decl);
1082 DS.ClearStorageClassSpecs();
1083 }
1084 if (DS.isThreadSpecified()) {
1085 Diag(DS.getThreadSpecLoc(),
1086 diag::err_invalid_storage_class_in_func_decl);
1087 DS.ClearStorageClassSpecs();
1088 }
1089
1090
1091 // In this context, we *do not* check D.getInvalidType(). If the declarator
1092 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1093 // though it will not reflect the user specified type.
1094 QualType parmDeclType = GetTypeForDeclarator(D, S);
1095
1096 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1097
Reid Spencer5f016e22007-07-11 17:01:13 +00001098 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1099 // Can this happen for params? We already checked that they don't conflict
1100 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001101 IdentifierInfo *II = D.getIdentifier();
1102 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1103 if (S->isDeclScope(PrevDecl)) {
1104 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1105 dyn_cast<NamedDecl>(PrevDecl)->getName());
1106
1107 // Recover by removing the name
1108 II = 0;
1109 D.SetIdentifier(0, D.getIdentifierLoc());
1110 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001111 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001112
1113 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1114 // Doing the promotion here has a win and a loss. The win is the type for
1115 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1116 // code generator). The loss is the orginal type isn't preserved. For example:
1117 //
1118 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1119 // int blockvardecl[5];
1120 // sizeof(parmvardecl); // size == 4
1121 // sizeof(blockvardecl); // size == 20
1122 // }
1123 //
1124 // For expressions, all implicit conversions are captured using the
1125 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1126 //
1127 // FIXME: If a source translation tool needs to see the original type, then
1128 // we need to consider storing both types (in ParmVarDecl)...
1129 //
Chris Lattnere6327742008-04-02 05:18:44 +00001130 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001131 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001132 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001133 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001134 parmDeclType = Context.getPointerType(parmDeclType);
1135
Chris Lattner04421082008-04-08 04:40:51 +00001136 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1137 D.getIdentifierLoc(), II,
1138 parmDeclType, VarDecl::None,
1139 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001140
Chris Lattner04421082008-04-08 04:40:51 +00001141 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001142 New->setInvalidDecl();
1143
Reid Spencer5f016e22007-07-11 17:01:13 +00001144 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +00001145 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001146 II->setFETokenInfo(New);
Chris Lattner04421082008-04-08 04:40:51 +00001147 S->AddDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00001148 }
Nate Begemanb7894b52008-02-17 21:20:31 +00001149
Chris Lattner04421082008-04-08 04:40:51 +00001150 HandleDeclAttributes(New, D.getAttributes(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001151 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001152
Reid Spencer5f016e22007-07-11 17:01:13 +00001153}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001154
Chris Lattnerb652cea2007-10-09 17:14:05 +00001155Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001156 assert(CurFunctionDecl == 0 && "Function parsing confused");
1157 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1158 "Not a function declarator!");
1159 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001160
Reid Spencer5f016e22007-07-11 17:01:13 +00001161 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1162 // for a K&R function.
1163 if (!FTI.hasPrototype) {
1164 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001165 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001166 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1167 FTI.ArgInfo[i].Ident->getName());
1168 // Implicitly declare the argument as type 'int' for lack of a better
1169 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001170 DeclSpec DS;
1171 const char* PrevSpec; // unused
1172 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1173 PrevSpec);
1174 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1175 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1176 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001177 }
1178 }
Chris Lattner52804082008-02-17 19:31:09 +00001179
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 // Since this is a function definition, act as though we have information
1181 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001182 if (FTI.NumArgs)
1183 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001184 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001185 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001186 }
1187
1188 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001189
1190 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001191 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001192 GlobalScope);
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001193 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1194 if (FD->getBody()) {
1195 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1196 D.getIdentifier()->getName());
1197 Diag(FD->getLocation(), diag::err_previous_definition);
1198 }
1199 }
Steve Narofffabbc342008-02-12 01:09:36 +00001200 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001201 FunctionDecl *FD = cast<FunctionDecl>(decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 CurFunctionDecl = FD;
Chris Lattnerb048c982008-04-06 04:47:34 +00001203 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001204
1205 // Check the validity of our function parameters
1206 CheckParmsForFunctionDef(FD);
1207
1208 // Introduce our parameters into the function scope
1209 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1210 ParmVarDecl *Param = FD->getParamDecl(p);
1211 // If this has an identifier, add it to the scope stack.
1212 if (IdentifierInfo *II = Param->getIdentifier()) {
1213 Param->setNext(II->getFETokenInfo<ScopedDecl>());
1214 II->setFETokenInfo(Param);
1215 FnBodyScope->AddDecl(Param);
Steve Naroff66499922007-11-12 03:44:46 +00001216 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001217 }
Chris Lattner04421082008-04-08 04:40:51 +00001218
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 return FD;
1220}
1221
Steve Naroffd6d054d2007-11-11 23:20:51 +00001222Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1223 Decl *dcl = static_cast<Decl *>(D);
1224 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1225 FD->setBody((Stmt*)Body);
1226 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001227 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001228 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001229 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001230 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001231 }
Chris Lattnerb048c982008-04-06 04:47:34 +00001232 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001233 // Verify and clean out per-function state.
1234
1235 // Check goto/label use.
1236 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1237 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1238 // Verify that we have no forward references left. If so, there was a goto
1239 // or address of a label taken, but no definition of it. Label fwd
1240 // definitions are indicated with a null substmt.
1241 if (I->second->getSubStmt() == 0) {
1242 LabelStmt *L = I->second;
1243 // Emit error.
1244 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1245
1246 // At this point, we have gotos that use the bogus label. Stitch it into
1247 // the function body so that they aren't leaked and that the AST is well
1248 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001249 if (Body) {
1250 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1251 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1252 } else {
1253 // The whole function wasn't parsed correctly, just delete this.
1254 delete L;
1255 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001256 }
1257 }
1258 LabelMap.clear();
1259
Steve Naroffd6d054d2007-11-11 23:20:51 +00001260 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001261}
1262
Reid Spencer5f016e22007-07-11 17:01:13 +00001263/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1264/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001265ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1266 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 if (getLangOptions().C99) // Extension in C99.
1268 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1269 else // Legal in C90, but warn about it.
1270 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1271
1272 // FIXME: handle stuff like:
1273 // void foo() { extern float X(); }
1274 // void bar() { X(); } <-- implicit decl for X in another scope.
1275
1276 // Set a Declarator for the implicit definition: int foo();
1277 const char *Dummy;
1278 DeclSpec DS;
1279 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1280 Error = Error; // Silence warning.
1281 assert(!Error && "Error setting up implicit decl!");
1282 Declarator D(DS, Declarator::BlockContext);
1283 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1284 D.SetIdentifier(&II, Loc);
1285
1286 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +00001287 if (Scope *FnS = S->getFnParent())
1288 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +00001289 while (S->getParent())
1290 S = S->getParent();
1291
Steve Naroffe2ef8152008-04-04 14:32:09 +00001292 FunctionDecl *FD =
1293 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
1294 FD->setImplicit();
1295 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001296}
1297
1298
Chris Lattner41af0932007-11-14 06:34:38 +00001299TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001300 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001302 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001303
1304 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001305 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1306 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001307 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001308 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001309 if (D.getInvalidType())
1310 NewTD->setInvalidDecl();
1311 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001312}
1313
Steve Naroff08d92e42007-09-15 18:49:24 +00001314/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001315/// former case, Name will be non-null. In the later case, Name will be null.
1316/// TagType indicates what kind of tag this is. TK indicates whether this is a
1317/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001318Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001319 SourceLocation KWLoc, IdentifierInfo *Name,
1320 SourceLocation NameLoc, AttributeList *Attr) {
1321 // If this is a use of an existing tag, it must have a name.
1322 assert((Name != 0 || TK == TK_Definition) &&
1323 "Nameless record must be a definition!");
1324
1325 Decl::Kind Kind;
1326 switch (TagType) {
1327 default: assert(0 && "Unknown tag type!");
1328 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1329 case DeclSpec::TST_union: Kind = Decl::Union; break;
1330//case DeclSpec::TST_class: Kind = Decl::Class; break;
1331 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1332 }
1333
1334 // If this is a named struct, check to see if there was a previous forward
1335 // declaration or definition.
1336 if (TagDecl *PrevDecl =
Steve Naroffb327ce02008-04-02 14:35:35 +00001337 dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001338
1339 // If this is a use of a previous tag, or if the tag is already declared in
1340 // the same scope (so that the definition/declaration completes or
1341 // rementions the tag), reuse the decl.
1342 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1343 // Make sure that this wasn't declared as an enum and now used as a struct
1344 // or something similar.
1345 if (PrevDecl->getKind() != Kind) {
1346 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1347 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1348 }
1349
1350 // If this is a use or a forward declaration, we're good.
1351 if (TK != TK_Definition)
1352 return PrevDecl;
1353
1354 // Diagnose attempts to redefine a tag.
1355 if (PrevDecl->isDefinition()) {
1356 Diag(NameLoc, diag::err_redefinition, Name->getName());
1357 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1358 // If this is a redefinition, recover by making this struct be
1359 // anonymous, which will make any later references get the previous
1360 // definition.
1361 Name = 0;
1362 } else {
1363 // Okay, this is definition of a previously declared or referenced tag.
1364 // Move the location of the decl to be the definition site.
1365 PrevDecl->setLocation(NameLoc);
1366 return PrevDecl;
1367 }
1368 }
1369 // If we get here, this is a definition of a new struct type in a nested
1370 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1371 // type.
1372 }
1373
1374 // If there is an identifier, use the location of the identifier as the
1375 // location of the decl, otherwise use the location of the struct/union
1376 // keyword.
1377 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1378
1379 // Otherwise, if this is the first time we've seen this tag, create the decl.
1380 TagDecl *New;
1381 switch (Kind) {
1382 default: assert(0 && "Unknown tag kind!");
1383 case Decl::Enum:
1384 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1385 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001386 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001387 // If this is an undefined enum, warn.
1388 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1389 break;
1390 case Decl::Union:
1391 case Decl::Struct:
1392 case Decl::Class:
1393 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1394 // struct X { int A; } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001395 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001396 break;
1397 }
1398
1399 // If this has an identifier, add it to the scope stack.
1400 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001401 // The scope passed in may not be a decl scope. Zip up the scope tree until
1402 // we find one that is.
1403 while ((S->getFlags() & Scope::DeclScope) == 0)
1404 S = S->getParent();
1405
1406 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001407 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001408 Name->setFETokenInfo(New);
1409 S->AddDecl(New);
1410 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001411
Anders Carlssonad148062008-02-16 00:29:18 +00001412 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001413 return New;
1414}
1415
Steve Naroff08d92e42007-09-15 18:49:24 +00001416/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001417/// to create a FieldDecl object for it.
Chris Lattnerf9628082008-03-16 01:16:52 +00001418Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *tagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001419 SourceLocation DeclStart,
1420 Declarator &D, ExprTy *BitfieldWidth) {
1421 IdentifierInfo *II = D.getIdentifier();
1422 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattnerf9628082008-03-16 01:16:52 +00001423 Decl *TagDecl = static_cast<Decl *>(tagDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 SourceLocation Loc = DeclStart;
1425 if (II) Loc = D.getIdentifierLoc();
1426
1427 // FIXME: Unnamed fields can be handled in various different ways, for
1428 // example, unnamed unions inject all members into the struct namespace!
1429
1430
1431 if (BitWidth) {
1432 // TODO: Validate.
1433 //printf("WARNING: BITFIELDS IGNORED!\n");
1434
1435 // 6.7.2.1p3
1436 // 6.7.2.1p4
1437
1438 } else {
1439 // Not a bitfield.
1440
1441 // validate II.
1442
1443 }
1444
1445 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001446 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1447 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001448
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1450 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001451 if (T->isVariablyModifiedType()) {
1452 // FIXME: This diagnostic needs work
1453 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroffd7444aa2007-08-31 17:20:07 +00001454 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001455 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001457 FieldDecl *NewFD;
1458
Chris Lattnerb048c982008-04-06 04:47:34 +00001459 if (isa<RecordDecl>(TagDecl))
1460 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Chris Lattnerf9628082008-03-16 01:16:52 +00001461 else if (isa<ObjCInterfaceDecl>(TagDecl) ||
1462 isa<ObjCImplementationDecl>(TagDecl) ||
1463 isa<ObjCCategoryDecl>(TagDecl) ||
Steve Naroffddd600f2007-11-14 14:15:31 +00001464 // FIXME: ivars are currently used to model properties, and
1465 // properties can appear within a protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001466 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
Chris Lattnerf9628082008-03-16 01:16:52 +00001467 isa<ObjCProtocolDecl>(TagDecl))
Chris Lattnerb048c982008-04-06 04:47:34 +00001468 NewFD = ObjCIvarDecl::Create(Context, Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001469 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001470 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001471
Anders Carlssonad148062008-02-16 00:29:18 +00001472 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1473 D.getAttributes());
1474
Steve Naroff5912a352007-08-28 20:14:24 +00001475 if (D.getInvalidType() || InvalidDecl)
1476 NewFD->setInvalidDecl();
1477 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001478}
1479
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001480/// TranslateIvarVisibility - Translate visibility from a token ID to an
1481/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001482static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001483TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001484 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001485 case tok::objc_private: return ObjCIvarDecl::Private;
1486 case tok::objc_public: return ObjCIvarDecl::Public;
1487 case tok::objc_protected: return ObjCIvarDecl::Protected;
1488 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001489 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001490 }
1491}
1492
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001493void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001494 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001495 DeclTy **Fields, unsigned NumFields,
Steve Naroff60fccee2007-10-29 21:38:07 +00001496 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff08d92e42007-09-15 18:49:24 +00001497 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001498 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1499 assert(EnclosingDecl && "missing record or interface decl");
1500 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1501
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001502 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 // Diagnose code like:
1504 // struct S { struct S {} X; };
1505 // We discover this when we complete the outer S. Reject and ignore the
1506 // outer S.
1507 Diag(Record->getLocation(), diag::err_nested_redefinition,
1508 Record->getKindName());
1509 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001510 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001511 return;
1512 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001513 // Verify that all the fields are okay.
1514 unsigned NumNamedMembers = 0;
1515 llvm::SmallVector<FieldDecl*, 32> RecFields;
1516 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001517
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001519
Steve Naroff74216642007-09-14 22:20:54 +00001520 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1521 assert(FD && "missing field decl");
1522
1523 // Remember all fields.
1524 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001525
1526 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001527 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001528
Steve Narofff13271f2007-09-14 23:09:53 +00001529 // If we have visibility info, make sure the AST is set accordingly.
1530 if (visibility)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001531 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001532 TranslateIvarVisibility(visibility[i]));
Steve Narofff13271f2007-09-14 23:09:53 +00001533
Reid Spencer5f016e22007-07-11 17:01:13 +00001534 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001535 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001536 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001538 FD->setInvalidDecl();
1539 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 continue;
1541 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1543 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001544 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001545 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001546 FD->setInvalidDecl();
1547 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001548 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001549 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001550 if (i != NumFields-1 || // ... that the last member ...
1551 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001552 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001553 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001554 FD->setInvalidDecl();
1555 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001556 continue;
1557 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001558 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1560 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001561 FD->setInvalidDecl();
1562 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 continue;
1564 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001566 if (Record)
1567 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001568 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1570 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001571 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1573 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001574 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 Record->setHasFlexibleArrayMember(true);
1576 } else {
1577 // If this is a struct/class and this is not the last element, reject
1578 // it. Note that GCC supports variable sized arrays in the middle of
1579 // structures.
1580 if (i != NumFields-1) {
1581 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1582 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001583 FD->setInvalidDecl();
1584 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 continue;
1586 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 // We support flexible arrays at the end of structs in other structs
1588 // as an extension.
1589 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1590 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001591 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001592 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 }
1594 }
1595 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001596 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001597 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001598 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1599 FD->getName());
1600 FD->setInvalidDecl();
1601 EnclosingDecl->setInvalidDecl();
1602 continue;
1603 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 // Keep track of the number of named members.
1605 if (IdentifierInfo *II = FD->getIdentifier()) {
1606 // Detect duplicate member names.
1607 if (!FieldIDs.insert(II)) {
1608 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1609 // Find the previous decl.
1610 SourceLocation PrevLoc;
1611 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1612 assert(i != e && "Didn't find previous def!");
1613 if (RecFields[i]->getIdentifier() == II) {
1614 PrevLoc = RecFields[i]->getLocation();
1615 break;
1616 }
1617 }
1618 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001619 FD->setInvalidDecl();
1620 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001621 continue;
1622 }
1623 ++NumNamedMembers;
1624 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001625 }
1626
Reid Spencer5f016e22007-07-11 17:01:13 +00001627 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00001628 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001629 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00001630 Consumer.HandleTagDeclDefinition(Record);
1631 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00001632 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1633 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1634 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1635 else if (ObjCImplementationDecl *IMPDecl =
1636 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001637 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1638 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001639 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001640 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001641 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001642}
1643
Steve Naroff08d92e42007-09-15 18:49:24 +00001644Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 DeclTy *lastEnumConst,
1646 SourceLocation IdLoc, IdentifierInfo *Id,
1647 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00001648 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00001649 EnumConstantDecl *LastEnumConst =
1650 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1651 Expr *Val = static_cast<Expr*>(val);
1652
Chris Lattner31e05722007-08-26 06:24:45 +00001653 // The scope passed in may not be a decl scope. Zip up the scope tree until
1654 // we find one that is.
1655 while ((S->getFlags() & Scope::DeclScope) == 0)
1656 S = S->getParent();
1657
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 // Verify that there isn't already something declared with this name in this
1659 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00001660 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001661 if (S->isDeclScope(PrevDecl)) {
1662 if (isa<EnumConstantDecl>(PrevDecl))
1663 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1664 else
1665 Diag(IdLoc, diag::err_redefinition, Id->getName());
1666 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00001667 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 return 0;
1669 }
1670 }
1671
1672 llvm::APSInt EnumVal(32);
1673 QualType EltTy;
1674 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001675 // Make sure to promote the operand type to int.
1676 UsualUnaryConversions(Val);
1677
Reid Spencer5f016e22007-07-11 17:01:13 +00001678 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1679 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001680 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001681 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1682 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00001683 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001684 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001685 } else {
1686 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001687 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001688 }
1689
1690 if (!Val) {
1691 if (LastEnumConst) {
1692 // Assign the last value + 1.
1693 EnumVal = LastEnumConst->getInitVal();
1694 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001695
1696 // Check for overflow on increment.
1697 if (EnumVal < LastEnumConst->getInitVal())
1698 Diag(IdLoc, diag::warn_enum_value_overflow);
1699
Chris Lattnerb7416f92007-08-27 17:37:24 +00001700 EltTy = LastEnumConst->getType();
1701 } else {
1702 // First value, set to zero.
1703 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001704 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001705 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 }
1707
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001708 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00001709 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
1710 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001711 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00001712
1713 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001714 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001715 Id->setFETokenInfo(New);
1716 S->AddDecl(New);
1717 return New;
1718}
1719
Steve Naroff08d92e42007-09-15 18:49:24 +00001720void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001721 DeclTy **Elements, unsigned NumElements) {
1722 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1723 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1724
Chris Lattnere37f0be2007-08-28 05:10:31 +00001725 // TODO: If the result value doesn't fit in an int, it must be a long or long
1726 // long value. ISO C does not support this, but GCC does as an extension,
1727 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00001728 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00001729
Chris Lattnerac609682007-08-28 06:15:15 +00001730 // Verify that all the values are okay, compute the size of the values, and
1731 // reverse the list.
1732 unsigned NumNegativeBits = 0;
1733 unsigned NumPositiveBits = 0;
1734
1735 // Keep track of whether all elements have type int.
1736 bool AllElementsInt = true;
1737
Reid Spencer5f016e22007-07-11 17:01:13 +00001738 EnumConstantDecl *EltList = 0;
1739 for (unsigned i = 0; i != NumElements; ++i) {
1740 EnumConstantDecl *ECD =
1741 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1742 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001743
1744 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00001745 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00001746 assert(InitVal.getBitWidth() >= IntWidth &&
1747 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00001748 if (InitVal.getBitWidth() > IntWidth) {
1749 llvm::APSInt V(InitVal);
1750 V.trunc(IntWidth);
1751 V.extend(InitVal.getBitWidth());
1752 if (V != InitVal)
1753 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1754 InitVal.toString());
1755 }
Chris Lattnerac609682007-08-28 06:15:15 +00001756
1757 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00001758 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00001759 NumPositiveBits = std::max(NumPositiveBits,
1760 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00001761 else
Chris Lattner21dd8212008-01-14 21:47:29 +00001762 NumNegativeBits = std::max(NumNegativeBits,
1763 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001764
Chris Lattnerac609682007-08-28 06:15:15 +00001765 // Keep track of whether every enum element has type int (very commmon).
1766 if (AllElementsInt)
1767 AllElementsInt = ECD->getType() == Context.IntTy;
1768
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 ECD->setNextDeclarator(EltList);
1770 EltList = ECD;
1771 }
1772
Chris Lattnerac609682007-08-28 06:15:15 +00001773 // Figure out the type that should be used for this enum.
1774 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1775 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001776 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001777
1778 if (NumNegativeBits) {
1779 // If there is a negative value, figure out the smallest integer type (of
1780 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001781 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001782 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001783 BestWidth = IntWidth;
1784 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00001785 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001786
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001787 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001788 BestType = Context.LongTy;
1789 else {
Chris Lattner98be4942008-03-05 18:54:05 +00001790 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001791
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001792 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001793 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1794 BestType = Context.LongLongTy;
1795 }
1796 }
1797 } else {
1798 // If there is no negative value, figure out which of uint, ulong, ulonglong
1799 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001800 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001801 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001802 BestWidth = IntWidth;
1803 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00001804 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00001805 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001806 } else {
1807 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001808 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001809 "How could an initializer get larger than ULL?");
1810 BestType = Context.UnsignedLongLongTy;
1811 }
1812 }
1813
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001814 // Loop over all of the enumerator constants, changing their types to match
1815 // the type of the enum if needed.
1816 for (unsigned i = 0; i != NumElements; ++i) {
1817 EnumConstantDecl *ECD =
1818 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1819 if (!ECD) continue; // Already issued a diagnostic.
1820
1821 // Standard C says the enumerators have int type, but we allow, as an
1822 // extension, the enumerators to be larger than int size. If each
1823 // enumerator value fits in an int, type it as an int, otherwise type it the
1824 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1825 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00001826 if (ECD->getType() == Context.IntTy) {
1827 // Make sure the init value is signed.
1828 llvm::APSInt IV = ECD->getInitVal();
1829 IV.setIsSigned(true);
1830 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001831 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00001832 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001833
1834 // Determine whether the value fits into an int.
1835 llvm::APSInt InitVal = ECD->getInitVal();
1836 bool FitsInInt;
1837 if (InitVal.isUnsigned() || !InitVal.isNegative())
1838 FitsInInt = InitVal.getActiveBits() < IntWidth;
1839 else
1840 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1841
1842 // If it fits into an integer type, force it. Otherwise force it to match
1843 // the enum decl type.
1844 QualType NewTy;
1845 unsigned NewWidth;
1846 bool NewSign;
1847 if (FitsInInt) {
1848 NewTy = Context.IntTy;
1849 NewWidth = IntWidth;
1850 NewSign = true;
1851 } else if (ECD->getType() == BestType) {
1852 // Already the right type!
1853 continue;
1854 } else {
1855 NewTy = BestType;
1856 NewWidth = BestWidth;
1857 NewSign = BestType->isSignedIntegerType();
1858 }
1859
1860 // Adjust the APSInt value.
1861 InitVal.extOrTrunc(NewWidth);
1862 InitVal.setIsSigned(NewSign);
1863 ECD->setInitVal(InitVal);
1864
1865 // Adjust the Expr initializer and type.
1866 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1867 ECD->setType(NewTy);
1868 }
Chris Lattnerac609682007-08-28 06:15:15 +00001869
Chris Lattnere00b18c2007-08-28 18:24:31 +00001870 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00001871 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00001872}
1873
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001874Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1875 ExprTy *expr) {
1876 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1877
Chris Lattner8e25d862008-03-16 00:16:02 +00001878 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001879}
1880
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001881Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00001882 SourceLocation LBrace,
1883 SourceLocation RBrace,
1884 const char *Lang,
1885 unsigned StrSize,
1886 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001887 LinkageSpecDecl::LanguageIDs Language;
1888 Decl *dcl = static_cast<Decl *>(D);
1889 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1890 Language = LinkageSpecDecl::lang_c;
1891 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1892 Language = LinkageSpecDecl::lang_cxx;
1893 else {
1894 Diag(Loc, diag::err_bad_language);
1895 return 0;
1896 }
1897
1898 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00001899 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001900}
1901
Chris Lattner74788ba2008-02-21 00:48:22 +00001902void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00001903
Chris Lattner74788ba2008-02-21 00:48:22 +00001904 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00001905 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00001906 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00001907 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001908 if (!newType.isNull()) // install the new vector type into the decl
1909 vDecl->setType(newType);
1910 }
1911 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1912 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001913 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001914 if (!newType.isNull()) // install the new vector type into the decl
1915 tDecl->setUnderlyingType(newType);
1916 }
Chris Lattner212839c2008-02-20 23:17:35 +00001917 break;
1918 case AttributeList::AT_ocu_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00001919 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Chris Lattner74788ba2008-02-21 00:48:22 +00001920 HandleOCUVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00001921 else
Chris Lattner74788ba2008-02-21 00:48:22 +00001922 Diag(Attr->getLoc(),
Steve Naroff73322922007-07-18 18:00:27 +00001923 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00001924 break;
1925 case AttributeList::AT_address_space:
Christopher Lambebb97e92008-02-04 02:31:56 +00001926 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1927 QualType newType = HandleAddressSpaceTypeAttribute(
1928 tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001929 Attr);
1930 tDecl->setUnderlyingType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001931 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1932 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001933 Attr);
1934 // install the new addr spaced type into the decl
1935 vDecl->setType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001936 }
Chris Lattner212839c2008-02-20 23:17:35 +00001937 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00001938 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00001939 HandleDeprecatedAttribute(New, Attr);
1940 break;
1941 case AttributeList::AT_visibility:
1942 HandleVisibilityAttribute(New, Attr);
1943 break;
1944 case AttributeList::AT_weak:
1945 HandleWeakAttribute(New, Attr);
1946 break;
1947 case AttributeList::AT_dllimport:
1948 HandleDLLImportAttribute(New, Attr);
1949 break;
1950 case AttributeList::AT_dllexport:
1951 HandleDLLExportAttribute(New, Attr);
1952 break;
1953 case AttributeList::AT_nothrow:
1954 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00001955 break;
Nate Begeman440b4562008-03-07 20:04:22 +00001956 case AttributeList::AT_stdcall:
1957 HandleStdCallAttribute(New, Attr);
1958 break;
1959 case AttributeList::AT_fastcall:
1960 HandleFastCallAttribute(New, Attr);
1961 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001962 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00001963 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001964 break;
1965 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00001966 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001967 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00001968 case AttributeList::AT_annotate:
1969 HandleAnnotateAttribute(New, Attr);
1970 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00001971 case AttributeList::AT_noreturn:
1972 HandleNoReturnAttribute(New, Attr);
1973 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00001974 case AttributeList::AT_format:
1975 HandleFormatAttribute(New, Attr);
1976 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001977 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00001978#if 0
1979 // TODO: when we have the full set of attributes, warn about unknown ones.
1980 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
1981 Attr->getName()->getName());
1982#endif
Chris Lattner212839c2008-02-20 23:17:35 +00001983 break;
1984 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001985}
1986
1987void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1988 AttributeList *declarator_postfix) {
1989 while (declspec_prefix) {
1990 HandleDeclAttribute(New, declspec_prefix);
1991 declspec_prefix = declspec_prefix->getNext();
1992 }
1993 while (declarator_postfix) {
1994 HandleDeclAttribute(New, declarator_postfix);
1995 declarator_postfix = declarator_postfix->getNext();
1996 }
1997}
1998
Steve Naroffbea0b342007-07-29 16:33:31 +00001999void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
2000 AttributeList *rawAttr) {
2001 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00002002 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00002003 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002004 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00002005 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002006 return;
Steve Naroff73322922007-07-18 18:00:27 +00002007 }
2008 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2009 llvm::APSInt vecSize(32);
2010 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002011 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002012 "ocu_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002013 return;
Steve Naroff73322922007-07-18 18:00:27 +00002014 }
2015 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2016 // in conjunction with complex types (pointers, arrays, functions, etc.).
2017 Type *canonType = curType.getCanonicalType().getTypePtr();
2018 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002019 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00002020 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002021 return;
Steve Naroff73322922007-07-18 18:00:27 +00002022 }
2023 // unlike gcc's vector_size attribute, the size is specified as the
2024 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002025 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002026
2027 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002028 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00002029 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002030 return;
Steve Naroff73322922007-07-18 18:00:27 +00002031 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002032 // Instantiate/Install the vector type, the number of elements is > 0.
2033 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
2034 // Remember this typedef decl, we will need it later for diagnostics.
2035 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002036}
2037
Reid Spencer5f016e22007-07-11 17:01:13 +00002038QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002039 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002040 // check the attribute arugments.
2041 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002042 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00002043 std::string("1"));
2044 return QualType();
2045 }
2046 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2047 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002048 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002049 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002050 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002051 return QualType();
2052 }
2053 // navigate to the base type - we need to provide for vector pointers,
2054 // vector arrays, and functions returning vectors.
2055 Type *canonType = curType.getCanonicalType().getTypePtr();
2056
Steve Naroff73322922007-07-18 18:00:27 +00002057 if (canonType->isPointerType() || canonType->isArrayType() ||
2058 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00002059 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00002060 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2061 do {
2062 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2063 canonType = PT->getPointeeType().getTypePtr();
2064 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2065 canonType = AT->getElementType().getTypePtr();
2066 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2067 canonType = FT->getResultType().getTypePtr();
2068 } while (canonType->isPointerType() || canonType->isArrayType() ||
2069 canonType->isFunctionType());
2070 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002071 }
2072 // the base type must be integer or float.
2073 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002074 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00002075 curType.getCanonicalType().getAsString());
2076 return QualType();
2077 }
Chris Lattner98be4942008-03-05 18:54:05 +00002078 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Reid Spencer5f016e22007-07-11 17:01:13 +00002079 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002080 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002081
2082 // the vector size needs to be an integral multiple of the type size.
2083 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00002084 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002085 sizeExpr->getSourceRange());
2086 return QualType();
2087 }
2088 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002089 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002090 sizeExpr->getSourceRange());
2091 return QualType();
2092 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00002093 // Instantiate the vector type, the number of elements is > 0, and not
2094 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00002095 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002096}
2097
Chris Lattner2070d802008-02-20 23:25:22 +00002098void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00002099 // check the attribute arguments.
2100 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002101 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00002102 std::string("0"));
2103 return;
2104 }
2105
2106 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2107 TD->addAttr(new PackedAttr);
2108 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2109 // If the alignment is less than or equal to 8 bits, the packed attribute
2110 // has no effect.
Chris Lattner98be4942008-03-05 18:54:05 +00002111 if (Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00002112 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00002113 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00002114 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00002115 else
Anders Carlsson425a6092008-02-16 00:39:40 +00002116 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00002117 } else
Chris Lattner2070d802008-02-20 23:25:22 +00002118 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2119 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00002120}
Nate Begemanc398f0b2008-02-21 19:30:49 +00002121
Ted Kremenekaecb3832008-02-27 20:43:06 +00002122void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2123 // check the attribute arguments.
2124 if (rawAttr->getNumArgs() != 0) {
2125 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2126 std::string("0"));
2127 return;
2128 }
2129
Ted Kremenek3465fb32008-03-03 16:52:27 +00002130 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2131
2132 if (!Fn) {
2133 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2134 "noreturn", "function");
2135 return;
2136 }
2137
Ted Kremenekaecb3832008-02-27 20:43:06 +00002138 d->addAttr(new NoReturnAttr());
2139}
2140
Chris Lattnerddee4232008-03-03 03:28:21 +00002141void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2142 // check the attribute arguments.
2143 if (rawAttr->getNumArgs() != 0) {
2144 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2145 std::string("0"));
2146 return;
2147 }
2148
2149 d->addAttr(new DeprecatedAttr());
2150}
2151
2152void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2153 // check the attribute arguments.
Chris Lattner7b937ae2008-03-04 18:08:48 +00002154 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002155 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2156 std::string("1"));
2157 return;
2158 }
2159
Chris Lattner7b937ae2008-03-04 18:08:48 +00002160 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2161 Arg = Arg->IgnoreParenCasts();
2162 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2163
2164 if (Str == 0 || Str->isWide()) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002165 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002166 "visibility", std::string("1"));
Chris Lattnerddee4232008-03-03 03:28:21 +00002167 return;
2168 }
2169
Chris Lattner7b937ae2008-03-04 18:08:48 +00002170 const char *TypeStr = Str->getStrData();
2171 unsigned TypeLen = Str->getByteLength();
Chris Lattnerddee4232008-03-03 03:28:21 +00002172 llvm::GlobalValue::VisibilityTypes type;
2173
Chris Lattner7b937ae2008-03-04 18:08:48 +00002174 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Chris Lattnerddee4232008-03-03 03:28:21 +00002175 type = llvm::GlobalValue::DefaultVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002176 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Chris Lattnerddee4232008-03-03 03:28:21 +00002177 type = llvm::GlobalValue::HiddenVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002178 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Chris Lattnerddee4232008-03-03 03:28:21 +00002179 type = llvm::GlobalValue::HiddenVisibility; // FIXME
Chris Lattner7b937ae2008-03-04 18:08:48 +00002180 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Chris Lattnerddee4232008-03-03 03:28:21 +00002181 type = llvm::GlobalValue::ProtectedVisibility;
2182 else {
2183 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002184 "visibility", TypeStr);
Chris Lattnerddee4232008-03-03 03:28:21 +00002185 return;
2186 }
2187
2188 d->addAttr(new VisibilityAttr(type));
2189}
2190
2191void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2192 // check the attribute arguments.
2193 if (rawAttr->getNumArgs() != 0) {
2194 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2195 std::string("0"));
2196 return;
2197 }
2198
2199 d->addAttr(new WeakAttr());
2200}
2201
2202void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2203 // check the attribute arguments.
2204 if (rawAttr->getNumArgs() != 0) {
2205 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2206 std::string("0"));
2207 return;
2208 }
2209
2210 d->addAttr(new DLLImportAttr());
2211}
2212
2213void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2214 // check the attribute arguments.
2215 if (rawAttr->getNumArgs() != 0) {
2216 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2217 std::string("0"));
2218 return;
2219 }
2220
2221 d->addAttr(new DLLExportAttr());
2222}
2223
Nate Begeman440b4562008-03-07 20:04:22 +00002224void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2225 // check the attribute arguments.
2226 if (rawAttr->getNumArgs() != 0) {
2227 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2228 std::string("0"));
2229 return;
2230 }
2231
2232 d->addAttr(new StdCallAttr());
2233}
2234
2235void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2236 // check the attribute arguments.
2237 if (rawAttr->getNumArgs() != 0) {
2238 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2239 std::string("0"));
2240 return;
2241 }
2242
2243 d->addAttr(new FastCallAttr());
2244}
2245
Chris Lattnerddee4232008-03-03 03:28:21 +00002246void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2247 // check the attribute arguments.
2248 if (rawAttr->getNumArgs() != 0) {
2249 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2250 std::string("0"));
2251 return;
2252 }
2253
2254 d->addAttr(new NoThrowAttr());
2255}
2256
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002257static const FunctionTypeProto *getFunctionProto(Decl *d) {
2258 ValueDecl *decl = dyn_cast<ValueDecl>(d);
2259 if (!decl) return 0;
2260
2261 QualType Ty = decl->getType();
2262
2263 if (Ty->isFunctionPointerType()) {
2264 const PointerType *PtrTy = Ty->getAsPointerType();
2265 Ty = PtrTy->getPointeeType();
2266 }
2267
2268 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2269 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2270
2271 return 0;
2272}
2273
2274
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002275/// Handle __attribute__((format(type,idx,firstarg))) attributes
2276/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattnerddee4232008-03-03 03:28:21 +00002277void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2278
2279 if (!rawAttr->getParameterName()) {
2280 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2281 "format", std::string("1"));
2282 return;
2283 }
2284
2285 if (rawAttr->getNumArgs() != 2) {
2286 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2287 std::string("3"));
2288 return;
2289 }
2290
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002291 // GCC ignores the format attribute on K&R style function
2292 // prototypes, so we ignore it as well
2293 const FunctionTypeProto *proto = getFunctionProto(d);
2294
2295 if (!proto) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002296 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2297 "format", "function");
2298 return;
2299 }
2300
2301 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002302 // this is needed in order to be compatible with GCC
Chris Lattnerddee4232008-03-03 03:28:21 +00002303 // the index must start in 1 and the limit is numargs+1
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002304 unsigned NumArgs = proto->getNumArgs();
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002305 unsigned FirstIdx = 1;
Chris Lattnerddee4232008-03-03 03:28:21 +00002306
2307 const char *Format = rawAttr->getParameterName()->getName();
2308 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2309
2310 // Normalize the argument, __foo__ becomes foo.
2311 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2312 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2313 Format += 2;
2314 FormatLen -= 4;
2315 }
2316
2317 if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2318 || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2319 || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2320 || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2321 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2322 "format", rawAttr->getParameterName()->getName());
2323 return;
2324 }
2325
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002326 // checks for the 2nd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002327 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002328 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002329 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2330 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2331 "format", std::string("2"), IdxExpr->getSourceRange());
2332 return;
2333 }
2334
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002335 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002336 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2337 "format", std::string("2"), IdxExpr->getSourceRange());
2338 return;
2339 }
2340
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002341 // make sure the format string is really a string
2342 QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2343 if (!Ty->isPointerType() ||
2344 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2345 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2346 IdxExpr->getSourceRange());
2347 return;
2348 }
2349
2350
2351 // check the 3rd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002352 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002353 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002354 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2355 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2356 "format", std::string("3"), FirstArgExpr->getSourceRange());
2357 return;
2358 }
2359
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002360 // check if the function is variadic if the 3rd argument non-zero
2361 if (FirstArg != 0) {
2362 if (proto->isVariadic()) {
2363 ++NumArgs; // +1 for ...
2364 } else {
2365 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2366 return;
2367 }
2368 }
2369
2370 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2371 // the input is just the current time + the format string
Chris Lattnerddee4232008-03-03 03:28:21 +00002372 if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002373 if (FirstArg != 0) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002374 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2375 FirstArgExpr->getSourceRange());
2376 return;
2377 }
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002378 // if 0 it disables parameter checking (to use with e.g. va_list)
2379 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002380 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2381 "format", std::string("3"), FirstArgExpr->getSourceRange());
2382 return;
2383 }
2384
2385 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2386 Idx.getZExtValue(), FirstArg.getZExtValue()));
2387}
2388
Nate Begemanc398f0b2008-02-21 19:30:49 +00002389void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2390 // check the attribute arguments.
2391 if (rawAttr->getNumArgs() != 1) {
2392 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2393 std::string("1"));
2394 return;
2395 }
2396 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2397 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002398
Nate Begemanc398f0b2008-02-21 19:30:49 +00002399 // Make sure that there is a string literal as the annotation's single
2400 // argument.
2401 if (!SE) {
2402 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2403 return;
2404 }
2405 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2406 SE->getByteLength())));
2407}
2408
Anders Carlsson78aaae92007-12-19 07:19:40 +00002409void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2410{
2411 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002412 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002413 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002414 std::string("1"));
2415 return;
2416 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002417
Anders Carlsson042c4e72008-02-16 19:51:27 +00002418 unsigned Align = 0;
2419
2420 if (rawAttr->getNumArgs() == 0) {
2421 // FIXME: This should be the target specific maximum alignment.
2422 // (For now we just use 128 bits which is the maximum on X86.
2423 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002424 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002425 } else {
2426 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2427 llvm::APSInt alignment(32);
2428 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002429 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002430 "aligned", alignmentExpr->getSourceRange());
2431 return;
2432 }
2433
2434 Align = alignment.getZExtValue() * 8;
2435 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002436
Anders Carlsson042c4e72008-02-16 19:51:27 +00002437 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002438}