blob: 882ec0e1a449a901bdd908828374527028e6779b [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
Anders Carlssonf78915f2008-02-15 07:04:12 +000017#include "clang/AST/Attr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/Builtins.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/Type.h"
22#include "clang/Parse/DeclSpec.h"
23#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Basic/SourceManager.h"
27// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000028#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000029#include "clang/Lex/HeaderSearch.h"
Steve Naroff563477d2007-09-18 23:55:05 +000030#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000032#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
34
Steve Naroffb327ce02008-04-02 14:35:35 +000035Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
36 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
37
38 if (IIDecl && (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000039 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000040 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000041}
42
Chris Lattner0ed844b2008-04-04 06:12:32 +000043void Sema::PushContextDecl(ContextDecl *CD) {
44 assert(CD->getParent() == CurContext &&
45 "The next ContextDecl should be directly contained in the current one.");
46 CurContext = CD;
47}
48
49void Sema::PopContextDecl() {
50 assert(CurContext && "ContextDecl imbalance!");
51 CurContext = CurContext->getParent();
52}
53
Steve Naroffb216c882007-10-09 22:01:59 +000054void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000055 if (S->decl_empty()) return;
56 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
57
Reid Spencer5f016e22007-07-11 17:01:13 +000058 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
59 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000060 Decl *TmpD = static_cast<Decl*>(*I);
61 assert(TmpD && "This decl didn't get pushed??");
62 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
63 assert(D && "This decl isn't a ScopedDecl?");
64
Reid Spencer5f016e22007-07-11 17:01:13 +000065 IdentifierInfo *II = D->getIdentifier();
66 if (!II) continue;
67
68 // Unlink this decl from the identifier. Because the scope contains decls
69 // in an unordered collection, and because we have multiple identifier
70 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
71 if (II->getFETokenInfo<Decl>() == D) {
72 // Normal case, no multiple decls in different namespaces.
73 II->setFETokenInfo(D->getNext());
74 } else {
75 // Scan ahead. There are only three namespaces in C, so this loop can
76 // never execute more than 3 times.
Steve Naroffc752d042007-09-13 18:10:37 +000077 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +000078 while (SomeDecl->getNext() != D) {
79 SomeDecl = SomeDecl->getNext();
80 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
81 }
82 SomeDecl->setNext(D->getNext());
83 }
84
85 // This will have to be revisited for C++: there we want to nest stuff in
86 // namespace decls etc. Even for C, we might want a top-level translation
87 // unit decl or something.
88 if (!CurFunctionDecl)
89 continue;
90
91 // Chain this decl to the containing function, it now owns the memory for
92 // the decl.
93 D->setNext(CurFunctionDecl->getDeclChain());
94 CurFunctionDecl->setDeclChain(D);
95 }
96}
97
Steve Naroffe8043c32008-04-01 23:04:06 +000098/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
99/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000100ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000101 // The third "scope" argument is 0 since we aren't enabling lazy built-in
102 // creation from this context.
103 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000104
Steve Naroffb327ce02008-04-02 14:35:35 +0000105 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000106}
107
Steve Naroffe8043c32008-04-01 23:04:06 +0000108/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000109/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000110Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
111 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000112 if (II == 0) return 0;
113 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
114
115 // Scan up the scope chain looking for a decl that matches this identifier
116 // that is in the appropriate namespace. This search should not take long, as
117 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffc752d042007-09-13 18:10:37 +0000118 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 if (D->getIdentifierNamespace() == NS)
120 return D;
121
122 // If we didn't find a use of this identifier, and if the identifier
123 // corresponds to a compiler builtin, create the decl object for the builtin
124 // now, injecting it into translation unit scope, and return it.
125 if (NS == Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000126 if (enableLazyBuiltinCreation) {
127 // If this is a builtin on this (or all) targets, create the decl.
128 if (unsigned BuiltinID = II->getBuiltinID())
129 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
130 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000131 if (getLangOptions().ObjC1) {
132 // @interface and @compatibility_alias introduce typedef-like names.
133 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000134 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000135 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000136 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
137 if (IDI != ObjCInterfaceDecls.end())
138 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000139 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
140 if (I != ObjCAliasDecls.end())
141 return I->second->getClassInterface();
142 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 }
144 return 0;
145}
146
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000147void Sema::InitBuiltinVaListType()
148{
149 if (!Context.getBuiltinVaListType().isNull())
150 return;
151
152 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000153 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000154 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000155 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
156}
157
Reid Spencer5f016e22007-07-11 17:01:13 +0000158/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
159/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000160ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
161 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000162 Builtin::ID BID = (Builtin::ID)bid;
163
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000164 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson793680e2007-10-12 23:56:29 +0000165 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000166 BID == Builtin::BI__builtin_va_end)
167 InitBuiltinVaListType();
168
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000169 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000170 FunctionDecl *New = FunctionDecl::Create(Context, CurContext,
171 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000172 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000173
174 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000175 if (Scope *FnS = S->getFnParent())
176 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000177 while (S->getParent())
178 S = S->getParent();
179 S->AddDecl(New);
180
181 // Add this decl to the end of the identifier info.
Steve Naroffc752d042007-09-13 18:10:37 +0000182 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 // Scan until we find the last (outermost) decl in the id chain.
184 while (LastDecl->getNext())
185 LastDecl = LastDecl->getNext();
186 // Insert before (outside) it.
187 LastDecl->setNext(New);
188 } else {
189 II->setFETokenInfo(New);
190 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 return New;
192}
193
194/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
195/// and scope as a previous declaration 'Old'. Figure out how to resolve this
196/// situation, merging decls or emitting diagnostics as appropriate.
197///
Steve Naroffe8043c32008-04-01 23:04:06 +0000198TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000199 // Verify the old decl was also a typedef.
200 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
201 if (!Old) {
202 Diag(New->getLocation(), diag::err_redefinition_different_kind,
203 New->getName());
204 Diag(OldD->getLocation(), diag::err_previous_definition);
205 return New;
206 }
207
Steve Naroff8ee529b2007-10-31 18:42:27 +0000208 // Allow multiple definitions for ObjC built-in typedefs.
209 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000210 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000211 return Old;
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000212
213 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
214 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
215 // *either* declaration is in a system header. The code below implements
216 // this adhoc compatibility rule. FIXME: The following code will not
217 // work properly when compiling ".i" files (containing preprocessed output).
218 SourceManager &SrcMgr = Context.getSourceManager();
219 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
220 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
221 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
222 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
223 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
224
Steve Naroffc5e2f342008-03-26 21:27:00 +0000225 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
226 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
227 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroffd62701b2008-02-07 03:50:06 +0000228 getLangOptions().Microsoft)
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000229 return New;
Steve Naroffc5e2f342008-03-26 21:27:00 +0000230
Reid Spencer5f016e22007-07-11 17:01:13 +0000231 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
232 // TODO: This is totally simplistic. It should handle merging functions
233 // together etc, merging extern int X; int X; ...
234 Diag(New->getLocation(), diag::err_redefinition, New->getName());
235 Diag(Old->getLocation(), diag::err_previous_definition);
236 return New;
237}
238
Chris Lattnerddee4232008-03-03 03:28:21 +0000239/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
240static bool DeclHasAttr(const Decl *decl, const Attr *target) {
241 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
242 if (attr->getKind() == target->getKind())
243 return true;
244
245 return false;
246}
247
248/// MergeAttributes - append attributes from the Old decl to the New one.
249static void MergeAttributes(Decl *New, Decl *Old) {
250 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
251
252// FIXME: fix this code to cleanup the Old attrs correctly
253 while (attr) {
254 tmp = attr;
255 attr = attr->getNext();
256
257 if (!DeclHasAttr(New, tmp)) {
258 New->addAttr(tmp);
259 } else {
260 tmp->setNext(0);
261 delete(tmp);
262 }
263 }
264}
265
Reid Spencer5f016e22007-07-11 17:01:13 +0000266/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
267/// and scope as a previous declaration 'Old'. Figure out how to resolve this
268/// situation, merging decls or emitting diagnostics as appropriate.
269///
Steve Naroffe8043c32008-04-01 23:04:06 +0000270FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000271 // Verify the old decl was also a function.
272 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
273 if (!Old) {
274 Diag(New->getLocation(), diag::err_redefinition_different_kind,
275 New->getName());
276 Diag(OldD->getLocation(), diag::err_previous_definition);
277 return New;
278 }
Chris Lattner7e669b22008-02-29 16:48:43 +0000279
Chris Lattnerddee4232008-03-03 03:28:21 +0000280 MergeAttributes(New, Old);
281
Reid Spencer5f016e22007-07-11 17:01:13 +0000282
Chris Lattner55196442007-11-20 19:04:50 +0000283 QualType OldQType = Old->getCanonicalType();
284 QualType NewQType = New->getCanonicalType();
285
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000286 // Function types need to be compatible, not identical. This handles
287 // duplicate function decls like "void f(int); void f(enum X);" properly.
288 if (Context.functionTypesAreCompatible(OldQType, NewQType))
289 return New;
Chris Lattnere3995fe2007-11-06 06:07:26 +0000290
Steve Naroff837618c2008-01-16 15:01:34 +0000291 // A function that has already been declared has been redeclared or defined
292 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000293 diag::kind PrevDiag;
294 if (Old->getBody())
295 PrevDiag = diag::err_previous_definition;
296 else if (Old->isImplicit())
297 PrevDiag = diag::err_previous_implicit_declaration;
298 else
299 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000300
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
302 // TODO: This is totally simplistic. It should handle merging functions
303 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000304 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
305 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000306 return New;
307}
308
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000309/// equivalentArrayTypes - Used to determine whether two array types are
310/// equivalent.
311/// We need to check this explicitly as an incomplete array definition is
312/// considered a VariableArrayType, so will not match a complete array
313/// definition that would be otherwise equivalent.
314static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
315 const ArrayType *NewAT = NewQType->getAsArrayType();
316 const ArrayType *OldAT = OldQType->getAsArrayType();
317
318 if (!NewAT || !OldAT)
319 return false;
320
321 // If either (or both) array types in incomplete we need to strip off the
322 // outer VariableArrayType. Once the outer VAT is removed the remaining
323 // types must be identical if the array types are to be considered
324 // equivalent.
325 // eg. int[][1] and int[1][1] become
326 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
327 // removing the outermost VAT gives
328 // CAT(1, int) and CAT(1, int)
329 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000330 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000331 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
332 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000333 NewQType = NewAT->getElementType().getCanonicalType();
334 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000335 }
336
337 return NewQType == OldQType;
338}
339
Reid Spencer5f016e22007-07-11 17:01:13 +0000340/// MergeVarDecl - We just parsed a variable 'New' which has the same name
341/// and scope as a previous declaration 'Old'. Figure out how to resolve this
342/// situation, merging decls or emitting diagnostics as appropriate.
343///
344/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
345/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
346///
Steve Naroffe8043c32008-04-01 23:04:06 +0000347VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 // Verify the old decl was also a variable.
349 VarDecl *Old = dyn_cast<VarDecl>(OldD);
350 if (!Old) {
351 Diag(New->getLocation(), diag::err_redefinition_different_kind,
352 New->getName());
353 Diag(OldD->getLocation(), diag::err_previous_definition);
354 return New;
355 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000356
357 MergeAttributes(New, Old);
358
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 // Verify the types match.
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000360 if (Old->getCanonicalType() != New->getCanonicalType() &&
361 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 Diag(New->getLocation(), diag::err_redefinition, New->getName());
363 Diag(Old->getLocation(), diag::err_previous_definition);
364 return New;
365 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000366 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
367 if (New->getStorageClass() == VarDecl::Static &&
368 (Old->getStorageClass() == VarDecl::None ||
369 Old->getStorageClass() == VarDecl::Extern)) {
370 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
371 Diag(Old->getLocation(), diag::err_previous_definition);
372 return New;
373 }
374 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
375 if (New->getStorageClass() != VarDecl::Static &&
376 Old->getStorageClass() == VarDecl::Static) {
377 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
378 Diag(Old->getLocation(), diag::err_previous_definition);
379 return New;
380 }
381 // We've verified the types match, now handle "tentative" definitions.
382 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
383 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
384
385 if (OldFSDecl && NewFSDecl) {
386 // Handle C "tentative" external object definitions (C99 6.9.2).
387 bool OldIsTentative = false;
388 bool NewIsTentative = false;
389
390 if (!OldFSDecl->getInit() &&
391 (OldFSDecl->getStorageClass() == VarDecl::None ||
392 OldFSDecl->getStorageClass() == VarDecl::Static))
393 OldIsTentative = true;
394
395 // FIXME: this check doesn't work (since the initializer hasn't been
396 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
397 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
398 // thrown out the old decl.
399 if (!NewFSDecl->getInit() &&
400 (NewFSDecl->getStorageClass() == VarDecl::None ||
401 NewFSDecl->getStorageClass() == VarDecl::Static))
402 ; // change to NewIsTentative = true; once the code is moved.
403
404 if (NewIsTentative || OldIsTentative)
405 return New;
406 }
407 if (Old->getStorageClass() != VarDecl::Extern &&
408 New->getStorageClass() != VarDecl::Extern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 Diag(New->getLocation(), diag::err_redefinition, New->getName());
410 Diag(Old->getLocation(), diag::err_previous_definition);
411 }
412 return New;
413}
414
415/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
416/// no declarator (e.g. "struct foo;") is parsed.
417Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
418 // TODO: emit error on 'int;' or 'const enum foo;'.
419 // TODO: emit error on 'typedef int;'
420 // if (!DS.isMissingDeclaratorOk()) Diag(...);
421
Steve Naroff92199282007-11-17 21:37:36 +0000422 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000423}
424
Steve Naroffd0091aa2008-01-10 22:15:12 +0000425bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000426 // Get the type before calling CheckSingleAssignmentConstraints(), since
427 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000428 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000429
Chris Lattner5cf216b2008-01-04 18:04:52 +0000430 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
431 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
432 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000433}
434
Steve Naroff9e8925e2007-09-04 14:36:54 +0000435bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000436 QualType ElementType) {
Chris Lattner33b7b062007-12-11 23:15:04 +0000437 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffd0091aa2008-01-10 22:15:12 +0000438 if (CheckSingleInitializer(expr, ElementType))
Chris Lattner33b7b062007-12-11 23:15:04 +0000439 return true; // types weren't compatible.
440
Steve Naroff9e8925e2007-09-04 14:36:54 +0000441 if (savExpr != expr) // The type was promoted, update initializer list.
442 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000443 return false;
444}
445
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000446bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000447 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000448 // C99 6.7.8p14. We have an array of character type with unknown size
449 // being initialized to a string literal.
450 llvm::APSInt ConstVal(32);
451 ConstVal = strLiteral->getByteLength() + 1;
452 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000453 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000454 ArrayType::Normal, 0);
455 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
456 // C99 6.7.8p14. We have an array of character type with known size.
457 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
458 Diag(strLiteral->getSourceRange().getBegin(),
459 diag::warn_initializer_string_for_char_array_too_long,
460 strLiteral->getSourceRange());
461 } else {
462 assert(0 && "HandleStringLiteralInit(): Invalid array type");
463 }
464 // Set type from "char *" to "constant array of char".
465 strLiteral->setType(DeclT);
466 // For now, we always return false (meaning success).
467 return false;
468}
469
470StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000471 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000472 if (AT && AT->getElementType()->isCharType()) {
473 return dyn_cast<StringLiteral>(Init);
474 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000475 return 0;
476}
477
Steve Naroffa9960332008-01-25 00:51:06 +0000478// CheckInitializerListTypes - Checks the types of elements of an initializer
479// list. This function is recursive: it calls itself to initialize subelements
480// of aggregate types. Note that the topLevel parameter essentially refers to
481// whether this expression "owns" the initializer list passed in, or if this
482// initialization is taking elements out of a parent initializer. Each
483// call to this function adds zero or more to startIndex, reports any errors,
484// and returns true if it found any inconsistent types.
485bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
486 bool topLevel, unsigned& startIndex) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000487 bool hadError = false;
Steve Naroffa9960332008-01-25 00:51:06 +0000488
489 if (DeclType->isScalarType()) {
490 // The simplest case: initializing a single scalar
491 if (topLevel) {
492 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
493 IList->getSourceRange());
494 }
495 if (startIndex < IList->getNumInits()) {
496 Expr* expr = IList->getInit(startIndex);
497 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
498 // FIXME: Should an error be reported here instead?
499 unsigned newIndex = 0;
500 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
501 } else {
502 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
503 }
504 ++startIndex;
505 }
506 // FIXME: Should an error be reported for empty initializer list + scalar?
507 } else if (DeclType->isVectorType()) {
508 if (startIndex < IList->getNumInits()) {
509 const VectorType *VT = DeclType->getAsVectorType();
510 int maxElements = VT->getNumElements();
511 QualType elementType = VT->getElementType();
512
513 for (int i = 0; i < maxElements; ++i) {
514 // Don't attempt to go past the end of the init list
515 if (startIndex >= IList->getNumInits())
516 break;
517 Expr* expr = IList->getInit(startIndex);
518 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
519 unsigned newIndex = 0;
520 hadError |= CheckInitializerListTypes(SubInitList, elementType,
521 true, newIndex);
522 ++startIndex;
523 } else {
524 hadError |= CheckInitializerListTypes(IList, elementType,
525 false, startIndex);
526 }
527 }
528 }
529 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
530 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroff578edc62008-01-28 02:00:41 +0000531 if (startIndex < IList->getNumInits() && !topLevel &&
532 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
533 DeclType)) {
Steve Naroffa9960332008-01-25 00:51:06 +0000534 // We found a compatible struct; per the standard, this initializes the
535 // struct. (The C standard technically says that this only applies for
536 // initializers for declarations with automatic scope; however, this
537 // construct is unambiguous anyway because a struct cannot contain
538 // a type compatible with itself. We'll output an error when we check
539 // if the initializer is constant.)
540 // FIXME: Is a call to CheckSingleInitializer required here?
541 ++startIndex;
542 } else {
543 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffb43eaa52008-02-11 00:06:17 +0000544
Steve Naroff406db932008-02-11 21:52:37 +0000545 // If the record is invalid, some of it's members are invalid. To avoid
546 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffb43eaa52008-02-11 00:06:17 +0000547 if (structDecl->isInvalidDecl())
548 return true;
549
Steve Naroffa9960332008-01-25 00:51:06 +0000550 // If structDecl is a forward declaration, this loop won't do anything;
551 // That's okay, because an error should get printed out elsewhere. It
552 // might be worthwhile to skip over the rest of the initializer, though.
553 int numMembers = structDecl->getNumMembers() -
554 structDecl->hasFlexibleArrayMember();
555 for (int i = 0; i < numMembers; i++) {
556 // Don't attempt to go past the end of the init list
557 if (startIndex >= IList->getNumInits())
558 break;
559 FieldDecl * curField = structDecl->getMember(i);
560 if (!curField->getIdentifier()) {
561 // Don't initialize unnamed fields, e.g. "int : 20;"
562 continue;
563 }
564 QualType fieldType = curField->getType();
565 Expr* expr = IList->getInit(startIndex);
566 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
567 unsigned newStart = 0;
568 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
569 true, newStart);
570 ++startIndex;
571 } else {
572 hadError |= CheckInitializerListTypes(IList, fieldType,
573 false, startIndex);
574 }
575 if (DeclType->isUnionType())
576 break;
577 }
578 // FIXME: Implement flexible array initialization GCC extension (it's a
579 // really messy extension to implement, unfortunately...the necessary
580 // information isn't actually even here!)
581 }
582 } else if (DeclType->isArrayType()) {
583 // Check for the special-case of initializing an array with a string.
584 if (startIndex < IList->getNumInits()) {
585 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
586 DeclType)) {
587 CheckStringLiteralInit(lit, DeclType);
588 ++startIndex;
589 if (topLevel && startIndex < IList->getNumInits()) {
590 // We have leftover initializers; warn
591 Diag(IList->getInit(startIndex)->getLocStart(),
592 diag::err_excess_initializers_in_char_array_initializer,
593 IList->getInit(startIndex)->getSourceRange());
594 }
595 return false;
596 }
597 }
598 int maxElements;
Eli Friedmanc5773c42008-02-15 18:16:39 +0000599 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000600 // FIXME: use a proper constant
601 maxElements = 0x7FFFFFFF;
Chris Lattner212839c2008-02-20 23:17:35 +0000602 } else if (const VariableArrayType *VAT =
603 DeclType->getAsVariableArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000604 // Check for VLAs; in standard C it would be possible to check this
605 // earlier, but I don't know where clang accepts VLAs (gcc accepts
606 // them in all sorts of strange places).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000607 Diag(VAT->getSizeExpr()->getLocStart(),
608 diag::err_variable_object_no_init,
609 VAT->getSizeExpr()->getSourceRange());
610 hadError = true;
611 maxElements = 0x7FFFFFFF;
Steve Naroffa9960332008-01-25 00:51:06 +0000612 } else {
613 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
614 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
615 }
616 QualType elementType = DeclType->getAsArrayType()->getElementType();
617 int numElements = 0;
618 for (int i = 0; i < maxElements; ++i, ++numElements) {
619 // Don't attempt to go past the end of the init list
620 if (startIndex >= IList->getNumInits())
621 break;
622 Expr* expr = IList->getInit(startIndex);
623 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
624 unsigned newIndex = 0;
625 hadError |= CheckInitializerListTypes(SubInitList, elementType,
626 true, newIndex);
627 ++startIndex;
628 } else {
629 hadError |= CheckInitializerListTypes(IList, elementType,
630 false, startIndex);
631 }
632 }
Eli Friedman9db13972008-02-15 12:53:51 +0000633 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000634 // If this is an incomplete array type, the actual type needs to
635 // be calculated here
636 if (numElements == 0) {
637 // Sizing an array implicitly to zero is not allowed
638 // (It could in theory be allowed, but it doesn't really matter.)
639 Diag(IList->getLocStart(),
640 diag::err_at_least_one_initializer_needed_to_size_array);
641 hadError = true;
642 } else {
643 llvm::APSInt ConstVal(32);
644 ConstVal = numElements;
645 DeclType = Context.getConstantArrayType(elementType, ConstVal,
646 ArrayType::Normal, 0);
647 }
648 }
649 } else {
650 assert(0 && "Aggregate that isn't a function or array?!");
651 }
652 } else {
653 // In C, all types are either scalars or aggregates, but
654 // additional handling is needed here for C++ (and possibly others?).
655 assert(0 && "Unsupported initializer type");
656 }
657
658 // If this init list is a base list, we set the type; an initializer doesn't
659 // fundamentally have a type, but this makes the ASTs a bit easier to read
660 if (topLevel)
661 IList->setType(DeclType);
662
663 if (topLevel && startIndex < IList->getNumInits()) {
664 // We have leftover initializers; warn
665 Diag(IList->getInit(startIndex)->getLocStart(),
666 diag::warn_excess_initializers,
667 IList->getInit(startIndex)->getSourceRange());
668 }
669 return hadError;
670}
671
672bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000673 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
674 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000675 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000676 return Diag(VAT->getSizeExpr()->getLocStart(),
677 diag::err_variable_object_no_init,
678 VAT->getSizeExpr()->getSourceRange());
679
Steve Naroff2fdc3742007-12-10 22:44:33 +0000680 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
681 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000682 // FIXME: Handle wide strings
683 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
684 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000685
686 if (DeclType->isArrayType())
687 return Diag(Init->getLocStart(),
688 diag::err_array_init_list_required,
689 Init->getSourceRange());
690
Steve Naroffd0091aa2008-01-10 22:15:12 +0000691 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000692 }
Steve Naroffa9960332008-01-25 00:51:06 +0000693 unsigned newIndex = 0;
694 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Narofff0090632007-09-02 02:04:30 +0000695}
696
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000697Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000698Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000699 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 IdentifierInfo *II = D.getIdentifier();
701
Chris Lattnere80a59c2007-07-25 00:24:17 +0000702 // All of these full declarators require an identifier. If it doesn't have
703 // one, the ParsedFreeStandingDeclSpec action should be used.
704 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000705 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000706 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000707 D.getDeclSpec().getSourceRange(), D.getSourceRange());
708 return 0;
709 }
710
Chris Lattner31e05722007-08-26 06:24:45 +0000711 // The scope passed in may not be a decl scope. Zip up the scope tree until
712 // we find one that is.
713 while ((S->getFlags() & Scope::DeclScope) == 0)
714 S = S->getParent();
715
Reid Spencer5f016e22007-07-11 17:01:13 +0000716 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000717 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000718 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000719 bool InvalidDecl = false;
720
Chris Lattner41af0932007-11-14 06:34:38 +0000721 QualType R = GetTypeForDeclarator(D, S);
722 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
723
Reid Spencer5f016e22007-07-11 17:01:13 +0000724 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner41af0932007-11-14 06:34:38 +0000725 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 if (!NewTD) return 0;
727
728 // Handle attributes prior to checking for duplicates in MergeVarDecl
729 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
730 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000731 // Merge the decl with the existing one if appropriate. If the decl is
732 // in an outer scope, it isn't the same thing.
733 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
735 if (NewTD == 0) return 0;
736 }
737 New = NewTD;
738 if (S->getParent() == 0) {
739 // C99 6.7.7p2: If a typedef name specifies a variably modified type
740 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000741 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
742 // FIXME: Diagnostic needs to be fixed.
743 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000744 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 }
746 }
Chris Lattner41af0932007-11-14 06:34:38 +0000747 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000748 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000749 switch (D.getDeclSpec().getStorageClassSpec()) {
750 default: assert(0 && "Unknown storage class!");
751 case DeclSpec::SCS_auto:
752 case DeclSpec::SCS_register:
753 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
754 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000755 InvalidDecl = true;
756 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000757 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
758 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
759 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000760 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 }
762
Chris Lattnera98e58d2008-03-15 21:24:04 +0000763 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattner0ed844b2008-04-04 06:12:32 +0000764 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
765 D.getIdentifierLoc(),
Chris Lattnera98e58d2008-03-15 21:24:04 +0000766 II, R, SC, isInline,
767 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000768 // Handle attributes.
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000769 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
770 D.getAttributes());
Reid Spencer5f016e22007-07-11 17:01:13 +0000771
Steve Naroffffce4d52008-01-09 23:34:55 +0000772 // Merge the decl with the existing one if appropriate. Since C functions
773 // are in a flat namespace, make sure we consider decls in outer scopes.
Reid Spencer5f016e22007-07-11 17:01:13 +0000774 if (PrevDecl) {
775 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
776 if (NewFD == 0) return 0;
777 }
778 New = NewFD;
779 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000780 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000781 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
782 D.getIdentifier()->getName());
783 InvalidDecl = true;
784 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000785
786 VarDecl *NewVD;
787 VarDecl::StorageClass SC;
788 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000789 default: assert(0 && "Unknown storage class!");
790 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
791 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
792 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
793 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
794 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
795 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000796 }
797 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000798 // C99 6.9p2: The storage-class specifiers auto and register shall not
799 // appear in the declaration specifiers in an external declaration.
800 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
801 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
802 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000803 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000804 }
Chris Lattner0ed844b2008-04-04 06:12:32 +0000805 NewVD = FileVarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
806 II, R, SC,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000807 LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000808 } else {
Chris Lattner0ed844b2008-04-04 06:12:32 +0000809 NewVD = BlockVarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
810 II, R, SC,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000811 LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000812 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000813 // Handle attributes prior to checking for duplicates in MergeVarDecl
814 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
815 D.getAttributes());
Nate Begemanc8e89a82008-03-14 18:07:10 +0000816
817 // Emit an error if an address space was applied to decl with local storage.
818 // This includes arrays of objects with address space qualifiers, but not
819 // automatic variables that point to other address spaces.
820 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000821 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
822 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
823 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000824 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000825 // Merge the decl with the existing one if appropriate. If the decl is
826 // in an outer scope, it isn't the same thing.
827 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000828 NewVD = MergeVarDecl(NewVD, PrevDecl);
829 if (NewVD == 0) return 0;
830 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000831 New = NewVD;
832 }
833
834 // If this has an identifier, add it to the scope stack.
835 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000836 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000837 II->setFETokenInfo(New);
838 S->AddDecl(New);
839 }
Steve Naroff5912a352007-08-28 20:14:24 +0000840 // If any semantic error occurred, mark the decl as invalid.
841 if (D.getInvalidType() || InvalidDecl)
842 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000843
844 return New;
845}
846
Steve Naroffd0091aa2008-01-10 22:15:12 +0000847bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
848 SourceLocation loc;
849 // FIXME: Remove the isReference check and handle assignment to a reference.
850 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
851 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
852 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
853 return true;
854 }
855 return false;
856}
857
Steve Naroffbb204692007-09-12 14:07:44 +0000858void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000859 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000860 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000861 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000862
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000863 // If there is no declaration, there was an error parsing it. Just ignore
864 // the initializer.
865 if (RealDecl == 0) {
866 delete Init;
867 return;
868 }
Steve Naroffbb204692007-09-12 14:07:44 +0000869
Steve Naroff410e3e22007-09-12 20:13:48 +0000870 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
871 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000872 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
873 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000874 RealDecl->setInvalidDecl();
875 return;
876 }
Steve Naroffbb204692007-09-12 14:07:44 +0000877 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +0000878 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000879 QualType DclT = VDecl->getType(), SavT = DclT;
880 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000881 VarDecl::StorageClass SC = BVD->getStorageClass();
882 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000883 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000884 BVD->setInvalidDecl();
885 } else if (!BVD->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000886 if (CheckInitializerTypes(Init, DclT))
887 BVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000888 if (SC == VarDecl::Static) // C99 6.7.8p4.
889 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000890 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000891 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000892 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000893 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000894 if (!FVD->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +0000895 if (CheckInitializerTypes(Init, DclT))
896 FVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000897
898 // C99 6.7.8p4. All file scoped initializers need to be constant.
899 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000900 }
901 // If the type changed, it means we had an incomplete type that was
902 // completed by the initializer. For example:
903 // int ary[] = { 1, 3, 5 };
904 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +0000905 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000906 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +0000907 Init->setType(DclT);
908 }
Steve Naroffbb204692007-09-12 14:07:44 +0000909
910 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000911 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000912 return;
913}
914
Reid Spencer5f016e22007-07-11 17:01:13 +0000915/// The declarators are chained together backwards, reverse the list.
916Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
917 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000918 Decl *GroupDecl = static_cast<Decl*>(group);
919 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000920 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000921
922 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
923 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000924 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000925 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000926 else { // reverse the list.
927 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000928 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000929 Group->setNextDeclarator(NewGroup);
930 NewGroup = Group;
931 Group = Next;
932 }
933 }
934 // Perform semantic analysis that depends on having fully processed both
935 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000936 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000937 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
938 if (!IDecl)
939 continue;
940 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
941 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
942 QualType T = IDecl->getType();
943
944 // C99 6.7.5.2p2: If an identifier is declared to be an object with
945 // static storage duration, it shall not have a variable length array.
946 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +0000947 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000948 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
949 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +0000950 }
951 }
952 // Block scope. C99 6.7p7: If an identifier for an object is declared with
953 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
954 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +0000955 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +0000956 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
957 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000958 IDecl->setInvalidDecl();
959 }
960 }
961 // File scope. C99 6.9.2p2: A declaration of an identifier for and
962 // object that has file scope without an initializer, and without a
963 // storage-class specifier or with the storage-class specifier "static",
964 // constitutes a tentative definition. Note: A tentative definition with
965 // external linkage is valid (C99 6.2.2p5).
Steve Naroffd3cd1e52008-01-18 00:39:39 +0000966 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
967 FVD->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +0000968 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +0000969 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
970 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +0000971 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +0000972 // C99 6.9.2p3: If the declaration of an identifier for an object is
973 // a tentative definition and has internal linkage (C99 6.2.2p3), the
974 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +0000975 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
976 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000977 IDecl->setInvalidDecl();
978 }
979 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000980 }
981 return NewGroup;
982}
Steve Naroffe1223f72007-08-28 03:03:08 +0000983
984// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000985ParmVarDecl *
Nate Begeman6d20d032008-02-17 21:02:04 +0000986Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI,
987 Scope *FnScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000988 IdentifierInfo *II = PI.Ident;
989 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
990 // Can this happen for params? We already checked that they don't conflict
991 // among each other. Here they can only shadow globals, which is ok.
Steve Naroffb327ce02008-04-02 14:35:35 +0000992 if (/*Decl *PrevDecl = */LookupDecl(II, Decl::IDNS_Ordinary, FnScope)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000993
994 }
995
996 // FIXME: Handle storage class (auto, register). No declarator?
997 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000998
999 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1000 // Doing the promotion here has a win and a loss. The win is the type for
1001 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1002 // code generator). The loss is the orginal type isn't preserved. For example:
1003 //
1004 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1005 // int blockvardecl[5];
1006 // sizeof(parmvardecl); // size == 4
1007 // sizeof(blockvardecl); // size == 20
1008 // }
1009 //
1010 // For expressions, all implicit conversions are captured using the
1011 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1012 //
1013 // FIXME: If a source translation tool needs to see the original type, then
1014 // we need to consider storing both types (in ParmVarDecl)...
1015 //
1016 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattnere6327742008-04-02 05:18:44 +00001017 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001018 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001019 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001020 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001021 parmDeclType = Context.getPointerType(parmDeclType);
1022
Chris Lattner0ed844b2008-04-04 06:12:32 +00001023 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, PI.IdentLoc, II,
1024 parmDeclType,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001025 VarDecl::None, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001026
Steve Naroff53a32342007-08-28 18:45:29 +00001027 if (PI.InvalidType)
1028 New->setInvalidDecl();
1029
Reid Spencer5f016e22007-07-11 17:01:13 +00001030 // If this has an identifier, add it to the scope stack.
1031 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +00001032 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001033 II->setFETokenInfo(New);
1034 FnScope->AddDecl(New);
1035 }
Nate Begemanb7894b52008-02-17 21:20:31 +00001036
1037 HandleDeclAttributes(New, PI.AttrList, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001038 return New;
1039}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001040
Chris Lattnerb652cea2007-10-09 17:14:05 +00001041Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001042 assert(CurFunctionDecl == 0 && "Function parsing confused");
1043 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1044 "Not a function declarator!");
1045 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1046
1047 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1048 // for a K&R function.
1049 if (!FTI.hasPrototype) {
1050 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1051 if (FTI.ArgInfo[i].TypeInfo == 0) {
1052 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1053 FTI.ArgInfo[i].Ident->getName());
1054 // Implicitly declare the argument as type 'int' for lack of a better
1055 // type.
1056 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
1057 }
1058 }
Chris Lattner52804082008-02-17 19:31:09 +00001059
Reid Spencer5f016e22007-07-11 17:01:13 +00001060 // Since this is a function definition, act as though we have information
1061 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001062 if (FTI.NumArgs)
1063 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001064 } else {
1065 // FIXME: Diagnose arguments without names in C.
1066
1067 }
1068
1069 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001070
1071 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001072 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001073 GlobalScope);
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001074 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1075 if (FD->getBody()) {
1076 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1077 D.getIdentifier()->getName());
1078 Diag(FD->getLocation(), diag::err_previous_definition);
1079 }
1080 }
Steve Narofffabbc342008-02-12 01:09:36 +00001081 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001082 FunctionDecl *FD = cast<FunctionDecl>(decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 CurFunctionDecl = FD;
Chris Lattner0ed844b2008-04-04 06:12:32 +00001084 PushContextDecl(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001085
1086 // Create Decl objects for each parameter, adding them to the FunctionDecl.
1087 llvm::SmallVector<ParmVarDecl*, 16> Params;
1088
1089 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1090 // no arguments, not a function that takes a single void argument.
1091 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerf46699c2008-02-20 20:55:12 +00001092 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getCVRQualifiers() &&
Chris Lattnerb751c282007-11-28 18:51:29 +00001093 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001094 // empty arg list, don't push any params.
1095 } else {
Steve Naroff66499922007-11-12 03:44:46 +00001096 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Steve Naroff657aefe2008-03-19 23:07:49 +00001097 ParmVarDecl *parmDecl;
1098
1099 parmDecl = ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
1100 FnBodyScope);
1101 // C99 6.7.5.3p4: the parameters in a parameter type list in a function
1102 // declarator that is part of a function definition of that function
1103 // shall not have incomplete type.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001104 if (parmDecl->getType()->isIncompleteType() &&
1105 !parmDecl->isInvalidDecl()) {
Steve Naroff657aefe2008-03-19 23:07:49 +00001106 Diag(parmDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1107 parmDecl->getType().getAsString());
1108 parmDecl->setInvalidDecl();
1109 }
1110 Params.push_back(parmDecl);
Steve Naroff66499922007-11-12 03:44:46 +00001111 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001112 }
1113
1114 FD->setParams(&Params[0], Params.size());
1115
1116 return FD;
1117}
1118
Steve Naroffd6d054d2007-11-11 23:20:51 +00001119Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1120 Decl *dcl = static_cast<Decl *>(D);
1121 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1122 FD->setBody((Stmt*)Body);
1123 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001124 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001125 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001126 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001127 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001128 }
Chris Lattner0ed844b2008-04-04 06:12:32 +00001129 PopContextDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001130 // Verify and clean out per-function state.
1131
1132 // Check goto/label use.
1133 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1134 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1135 // Verify that we have no forward references left. If so, there was a goto
1136 // or address of a label taken, but no definition of it. Label fwd
1137 // definitions are indicated with a null substmt.
1138 if (I->second->getSubStmt() == 0) {
1139 LabelStmt *L = I->second;
1140 // Emit error.
1141 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1142
1143 // At this point, we have gotos that use the bogus label. Stitch it into
1144 // the function body so that they aren't leaked and that the AST is well
1145 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001146 if (Body) {
1147 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1148 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1149 } else {
1150 // The whole function wasn't parsed correctly, just delete this.
1151 delete L;
1152 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 }
1154 }
1155 LabelMap.clear();
1156
Steve Naroffd6d054d2007-11-11 23:20:51 +00001157 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001158}
1159
Reid Spencer5f016e22007-07-11 17:01:13 +00001160/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1161/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001162ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1163 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001164 if (getLangOptions().C99) // Extension in C99.
1165 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1166 else // Legal in C90, but warn about it.
1167 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1168
1169 // FIXME: handle stuff like:
1170 // void foo() { extern float X(); }
1171 // void bar() { X(); } <-- implicit decl for X in another scope.
1172
1173 // Set a Declarator for the implicit definition: int foo();
1174 const char *Dummy;
1175 DeclSpec DS;
1176 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1177 Error = Error; // Silence warning.
1178 assert(!Error && "Error setting up implicit decl!");
1179 Declarator D(DS, Declarator::BlockContext);
1180 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1181 D.SetIdentifier(&II, Loc);
1182
1183 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +00001184 if (Scope *FnS = S->getFnParent())
1185 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +00001186 while (S->getParent())
1187 S = S->getParent();
1188
Steve Naroffe2ef8152008-04-04 14:32:09 +00001189 FunctionDecl *FD =
1190 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
1191 FD->setImplicit();
1192 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001193}
1194
1195
Chris Lattner41af0932007-11-14 06:34:38 +00001196TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001197 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001198 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001199 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001200
1201 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001202 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1203 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001204 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001205 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001206 if (D.getInvalidType())
1207 NewTD->setInvalidDecl();
1208 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001209}
1210
Steve Naroff08d92e42007-09-15 18:49:24 +00001211/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001212/// former case, Name will be non-null. In the later case, Name will be null.
1213/// TagType indicates what kind of tag this is. TK indicates whether this is a
1214/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001215Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001216 SourceLocation KWLoc, IdentifierInfo *Name,
1217 SourceLocation NameLoc, AttributeList *Attr) {
1218 // If this is a use of an existing tag, it must have a name.
1219 assert((Name != 0 || TK == TK_Definition) &&
1220 "Nameless record must be a definition!");
1221
1222 Decl::Kind Kind;
1223 switch (TagType) {
1224 default: assert(0 && "Unknown tag type!");
1225 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1226 case DeclSpec::TST_union: Kind = Decl::Union; break;
1227//case DeclSpec::TST_class: Kind = Decl::Class; break;
1228 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1229 }
1230
1231 // If this is a named struct, check to see if there was a previous forward
1232 // declaration or definition.
1233 if (TagDecl *PrevDecl =
Steve Naroffb327ce02008-04-02 14:35:35 +00001234 dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001235
1236 // If this is a use of a previous tag, or if the tag is already declared in
1237 // the same scope (so that the definition/declaration completes or
1238 // rementions the tag), reuse the decl.
1239 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1240 // Make sure that this wasn't declared as an enum and now used as a struct
1241 // or something similar.
1242 if (PrevDecl->getKind() != Kind) {
1243 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1244 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1245 }
1246
1247 // If this is a use or a forward declaration, we're good.
1248 if (TK != TK_Definition)
1249 return PrevDecl;
1250
1251 // Diagnose attempts to redefine a tag.
1252 if (PrevDecl->isDefinition()) {
1253 Diag(NameLoc, diag::err_redefinition, Name->getName());
1254 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1255 // If this is a redefinition, recover by making this struct be
1256 // anonymous, which will make any later references get the previous
1257 // definition.
1258 Name = 0;
1259 } else {
1260 // Okay, this is definition of a previously declared or referenced tag.
1261 // Move the location of the decl to be the definition site.
1262 PrevDecl->setLocation(NameLoc);
1263 return PrevDecl;
1264 }
1265 }
1266 // If we get here, this is a definition of a new struct type in a nested
1267 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1268 // type.
1269 }
1270
1271 // If there is an identifier, use the location of the identifier as the
1272 // location of the decl, otherwise use the location of the struct/union
1273 // keyword.
1274 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1275
1276 // Otherwise, if this is the first time we've seen this tag, create the decl.
1277 TagDecl *New;
1278 switch (Kind) {
1279 default: assert(0 && "Unknown tag kind!");
1280 case Decl::Enum:
1281 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1282 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001283 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001284 // If this is an undefined enum, warn.
1285 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1286 break;
1287 case Decl::Union:
1288 case Decl::Struct:
1289 case Decl::Class:
1290 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1291 // struct X { int A; } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001292 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 break;
1294 }
1295
1296 // If this has an identifier, add it to the scope stack.
1297 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001298 // The scope passed in may not be a decl scope. Zip up the scope tree until
1299 // we find one that is.
1300 while ((S->getFlags() & Scope::DeclScope) == 0)
1301 S = S->getParent();
1302
1303 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001304 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001305 Name->setFETokenInfo(New);
1306 S->AddDecl(New);
1307 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001308
Anders Carlssonad148062008-02-16 00:29:18 +00001309 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001310 return New;
1311}
1312
Steve Naroff08d92e42007-09-15 18:49:24 +00001313/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001314/// to create a FieldDecl object for it.
Chris Lattnerf9628082008-03-16 01:16:52 +00001315Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *tagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001316 SourceLocation DeclStart,
1317 Declarator &D, ExprTy *BitfieldWidth) {
1318 IdentifierInfo *II = D.getIdentifier();
1319 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattnerf9628082008-03-16 01:16:52 +00001320 Decl *TagDecl = static_cast<Decl *>(tagDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001321 SourceLocation Loc = DeclStart;
1322 if (II) Loc = D.getIdentifierLoc();
1323
1324 // FIXME: Unnamed fields can be handled in various different ways, for
1325 // example, unnamed unions inject all members into the struct namespace!
1326
1327
1328 if (BitWidth) {
1329 // TODO: Validate.
1330 //printf("WARNING: BITFIELDS IGNORED!\n");
1331
1332 // 6.7.2.1p3
1333 // 6.7.2.1p4
1334
1335 } else {
1336 // Not a bitfield.
1337
1338 // validate II.
1339
1340 }
1341
1342 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001343 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1344 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001345
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1347 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001348 if (T->isVariablyModifiedType()) {
1349 // FIXME: This diagnostic needs work
1350 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroffd7444aa2007-08-31 17:20:07 +00001351 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001352 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001354 FieldDecl *NewFD;
1355
Chris Lattner0ed844b2008-04-04 06:12:32 +00001356 if (RecordDecl *RD = dyn_cast<RecordDecl>(TagDecl))
1357 NewFD = FieldDecl::Create(Context, RD, Loc, II, T, BitWidth);
Chris Lattnerf9628082008-03-16 01:16:52 +00001358 else if (isa<ObjCInterfaceDecl>(TagDecl) ||
1359 isa<ObjCImplementationDecl>(TagDecl) ||
1360 isa<ObjCCategoryDecl>(TagDecl) ||
Steve Naroffddd600f2007-11-14 14:15:31 +00001361 // FIXME: ivars are currently used to model properties, and
1362 // properties can appear within a protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001363 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
Chris Lattnerf9628082008-03-16 01:16:52 +00001364 isa<ObjCProtocolDecl>(TagDecl))
Chris Lattner0ed844b2008-04-04 06:12:32 +00001365 NewFD = ObjCIvarDecl::Create(Context, dyn_cast<ObjCInterfaceDecl>(TagDecl), Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001366 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001367 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001368
Anders Carlssonad148062008-02-16 00:29:18 +00001369 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1370 D.getAttributes());
1371
Steve Naroff5912a352007-08-28 20:14:24 +00001372 if (D.getInvalidType() || InvalidDecl)
1373 NewFD->setInvalidDecl();
1374 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001375}
1376
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001377/// TranslateIvarVisibility - Translate visibility from a token ID to an
1378/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001379static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001380TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001381 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001382 case tok::objc_private: return ObjCIvarDecl::Private;
1383 case tok::objc_public: return ObjCIvarDecl::Public;
1384 case tok::objc_protected: return ObjCIvarDecl::Protected;
1385 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001386 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001387 }
1388}
1389
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001390void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001391 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001392 DeclTy **Fields, unsigned NumFields,
Steve Naroff60fccee2007-10-29 21:38:07 +00001393 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff08d92e42007-09-15 18:49:24 +00001394 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001395 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1396 assert(EnclosingDecl && "missing record or interface decl");
1397 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1398
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001399 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 // Diagnose code like:
1401 // struct S { struct S {} X; };
1402 // We discover this when we complete the outer S. Reject and ignore the
1403 // outer S.
1404 Diag(Record->getLocation(), diag::err_nested_redefinition,
1405 Record->getKindName());
1406 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001407 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001408 return;
1409 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001410 // Verify that all the fields are okay.
1411 unsigned NumNamedMembers = 0;
1412 llvm::SmallVector<FieldDecl*, 32> RecFields;
1413 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001414
Reid Spencer5f016e22007-07-11 17:01:13 +00001415 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001416
Steve Naroff74216642007-09-14 22:20:54 +00001417 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1418 assert(FD && "missing field decl");
1419
1420 // Remember all fields.
1421 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001422
1423 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001424 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001425
Steve Narofff13271f2007-09-14 23:09:53 +00001426 // If we have visibility info, make sure the AST is set accordingly.
1427 if (visibility)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001428 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001429 TranslateIvarVisibility(visibility[i]));
Steve Narofff13271f2007-09-14 23:09:53 +00001430
Reid Spencer5f016e22007-07-11 17:01:13 +00001431 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001432 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001433 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001434 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001435 FD->setInvalidDecl();
1436 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001437 continue;
1438 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001439 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1440 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001441 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001442 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001443 FD->setInvalidDecl();
1444 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001445 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001446 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001447 if (i != NumFields-1 || // ... that the last member ...
1448 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001449 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001450 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001451 FD->setInvalidDecl();
1452 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001453 continue;
1454 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001455 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1457 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001458 FD->setInvalidDecl();
1459 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001460 continue;
1461 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001462 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001463 if (Record)
1464 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001465 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001466 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1467 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001468 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001469 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1470 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001471 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 Record->setHasFlexibleArrayMember(true);
1473 } else {
1474 // If this is a struct/class and this is not the last element, reject
1475 // it. Note that GCC supports variable sized arrays in the middle of
1476 // structures.
1477 if (i != NumFields-1) {
1478 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1479 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001480 FD->setInvalidDecl();
1481 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 continue;
1483 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 // We support flexible arrays at the end of structs in other structs
1485 // as an extension.
1486 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1487 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001488 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001489 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 }
1491 }
1492 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001493 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001494 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001495 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1496 FD->getName());
1497 FD->setInvalidDecl();
1498 EnclosingDecl->setInvalidDecl();
1499 continue;
1500 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 // Keep track of the number of named members.
1502 if (IdentifierInfo *II = FD->getIdentifier()) {
1503 // Detect duplicate member names.
1504 if (!FieldIDs.insert(II)) {
1505 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1506 // Find the previous decl.
1507 SourceLocation PrevLoc;
1508 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1509 assert(i != e && "Didn't find previous def!");
1510 if (RecFields[i]->getIdentifier() == II) {
1511 PrevLoc = RecFields[i]->getLocation();
1512 break;
1513 }
1514 }
1515 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001516 FD->setInvalidDecl();
1517 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 continue;
1519 }
1520 ++NumNamedMembers;
1521 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001522 }
1523
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00001525 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001526 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00001527 Consumer.HandleTagDeclDefinition(Record);
1528 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00001529 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1530 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1531 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1532 else if (ObjCImplementationDecl *IMPDecl =
1533 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001534 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1535 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001536 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001537 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001538 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001539}
1540
Steve Naroff08d92e42007-09-15 18:49:24 +00001541Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 DeclTy *lastEnumConst,
1543 SourceLocation IdLoc, IdentifierInfo *Id,
1544 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00001545 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00001546 EnumConstantDecl *LastEnumConst =
1547 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1548 Expr *Val = static_cast<Expr*>(val);
1549
Chris Lattner31e05722007-08-26 06:24:45 +00001550 // The scope passed in may not be a decl scope. Zip up the scope tree until
1551 // we find one that is.
1552 while ((S->getFlags() & Scope::DeclScope) == 0)
1553 S = S->getParent();
1554
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 // Verify that there isn't already something declared with this name in this
1556 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00001557 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 if (S->isDeclScope(PrevDecl)) {
1559 if (isa<EnumConstantDecl>(PrevDecl))
1560 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1561 else
1562 Diag(IdLoc, diag::err_redefinition, Id->getName());
1563 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00001564 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 return 0;
1566 }
1567 }
1568
1569 llvm::APSInt EnumVal(32);
1570 QualType EltTy;
1571 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001572 // Make sure to promote the operand type to int.
1573 UsualUnaryConversions(Val);
1574
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1576 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001577 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1579 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00001580 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001581 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001582 } else {
1583 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001584 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001585 }
1586
1587 if (!Val) {
1588 if (LastEnumConst) {
1589 // Assign the last value + 1.
1590 EnumVal = LastEnumConst->getInitVal();
1591 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001592
1593 // Check for overflow on increment.
1594 if (EnumVal < LastEnumConst->getInitVal())
1595 Diag(IdLoc, diag::warn_enum_value_overflow);
1596
Chris Lattnerb7416f92007-08-27 17:37:24 +00001597 EltTy = LastEnumConst->getType();
1598 } else {
1599 // First value, set to zero.
1600 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001601 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001602 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001603 }
1604
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001605 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00001606 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
1607 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001608 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00001609
1610 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001611 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001612 Id->setFETokenInfo(New);
1613 S->AddDecl(New);
1614 return New;
1615}
1616
Steve Naroff08d92e42007-09-15 18:49:24 +00001617void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 DeclTy **Elements, unsigned NumElements) {
1619 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1620 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1621
Chris Lattnere37f0be2007-08-28 05:10:31 +00001622 // TODO: If the result value doesn't fit in an int, it must be a long or long
1623 // long value. ISO C does not support this, but GCC does as an extension,
1624 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00001625 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00001626
Chris Lattnerac609682007-08-28 06:15:15 +00001627 // Verify that all the values are okay, compute the size of the values, and
1628 // reverse the list.
1629 unsigned NumNegativeBits = 0;
1630 unsigned NumPositiveBits = 0;
1631
1632 // Keep track of whether all elements have type int.
1633 bool AllElementsInt = true;
1634
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 EnumConstantDecl *EltList = 0;
1636 for (unsigned i = 0; i != NumElements; ++i) {
1637 EnumConstantDecl *ECD =
1638 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1639 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001640
1641 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00001642 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00001643 assert(InitVal.getBitWidth() >= IntWidth &&
1644 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00001645 if (InitVal.getBitWidth() > IntWidth) {
1646 llvm::APSInt V(InitVal);
1647 V.trunc(IntWidth);
1648 V.extend(InitVal.getBitWidth());
1649 if (V != InitVal)
1650 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1651 InitVal.toString());
1652 }
Chris Lattnerac609682007-08-28 06:15:15 +00001653
1654 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00001655 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00001656 NumPositiveBits = std::max(NumPositiveBits,
1657 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00001658 else
Chris Lattner21dd8212008-01-14 21:47:29 +00001659 NumNegativeBits = std::max(NumNegativeBits,
1660 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001661
Chris Lattnerac609682007-08-28 06:15:15 +00001662 // Keep track of whether every enum element has type int (very commmon).
1663 if (AllElementsInt)
1664 AllElementsInt = ECD->getType() == Context.IntTy;
1665
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 ECD->setNextDeclarator(EltList);
1667 EltList = ECD;
1668 }
1669
Chris Lattnerac609682007-08-28 06:15:15 +00001670 // Figure out the type that should be used for this enum.
1671 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1672 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001673 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001674
1675 if (NumNegativeBits) {
1676 // If there is a negative value, figure out the smallest integer type (of
1677 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001678 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001679 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001680 BestWidth = IntWidth;
1681 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00001682 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001683
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001684 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001685 BestType = Context.LongTy;
1686 else {
Chris Lattner98be4942008-03-05 18:54:05 +00001687 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001688
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001689 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001690 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1691 BestType = Context.LongLongTy;
1692 }
1693 }
1694 } else {
1695 // If there is no negative value, figure out which of uint, ulong, ulonglong
1696 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001697 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001698 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001699 BestWidth = IntWidth;
1700 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00001701 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00001702 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001703 } else {
1704 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001705 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001706 "How could an initializer get larger than ULL?");
1707 BestType = Context.UnsignedLongLongTy;
1708 }
1709 }
1710
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001711 // Loop over all of the enumerator constants, changing their types to match
1712 // the type of the enum if needed.
1713 for (unsigned i = 0; i != NumElements; ++i) {
1714 EnumConstantDecl *ECD =
1715 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1716 if (!ECD) continue; // Already issued a diagnostic.
1717
1718 // Standard C says the enumerators have int type, but we allow, as an
1719 // extension, the enumerators to be larger than int size. If each
1720 // enumerator value fits in an int, type it as an int, otherwise type it the
1721 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1722 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00001723 if (ECD->getType() == Context.IntTy) {
1724 // Make sure the init value is signed.
1725 llvm::APSInt IV = ECD->getInitVal();
1726 IV.setIsSigned(true);
1727 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001728 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00001729 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001730
1731 // Determine whether the value fits into an int.
1732 llvm::APSInt InitVal = ECD->getInitVal();
1733 bool FitsInInt;
1734 if (InitVal.isUnsigned() || !InitVal.isNegative())
1735 FitsInInt = InitVal.getActiveBits() < IntWidth;
1736 else
1737 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1738
1739 // If it fits into an integer type, force it. Otherwise force it to match
1740 // the enum decl type.
1741 QualType NewTy;
1742 unsigned NewWidth;
1743 bool NewSign;
1744 if (FitsInInt) {
1745 NewTy = Context.IntTy;
1746 NewWidth = IntWidth;
1747 NewSign = true;
1748 } else if (ECD->getType() == BestType) {
1749 // Already the right type!
1750 continue;
1751 } else {
1752 NewTy = BestType;
1753 NewWidth = BestWidth;
1754 NewSign = BestType->isSignedIntegerType();
1755 }
1756
1757 // Adjust the APSInt value.
1758 InitVal.extOrTrunc(NewWidth);
1759 InitVal.setIsSigned(NewSign);
1760 ECD->setInitVal(InitVal);
1761
1762 // Adjust the Expr initializer and type.
1763 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1764 ECD->setType(NewTy);
1765 }
Chris Lattnerac609682007-08-28 06:15:15 +00001766
Chris Lattnere00b18c2007-08-28 18:24:31 +00001767 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00001768 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00001769}
1770
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001771Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1772 ExprTy *expr) {
1773 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1774
Chris Lattner8e25d862008-03-16 00:16:02 +00001775 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001776}
1777
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001778Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00001779 SourceLocation LBrace,
1780 SourceLocation RBrace,
1781 const char *Lang,
1782 unsigned StrSize,
1783 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001784 LinkageSpecDecl::LanguageIDs Language;
1785 Decl *dcl = static_cast<Decl *>(D);
1786 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1787 Language = LinkageSpecDecl::lang_c;
1788 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1789 Language = LinkageSpecDecl::lang_cxx;
1790 else {
1791 Diag(Loc, diag::err_bad_language);
1792 return 0;
1793 }
1794
1795 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00001796 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001797}
1798
Chris Lattner74788ba2008-02-21 00:48:22 +00001799void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00001800
Chris Lattner74788ba2008-02-21 00:48:22 +00001801 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00001802 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00001803 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00001804 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001805 if (!newType.isNull()) // install the new vector type into the decl
1806 vDecl->setType(newType);
1807 }
1808 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1809 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001810 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001811 if (!newType.isNull()) // install the new vector type into the decl
1812 tDecl->setUnderlyingType(newType);
1813 }
Chris Lattner212839c2008-02-20 23:17:35 +00001814 break;
1815 case AttributeList::AT_ocu_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00001816 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Chris Lattner74788ba2008-02-21 00:48:22 +00001817 HandleOCUVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00001818 else
Chris Lattner74788ba2008-02-21 00:48:22 +00001819 Diag(Attr->getLoc(),
Steve Naroff73322922007-07-18 18:00:27 +00001820 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00001821 break;
1822 case AttributeList::AT_address_space:
Christopher Lambebb97e92008-02-04 02:31:56 +00001823 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1824 QualType newType = HandleAddressSpaceTypeAttribute(
1825 tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001826 Attr);
1827 tDecl->setUnderlyingType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001828 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1829 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001830 Attr);
1831 // install the new addr spaced type into the decl
1832 vDecl->setType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001833 }
Chris Lattner212839c2008-02-20 23:17:35 +00001834 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00001835 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00001836 HandleDeprecatedAttribute(New, Attr);
1837 break;
1838 case AttributeList::AT_visibility:
1839 HandleVisibilityAttribute(New, Attr);
1840 break;
1841 case AttributeList::AT_weak:
1842 HandleWeakAttribute(New, Attr);
1843 break;
1844 case AttributeList::AT_dllimport:
1845 HandleDLLImportAttribute(New, Attr);
1846 break;
1847 case AttributeList::AT_dllexport:
1848 HandleDLLExportAttribute(New, Attr);
1849 break;
1850 case AttributeList::AT_nothrow:
1851 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00001852 break;
Nate Begeman440b4562008-03-07 20:04:22 +00001853 case AttributeList::AT_stdcall:
1854 HandleStdCallAttribute(New, Attr);
1855 break;
1856 case AttributeList::AT_fastcall:
1857 HandleFastCallAttribute(New, Attr);
1858 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001859 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00001860 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001861 break;
1862 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00001863 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001864 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00001865 case AttributeList::AT_annotate:
1866 HandleAnnotateAttribute(New, Attr);
1867 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00001868 case AttributeList::AT_noreturn:
1869 HandleNoReturnAttribute(New, Attr);
1870 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00001871 case AttributeList::AT_format:
1872 HandleFormatAttribute(New, Attr);
1873 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001874 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00001875#if 0
1876 // TODO: when we have the full set of attributes, warn about unknown ones.
1877 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
1878 Attr->getName()->getName());
1879#endif
Chris Lattner212839c2008-02-20 23:17:35 +00001880 break;
1881 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001882}
1883
1884void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1885 AttributeList *declarator_postfix) {
1886 while (declspec_prefix) {
1887 HandleDeclAttribute(New, declspec_prefix);
1888 declspec_prefix = declspec_prefix->getNext();
1889 }
1890 while (declarator_postfix) {
1891 HandleDeclAttribute(New, declarator_postfix);
1892 declarator_postfix = declarator_postfix->getNext();
1893 }
1894}
1895
Steve Naroffbea0b342007-07-29 16:33:31 +00001896void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1897 AttributeList *rawAttr) {
1898 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00001899 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00001900 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00001901 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00001902 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001903 return;
Steve Naroff73322922007-07-18 18:00:27 +00001904 }
1905 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1906 llvm::APSInt vecSize(32);
1907 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00001908 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00001909 "ocu_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001910 return;
Steve Naroff73322922007-07-18 18:00:27 +00001911 }
1912 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1913 // in conjunction with complex types (pointers, arrays, functions, etc.).
1914 Type *canonType = curType.getCanonicalType().getTypePtr();
1915 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00001916 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00001917 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001918 return;
Steve Naroff73322922007-07-18 18:00:27 +00001919 }
1920 // unlike gcc's vector_size attribute, the size is specified as the
1921 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001922 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001923
1924 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00001925 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00001926 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001927 return;
Steve Naroff73322922007-07-18 18:00:27 +00001928 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001929 // Instantiate/Install the vector type, the number of elements is > 0.
1930 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1931 // Remember this typedef decl, we will need it later for diagnostics.
1932 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001933}
1934
Reid Spencer5f016e22007-07-11 17:01:13 +00001935QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001936 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001937 // check the attribute arugments.
1938 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00001939 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00001940 std::string("1"));
1941 return QualType();
1942 }
1943 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1944 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001945 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00001946 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00001947 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001948 return QualType();
1949 }
1950 // navigate to the base type - we need to provide for vector pointers,
1951 // vector arrays, and functions returning vectors.
1952 Type *canonType = curType.getCanonicalType().getTypePtr();
1953
Steve Naroff73322922007-07-18 18:00:27 +00001954 if (canonType->isPointerType() || canonType->isArrayType() ||
1955 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00001956 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00001957 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1958 do {
1959 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1960 canonType = PT->getPointeeType().getTypePtr();
1961 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1962 canonType = AT->getElementType().getTypePtr();
1963 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1964 canonType = FT->getResultType().getTypePtr();
1965 } while (canonType->isPointerType() || canonType->isArrayType() ||
1966 canonType->isFunctionType());
1967 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 }
1969 // the base type must be integer or float.
1970 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00001971 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00001972 curType.getCanonicalType().getAsString());
1973 return QualType();
1974 }
Chris Lattner98be4942008-03-05 18:54:05 +00001975 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Reid Spencer5f016e22007-07-11 17:01:13 +00001976 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001977 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00001978
1979 // the vector size needs to be an integral multiple of the type size.
1980 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00001981 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 sizeExpr->getSourceRange());
1983 return QualType();
1984 }
1985 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00001986 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00001987 sizeExpr->getSourceRange());
1988 return QualType();
1989 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00001990 // Instantiate the vector type, the number of elements is > 0, and not
1991 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00001992 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001993}
1994
Chris Lattner2070d802008-02-20 23:25:22 +00001995void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00001996 // check the attribute arguments.
1997 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00001998 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00001999 std::string("0"));
2000 return;
2001 }
2002
2003 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2004 TD->addAttr(new PackedAttr);
2005 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2006 // If the alignment is less than or equal to 8 bits, the packed attribute
2007 // has no effect.
Chris Lattner98be4942008-03-05 18:54:05 +00002008 if (Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00002009 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00002010 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00002011 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00002012 else
Anders Carlsson425a6092008-02-16 00:39:40 +00002013 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00002014 } else
Chris Lattner2070d802008-02-20 23:25:22 +00002015 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2016 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00002017}
Nate Begemanc398f0b2008-02-21 19:30:49 +00002018
Ted Kremenekaecb3832008-02-27 20:43:06 +00002019void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2020 // check the attribute arguments.
2021 if (rawAttr->getNumArgs() != 0) {
2022 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2023 std::string("0"));
2024 return;
2025 }
2026
Ted Kremenek3465fb32008-03-03 16:52:27 +00002027 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2028
2029 if (!Fn) {
2030 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2031 "noreturn", "function");
2032 return;
2033 }
2034
Ted Kremenekaecb3832008-02-27 20:43:06 +00002035 d->addAttr(new NoReturnAttr());
2036}
2037
Chris Lattnerddee4232008-03-03 03:28:21 +00002038void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2039 // check the attribute arguments.
2040 if (rawAttr->getNumArgs() != 0) {
2041 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2042 std::string("0"));
2043 return;
2044 }
2045
2046 d->addAttr(new DeprecatedAttr());
2047}
2048
2049void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2050 // check the attribute arguments.
Chris Lattner7b937ae2008-03-04 18:08:48 +00002051 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002052 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2053 std::string("1"));
2054 return;
2055 }
2056
Chris Lattner7b937ae2008-03-04 18:08:48 +00002057 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2058 Arg = Arg->IgnoreParenCasts();
2059 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2060
2061 if (Str == 0 || Str->isWide()) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002062 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002063 "visibility", std::string("1"));
Chris Lattnerddee4232008-03-03 03:28:21 +00002064 return;
2065 }
2066
Chris Lattner7b937ae2008-03-04 18:08:48 +00002067 const char *TypeStr = Str->getStrData();
2068 unsigned TypeLen = Str->getByteLength();
Chris Lattnerddee4232008-03-03 03:28:21 +00002069 llvm::GlobalValue::VisibilityTypes type;
2070
Chris Lattner7b937ae2008-03-04 18:08:48 +00002071 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Chris Lattnerddee4232008-03-03 03:28:21 +00002072 type = llvm::GlobalValue::DefaultVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002073 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Chris Lattnerddee4232008-03-03 03:28:21 +00002074 type = llvm::GlobalValue::HiddenVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002075 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Chris Lattnerddee4232008-03-03 03:28:21 +00002076 type = llvm::GlobalValue::HiddenVisibility; // FIXME
Chris Lattner7b937ae2008-03-04 18:08:48 +00002077 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Chris Lattnerddee4232008-03-03 03:28:21 +00002078 type = llvm::GlobalValue::ProtectedVisibility;
2079 else {
2080 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002081 "visibility", TypeStr);
Chris Lattnerddee4232008-03-03 03:28:21 +00002082 return;
2083 }
2084
2085 d->addAttr(new VisibilityAttr(type));
2086}
2087
2088void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2089 // check the attribute arguments.
2090 if (rawAttr->getNumArgs() != 0) {
2091 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2092 std::string("0"));
2093 return;
2094 }
2095
2096 d->addAttr(new WeakAttr());
2097}
2098
2099void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2100 // check the attribute arguments.
2101 if (rawAttr->getNumArgs() != 0) {
2102 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2103 std::string("0"));
2104 return;
2105 }
2106
2107 d->addAttr(new DLLImportAttr());
2108}
2109
2110void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2111 // check the attribute arguments.
2112 if (rawAttr->getNumArgs() != 0) {
2113 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2114 std::string("0"));
2115 return;
2116 }
2117
2118 d->addAttr(new DLLExportAttr());
2119}
2120
Nate Begeman440b4562008-03-07 20:04:22 +00002121void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2122 // check the attribute arguments.
2123 if (rawAttr->getNumArgs() != 0) {
2124 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2125 std::string("0"));
2126 return;
2127 }
2128
2129 d->addAttr(new StdCallAttr());
2130}
2131
2132void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2133 // check the attribute arguments.
2134 if (rawAttr->getNumArgs() != 0) {
2135 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2136 std::string("0"));
2137 return;
2138 }
2139
2140 d->addAttr(new FastCallAttr());
2141}
2142
Chris Lattnerddee4232008-03-03 03:28:21 +00002143void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2144 // check the attribute arguments.
2145 if (rawAttr->getNumArgs() != 0) {
2146 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2147 std::string("0"));
2148 return;
2149 }
2150
2151 d->addAttr(new NoThrowAttr());
2152}
2153
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002154static const FunctionTypeProto *getFunctionProto(Decl *d) {
2155 ValueDecl *decl = dyn_cast<ValueDecl>(d);
2156 if (!decl) return 0;
2157
2158 QualType Ty = decl->getType();
2159
2160 if (Ty->isFunctionPointerType()) {
2161 const PointerType *PtrTy = Ty->getAsPointerType();
2162 Ty = PtrTy->getPointeeType();
2163 }
2164
2165 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2166 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2167
2168 return 0;
2169}
2170
2171
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002172/// Handle __attribute__((format(type,idx,firstarg))) attributes
2173/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattnerddee4232008-03-03 03:28:21 +00002174void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2175
2176 if (!rawAttr->getParameterName()) {
2177 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2178 "format", std::string("1"));
2179 return;
2180 }
2181
2182 if (rawAttr->getNumArgs() != 2) {
2183 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2184 std::string("3"));
2185 return;
2186 }
2187
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002188 // GCC ignores the format attribute on K&R style function
2189 // prototypes, so we ignore it as well
2190 const FunctionTypeProto *proto = getFunctionProto(d);
2191
2192 if (!proto) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002193 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2194 "format", "function");
2195 return;
2196 }
2197
2198 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002199 // this is needed in order to be compatible with GCC
Chris Lattnerddee4232008-03-03 03:28:21 +00002200 // the index must start in 1 and the limit is numargs+1
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002201 unsigned NumArgs = proto->getNumArgs();
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002202 unsigned FirstIdx = 1;
Chris Lattnerddee4232008-03-03 03:28:21 +00002203
2204 const char *Format = rawAttr->getParameterName()->getName();
2205 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2206
2207 // Normalize the argument, __foo__ becomes foo.
2208 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2209 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2210 Format += 2;
2211 FormatLen -= 4;
2212 }
2213
2214 if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2215 || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2216 || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2217 || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2218 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2219 "format", rawAttr->getParameterName()->getName());
2220 return;
2221 }
2222
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002223 // checks for the 2nd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002224 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002225 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002226 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2227 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2228 "format", std::string("2"), IdxExpr->getSourceRange());
2229 return;
2230 }
2231
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002232 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002233 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2234 "format", std::string("2"), IdxExpr->getSourceRange());
2235 return;
2236 }
2237
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002238 // make sure the format string is really a string
2239 QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2240 if (!Ty->isPointerType() ||
2241 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2242 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2243 IdxExpr->getSourceRange());
2244 return;
2245 }
2246
2247
2248 // check the 3rd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002249 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002250 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002251 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2252 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2253 "format", std::string("3"), FirstArgExpr->getSourceRange());
2254 return;
2255 }
2256
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002257 // check if the function is variadic if the 3rd argument non-zero
2258 if (FirstArg != 0) {
2259 if (proto->isVariadic()) {
2260 ++NumArgs; // +1 for ...
2261 } else {
2262 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2263 return;
2264 }
2265 }
2266
2267 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2268 // the input is just the current time + the format string
Chris Lattnerddee4232008-03-03 03:28:21 +00002269 if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002270 if (FirstArg != 0) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002271 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2272 FirstArgExpr->getSourceRange());
2273 return;
2274 }
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002275 // if 0 it disables parameter checking (to use with e.g. va_list)
2276 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002277 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2278 "format", std::string("3"), FirstArgExpr->getSourceRange());
2279 return;
2280 }
2281
2282 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2283 Idx.getZExtValue(), FirstArg.getZExtValue()));
2284}
2285
Nate Begemanc398f0b2008-02-21 19:30:49 +00002286void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2287 // check the attribute arguments.
2288 if (rawAttr->getNumArgs() != 1) {
2289 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2290 std::string("1"));
2291 return;
2292 }
2293 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2294 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002295
Nate Begemanc398f0b2008-02-21 19:30:49 +00002296 // Make sure that there is a string literal as the annotation's single
2297 // argument.
2298 if (!SE) {
2299 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2300 return;
2301 }
2302 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2303 SE->getByteLength())));
2304}
2305
Anders Carlsson78aaae92007-12-19 07:19:40 +00002306void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2307{
2308 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002309 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002310 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002311 std::string("1"));
2312 return;
2313 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002314
Anders Carlsson042c4e72008-02-16 19:51:27 +00002315 unsigned Align = 0;
2316
2317 if (rawAttr->getNumArgs() == 0) {
2318 // FIXME: This should be the target specific maximum alignment.
2319 // (For now we just use 128 bits which is the maximum on X86.
2320 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002321 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002322 } else {
2323 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2324 llvm::APSInt alignment(32);
2325 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002326 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002327 "aligned", alignmentExpr->getSourceRange());
2328 return;
2329 }
2330
2331 Align = alignment.getZExtValue() * 8;
2332 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002333
Anders Carlsson042c4e72008-02-16 19:51:27 +00002334 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002335}