blob: f0e469791a7754496f1f3e8be8638aac70bc090d [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
Anders Carlsson3f70c542008-02-15 07:04:12 +000017#include "clang/AST/Attr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "clang/AST/Builtins.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/Type.h"
22#include "clang/Parse/DeclSpec.h"
23#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Basic/SourceManager.h"
27// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner33aad6e2008-02-06 00:51:33 +000028#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000029#include "clang/Lex/HeaderSearch.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000030#include "llvm/ADT/SmallString.h"
Chris Lattner4b009652007-07-25 00:24:17 +000031#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian67907bd2007-10-05 18:00:57 +000032#include "llvm/ADT/DenseSet.h"
Chris Lattner4b009652007-07-25 00:24:17 +000033using namespace clang;
34
Steve Naroff6384a012008-04-02 14:35:35 +000035Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
36 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
37
Douglas Gregor1d661552008-04-13 21:07:44 +000038 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
39 isa<ObjCInterfaceDecl>(IIDecl) ||
40 isa<TagDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000041 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000042 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000043}
44
Chris Lattnerf3874bc2008-04-06 04:47:34 +000045void Sema::PushDeclContext(DeclContext *CD) {
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000046 assert( ( (CD->isFunctionOrMethod() && isa<TranslationUnitDecl>(CurContext))
47 || CD->getParent() == CurContext ) &&
Chris Lattnerf3874bc2008-04-06 04:47:34 +000048 "The next DeclContext should be directly contained in the current one.");
Chris Lattnereee57c02008-04-04 06:12:32 +000049 CurContext = CD;
50}
51
Chris Lattnerf3874bc2008-04-06 04:47:34 +000052void Sema::PopDeclContext() {
53 assert(CurContext && "DeclContext imbalance!");
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000054 // If CurContext is a ObjC method, getParent() will return NULL.
55 CurContext = CurContext->isFunctionOrMethod()
56 ? Context.getTranslationUnitDecl()
57 : CurContext->getParent();
Chris Lattnereee57c02008-04-04 06:12:32 +000058}
59
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000060/// Add this decl to the scope shadowed decl chains.
61void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
62 IdResolver.AddDecl(D, S);
63 S->AddDecl(D);
64}
65
Steve Naroff9637a9b2007-10-09 22:01:59 +000066void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000067 if (S->decl_empty()) return;
68 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
69
Chris Lattner4b009652007-07-25 00:24:17 +000070 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
71 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +000072 Decl *TmpD = static_cast<Decl*>(*I);
73 assert(TmpD && "This decl didn't get pushed??");
74 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
75 assert(D && "This decl isn't a ScopedDecl?");
76
Chris Lattner4b009652007-07-25 00:24:17 +000077 IdentifierInfo *II = D->getIdentifier();
78 if (!II) continue;
79
Chris Lattner2a1e2ed2008-04-11 07:00:53 +000080 // Unlink this decl from the identifier.
81 IdResolver.RemoveDecl(D);
82
Chris Lattner4b009652007-07-25 00:24:17 +000083 // This will have to be revisited for C++: there we want to nest stuff in
84 // namespace decls etc. Even for C, we might want a top-level translation
85 // unit decl or something.
86 if (!CurFunctionDecl)
87 continue;
88
89 // Chain this decl to the containing function, it now owns the memory for
90 // the decl.
91 D->setNext(CurFunctionDecl->getDeclChain());
92 CurFunctionDecl->setDeclChain(D);
93 }
94}
95
Steve Naroffe57c21a2008-04-01 23:04:06 +000096/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
97/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +000098ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +000099 // The third "scope" argument is 0 since we aren't enabling lazy built-in
100 // creation from this context.
101 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000102
Steve Naroff6384a012008-04-02 14:35:35 +0000103 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000104}
105
Steve Naroffe57c21a2008-04-01 23:04:06 +0000106/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000107/// namespace.
Steve Naroff6384a012008-04-02 14:35:35 +0000108Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
109 Scope *S, bool enableLazyBuiltinCreation) {
Chris Lattner4b009652007-07-25 00:24:17 +0000110 if (II == 0) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000111 unsigned NS = NSI;
112 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
113 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000114
Chris Lattner4b009652007-07-25 00:24:17 +0000115 // Scan up the scope chain looking for a decl that matches this identifier
116 // that is in the appropriate namespace. This search should not take long, as
117 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000118 NamedDecl *ND = IdResolver.Lookup(II, NS);
119 if (ND) return ND;
120
Chris Lattner4b009652007-07-25 00:24:17 +0000121 // If we didn't find a use of this identifier, and if the identifier
122 // corresponds to a compiler builtin, create the decl object for the builtin
123 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1d661552008-04-13 21:07:44 +0000124 if (NS & Decl::IDNS_Ordinary) {
Steve Naroff6384a012008-04-02 14:35:35 +0000125 if (enableLazyBuiltinCreation) {
126 // If this is a builtin on this (or all) targets, create the decl.
127 if (unsigned BuiltinID = II->getBuiltinID())
128 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
129 }
Steve Naroffe57c21a2008-04-01 23:04:06 +0000130 if (getLangOptions().ObjC1) {
131 // @interface and @compatibility_alias introduce typedef-like names.
132 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000133 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000134 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000135 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
136 if (IDI != ObjCInterfaceDecls.end())
137 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000138 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
139 if (I != ObjCAliasDecls.end())
140 return I->second->getClassInterface();
141 }
Chris Lattner4b009652007-07-25 00:24:17 +0000142 }
143 return 0;
144}
145
Anders Carlsson36760332007-10-15 20:28:48 +0000146void Sema::InitBuiltinVaListType()
147{
148 if (!Context.getBuiltinVaListType().isNull())
149 return;
150
151 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000152 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000153 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000154 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
155}
156
Chris Lattner4b009652007-07-25 00:24:17 +0000157/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
158/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000159ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
160 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000161 Builtin::ID BID = (Builtin::ID)bid;
162
Anders Carlsson36760332007-10-15 20:28:48 +0000163 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000164 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson36760332007-10-15 20:28:48 +0000165 BID == Builtin::BI__builtin_va_end)
166 InitBuiltinVaListType();
167
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000168 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattnereee57c02008-04-04 06:12:32 +0000169 FunctionDecl *New = FunctionDecl::Create(Context, CurContext,
170 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000171 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000172
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000173 // TUScope is the translation-unit scope to insert this function into.
174 TUScope->AddDecl(New);
Chris Lattner4b009652007-07-25 00:24:17 +0000175
176 // Add this decl to the end of the identifier info.
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000177 IdResolver.AddGlobalDecl(New);
178
Chris Lattner4b009652007-07-25 00:24:17 +0000179 return New;
180}
181
182/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
183/// and scope as a previous declaration 'Old'. Figure out how to resolve this
184/// situation, merging decls or emitting diagnostics as appropriate.
185///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000186TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000187 // Verify the old decl was also a typedef.
188 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
189 if (!Old) {
190 Diag(New->getLocation(), diag::err_redefinition_different_kind,
191 New->getName());
192 Diag(OldD->getLocation(), diag::err_previous_definition);
193 return New;
194 }
195
Steve Naroffae84af82007-10-31 18:42:27 +0000196 // Allow multiple definitions for ObjC built-in typedefs.
197 // FIXME: Verify the underlying types are equivalent!
Ted Kremenek42730c52008-01-07 19:49:32 +0000198 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroffae84af82007-10-31 18:42:27 +0000199 return Old;
Steve Naroffa9eae582008-01-30 23:46:05 +0000200
201 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
202 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
203 // *either* declaration is in a system header. The code below implements
204 // this adhoc compatibility rule. FIXME: The following code will not
205 // work properly when compiling ".i" files (containing preprocessed output).
206 SourceManager &SrcMgr = Context.getSourceManager();
207 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
208 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
209 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
210 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
211 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
212
Steve Naroff1997d2c2008-03-26 21:27:00 +0000213 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
214 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
215 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroff73a07032008-02-07 03:50:06 +0000216 getLangOptions().Microsoft)
Steve Naroffa9eae582008-01-30 23:46:05 +0000217 return New;
Steve Naroff1997d2c2008-03-26 21:27:00 +0000218
Chris Lattner4b009652007-07-25 00:24:17 +0000219 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
220 // TODO: This is totally simplistic. It should handle merging functions
221 // together etc, merging extern int X; int X; ...
222 Diag(New->getLocation(), diag::err_redefinition, New->getName());
223 Diag(Old->getLocation(), diag::err_previous_definition);
224 return New;
225}
226
Chris Lattner402b3372008-03-03 03:28:21 +0000227/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
228static bool DeclHasAttr(const Decl *decl, const Attr *target) {
229 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
230 if (attr->getKind() == target->getKind())
231 return true;
232
233 return false;
234}
235
236/// MergeAttributes - append attributes from the Old decl to the New one.
237static void MergeAttributes(Decl *New, Decl *Old) {
238 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
239
240// FIXME: fix this code to cleanup the Old attrs correctly
241 while (attr) {
242 tmp = attr;
243 attr = attr->getNext();
244
245 if (!DeclHasAttr(New, tmp)) {
246 New->addAttr(tmp);
247 } else {
248 tmp->setNext(0);
249 delete(tmp);
250 }
251 }
252}
253
Chris Lattner3e254fb2008-04-08 04:40:51 +0000254/// MergeFunctionDecl - We just parsed a function 'New' from
255/// declarator D which has the same name and scope as a previous
256/// declaration 'Old'. Figure out how to resolve this situation,
257/// merging decls or emitting diagnostics as appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000258///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000259FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000260 // Verify the old decl was also a function.
261 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
262 if (!Old) {
263 Diag(New->getLocation(), diag::err_redefinition_different_kind,
264 New->getName());
265 Diag(OldD->getLocation(), diag::err_previous_definition);
266 return New;
267 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000268
Chris Lattner402b3372008-03-03 03:28:21 +0000269 MergeAttributes(New, Old);
270
Chris Lattner42a21742008-04-06 23:10:54 +0000271 QualType OldQType = Context.getCanonicalType(Old->getType());
272 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000273
Chris Lattner3e254fb2008-04-08 04:40:51 +0000274 // C++ [dcl.fct]p3:
275 // All declarations for a function shall agree exactly in both the
276 // return type and the parameter-type-list.
277 if (getLangOptions().CPlusPlus && OldQType == NewQType)
278 return MergeCXXFunctionDecl(New, Old);
279
280 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000281 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000282 if (!getLangOptions().CPlusPlus &&
283 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Steve Naroff1d5bd642008-01-14 20:51:29 +0000284 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000285 }
Chris Lattner1470b072007-11-06 06:07:26 +0000286
Steve Naroff6c9e7922008-01-16 15:01:34 +0000287 // A function that has already been declared has been redeclared or defined
288 // with a different type- show appropriate diagnostic
Steve Naroff9104f3c2008-04-04 14:32:09 +0000289 diag::kind PrevDiag;
290 if (Old->getBody())
291 PrevDiag = diag::err_previous_definition;
292 else if (Old->isImplicit())
293 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000294 else
Steve Naroff9104f3c2008-04-04 14:32:09 +0000295 PrevDiag = diag::err_previous_declaration;
Steve Naroff6c9e7922008-01-16 15:01:34 +0000296
Chris Lattner4b009652007-07-25 00:24:17 +0000297 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
298 // TODO: This is totally simplistic. It should handle merging functions
299 // together etc, merging extern int X; int X; ...
Steve Naroff6c9e7922008-01-16 15:01:34 +0000300 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
301 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000302 return New;
303}
304
Chris Lattnerf9167d12007-11-06 04:28:31 +0000305/// equivalentArrayTypes - Used to determine whether two array types are
306/// equivalent.
307/// We need to check this explicitly as an incomplete array definition is
308/// considered a VariableArrayType, so will not match a complete array
309/// definition that would be otherwise equivalent.
310static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
311 const ArrayType *NewAT = NewQType->getAsArrayType();
312 const ArrayType *OldAT = OldQType->getAsArrayType();
313
314 if (!NewAT || !OldAT)
315 return false;
316
317 // If either (or both) array types in incomplete we need to strip off the
318 // outer VariableArrayType. Once the outer VAT is removed the remaining
319 // types must be identical if the array types are to be considered
320 // equivalent.
321 // eg. int[][1] and int[1][1] become
322 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
323 // removing the outermost VAT gives
324 // CAT(1, int) and CAT(1, int)
325 // which are equal, therefore the array types are equivalent.
Eli Friedmane0079792008-02-15 12:53:51 +0000326 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerf9167d12007-11-06 04:28:31 +0000327 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
328 return false;
Eli Friedmand32157f2008-01-29 07:51:12 +0000329 NewQType = NewAT->getElementType().getCanonicalType();
330 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerf9167d12007-11-06 04:28:31 +0000331 }
332
333 return NewQType == OldQType;
334}
335
Chris Lattner4b009652007-07-25 00:24:17 +0000336/// MergeVarDecl - We just parsed a variable 'New' which has the same name
337/// and scope as a previous declaration 'Old'. Figure out how to resolve this
338/// situation, merging decls or emitting diagnostics as appropriate.
339///
340/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
341/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
342///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000343VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000344 // Verify the old decl was also a variable.
345 VarDecl *Old = dyn_cast<VarDecl>(OldD);
346 if (!Old) {
347 Diag(New->getLocation(), diag::err_redefinition_different_kind,
348 New->getName());
349 Diag(OldD->getLocation(), diag::err_previous_definition);
350 return New;
351 }
Chris Lattner402b3372008-03-03 03:28:21 +0000352
353 MergeAttributes(New, Old);
354
Chris Lattner4b009652007-07-25 00:24:17 +0000355 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000356 QualType OldCType = Context.getCanonicalType(Old->getType());
357 QualType NewCType = Context.getCanonicalType(New->getType());
358 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000359 Diag(New->getLocation(), diag::err_redefinition, New->getName());
360 Diag(Old->getLocation(), diag::err_previous_definition);
361 return New;
362 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000363 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
364 if (New->getStorageClass() == VarDecl::Static &&
365 (Old->getStorageClass() == VarDecl::None ||
366 Old->getStorageClass() == VarDecl::Extern)) {
367 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
368 Diag(Old->getLocation(), diag::err_previous_definition);
369 return New;
370 }
371 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
372 if (New->getStorageClass() != VarDecl::Static &&
373 Old->getStorageClass() == VarDecl::Static) {
374 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
375 Diag(Old->getLocation(), diag::err_previous_definition);
376 return New;
377 }
378 // We've verified the types match, now handle "tentative" definitions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000379 if (Old->isFileVarDecl() && New->isFileVarDecl()) {
Steve Naroffb00247f2008-01-30 00:44:01 +0000380 // Handle C "tentative" external object definitions (C99 6.9.2).
381 bool OldIsTentative = false;
382 bool NewIsTentative = false;
383
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000384 if (!Old->getInit() &&
385 (Old->getStorageClass() == VarDecl::None ||
386 Old->getStorageClass() == VarDecl::Static))
Steve Naroffb00247f2008-01-30 00:44:01 +0000387 OldIsTentative = true;
388
389 // FIXME: this check doesn't work (since the initializer hasn't been
390 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
391 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
392 // thrown out the old decl.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000393 if (!New->getInit() &&
394 (New->getStorageClass() == VarDecl::None ||
395 New->getStorageClass() == VarDecl::Static))
Steve Naroffb00247f2008-01-30 00:44:01 +0000396 ; // change to NewIsTentative = true; once the code is moved.
397
398 if (NewIsTentative || OldIsTentative)
399 return New;
400 }
401 if (Old->getStorageClass() != VarDecl::Extern &&
402 New->getStorageClass() != VarDecl::Extern) {
Chris Lattner4b009652007-07-25 00:24:17 +0000403 Diag(New->getLocation(), diag::err_redefinition, New->getName());
404 Diag(Old->getLocation(), diag::err_previous_definition);
405 }
406 return New;
407}
408
Chris Lattner3e254fb2008-04-08 04:40:51 +0000409/// CheckParmsForFunctionDef - Check that the parameters of the given
410/// function are appropriate for the definition of a function. This
411/// takes care of any checks that cannot be performed on the
412/// declaration itself, e.g., that the types of each of the function
413/// parameters are complete.
414bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
415 bool HasInvalidParm = false;
416 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
417 ParmVarDecl *Param = FD->getParamDecl(p);
418
419 // C99 6.7.5.3p4: the parameters in a parameter type list in a
420 // function declarator that is part of a function definition of
421 // that function shall not have incomplete type.
422 if (Param->getType()->isIncompleteType() &&
423 !Param->isInvalidDecl()) {
424 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
425 Param->getType().getAsString());
426 Param->setInvalidDecl();
427 HasInvalidParm = true;
428 }
429 }
430
431 return HasInvalidParm;
432}
433
434/// CreateImplicitParameter - Creates an implicit function parameter
435/// in the scope S and with the given type. This routine is used, for
436/// example, to create the implicit "self" parameter in an Objective-C
437/// method.
438ParmVarDecl *
439Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
440 SourceLocation IdLoc, QualType Type) {
441 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
442 VarDecl::None, 0, 0);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000443 if (Id)
444 PushOnScopeChains(New, S);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000445
446 return New;
447}
448
Chris Lattner4b009652007-07-25 00:24:17 +0000449/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
450/// no declarator (e.g. "struct foo;") is parsed.
451Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
452 // TODO: emit error on 'int;' or 'const enum foo;'.
453 // TODO: emit error on 'typedef int;'
454 // if (!DS.isMissingDeclaratorOk()) Diag(...);
455
Steve Naroffedafc0b2007-11-17 21:37:36 +0000456 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000457}
458
Steve Narofff0b23542008-01-10 22:15:12 +0000459bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000460 // Get the type before calling CheckSingleAssignmentConstraints(), since
461 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000462 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000463
Chris Lattner005ed752008-01-04 18:04:52 +0000464 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
465 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
466 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000467}
468
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000469bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Narofff0b23542008-01-10 22:15:12 +0000470 QualType ElementType) {
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000471 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Narofff0b23542008-01-10 22:15:12 +0000472 if (CheckSingleInitializer(expr, ElementType))
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000473 return true; // types weren't compatible.
474
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000475 if (savExpr != expr) // The type was promoted, update initializer list.
476 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000477 return false;
478}
479
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000480bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedman8ff07782008-02-15 18:16:39 +0000481 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000482 // C99 6.7.8p14. We have an array of character type with unknown size
483 // being initialized to a string literal.
484 llvm::APSInt ConstVal(32);
485 ConstVal = strLiteral->getByteLength() + 1;
486 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000487 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000488 ArrayType::Normal, 0);
489 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
490 // C99 6.7.8p14. We have an array of character type with known size.
491 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
492 Diag(strLiteral->getSourceRange().getBegin(),
493 diag::warn_initializer_string_for_char_array_too_long,
494 strLiteral->getSourceRange());
495 } else {
496 assert(0 && "HandleStringLiteralInit(): Invalid array type");
497 }
498 // Set type from "char *" to "constant array of char".
499 strLiteral->setType(DeclT);
500 // For now, we always return false (meaning success).
501 return false;
502}
503
504StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000505 const ArrayType *AT = DeclType->getAsArrayType();
Steve Narofff3cb5142008-01-25 00:51:06 +0000506 if (AT && AT->getElementType()->isCharType()) {
507 return dyn_cast<StringLiteral>(Init);
508 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000509 return 0;
510}
511
Steve Narofff3cb5142008-01-25 00:51:06 +0000512// CheckInitializerListTypes - Checks the types of elements of an initializer
513// list. This function is recursive: it calls itself to initialize subelements
514// of aggregate types. Note that the topLevel parameter essentially refers to
515// whether this expression "owns" the initializer list passed in, or if this
516// initialization is taking elements out of a parent initializer. Each
517// call to this function adds zero or more to startIndex, reports any errors,
518// and returns true if it found any inconsistent types.
519bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
520 bool topLevel, unsigned& startIndex) {
Steve Naroffcb69fb72007-12-10 22:44:33 +0000521 bool hadError = false;
Steve Narofff3cb5142008-01-25 00:51:06 +0000522
523 if (DeclType->isScalarType()) {
524 // The simplest case: initializing a single scalar
525 if (topLevel) {
526 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
527 IList->getSourceRange());
528 }
529 if (startIndex < IList->getNumInits()) {
530 Expr* expr = IList->getInit(startIndex);
531 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
532 // FIXME: Should an error be reported here instead?
533 unsigned newIndex = 0;
534 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
535 } else {
536 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
537 }
538 ++startIndex;
539 }
540 // FIXME: Should an error be reported for empty initializer list + scalar?
541 } else if (DeclType->isVectorType()) {
542 if (startIndex < IList->getNumInits()) {
543 const VectorType *VT = DeclType->getAsVectorType();
544 int maxElements = VT->getNumElements();
545 QualType elementType = VT->getElementType();
546
547 for (int i = 0; i < maxElements; ++i) {
548 // Don't attempt to go past the end of the init list
549 if (startIndex >= IList->getNumInits())
550 break;
551 Expr* expr = IList->getInit(startIndex);
552 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
553 unsigned newIndex = 0;
554 hadError |= CheckInitializerListTypes(SubInitList, elementType,
555 true, newIndex);
556 ++startIndex;
557 } else {
558 hadError |= CheckInitializerListTypes(IList, elementType,
559 false, startIndex);
560 }
561 }
562 }
563 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
564 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroffedce4ec2008-01-28 02:00:41 +0000565 if (startIndex < IList->getNumInits() && !topLevel &&
566 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
567 DeclType)) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000568 // We found a compatible struct; per the standard, this initializes the
569 // struct. (The C standard technically says that this only applies for
570 // initializers for declarations with automatic scope; however, this
571 // construct is unambiguous anyway because a struct cannot contain
572 // a type compatible with itself. We'll output an error when we check
573 // if the initializer is constant.)
574 // FIXME: Is a call to CheckSingleInitializer required here?
575 ++startIndex;
576 } else {
577 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffee467032008-02-11 00:06:17 +0000578
Steve Naroff576df292008-02-11 21:52:37 +0000579 // If the record is invalid, some of it's members are invalid. To avoid
580 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffee467032008-02-11 00:06:17 +0000581 if (structDecl->isInvalidDecl())
582 return true;
583
Steve Narofff3cb5142008-01-25 00:51:06 +0000584 // If structDecl is a forward declaration, this loop won't do anything;
585 // That's okay, because an error should get printed out elsewhere. It
586 // might be worthwhile to skip over the rest of the initializer, though.
587 int numMembers = structDecl->getNumMembers() -
588 structDecl->hasFlexibleArrayMember();
589 for (int i = 0; i < numMembers; i++) {
590 // Don't attempt to go past the end of the init list
591 if (startIndex >= IList->getNumInits())
592 break;
593 FieldDecl * curField = structDecl->getMember(i);
594 if (!curField->getIdentifier()) {
595 // Don't initialize unnamed fields, e.g. "int : 20;"
596 continue;
597 }
598 QualType fieldType = curField->getType();
599 Expr* expr = IList->getInit(startIndex);
600 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
601 unsigned newStart = 0;
602 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
603 true, newStart);
604 ++startIndex;
605 } else {
606 hadError |= CheckInitializerListTypes(IList, fieldType,
607 false, startIndex);
608 }
609 if (DeclType->isUnionType())
610 break;
611 }
612 // FIXME: Implement flexible array initialization GCC extension (it's a
613 // really messy extension to implement, unfortunately...the necessary
614 // information isn't actually even here!)
615 }
616 } else if (DeclType->isArrayType()) {
617 // Check for the special-case of initializing an array with a string.
618 if (startIndex < IList->getNumInits()) {
619 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
620 DeclType)) {
621 CheckStringLiteralInit(lit, DeclType);
622 ++startIndex;
623 if (topLevel && startIndex < IList->getNumInits()) {
624 // We have leftover initializers; warn
625 Diag(IList->getInit(startIndex)->getLocStart(),
626 diag::err_excess_initializers_in_char_array_initializer,
627 IList->getInit(startIndex)->getSourceRange());
628 }
629 return false;
630 }
631 }
632 int maxElements;
Eli Friedman8ff07782008-02-15 18:16:39 +0000633 if (DeclType->isIncompleteArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000634 // FIXME: use a proper constant
635 maxElements = 0x7FFFFFFF;
Chris Lattnerb9716a62008-02-20 23:17:35 +0000636 } else if (const VariableArrayType *VAT =
637 DeclType->getAsVariableArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000638 // Check for VLAs; in standard C it would be possible to check this
639 // earlier, but I don't know where clang accepts VLAs (gcc accepts
640 // them in all sorts of strange places).
Eli Friedman8ff07782008-02-15 18:16:39 +0000641 Diag(VAT->getSizeExpr()->getLocStart(),
642 diag::err_variable_object_no_init,
643 VAT->getSizeExpr()->getSourceRange());
644 hadError = true;
645 maxElements = 0x7FFFFFFF;
Steve Narofff3cb5142008-01-25 00:51:06 +0000646 } else {
647 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
648 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
649 }
650 QualType elementType = DeclType->getAsArrayType()->getElementType();
651 int numElements = 0;
652 for (int i = 0; i < maxElements; ++i, ++numElements) {
653 // Don't attempt to go past the end of the init list
654 if (startIndex >= IList->getNumInits())
655 break;
656 Expr* expr = IList->getInit(startIndex);
657 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
658 unsigned newIndex = 0;
659 hadError |= CheckInitializerListTypes(SubInitList, elementType,
660 true, newIndex);
661 ++startIndex;
662 } else {
663 hadError |= CheckInitializerListTypes(IList, elementType,
664 false, startIndex);
665 }
666 }
Eli Friedmane0079792008-02-15 12:53:51 +0000667 if (DeclType->isIncompleteArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000668 // If this is an incomplete array type, the actual type needs to
669 // be calculated here
670 if (numElements == 0) {
671 // Sizing an array implicitly to zero is not allowed
672 // (It could in theory be allowed, but it doesn't really matter.)
673 Diag(IList->getLocStart(),
674 diag::err_at_least_one_initializer_needed_to_size_array);
675 hadError = true;
676 } else {
677 llvm::APSInt ConstVal(32);
678 ConstVal = numElements;
679 DeclType = Context.getConstantArrayType(elementType, ConstVal,
680 ArrayType::Normal, 0);
681 }
682 }
683 } else {
684 assert(0 && "Aggregate that isn't a function or array?!");
685 }
686 } else {
687 // In C, all types are either scalars or aggregates, but
688 // additional handling is needed here for C++ (and possibly others?).
689 assert(0 && "Unsupported initializer type");
690 }
691
692 // If this init list is a base list, we set the type; an initializer doesn't
693 // fundamentally have a type, but this makes the ASTs a bit easier to read
694 if (topLevel)
695 IList->setType(DeclType);
696
697 if (topLevel && startIndex < IList->getNumInits()) {
698 // We have leftover initializers; warn
699 Diag(IList->getInit(startIndex)->getLocStart(),
700 diag::warn_excess_initializers,
701 IList->getInit(startIndex)->getSourceRange());
702 }
703 return hadError;
704}
705
706bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroff8e9337f2008-01-21 23:53:58 +0000707 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
708 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedman8ff07782008-02-15 18:16:39 +0000709 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroff8e9337f2008-01-21 23:53:58 +0000710 return Diag(VAT->getSizeExpr()->getLocStart(),
711 diag::err_variable_object_no_init,
712 VAT->getSizeExpr()->getSourceRange());
713
Steve Naroffcb69fb72007-12-10 22:44:33 +0000714 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
715 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000716 // FIXME: Handle wide strings
717 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
718 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000719
720 if (DeclType->isArrayType())
721 return Diag(Init->getLocStart(),
722 diag::err_array_init_list_required,
723 Init->getSourceRange());
724
Steve Narofff0b23542008-01-10 22:15:12 +0000725 return CheckSingleInitializer(Init, DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000726 }
Steve Narofff3cb5142008-01-25 00:51:06 +0000727 unsigned newIndex = 0;
728 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Naroffe14e5542007-09-02 02:04:30 +0000729}
730
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000731Sema::DeclTy *
Steve Naroff0acc9c92007-09-15 18:49:24 +0000732Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000733 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000734 IdentifierInfo *II = D.getIdentifier();
735
736 // All of these full declarators require an identifier. If it doesn't have
737 // one, the ParsedFreeStandingDeclSpec action should be used.
738 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000739 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000740 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000741 D.getDeclSpec().getSourceRange(), D.getSourceRange());
742 return 0;
743 }
744
Chris Lattnera7549902007-08-26 06:24:45 +0000745 // The scope passed in may not be a decl scope. Zip up the scope tree until
746 // we find one that is.
747 while ((S->getFlags() & Scope::DeclScope) == 0)
748 S = S->getParent();
749
Chris Lattner4b009652007-07-25 00:24:17 +0000750 // See if this is a redefinition of a variable in the same scope.
Steve Naroff6384a012008-04-02 14:35:35 +0000751 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000752 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000753 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000754
755 // In C++, the previous declaration we find might be a tag type
756 // (class or enum). In this case, the new declaration will hide the
757 // tag type.
758 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
759 PrevDecl = 0;
760
Chris Lattner82bb4792007-11-14 06:34:38 +0000761 QualType R = GetTypeForDeclarator(D, S);
762 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
763
Chris Lattner4b009652007-07-25 00:24:17 +0000764 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner82bb4792007-11-14 06:34:38 +0000765 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000766 if (!NewTD) return 0;
767
768 // Handle attributes prior to checking for duplicates in MergeVarDecl
769 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
770 D.getAttributes());
Steve Narofff8a09432008-01-09 23:34:55 +0000771 // Merge the decl with the existing one if appropriate. If the decl is
772 // in an outer scope, it isn't the same thing.
773 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000774 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
775 if (NewTD == 0) return 0;
776 }
777 New = NewTD;
778 if (S->getParent() == 0) {
779 // C99 6.7.7p2: If a typedef name specifies a variably modified type
780 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000781 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
782 // FIXME: Diagnostic needs to be fixed.
783 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff5eb879b2007-08-31 17:20:07 +0000784 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000785 }
786 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000787 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000788 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000789 switch (D.getDeclSpec().getStorageClassSpec()) {
790 default: assert(0 && "Unknown storage class!");
791 case DeclSpec::SCS_auto:
792 case DeclSpec::SCS_register:
793 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
794 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000795 InvalidDecl = true;
796 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000797 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
798 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
799 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000800 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000801 }
802
Chris Lattner4c7802b2008-03-15 21:24:04 +0000803 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattnereee57c02008-04-04 06:12:32 +0000804 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
805 D.getIdentifierLoc(),
Chris Lattner4c7802b2008-03-15 21:24:04 +0000806 II, R, SC, isInline,
807 LastDeclarator);
Ted Kremenek117f1862008-02-27 22:18:07 +0000808 // Handle attributes.
Ted Kremenek117f1862008-02-27 22:18:07 +0000809 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
810 D.getAttributes());
Chris Lattner3e254fb2008-04-08 04:40:51 +0000811
812 // Copy the parameter declarations from the declarator D to
813 // the function declaration NewFD, if they are available.
814 if (D.getNumTypeObjects() > 0 &&
815 D.getTypeObject(0).Fun.hasPrototype) {
816 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
817
818 // Create Decl objects for each parameter, adding them to the
819 // FunctionDecl.
820 llvm::SmallVector<ParmVarDecl*, 16> Params;
821
822 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
823 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +0000824 // single void argument.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000825 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
826 FTI.ArgInfo[0].Param &&
827 !((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
828 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
829 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +0000830 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
831
Chris Lattnerda7b5f02008-04-10 02:26:16 +0000832 // In C++, the empty parameter-type-list must be spelled "void"; a
833 // typedef of void is not permitted.
834 if (getLangOptions().CPlusPlus &&
Chris Lattner97316c02008-04-10 02:22:51 +0000835 Param->getType() != Context.VoidTy) {
836 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
837 }
838
Chris Lattner3e254fb2008-04-08 04:40:51 +0000839 } else {
840 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
841 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
842 }
843
844 NewFD->setParams(&Params[0], Params.size());
845 }
846
Steve Narofff8a09432008-01-09 23:34:55 +0000847 // Merge the decl with the existing one if appropriate. Since C functions
848 // are in a flat namespace, make sure we consider decls in outer scopes.
Chris Lattner4b009652007-07-25 00:24:17 +0000849 if (PrevDecl) {
850 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
851 if (NewFD == 0) return 0;
852 }
853 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000854
855 // In C++, check default arguments now that we have merged decls.
856 if (getLangOptions().CPlusPlus)
857 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +0000858 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +0000859 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000860 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
861 D.getIdentifier()->getName());
862 InvalidDecl = true;
863 }
Chris Lattner4b009652007-07-25 00:24:17 +0000864
865 VarDecl *NewVD;
866 VarDecl::StorageClass SC;
867 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +0000868 default: assert(0 && "Unknown storage class!");
869 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
870 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
871 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
872 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
873 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
874 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000875 }
876 if (S->getParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000877 // C99 6.9p2: The storage-class specifiers auto and register shall not
878 // appear in the declaration specifiers in an external declaration.
879 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
880 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
881 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000882 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000883 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000884 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
885 II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000886 } else {
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000887 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
888 II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000889 }
Chris Lattner4b009652007-07-25 00:24:17 +0000890 // Handle attributes prior to checking for duplicates in MergeVarDecl
891 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
892 D.getAttributes());
Nate Begemanea583262008-03-14 18:07:10 +0000893
894 // Emit an error if an address space was applied to decl with local storage.
895 // This includes arrays of objects with address space qualifiers, but not
896 // automatic variables that point to other address spaces.
897 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +0000898 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
899 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
900 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +0000901 }
Steve Narofff8a09432008-01-09 23:34:55 +0000902 // Merge the decl with the existing one if appropriate. If the decl is
903 // in an outer scope, it isn't the same thing.
904 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000905 NewVD = MergeVarDecl(NewVD, PrevDecl);
906 if (NewVD == 0) return 0;
907 }
Chris Lattner4b009652007-07-25 00:24:17 +0000908 New = NewVD;
909 }
910
911 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000912 if (II)
913 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000914 // If any semantic error occurred, mark the decl as invalid.
915 if (D.getInvalidType() || InvalidDecl)
916 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000917
918 return New;
919}
920
Steve Narofff0b23542008-01-10 22:15:12 +0000921bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
922 SourceLocation loc;
923 // FIXME: Remove the isReference check and handle assignment to a reference.
924 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
925 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
926 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
927 return true;
928 }
929 return false;
930}
931
Steve Naroff6a0e2092007-09-12 14:07:44 +0000932void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000933 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000934 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +0000935 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +0000936
Chris Lattnerf31a2fb2007-10-19 20:10:30 +0000937 // If there is no declaration, there was an error parsing it. Just ignore
938 // the initializer.
939 if (RealDecl == 0) {
940 delete Init;
941 return;
942 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000943
Steve Naroff420d0f52007-09-12 20:13:48 +0000944 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
945 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +0000946 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
947 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +0000948 RealDecl->setInvalidDecl();
949 return;
950 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000951 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +0000952 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +0000953 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000954 if (VDecl->isBlockVarDecl()) {
955 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +0000956 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +0000957 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000958 VDecl->setInvalidDecl();
959 } else if (!VDecl->isInvalidDecl()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000960 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000961 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +0000962 if (SC == VarDecl::Static) // C99 6.7.8p4.
963 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000964 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000965 } else if (VDecl->isFileVarDecl()) {
966 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +0000967 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000968 if (!VDecl->isInvalidDecl())
Steve Narofff3cb5142008-01-25 00:51:06 +0000969 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000970 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +0000971
972 // C99 6.7.8p4. All file scoped initializers need to be constant.
973 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000974 }
975 // If the type changed, it means we had an incomplete type that was
976 // completed by the initializer. For example:
977 // int ary[] = { 1, 3, 5 };
978 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +0000979 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000980 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +0000981 Init->setType(DclT);
982 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000983
984 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +0000985 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000986 return;
987}
988
Chris Lattner4b009652007-07-25 00:24:17 +0000989/// The declarators are chained together backwards, reverse the list.
990Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
991 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000992 Decl *GroupDecl = static_cast<Decl*>(group);
993 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +0000994 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +0000995
996 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
997 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000998 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000999 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001000 else { // reverse the list.
1001 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001002 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001003 Group->setNextDeclarator(NewGroup);
1004 NewGroup = Group;
1005 Group = Next;
1006 }
1007 }
1008 // Perform semantic analysis that depends on having fully processed both
1009 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001010 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00001011 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1012 if (!IDecl)
1013 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001014 QualType T = IDecl->getType();
1015
1016 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1017 // static storage duration, it shall not have a variable length array.
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001018 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1019 IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman70f414d2008-02-15 19:53:52 +00001020 if (T->getAsVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001021 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1022 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001023 }
1024 }
1025 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1026 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001027 if (IDecl->isBlockVarDecl() &&
1028 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001029 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +00001030 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1031 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001032 IDecl->setInvalidDecl();
1033 }
1034 }
1035 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1036 // object that has file scope without an initializer, and without a
1037 // storage-class specifier or with the storage-class specifier "static",
1038 // constitutes a tentative definition. Note: A tentative definition with
1039 // external linkage is valid (C99 6.2.2p5).
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001040 if (IDecl && !IDecl->getInit() &&
1041 (IDecl->getStorageClass() == VarDecl::Static ||
1042 IDecl->getStorageClass() == VarDecl::None)) {
Eli Friedmane0079792008-02-15 12:53:51 +00001043 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00001044 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1045 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001046 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00001047 // C99 6.9.2p3: If the declaration of an identifier for an object is
1048 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1049 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +00001050 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1051 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001052 IDecl->setInvalidDecl();
1053 }
1054 }
Chris Lattner4b009652007-07-25 00:24:17 +00001055 }
1056 return NewGroup;
1057}
Steve Naroff91b03f72007-08-28 03:03:08 +00001058
Chris Lattner3e254fb2008-04-08 04:40:51 +00001059/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1060/// to introduce parameters into function prototype scope.
1061Sema::DeclTy *
1062Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1063 DeclSpec &DS = D.getDeclSpec();
1064
1065 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1066 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1067 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1068 Diag(DS.getStorageClassSpecLoc(),
1069 diag::err_invalid_storage_class_in_func_decl);
1070 DS.ClearStorageClassSpecs();
1071 }
1072 if (DS.isThreadSpecified()) {
1073 Diag(DS.getThreadSpecLoc(),
1074 diag::err_invalid_storage_class_in_func_decl);
1075 DS.ClearStorageClassSpecs();
1076 }
1077
1078
1079 // In this context, we *do not* check D.getInvalidType(). If the declarator
1080 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1081 // though it will not reflect the user specified type.
1082 QualType parmDeclType = GetTypeForDeclarator(D, S);
1083
1084 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1085
Chris Lattner4b009652007-07-25 00:24:17 +00001086 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1087 // Can this happen for params? We already checked that they don't conflict
1088 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001089 IdentifierInfo *II = D.getIdentifier();
1090 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1091 if (S->isDeclScope(PrevDecl)) {
1092 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1093 dyn_cast<NamedDecl>(PrevDecl)->getName());
1094
1095 // Recover by removing the name
1096 II = 0;
1097 D.SetIdentifier(0, D.getIdentifierLoc());
1098 }
Chris Lattner4b009652007-07-25 00:24:17 +00001099 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00001100
1101 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1102 // Doing the promotion here has a win and a loss. The win is the type for
1103 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1104 // code generator). The loss is the orginal type isn't preserved. For example:
1105 //
1106 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1107 // int blockvardecl[5];
1108 // sizeof(parmvardecl); // size == 4
1109 // sizeof(blockvardecl); // size == 20
1110 // }
1111 //
1112 // For expressions, all implicit conversions are captured using the
1113 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1114 //
1115 // FIXME: If a source translation tool needs to see the original type, then
1116 // we need to consider storing both types (in ParmVarDecl)...
1117 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00001118 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00001119 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00001120 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00001121 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00001122 parmDeclType = Context.getPointerType(parmDeclType);
1123
Chris Lattner3e254fb2008-04-08 04:40:51 +00001124 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1125 D.getIdentifierLoc(), II,
1126 parmDeclType, VarDecl::None,
1127 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00001128
Chris Lattner3e254fb2008-04-08 04:40:51 +00001129 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00001130 New->setInvalidDecl();
1131
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001132 if (II)
1133 PushOnScopeChains(New, S);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00001134
Chris Lattner3e254fb2008-04-08 04:40:51 +00001135 HandleDeclAttributes(New, D.getAttributes(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001136 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001137
Chris Lattner4b009652007-07-25 00:24:17 +00001138}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001139
Chris Lattnerea148702007-10-09 17:14:05 +00001140Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +00001141 assert(CurFunctionDecl == 0 && "Function parsing confused");
1142 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1143 "Not a function declarator!");
1144 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001145
Chris Lattner4b009652007-07-25 00:24:17 +00001146 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1147 // for a K&R function.
1148 if (!FTI.hasPrototype) {
1149 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001150 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001151 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1152 FTI.ArgInfo[i].Ident->getName());
1153 // Implicitly declare the argument as type 'int' for lack of a better
1154 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001155 DeclSpec DS;
1156 const char* PrevSpec; // unused
1157 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1158 PrevSpec);
1159 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1160 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1161 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00001162 }
1163 }
Chris Lattnerec9361f2008-02-17 19:31:09 +00001164
Chris Lattner4b009652007-07-25 00:24:17 +00001165 // Since this is a function definition, act as though we have information
1166 // about the arguments.
Chris Lattnerec9361f2008-02-17 19:31:09 +00001167 if (FTI.NumArgs)
1168 FTI.hasPrototype = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001169 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001170 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00001171 }
1172
1173 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001174
1175 // See if this is a redefinition.
Steve Naroffe57c21a2008-04-01 23:04:06 +00001176 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroff6384a012008-04-02 14:35:35 +00001177 GlobalScope);
Steve Naroff1d5bd642008-01-14 20:51:29 +00001178 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1179 if (FD->getBody()) {
1180 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1181 D.getIdentifier()->getName());
1182 Diag(FD->getLocation(), diag::err_previous_definition);
1183 }
1184 }
Steve Naroff4a712442008-02-12 01:09:36 +00001185 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattner2d2216b2008-02-16 01:20:36 +00001186 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattner4b009652007-07-25 00:24:17 +00001187 CurFunctionDecl = FD;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001188 PushDeclContext(FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001189
1190 // Check the validity of our function parameters
1191 CheckParmsForFunctionDef(FD);
1192
1193 // Introduce our parameters into the function scope
1194 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1195 ParmVarDecl *Param = FD->getParamDecl(p);
1196 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001197 if (Param->getIdentifier())
1198 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001199 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001200
Chris Lattner4b009652007-07-25 00:24:17 +00001201 return FD;
1202}
1203
Steve Naroff99ee4302007-11-11 23:20:51 +00001204Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1205 Decl *dcl = static_cast<Decl *>(D);
1206 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1207 FD->setBody((Stmt*)Body);
1208 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff8ba51142007-12-13 18:18:56 +00001209 CurFunctionDecl = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001210 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001211 MD->setBody((Stmt*)Body);
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001212 CurMethodDecl = 0;
Steve Naroff8ba51142007-12-13 18:18:56 +00001213 }
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001214 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00001215 // Verify and clean out per-function state.
1216
1217 // Check goto/label use.
1218 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1219 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1220 // Verify that we have no forward references left. If so, there was a goto
1221 // or address of a label taken, but no definition of it. Label fwd
1222 // definitions are indicated with a null substmt.
1223 if (I->second->getSubStmt() == 0) {
1224 LabelStmt *L = I->second;
1225 // Emit error.
1226 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1227
1228 // At this point, we have gotos that use the bogus label. Stitch it into
1229 // the function body so that they aren't leaked and that the AST is well
1230 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00001231 if (Body) {
1232 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1233 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1234 } else {
1235 // The whole function wasn't parsed correctly, just delete this.
1236 delete L;
1237 }
Chris Lattner4b009652007-07-25 00:24:17 +00001238 }
1239 }
1240 LabelMap.clear();
1241
Steve Naroff99ee4302007-11-11 23:20:51 +00001242 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001243}
1244
Chris Lattner4b009652007-07-25 00:24:17 +00001245/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1246/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001247ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1248 IdentifierInfo &II, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +00001249 if (getLangOptions().C99) // Extension in C99.
1250 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1251 else // Legal in C90, but warn about it.
1252 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1253
1254 // FIXME: handle stuff like:
1255 // void foo() { extern float X(); }
1256 // void bar() { X(); } <-- implicit decl for X in another scope.
1257
1258 // Set a Declarator for the implicit definition: int foo();
1259 const char *Dummy;
1260 DeclSpec DS;
1261 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1262 Error = Error; // Silence warning.
1263 assert(!Error && "Error setting up implicit decl!");
1264 Declarator D(DS, Declarator::BlockContext);
1265 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1266 D.SetIdentifier(&II, Loc);
1267
1268 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +00001269 if (Scope *FnS = S->getFnParent())
1270 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +00001271 while (S->getParent())
1272 S = S->getParent();
1273
Steve Naroff9104f3c2008-04-04 14:32:09 +00001274 FunctionDecl *FD =
1275 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
1276 FD->setImplicit();
1277 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00001278}
1279
1280
Chris Lattner82bb4792007-11-14 06:34:38 +00001281TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00001282 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00001283 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001284 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00001285
1286 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00001287 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1288 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00001289 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00001290 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001291 if (D.getInvalidType())
1292 NewTD->setInvalidDecl();
1293 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00001294}
1295
Steve Naroff0acc9c92007-09-15 18:49:24 +00001296/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001297/// former case, Name will be non-null. In the later case, Name will be null.
1298/// TagType indicates what kind of tag this is. TK indicates whether this is a
1299/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001300Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001301 SourceLocation KWLoc, IdentifierInfo *Name,
1302 SourceLocation NameLoc, AttributeList *Attr) {
1303 // If this is a use of an existing tag, it must have a name.
1304 assert((Name != 0 || TK == TK_Definition) &&
1305 "Nameless record must be a definition!");
1306
1307 Decl::Kind Kind;
1308 switch (TagType) {
1309 default: assert(0 && "Unknown tag type!");
1310 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1311 case DeclSpec::TST_union: Kind = Decl::Union; break;
Chris Lattner2e78db32008-04-13 18:59:07 +00001312 case DeclSpec::TST_class: Kind = Decl::Class; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001313 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1314 }
1315
1316 // If this is a named struct, check to see if there was a previous forward
1317 // declaration or definition.
1318 if (TagDecl *PrevDecl =
Steve Naroff6384a012008-04-02 14:35:35 +00001319 dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Chris Lattner4b009652007-07-25 00:24:17 +00001320
1321 // If this is a use of a previous tag, or if the tag is already declared in
1322 // the same scope (so that the definition/declaration completes or
1323 // rementions the tag), reuse the decl.
1324 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1325 // Make sure that this wasn't declared as an enum and now used as a struct
1326 // or something similar.
1327 if (PrevDecl->getKind() != Kind) {
1328 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1329 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1330 }
1331
1332 // If this is a use or a forward declaration, we're good.
1333 if (TK != TK_Definition)
1334 return PrevDecl;
1335
1336 // Diagnose attempts to redefine a tag.
1337 if (PrevDecl->isDefinition()) {
1338 Diag(NameLoc, diag::err_redefinition, Name->getName());
1339 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1340 // If this is a redefinition, recover by making this struct be
1341 // anonymous, which will make any later references get the previous
1342 // definition.
1343 Name = 0;
1344 } else {
1345 // Okay, this is definition of a previously declared or referenced tag.
1346 // Move the location of the decl to be the definition site.
1347 PrevDecl->setLocation(NameLoc);
1348 return PrevDecl;
1349 }
1350 }
1351 // If we get here, this is a definition of a new struct type in a nested
1352 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1353 // type.
1354 }
1355
1356 // If there is an identifier, use the location of the identifier as the
1357 // location of the decl, otherwise use the location of the struct/union
1358 // keyword.
1359 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1360
1361 // Otherwise, if this is the first time we've seen this tag, create the decl.
1362 TagDecl *New;
1363 switch (Kind) {
1364 default: assert(0 && "Unknown tag kind!");
1365 case Decl::Enum:
1366 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1367 // enum X { A, B, C } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00001368 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001369 // If this is an undefined enum, warn.
1370 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1371 break;
1372 case Decl::Union:
1373 case Decl::Struct:
1374 case Decl::Class:
1375 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1376 // struct X { int A; } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00001377 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001378 break;
1379 }
1380
1381 // If this has an identifier, add it to the scope stack.
1382 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001383 // The scope passed in may not be a decl scope. Zip up the scope tree until
1384 // we find one that is.
1385 while ((S->getFlags() & Scope::DeclScope) == 0)
1386 S = S->getParent();
1387
1388 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001389 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00001390 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00001391
Anders Carlsson136cdc32008-02-16 00:29:18 +00001392 HandleDeclAttributes(New, Attr, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001393 return New;
1394}
1395
Steve Naroff0acc9c92007-09-15 18:49:24 +00001396/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001397/// to create a FieldDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001398Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner4b009652007-07-25 00:24:17 +00001399 SourceLocation DeclStart,
1400 Declarator &D, ExprTy *BitfieldWidth) {
1401 IdentifierInfo *II = D.getIdentifier();
1402 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001403 SourceLocation Loc = DeclStart;
1404 if (II) Loc = D.getIdentifierLoc();
1405
1406 // FIXME: Unnamed fields can be handled in various different ways, for
1407 // example, unnamed unions inject all members into the struct namespace!
1408
1409
1410 if (BitWidth) {
1411 // TODO: Validate.
1412 //printf("WARNING: BITFIELDS IGNORED!\n");
1413
1414 // 6.7.2.1p3
1415 // 6.7.2.1p4
1416
1417 } else {
1418 // Not a bitfield.
1419
1420 // validate II.
1421
1422 }
1423
1424 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001425 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1426 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001427
Chris Lattner4b009652007-07-25 00:24:17 +00001428 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1429 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00001430 if (T->isVariablyModifiedType()) {
1431 // FIXME: This diagnostic needs work
1432 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroff5eb879b2007-08-31 17:20:07 +00001433 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001434 }
Chris Lattner4b009652007-07-25 00:24:17 +00001435 // FIXME: Chain fielddecls together.
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001436 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff75494892007-09-11 21:17:26 +00001437
Anders Carlsson136cdc32008-02-16 00:29:18 +00001438 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1439 D.getAttributes());
1440
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001441 if (D.getInvalidType() || InvalidDecl)
1442 NewFD->setInvalidDecl();
1443 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001444}
1445
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001446/// TranslateIvarVisibility - Translate visibility from a token ID to an
1447/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00001448static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001449TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00001450 switch (ivarVisibility) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001451 case tok::objc_private: return ObjCIvarDecl::Private;
1452 case tok::objc_public: return ObjCIvarDecl::Public;
1453 case tok::objc_protected: return ObjCIvarDecl::Protected;
1454 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001455 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00001456 }
1457}
1458
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001459/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1460/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001461Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001462 SourceLocation DeclStart,
1463 Declarator &D, ExprTy *BitfieldWidth,
1464 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001465 IdentifierInfo *II = D.getIdentifier();
1466 Expr *BitWidth = (Expr*)BitfieldWidth;
1467 SourceLocation Loc = DeclStart;
1468 if (II) Loc = D.getIdentifierLoc();
1469
1470 // FIXME: Unnamed fields can be handled in various different ways, for
1471 // example, unnamed unions inject all members into the struct namespace!
1472
1473
1474 if (BitWidth) {
1475 // TODO: Validate.
1476 //printf("WARNING: BITFIELDS IGNORED!\n");
1477
1478 // 6.7.2.1p3
1479 // 6.7.2.1p4
1480
1481 } else {
1482 // Not a bitfield.
1483
1484 // validate II.
1485
1486 }
1487
1488 QualType T = GetTypeForDeclarator(D, S);
1489 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1490 bool InvalidDecl = false;
1491
1492 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1493 // than a variably modified type.
1494 if (T->isVariablyModifiedType()) {
1495 // FIXME: This diagnostic needs work
1496 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1497 InvalidDecl = true;
1498 }
1499
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001500 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001501
1502 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1503 D.getAttributes());
1504
1505 if (D.getInvalidType() || InvalidDecl)
1506 NewID->setInvalidDecl();
1507 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001508 if (Visibility != tok::objc_not_keyword)
1509 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001510 return NewID;
1511}
1512
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00001513void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001514 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001515 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001516 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001517 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1518 assert(EnclosingDecl && "missing record or interface decl");
1519 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1520
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001521 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001522 // Diagnose code like:
1523 // struct S { struct S {} X; };
1524 // We discover this when we complete the outer S. Reject and ignore the
1525 // outer S.
1526 Diag(Record->getLocation(), diag::err_nested_redefinition,
1527 Record->getKindName());
1528 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001529 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001530 return;
1531 }
Chris Lattner4b009652007-07-25 00:24:17 +00001532 // Verify that all the fields are okay.
1533 unsigned NumNamedMembers = 0;
1534 llvm::SmallVector<FieldDecl*, 32> RecFields;
1535 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00001536
Chris Lattner4b009652007-07-25 00:24:17 +00001537 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001538
Steve Naroff9bb759f2007-09-14 22:20:54 +00001539 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1540 assert(FD && "missing field decl");
1541
1542 // Remember all fields.
1543 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00001544
1545 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001546 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00001547
Chris Lattner4b009652007-07-25 00:24:17 +00001548 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001549 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001550 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00001551 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001552 FD->setInvalidDecl();
1553 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001554 continue;
1555 }
Chris Lattner4b009652007-07-25 00:24:17 +00001556 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1557 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001558 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001559 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001560 FD->setInvalidDecl();
1561 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001562 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001563 }
Chris Lattner4b009652007-07-25 00:24:17 +00001564 if (i != NumFields-1 || // ... that the last member ...
1565 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001566 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001567 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001568 FD->setInvalidDecl();
1569 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001570 continue;
1571 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001572 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00001573 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1574 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001575 FD->setInvalidDecl();
1576 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001577 continue;
1578 }
Chris Lattner4b009652007-07-25 00:24:17 +00001579 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001580 if (Record)
1581 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001582 }
Chris Lattner4b009652007-07-25 00:24:17 +00001583 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1584 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001585 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001586 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1587 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001588 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner4b009652007-07-25 00:24:17 +00001589 Record->setHasFlexibleArrayMember(true);
1590 } else {
1591 // If this is a struct/class and this is not the last element, reject
1592 // it. Note that GCC supports variable sized arrays in the middle of
1593 // structures.
1594 if (i != NumFields-1) {
1595 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1596 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001597 FD->setInvalidDecl();
1598 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001599 continue;
1600 }
Chris Lattner4b009652007-07-25 00:24:17 +00001601 // We support flexible arrays at the end of structs in other structs
1602 // as an extension.
1603 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1604 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001605 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001606 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001607 }
1608 }
1609 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001610 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00001611 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001612 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1613 FD->getName());
1614 FD->setInvalidDecl();
1615 EnclosingDecl->setInvalidDecl();
1616 continue;
1617 }
Chris Lattner4b009652007-07-25 00:24:17 +00001618 // Keep track of the number of named members.
1619 if (IdentifierInfo *II = FD->getIdentifier()) {
1620 // Detect duplicate member names.
1621 if (!FieldIDs.insert(II)) {
1622 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1623 // Find the previous decl.
1624 SourceLocation PrevLoc;
1625 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1626 assert(i != e && "Didn't find previous def!");
1627 if (RecFields[i]->getIdentifier() == II) {
1628 PrevLoc = RecFields[i]->getLocation();
1629 break;
1630 }
1631 }
1632 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001633 FD->setInvalidDecl();
1634 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001635 continue;
1636 }
1637 ++NumNamedMembers;
1638 }
Chris Lattner4b009652007-07-25 00:24:17 +00001639 }
1640
Chris Lattner4b009652007-07-25 00:24:17 +00001641 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00001642 if (Record) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001643 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattner33aad6e2008-02-06 00:51:33 +00001644 Consumer.HandleTagDeclDefinition(Record);
1645 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00001646 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1647 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1648 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1649 else if (ObjCImplementationDecl *IMPDecl =
1650 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001651 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1652 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00001653 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001654 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001655 }
Chris Lattner4b009652007-07-25 00:24:17 +00001656}
1657
Steve Naroff0acc9c92007-09-15 18:49:24 +00001658Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001659 DeclTy *lastEnumConst,
1660 SourceLocation IdLoc, IdentifierInfo *Id,
1661 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00001662 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00001663 EnumConstantDecl *LastEnumConst =
1664 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1665 Expr *Val = static_cast<Expr*>(val);
1666
Chris Lattnera7549902007-08-26 06:24:45 +00001667 // The scope passed in may not be a decl scope. Zip up the scope tree until
1668 // we find one that is.
1669 while ((S->getFlags() & Scope::DeclScope) == 0)
1670 S = S->getParent();
1671
Chris Lattner4b009652007-07-25 00:24:17 +00001672 // Verify that there isn't already something declared with this name in this
1673 // scope.
Steve Naroff6384a012008-04-02 14:35:35 +00001674 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001675 if (S->isDeclScope(PrevDecl)) {
1676 if (isa<EnumConstantDecl>(PrevDecl))
1677 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1678 else
1679 Diag(IdLoc, diag::err_redefinition, Id->getName());
1680 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001681 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00001682 return 0;
1683 }
1684 }
1685
1686 llvm::APSInt EnumVal(32);
1687 QualType EltTy;
1688 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001689 // Make sure to promote the operand type to int.
1690 UsualUnaryConversions(Val);
1691
Chris Lattner4b009652007-07-25 00:24:17 +00001692 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1693 SourceLocation ExpLoc;
1694 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1695 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1696 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001697 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001698 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001699 } else {
1700 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001701 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001702 }
1703
1704 if (!Val) {
1705 if (LastEnumConst) {
1706 // Assign the last value + 1.
1707 EnumVal = LastEnumConst->getInitVal();
1708 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001709
1710 // Check for overflow on increment.
1711 if (EnumVal < LastEnumConst->getInitVal())
1712 Diag(IdLoc, diag::warn_enum_value_overflow);
1713
Chris Lattnere7f53a42007-08-27 17:37:24 +00001714 EltTy = LastEnumConst->getType();
1715 } else {
1716 // First value, set to zero.
1717 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00001718 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001719 }
Chris Lattner4b009652007-07-25 00:24:17 +00001720 }
1721
Chris Lattnere4650482008-03-15 06:12:44 +00001722 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00001723 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
1724 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00001725 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00001726
1727 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001728 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00001729 return New;
1730}
1731
Steve Naroff0acc9c92007-09-15 18:49:24 +00001732void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00001733 DeclTy **Elements, unsigned NumElements) {
1734 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1735 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1736
Chris Lattner435c3fd2007-08-28 05:10:31 +00001737 // TODO: If the result value doesn't fit in an int, it must be a long or long
1738 // long value. ISO C does not support this, but GCC does as an extension,
1739 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001740 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00001741
Chris Lattner206754a2007-08-28 06:15:15 +00001742 // Verify that all the values are okay, compute the size of the values, and
1743 // reverse the list.
1744 unsigned NumNegativeBits = 0;
1745 unsigned NumPositiveBits = 0;
1746
1747 // Keep track of whether all elements have type int.
1748 bool AllElementsInt = true;
1749
Chris Lattner4b009652007-07-25 00:24:17 +00001750 EnumConstantDecl *EltList = 0;
1751 for (unsigned i = 0; i != NumElements; ++i) {
1752 EnumConstantDecl *ECD =
1753 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1754 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001755
1756 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001757 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001758 assert(InitVal.getBitWidth() >= IntWidth &&
1759 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00001760 if (InitVal.getBitWidth() > IntWidth) {
1761 llvm::APSInt V(InitVal);
1762 V.trunc(IntWidth);
1763 V.extend(InitVal.getBitWidth());
1764 if (V != InitVal)
1765 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1766 InitVal.toString());
1767 }
Chris Lattner206754a2007-08-28 06:15:15 +00001768
1769 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001770 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00001771 NumPositiveBits = std::max(NumPositiveBits,
1772 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00001773 else
Chris Lattneraff63f02008-01-14 21:47:29 +00001774 NumNegativeBits = std::max(NumNegativeBits,
1775 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001776
Chris Lattner206754a2007-08-28 06:15:15 +00001777 // Keep track of whether every enum element has type int (very commmon).
1778 if (AllElementsInt)
1779 AllElementsInt = ECD->getType() == Context.IntTy;
1780
Chris Lattner4b009652007-07-25 00:24:17 +00001781 ECD->setNextDeclarator(EltList);
1782 EltList = ECD;
1783 }
1784
Chris Lattner206754a2007-08-28 06:15:15 +00001785 // Figure out the type that should be used for this enum.
1786 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1787 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001788 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001789
1790 if (NumNegativeBits) {
1791 // If there is a negative value, figure out the smallest integer type (of
1792 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001793 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001794 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001795 BestWidth = IntWidth;
1796 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001797 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001798
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001799 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001800 BestType = Context.LongTy;
1801 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001802 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001803
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001804 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001805 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1806 BestType = Context.LongLongTy;
1807 }
1808 }
1809 } else {
1810 // If there is no negative value, figure out which of uint, ulong, ulonglong
1811 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001812 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001813 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001814 BestWidth = IntWidth;
1815 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00001816 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00001817 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00001818 } else {
1819 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001820 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001821 "How could an initializer get larger than ULL?");
1822 BestType = Context.UnsignedLongLongTy;
1823 }
1824 }
1825
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001826 // Loop over all of the enumerator constants, changing their types to match
1827 // the type of the enum if needed.
1828 for (unsigned i = 0; i != NumElements; ++i) {
1829 EnumConstantDecl *ECD =
1830 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1831 if (!ECD) continue; // Already issued a diagnostic.
1832
1833 // Standard C says the enumerators have int type, but we allow, as an
1834 // extension, the enumerators to be larger than int size. If each
1835 // enumerator value fits in an int, type it as an int, otherwise type it the
1836 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1837 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001838 if (ECD->getType() == Context.IntTy) {
1839 // Make sure the init value is signed.
1840 llvm::APSInt IV = ECD->getInitVal();
1841 IV.setIsSigned(true);
1842 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001843 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001844 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001845
1846 // Determine whether the value fits into an int.
1847 llvm::APSInt InitVal = ECD->getInitVal();
1848 bool FitsInInt;
1849 if (InitVal.isUnsigned() || !InitVal.isNegative())
1850 FitsInInt = InitVal.getActiveBits() < IntWidth;
1851 else
1852 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1853
1854 // If it fits into an integer type, force it. Otherwise force it to match
1855 // the enum decl type.
1856 QualType NewTy;
1857 unsigned NewWidth;
1858 bool NewSign;
1859 if (FitsInInt) {
1860 NewTy = Context.IntTy;
1861 NewWidth = IntWidth;
1862 NewSign = true;
1863 } else if (ECD->getType() == BestType) {
1864 // Already the right type!
1865 continue;
1866 } else {
1867 NewTy = BestType;
1868 NewWidth = BestWidth;
1869 NewSign = BestType->isSignedIntegerType();
1870 }
1871
1872 // Adjust the APSInt value.
1873 InitVal.extOrTrunc(NewWidth);
1874 InitVal.setIsSigned(NewSign);
1875 ECD->setInitVal(InitVal);
1876
1877 // Adjust the Expr initializer and type.
1878 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1879 ECD->setType(NewTy);
1880 }
Chris Lattner206754a2007-08-28 06:15:15 +00001881
Chris Lattner90a018d2007-08-28 18:24:31 +00001882 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00001883 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00001884}
1885
Anders Carlsson4f7f4412008-02-08 00:33:21 +00001886Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1887 ExprTy *expr) {
1888 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1889
Chris Lattner81db64a2008-03-16 00:16:02 +00001890 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00001891}
1892
Chris Lattner806a5f52008-01-12 07:05:38 +00001893Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00001894 SourceLocation LBrace,
1895 SourceLocation RBrace,
1896 const char *Lang,
1897 unsigned StrSize,
1898 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00001899 LinkageSpecDecl::LanguageIDs Language;
1900 Decl *dcl = static_cast<Decl *>(D);
1901 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1902 Language = LinkageSpecDecl::lang_c;
1903 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1904 Language = LinkageSpecDecl::lang_cxx;
1905 else {
1906 Diag(Loc, diag::err_bad_language);
1907 return 0;
1908 }
1909
1910 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00001911 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00001912}
1913
Chris Lattner49d15cb2008-02-21 00:48:22 +00001914void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson28e34e32007-12-19 06:16:30 +00001915
Chris Lattner49d15cb2008-02-21 00:48:22 +00001916 switch (Attr->getKind()) {
Chris Lattnerb9716a62008-02-20 23:17:35 +00001917 case AttributeList::AT_vector_size:
Chris Lattner4b009652007-07-25 00:24:17 +00001918 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner49d15cb2008-02-21 00:48:22 +00001919 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00001920 if (!newType.isNull()) // install the new vector type into the decl
1921 vDecl->setType(newType);
1922 }
1923 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1924 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00001925 Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00001926 if (!newType.isNull()) // install the new vector type into the decl
1927 tDecl->setUnderlyingType(newType);
1928 }
Chris Lattnerb9716a62008-02-20 23:17:35 +00001929 break;
1930 case AttributeList::AT_ocu_vector_type:
Steve Naroff82113e32007-07-29 16:33:31 +00001931 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Chris Lattner49d15cb2008-02-21 00:48:22 +00001932 HandleOCUVectorTypeAttribute(tDecl, Attr);
Steve Naroff82113e32007-07-29 16:33:31 +00001933 else
Chris Lattner49d15cb2008-02-21 00:48:22 +00001934 Diag(Attr->getLoc(),
Chris Lattner4b009652007-07-25 00:24:17 +00001935 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattnerb9716a62008-02-20 23:17:35 +00001936 break;
1937 case AttributeList::AT_address_space:
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001938 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1939 QualType newType = HandleAddressSpaceTypeAttribute(
1940 tDecl->getUnderlyingType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00001941 Attr);
1942 tDecl->setUnderlyingType(newType);
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001943 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1944 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00001945 Attr);
1946 // install the new addr spaced type into the decl
1947 vDecl->setType(newType);
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001948 }
Chris Lattnerb9716a62008-02-20 23:17:35 +00001949 break;
Chris Lattneree4c3bf2008-02-29 16:48:43 +00001950 case AttributeList::AT_deprecated:
Chris Lattner402b3372008-03-03 03:28:21 +00001951 HandleDeprecatedAttribute(New, Attr);
1952 break;
1953 case AttributeList::AT_visibility:
1954 HandleVisibilityAttribute(New, Attr);
1955 break;
1956 case AttributeList::AT_weak:
1957 HandleWeakAttribute(New, Attr);
1958 break;
1959 case AttributeList::AT_dllimport:
1960 HandleDLLImportAttribute(New, Attr);
1961 break;
1962 case AttributeList::AT_dllexport:
1963 HandleDLLExportAttribute(New, Attr);
1964 break;
1965 case AttributeList::AT_nothrow:
1966 HandleNothrowAttribute(New, Attr);
Chris Lattneree4c3bf2008-02-29 16:48:43 +00001967 break;
Nate Begemand75d28b2008-03-07 20:04:22 +00001968 case AttributeList::AT_stdcall:
1969 HandleStdCallAttribute(New, Attr);
1970 break;
1971 case AttributeList::AT_fastcall:
1972 HandleFastCallAttribute(New, Attr);
1973 break;
Chris Lattnerb9716a62008-02-20 23:17:35 +00001974 case AttributeList::AT_aligned:
Chris Lattner49d15cb2008-02-21 00:48:22 +00001975 HandleAlignedAttribute(New, Attr);
Chris Lattnerb9716a62008-02-20 23:17:35 +00001976 break;
1977 case AttributeList::AT_packed:
Chris Lattner49d15cb2008-02-21 00:48:22 +00001978 HandlePackedAttribute(New, Attr);
Chris Lattnerb9716a62008-02-20 23:17:35 +00001979 break;
Nate Begeman754d3fc2008-02-21 19:30:49 +00001980 case AttributeList::AT_annotate:
1981 HandleAnnotateAttribute(New, Attr);
1982 break;
Ted Kremenek13bfae62008-02-27 20:43:06 +00001983 case AttributeList::AT_noreturn:
1984 HandleNoReturnAttribute(New, Attr);
1985 break;
Chris Lattner402b3372008-03-03 03:28:21 +00001986 case AttributeList::AT_format:
1987 HandleFormatAttribute(New, Attr);
1988 break;
Chris Lattnerb9716a62008-02-20 23:17:35 +00001989 default:
Chris Lattneree4c3bf2008-02-29 16:48:43 +00001990#if 0
1991 // TODO: when we have the full set of attributes, warn about unknown ones.
1992 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
1993 Attr->getName()->getName());
1994#endif
Chris Lattnerb9716a62008-02-20 23:17:35 +00001995 break;
1996 }
Chris Lattner4b009652007-07-25 00:24:17 +00001997}
1998
1999void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2000 AttributeList *declarator_postfix) {
2001 while (declspec_prefix) {
2002 HandleDeclAttribute(New, declspec_prefix);
2003 declspec_prefix = declspec_prefix->getNext();
2004 }
2005 while (declarator_postfix) {
2006 HandleDeclAttribute(New, declarator_postfix);
2007 declarator_postfix = declarator_postfix->getNext();
2008 }
2009}
2010
Steve Naroff82113e32007-07-29 16:33:31 +00002011void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
2012 AttributeList *rawAttr) {
2013 QualType curType = tDecl->getUnderlyingType();
Anders Carlssonc8b44122007-12-19 07:19:40 +00002014 // check the attribute arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002015 if (rawAttr->getNumArgs() != 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00002016 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Chris Lattner4b009652007-07-25 00:24:17 +00002017 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00002018 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002019 }
2020 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2021 llvm::APSInt vecSize(32);
2022 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00002023 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson7dce0292008-02-16 19:51:27 +00002024 "ocu_vector_type", sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00002025 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002026 }
2027 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2028 // in conjunction with complex types (pointers, arrays, functions, etc.).
2029 Type *canonType = curType.getCanonicalType().getTypePtr();
2030 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner9384f502008-02-20 23:25:22 +00002031 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Chris Lattner4b009652007-07-25 00:24:17 +00002032 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00002033 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002034 }
2035 // unlike gcc's vector_size attribute, the size is specified as the
2036 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00002037 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00002038
2039 if (vectorSize == 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00002040 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Chris Lattner4b009652007-07-25 00:24:17 +00002041 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00002042 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002043 }
Steve Naroff82113e32007-07-29 16:33:31 +00002044 // Instantiate/Install the vector type, the number of elements is > 0.
2045 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
2046 // Remember this typedef decl, we will need it later for diagnostics.
2047 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002048}
2049
2050QualType Sema::HandleVectorTypeAttribute(QualType curType,
2051 AttributeList *rawAttr) {
2052 // check the attribute arugments.
2053 if (rawAttr->getNumArgs() != 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00002054 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Chris Lattner4b009652007-07-25 00:24:17 +00002055 std::string("1"));
2056 return QualType();
2057 }
2058 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2059 llvm::APSInt vecSize(32);
2060 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00002061 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson7dce0292008-02-16 19:51:27 +00002062 "vector_size", sizeExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002063 return QualType();
2064 }
2065 // navigate to the base type - we need to provide for vector pointers,
2066 // vector arrays, and functions returning vectors.
2067 Type *canonType = curType.getCanonicalType().getTypePtr();
2068
2069 if (canonType->isPointerType() || canonType->isArrayType() ||
2070 canonType->isFunctionType()) {
Chris Lattner5b5e1982007-12-19 05:38:06 +00002071 assert(0 && "HandleVector(): Complex type construction unimplemented");
Chris Lattner4b009652007-07-25 00:24:17 +00002072 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2073 do {
2074 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2075 canonType = PT->getPointeeType().getTypePtr();
2076 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2077 canonType = AT->getElementType().getTypePtr();
2078 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2079 canonType = FT->getResultType().getTypePtr();
2080 } while (canonType->isPointerType() || canonType->isArrayType() ||
2081 canonType->isFunctionType());
2082 */
2083 }
2084 // the base type must be integer or float.
2085 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner9384f502008-02-20 23:25:22 +00002086 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Chris Lattner4b009652007-07-25 00:24:17 +00002087 curType.getCanonicalType().getAsString());
2088 return QualType();
2089 }
Chris Lattner8cd0e932008-03-05 18:54:05 +00002090 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Chris Lattner4b009652007-07-25 00:24:17 +00002091 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00002092 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00002093
2094 // the vector size needs to be an integral multiple of the type size.
2095 if (vectorSize % typeSize) {
Chris Lattner9384f502008-02-20 23:25:22 +00002096 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Chris Lattner4b009652007-07-25 00:24:17 +00002097 sizeExpr->getSourceRange());
2098 return QualType();
2099 }
2100 if (vectorSize == 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00002101 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Chris Lattner4b009652007-07-25 00:24:17 +00002102 sizeExpr->getSourceRange());
2103 return QualType();
2104 }
Nate Begeman754d3fc2008-02-21 19:30:49 +00002105 // Instantiate the vector type, the number of elements is > 0, and not
2106 // required to be a power of 2, unlike GCC.
Chris Lattner4b009652007-07-25 00:24:17 +00002107 return Context.getVectorType(curType, vectorSize/typeSize);
2108}
2109
Chris Lattner9384f502008-02-20 23:25:22 +00002110void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlsson136cdc32008-02-16 00:29:18 +00002111 // check the attribute arguments.
2112 if (rawAttr->getNumArgs() > 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00002113 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson136cdc32008-02-16 00:29:18 +00002114 std::string("0"));
2115 return;
2116 }
2117
2118 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2119 TD->addAttr(new PackedAttr);
2120 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2121 // If the alignment is less than or equal to 8 bits, the packed attribute
2122 // has no effect.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002123 if (Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner9384f502008-02-20 23:25:22 +00002124 Diag(rawAttr->getLoc(),
Anders Carlsson136cdc32008-02-16 00:29:18 +00002125 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner9384f502008-02-20 23:25:22 +00002126 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlsson136cdc32008-02-16 00:29:18 +00002127 else
Anders Carlssonca133d92008-02-16 00:39:40 +00002128 FD->addAttr(new PackedAttr);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002129 } else
Chris Lattner9384f502008-02-20 23:25:22 +00002130 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2131 rawAttr->getName()->getName());
Anders Carlsson136cdc32008-02-16 00:29:18 +00002132}
Nate Begeman754d3fc2008-02-21 19:30:49 +00002133
Ted Kremenek13bfae62008-02-27 20:43:06 +00002134void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2135 // check the attribute arguments.
2136 if (rawAttr->getNumArgs() != 0) {
2137 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2138 std::string("0"));
2139 return;
2140 }
2141
Ted Kremenek40b95e52008-03-03 16:52:27 +00002142 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2143
2144 if (!Fn) {
2145 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2146 "noreturn", "function");
2147 return;
2148 }
2149
Ted Kremenek13bfae62008-02-27 20:43:06 +00002150 d->addAttr(new NoReturnAttr());
2151}
2152
Chris Lattner402b3372008-03-03 03:28:21 +00002153void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2154 // check the attribute arguments.
2155 if (rawAttr->getNumArgs() != 0) {
2156 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2157 std::string("0"));
2158 return;
2159 }
2160
2161 d->addAttr(new DeprecatedAttr());
2162}
2163
2164void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2165 // check the attribute arguments.
Chris Lattnere9d83be2008-03-04 18:08:48 +00002166 if (rawAttr->getNumArgs() != 1) {
Chris Lattner402b3372008-03-03 03:28:21 +00002167 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2168 std::string("1"));
2169 return;
2170 }
2171
Chris Lattnere9d83be2008-03-04 18:08:48 +00002172 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2173 Arg = Arg->IgnoreParenCasts();
2174 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2175
2176 if (Str == 0 || Str->isWide()) {
Chris Lattner402b3372008-03-03 03:28:21 +00002177 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattnere9d83be2008-03-04 18:08:48 +00002178 "visibility", std::string("1"));
Chris Lattner402b3372008-03-03 03:28:21 +00002179 return;
2180 }
2181
Chris Lattnere9d83be2008-03-04 18:08:48 +00002182 const char *TypeStr = Str->getStrData();
2183 unsigned TypeLen = Str->getByteLength();
Chris Lattner402b3372008-03-03 03:28:21 +00002184 llvm::GlobalValue::VisibilityTypes type;
2185
Chris Lattnere9d83be2008-03-04 18:08:48 +00002186 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Chris Lattner402b3372008-03-03 03:28:21 +00002187 type = llvm::GlobalValue::DefaultVisibility;
Chris Lattnere9d83be2008-03-04 18:08:48 +00002188 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Chris Lattner402b3372008-03-03 03:28:21 +00002189 type = llvm::GlobalValue::HiddenVisibility;
Chris Lattnere9d83be2008-03-04 18:08:48 +00002190 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Chris Lattner402b3372008-03-03 03:28:21 +00002191 type = llvm::GlobalValue::HiddenVisibility; // FIXME
Chris Lattnere9d83be2008-03-04 18:08:48 +00002192 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Chris Lattner402b3372008-03-03 03:28:21 +00002193 type = llvm::GlobalValue::ProtectedVisibility;
2194 else {
2195 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattnere9d83be2008-03-04 18:08:48 +00002196 "visibility", TypeStr);
Chris Lattner402b3372008-03-03 03:28:21 +00002197 return;
2198 }
2199
2200 d->addAttr(new VisibilityAttr(type));
2201}
2202
2203void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2204 // check the attribute arguments.
2205 if (rawAttr->getNumArgs() != 0) {
2206 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2207 std::string("0"));
2208 return;
2209 }
2210
2211 d->addAttr(new WeakAttr());
2212}
2213
2214void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2215 // check the attribute arguments.
2216 if (rawAttr->getNumArgs() != 0) {
2217 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2218 std::string("0"));
2219 return;
2220 }
2221
2222 d->addAttr(new DLLImportAttr());
2223}
2224
2225void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2226 // check the attribute arguments.
2227 if (rawAttr->getNumArgs() != 0) {
2228 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2229 std::string("0"));
2230 return;
2231 }
2232
2233 d->addAttr(new DLLExportAttr());
2234}
2235
Nate Begemand75d28b2008-03-07 20:04:22 +00002236void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2237 // check the attribute arguments.
2238 if (rawAttr->getNumArgs() != 0) {
2239 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2240 std::string("0"));
2241 return;
2242 }
2243
2244 d->addAttr(new StdCallAttr());
2245}
2246
2247void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2248 // check the attribute arguments.
2249 if (rawAttr->getNumArgs() != 0) {
2250 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2251 std::string("0"));
2252 return;
2253 }
2254
2255 d->addAttr(new FastCallAttr());
2256}
2257
Chris Lattner402b3372008-03-03 03:28:21 +00002258void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2259 // check the attribute arguments.
2260 if (rawAttr->getNumArgs() != 0) {
2261 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2262 std::string("0"));
2263 return;
2264 }
2265
2266 d->addAttr(new NoThrowAttr());
2267}
2268
Nuno Lopes02564e52008-03-25 23:01:48 +00002269static const FunctionTypeProto *getFunctionProto(Decl *d) {
2270 ValueDecl *decl = dyn_cast<ValueDecl>(d);
2271 if (!decl) return 0;
2272
2273 QualType Ty = decl->getType();
2274
2275 if (Ty->isFunctionPointerType()) {
2276 const PointerType *PtrTy = Ty->getAsPointerType();
2277 Ty = PtrTy->getPointeeType();
2278 }
2279
2280 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2281 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2282
2283 return 0;
2284}
2285
2286
Ted Kremeneke5769412008-03-07 18:43:49 +00002287/// Handle __attribute__((format(type,idx,firstarg))) attributes
2288/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattner402b3372008-03-03 03:28:21 +00002289void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2290
2291 if (!rawAttr->getParameterName()) {
2292 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2293 "format", std::string("1"));
2294 return;
2295 }
2296
2297 if (rawAttr->getNumArgs() != 2) {
2298 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2299 std::string("3"));
2300 return;
2301 }
2302
Nuno Lopes02564e52008-03-25 23:01:48 +00002303 // GCC ignores the format attribute on K&R style function
2304 // prototypes, so we ignore it as well
2305 const FunctionTypeProto *proto = getFunctionProto(d);
2306
2307 if (!proto) {
Chris Lattner402b3372008-03-03 03:28:21 +00002308 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2309 "format", "function");
2310 return;
2311 }
2312
2313 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremeneke5769412008-03-07 18:43:49 +00002314 // this is needed in order to be compatible with GCC
Chris Lattner402b3372008-03-03 03:28:21 +00002315 // the index must start in 1 and the limit is numargs+1
Nuno Lopes02564e52008-03-25 23:01:48 +00002316 unsigned NumArgs = proto->getNumArgs();
Ted Kremeneke5769412008-03-07 18:43:49 +00002317 unsigned FirstIdx = 1;
Chris Lattner402b3372008-03-03 03:28:21 +00002318
2319 const char *Format = rawAttr->getParameterName()->getName();
2320 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2321
2322 // Normalize the argument, __foo__ becomes foo.
2323 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2324 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2325 Format += 2;
2326 FormatLen -= 4;
2327 }
2328
2329 if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2330 || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2331 || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2332 || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2333 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2334 "format", rawAttr->getParameterName()->getName());
2335 return;
2336 }
2337
Ted Kremeneke5769412008-03-07 18:43:49 +00002338 // checks for the 2nd argument
Chris Lattner402b3372008-03-03 03:28:21 +00002339 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremeneke5769412008-03-07 18:43:49 +00002340 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattner402b3372008-03-03 03:28:21 +00002341 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2342 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2343 "format", std::string("2"), IdxExpr->getSourceRange());
2344 return;
2345 }
2346
Ted Kremeneke5769412008-03-07 18:43:49 +00002347 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattner402b3372008-03-03 03:28:21 +00002348 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2349 "format", std::string("2"), IdxExpr->getSourceRange());
2350 return;
2351 }
2352
Ted Kremeneke5769412008-03-07 18:43:49 +00002353 // make sure the format string is really a string
2354 QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2355 if (!Ty->isPointerType() ||
2356 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2357 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2358 IdxExpr->getSourceRange());
2359 return;
2360 }
2361
2362
2363 // check the 3rd argument
Chris Lattner402b3372008-03-03 03:28:21 +00002364 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremeneke5769412008-03-07 18:43:49 +00002365 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattner402b3372008-03-03 03:28:21 +00002366 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2367 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2368 "format", std::string("3"), FirstArgExpr->getSourceRange());
2369 return;
2370 }
2371
Ted Kremeneke5769412008-03-07 18:43:49 +00002372 // check if the function is variadic if the 3rd argument non-zero
2373 if (FirstArg != 0) {
2374 if (proto->isVariadic()) {
2375 ++NumArgs; // +1 for ...
2376 } else {
2377 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2378 return;
2379 }
2380 }
2381
2382 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2383 // the input is just the current time + the format string
Chris Lattner402b3372008-03-03 03:28:21 +00002384 if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
Ted Kremeneke5769412008-03-07 18:43:49 +00002385 if (FirstArg != 0) {
Chris Lattner402b3372008-03-03 03:28:21 +00002386 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2387 FirstArgExpr->getSourceRange());
2388 return;
2389 }
Ted Kremeneke5769412008-03-07 18:43:49 +00002390 // if 0 it disables parameter checking (to use with e.g. va_list)
2391 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattner402b3372008-03-03 03:28:21 +00002392 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2393 "format", std::string("3"), FirstArgExpr->getSourceRange());
2394 return;
2395 }
2396
2397 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2398 Idx.getZExtValue(), FirstArg.getZExtValue()));
2399}
2400
Nate Begeman754d3fc2008-02-21 19:30:49 +00002401void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2402 // check the attribute arguments.
2403 if (rawAttr->getNumArgs() != 1) {
2404 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2405 std::string("1"));
2406 return;
2407 }
2408 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2409 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002410
Nate Begeman754d3fc2008-02-21 19:30:49 +00002411 // Make sure that there is a string literal as the annotation's single
2412 // argument.
2413 if (!SE) {
2414 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2415 return;
2416 }
2417 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2418 SE->getByteLength())));
2419}
2420
Anders Carlssonc8b44122007-12-19 07:19:40 +00002421void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2422{
2423 // check the attribute arguments.
Eli Friedman74820702008-01-30 17:38:42 +00002424 if (rawAttr->getNumArgs() > 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00002425 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonc8b44122007-12-19 07:19:40 +00002426 std::string("1"));
2427 return;
2428 }
Eli Friedman74820702008-01-30 17:38:42 +00002429
Anders Carlsson7dce0292008-02-16 19:51:27 +00002430 unsigned Align = 0;
2431
2432 if (rawAttr->getNumArgs() == 0) {
2433 // FIXME: This should be the target specific maximum alignment.
2434 // (For now we just use 128 bits which is the maximum on X86.
2435 Align = 128;
Eli Friedman74820702008-01-30 17:38:42 +00002436 return;
Anders Carlsson7dce0292008-02-16 19:51:27 +00002437 } else {
2438 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2439 llvm::APSInt alignment(32);
2440 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00002441 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson7dce0292008-02-16 19:51:27 +00002442 "aligned", alignmentExpr->getSourceRange());
2443 return;
2444 }
2445
2446 Align = alignment.getZExtValue() * 8;
2447 }
Eli Friedman74820702008-01-30 17:38:42 +00002448
Anders Carlsson7dce0292008-02-16 19:51:27 +00002449 d->addAttr(new AlignedAttr(Align));
Anders Carlssonc8b44122007-12-19 07:19:40 +00002450}