blob: b56622ceb9c84d23f49cad48a7187331efd6f34e [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"
Eli Friedmanc594b322008-05-20 13:48:25 +000027#include "clang/AST/ExprCXX.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000028// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000029#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000030#include "clang/Lex/HeaderSearch.h"
Steve Naroff563477d2007-09-18 23:55:05 +000031#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000033#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034using namespace clang;
35
Steve Naroffb327ce02008-04-02 14:35:35 +000036Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
37 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
38
Douglas Gregor2ce52f32008-04-13 21:07:44 +000039 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
40 isa<ObjCInterfaceDecl>(IIDecl) ||
41 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000042 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000043 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000044}
45
Chris Lattner9fdf9c62008-04-22 18:39:57 +000046void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000047 assert( ( (isa<ObjCMethodDecl>(DC) && isa<TranslationUnitDecl>(CurContext))
Chris Lattner9fdf9c62008-04-22 18:39:57 +000048 || DC->getParent() == CurContext ) &&
Chris Lattnerb048c982008-04-06 04:47:34 +000049 "The next DeclContext should be directly contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000050 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000051}
52
Chris Lattnerb048c982008-04-06 04:47:34 +000053void Sema::PopDeclContext() {
54 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000055 // If CurContext is a ObjC method, getParent() will return NULL.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000056 CurContext = isa<ObjCMethodDecl>(CurContext)
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000057 ? Context.getTranslationUnitDecl()
58 : CurContext->getParent();
Chris Lattner0ed844b2008-04-04 06:12:32 +000059}
60
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000061/// Add this decl to the scope shadowed decl chains.
62void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000063 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000064
65 // C++ [basic.scope]p4:
66 // -- exactly one declaration shall declare a class name or
67 // enumeration name that is not a typedef name and the other
68 // declarations shall all refer to the same object or
69 // enumerator, or all refer to functions and function templates;
70 // in this case the class name or enumeration name is hidden.
71 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
72 // We are pushing the name of a tag (enum or class).
73 IdentifierResolver::ctx_iterator
74 CIT = IdResolver.ctx_begin(TD->getIdentifier(), TD->getDeclContext());
75 if (CIT != IdResolver.ctx_end(TD->getIdentifier()) &&
76 IdResolver.isDeclInScope(*CIT, TD->getDeclContext(), S)) {
77 // There is already a declaration with the same name in the same
78 // scope. It must be found before we find the new declaration,
79 // so swap the order on the shadowed declaration chain.
80
81 IdResolver.AddShadowedDecl(TD, *CIT);
82 return;
83 }
84 }
85
86 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000087}
88
Steve Naroffb216c882007-10-09 22:01:59 +000089void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000090 if (S->decl_empty()) return;
91 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000092
93 // We only want to remove the decls from the identifier decl chains for local
94 // scopes, when inside a function/method.
95 if (S->getFnParent() == 0)
96 return;
Chris Lattner31e05722007-08-26 06:24:45 +000097
Reid Spencer5f016e22007-07-11 17:01:13 +000098 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
99 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000100 Decl *TmpD = static_cast<Decl*>(*I);
101 assert(TmpD && "This decl didn't get pushed??");
102 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
103 assert(D && "This decl isn't a ScopedDecl?");
104
Reid Spencer5f016e22007-07-11 17:01:13 +0000105 IdentifierInfo *II = D->getIdentifier();
106 if (!II) continue;
107
Chris Lattner7f925cc2008-04-11 07:00:53 +0000108 // Unlink this decl from the identifier.
109 IdResolver.RemoveDecl(D);
110
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 // This will have to be revisited for C++: there we want to nest stuff in
112 // namespace decls etc. Even for C, we might want a top-level translation
113 // unit decl or something.
114 if (!CurFunctionDecl)
115 continue;
116
117 // Chain this decl to the containing function, it now owns the memory for
118 // the decl.
119 D->setNext(CurFunctionDecl->getDeclChain());
120 CurFunctionDecl->setDeclChain(D);
121 }
122}
123
Steve Naroffe8043c32008-04-01 23:04:06 +0000124/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
125/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000126ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000127 // The third "scope" argument is 0 since we aren't enabling lazy built-in
128 // creation from this context.
129 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000130
Steve Naroffb327ce02008-04-02 14:35:35 +0000131 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000132}
133
Steve Naroffe8043c32008-04-01 23:04:06 +0000134/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000135/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000136Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
137 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000138 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000139 unsigned NS = NSI;
140 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
141 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000142
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 // Scan up the scope chain looking for a decl that matches this identifier
144 // that is in the appropriate namespace. This search should not take long, as
145 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000146 for (IdentifierResolver::iterator
147 I = IdResolver.begin(II, CurContext), E = IdResolver.end(II); I != E; ++I)
148 if ((*I)->getIdentifierNamespace() & NS)
149 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000150
Reid Spencer5f016e22007-07-11 17:01:13 +0000151 // If we didn't find a use of this identifier, and if the identifier
152 // corresponds to a compiler builtin, create the decl object for the builtin
153 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000154 if (NS & Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000155 if (enableLazyBuiltinCreation) {
156 // If this is a builtin on this (or all) targets, create the decl.
157 if (unsigned BuiltinID = II->getBuiltinID())
158 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
159 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000160 if (getLangOptions().ObjC1) {
161 // @interface and @compatibility_alias introduce typedef-like names.
162 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000163 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000164 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000165 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
166 if (IDI != ObjCInterfaceDecls.end())
167 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000168 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
169 if (I != ObjCAliasDecls.end())
170 return I->second->getClassInterface();
171 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000172 }
173 return 0;
174}
175
Chris Lattner95e2c712008-05-05 22:18:14 +0000176void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000177 if (!Context.getBuiltinVaListType().isNull())
178 return;
179
180 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000181 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000182 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000183 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
184}
185
Reid Spencer5f016e22007-07-11 17:01:13 +0000186/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
187/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000188ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
189 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 Builtin::ID BID = (Builtin::ID)bid;
191
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000192 if (BID == Builtin::BI__builtin_va_start ||
Chris Lattner95e2c712008-05-05 22:18:14 +0000193 BID == Builtin::BI__builtin_va_copy ||
194 BID == Builtin::BI__builtin_va_end)
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000195 InitBuiltinVaListType();
196
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000197 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000198 FunctionDecl *New = FunctionDecl::Create(Context,
199 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000200 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000201 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000202
Chris Lattner95e2c712008-05-05 22:18:14 +0000203 // Create Decl objects for each parameter, adding them to the
204 // FunctionDecl.
205 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
206 llvm::SmallVector<ParmVarDecl*, 16> Params;
207 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
208 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
209 FT->getArgType(i), VarDecl::None, 0,
210 0));
211 New->setParams(&Params[0], Params.size());
212 }
213
214
215
Chris Lattner7f925cc2008-04-11 07:00:53 +0000216 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000217 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000218 return New;
219}
220
221/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
222/// and scope as a previous declaration 'Old'. Figure out how to resolve this
223/// situation, merging decls or emitting diagnostics as appropriate.
224///
Steve Naroffe8043c32008-04-01 23:04:06 +0000225TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000226 // Verify the old decl was also a typedef.
227 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
228 if (!Old) {
229 Diag(New->getLocation(), diag::err_redefinition_different_kind,
230 New->getName());
231 Diag(OldD->getLocation(), diag::err_previous_definition);
232 return New;
233 }
234
Steve Naroff8ee529b2007-10-31 18:42:27 +0000235 // Allow multiple definitions for ObjC built-in typedefs.
236 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000237 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000238 return Old;
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000239
240 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
241 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
242 // *either* declaration is in a system header. The code below implements
243 // this adhoc compatibility rule. FIXME: The following code will not
244 // work properly when compiling ".i" files (containing preprocessed output).
245 SourceManager &SrcMgr = Context.getSourceManager();
246 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
247 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
248 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
249 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
250 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
251
Steve Naroffc5e2f342008-03-26 21:27:00 +0000252 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
253 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
254 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroffd62701b2008-02-07 03:50:06 +0000255 getLangOptions().Microsoft)
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000256 return New;
Steve Naroffc5e2f342008-03-26 21:27:00 +0000257
Reid Spencer5f016e22007-07-11 17:01:13 +0000258 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
259 // TODO: This is totally simplistic. It should handle merging functions
260 // together etc, merging extern int X; int X; ...
Ted Kremenek2d05c082008-05-23 21:28:18 +0000261 Diag(New->getLocation(), diag::err_redefinition, New->getName());
262 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000263 return New;
264}
265
Chris Lattnerddee4232008-03-03 03:28:21 +0000266/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
267static bool DeclHasAttr(const Decl *decl, const Attr *target) {
268 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
269 if (attr->getKind() == target->getKind())
270 return true;
271
272 return false;
273}
274
275/// MergeAttributes - append attributes from the Old decl to the New one.
276static void MergeAttributes(Decl *New, Decl *Old) {
277 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
278
Chris Lattnerddee4232008-03-03 03:28:21 +0000279 while (attr) {
280 tmp = attr;
281 attr = attr->getNext();
282
283 if (!DeclHasAttr(New, tmp)) {
284 New->addAttr(tmp);
285 } else {
286 tmp->setNext(0);
287 delete(tmp);
288 }
289 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000290
291 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000292}
293
Chris Lattner04421082008-04-08 04:40:51 +0000294/// MergeFunctionDecl - We just parsed a function 'New' from
295/// declarator D which has the same name and scope as a previous
296/// declaration 'Old'. Figure out how to resolve this situation,
297/// merging decls or emitting diagnostics as appropriate.
Douglas Gregorf0097952008-04-21 02:02:58 +0000298/// Redeclaration will be set true if thisNew is a redeclaration OldD.
299FunctionDecl *
300Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
301 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000302 // Verify the old decl was also a function.
303 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
304 if (!Old) {
305 Diag(New->getLocation(), diag::err_redefinition_different_kind,
306 New->getName());
307 Diag(OldD->getLocation(), diag::err_previous_definition);
308 return New;
309 }
Chris Lattner04421082008-04-08 04:40:51 +0000310
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000311 QualType OldQType = Context.getCanonicalType(Old->getType());
312 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000313
Chris Lattner04421082008-04-08 04:40:51 +0000314 // C++ [dcl.fct]p3:
315 // All declarations for a function shall agree exactly in both the
316 // return type and the parameter-type-list.
Douglas Gregorf0097952008-04-21 02:02:58 +0000317 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
318 MergeAttributes(New, Old);
319 Redeclaration = true;
Chris Lattner04421082008-04-08 04:40:51 +0000320 return MergeCXXFunctionDecl(New, Old);
Douglas Gregorf0097952008-04-21 02:02:58 +0000321 }
Chris Lattner04421082008-04-08 04:40:51 +0000322
323 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000324 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000325 if (!getLangOptions().CPlusPlus &&
326 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000327 MergeAttributes(New, Old);
328 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000329 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000330 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000331
Steve Naroff837618c2008-01-16 15:01:34 +0000332 // A function that has already been declared has been redeclared or defined
333 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000334 diag::kind PrevDiag;
Douglas Gregorf0097952008-04-21 02:02:58 +0000335 if (Old->isThisDeclarationADefinition())
Steve Naroffe2ef8152008-04-04 14:32:09 +0000336 PrevDiag = diag::err_previous_definition;
337 else if (Old->isImplicit())
338 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000339 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000340 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000341
Reid Spencer5f016e22007-07-11 17:01:13 +0000342 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
343 // TODO: This is totally simplistic. It should handle merging functions
344 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000345 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
346 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 return New;
348}
349
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000350/// equivalentArrayTypes - Used to determine whether two array types are
351/// equivalent.
352/// We need to check this explicitly as an incomplete array definition is
353/// considered a VariableArrayType, so will not match a complete array
354/// definition that would be otherwise equivalent.
355static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
356 const ArrayType *NewAT = NewQType->getAsArrayType();
357 const ArrayType *OldAT = OldQType->getAsArrayType();
358
359 if (!NewAT || !OldAT)
360 return false;
361
362 // If either (or both) array types in incomplete we need to strip off the
363 // outer VariableArrayType. Once the outer VAT is removed the remaining
364 // types must be identical if the array types are to be considered
365 // equivalent.
366 // eg. int[][1] and int[1][1] become
367 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
368 // removing the outermost VAT gives
369 // CAT(1, int) and CAT(1, int)
370 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000371 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000372 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
373 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000374 NewQType = NewAT->getElementType().getCanonicalType();
375 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000376 }
377
378 return NewQType == OldQType;
379}
380
Reid Spencer5f016e22007-07-11 17:01:13 +0000381/// MergeVarDecl - We just parsed a variable 'New' which has the same name
382/// and scope as a previous declaration 'Old'. Figure out how to resolve this
383/// situation, merging decls or emitting diagnostics as appropriate.
384///
385/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
386/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
387///
Steve Naroffe8043c32008-04-01 23:04:06 +0000388VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 // Verify the old decl was also a variable.
390 VarDecl *Old = dyn_cast<VarDecl>(OldD);
391 if (!Old) {
392 Diag(New->getLocation(), diag::err_redefinition_different_kind,
393 New->getName());
394 Diag(OldD->getLocation(), diag::err_previous_definition);
395 return New;
396 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000397
398 MergeAttributes(New, Old);
399
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000401 QualType OldCType = Context.getCanonicalType(Old->getType());
402 QualType NewCType = Context.getCanonicalType(New->getType());
403 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 Diag(New->getLocation(), diag::err_redefinition, New->getName());
405 Diag(Old->getLocation(), diag::err_previous_definition);
406 return New;
407 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000408 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
409 if (New->getStorageClass() == VarDecl::Static &&
410 (Old->getStorageClass() == VarDecl::None ||
411 Old->getStorageClass() == VarDecl::Extern)) {
412 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
413 Diag(Old->getLocation(), diag::err_previous_definition);
414 return New;
415 }
416 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
417 if (New->getStorageClass() != VarDecl::Static &&
418 Old->getStorageClass() == VarDecl::Static) {
419 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
420 Diag(Old->getLocation(), diag::err_previous_definition);
421 return New;
422 }
423 // We've verified the types match, now handle "tentative" definitions.
Steve Naroff248a7532008-04-15 22:42:06 +0000424 if (Old->isFileVarDecl() && New->isFileVarDecl()) {
Steve Naroffb7b032e2008-01-30 00:44:01 +0000425 // Handle C "tentative" external object definitions (C99 6.9.2).
426 bool OldIsTentative = false;
427 bool NewIsTentative = false;
428
Steve Naroff248a7532008-04-15 22:42:06 +0000429 if (!Old->getInit() &&
430 (Old->getStorageClass() == VarDecl::None ||
431 Old->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000432 OldIsTentative = true;
433
434 // FIXME: this check doesn't work (since the initializer hasn't been
435 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
436 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
437 // thrown out the old decl.
Steve Naroff248a7532008-04-15 22:42:06 +0000438 if (!New->getInit() &&
439 (New->getStorageClass() == VarDecl::None ||
440 New->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000441 ; // change to NewIsTentative = true; once the code is moved.
442
443 if (NewIsTentative || OldIsTentative)
444 return New;
445 }
Steve Naroff235549c2008-05-12 22:36:43 +0000446 // Handle __private_extern__ just like extern.
Steve Naroffb7b032e2008-01-30 00:44:01 +0000447 if (Old->getStorageClass() != VarDecl::Extern &&
Steve Naroff235549c2008-05-12 22:36:43 +0000448 Old->getStorageClass() != VarDecl::PrivateExtern &&
449 New->getStorageClass() != VarDecl::Extern &&
450 New->getStorageClass() != VarDecl::PrivateExtern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 Diag(New->getLocation(), diag::err_redefinition, New->getName());
452 Diag(Old->getLocation(), diag::err_previous_definition);
453 }
454 return New;
455}
456
Chris Lattner04421082008-04-08 04:40:51 +0000457/// CheckParmsForFunctionDef - Check that the parameters of the given
458/// function are appropriate for the definition of a function. This
459/// takes care of any checks that cannot be performed on the
460/// declaration itself, e.g., that the types of each of the function
461/// parameters are complete.
462bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
463 bool HasInvalidParm = false;
464 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
465 ParmVarDecl *Param = FD->getParamDecl(p);
466
467 // C99 6.7.5.3p4: the parameters in a parameter type list in a
468 // function declarator that is part of a function definition of
469 // that function shall not have incomplete type.
470 if (Param->getType()->isIncompleteType() &&
471 !Param->isInvalidDecl()) {
472 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
473 Param->getType().getAsString());
474 Param->setInvalidDecl();
475 HasInvalidParm = true;
476 }
477 }
478
479 return HasInvalidParm;
480}
481
482/// CreateImplicitParameter - Creates an implicit function parameter
483/// in the scope S and with the given type. This routine is used, for
484/// example, to create the implicit "self" parameter in an Objective-C
485/// method.
486ParmVarDecl *
487Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
488 SourceLocation IdLoc, QualType Type) {
489 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
490 VarDecl::None, 0, 0);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000491 if (Id)
492 PushOnScopeChains(New, S);
Chris Lattner04421082008-04-08 04:40:51 +0000493
494 return New;
495}
496
Reid Spencer5f016e22007-07-11 17:01:13 +0000497/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
498/// no declarator (e.g. "struct foo;") is parsed.
499Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
500 // TODO: emit error on 'int;' or 'const enum foo;'.
501 // TODO: emit error on 'typedef int;'
502 // if (!DS.isMissingDeclaratorOk()) Diag(...);
503
Steve Naroff92199282007-11-17 21:37:36 +0000504 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000505}
506
Steve Naroffd0091aa2008-01-10 22:15:12 +0000507bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000508 // Get the type before calling CheckSingleAssignmentConstraints(), since
509 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000510 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000511
Chris Lattner5cf216b2008-01-04 18:04:52 +0000512 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
513 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
514 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000515}
516
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000517bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000518 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000519 // C99 6.7.8p14. We have an array of character type with unknown size
520 // being initialized to a string literal.
521 llvm::APSInt ConstVal(32);
522 ConstVal = strLiteral->getByteLength() + 1;
523 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000524 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000525 ArrayType::Normal, 0);
526 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
527 // C99 6.7.8p14. We have an array of character type with known size.
528 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
529 Diag(strLiteral->getSourceRange().getBegin(),
530 diag::warn_initializer_string_for_char_array_too_long,
531 strLiteral->getSourceRange());
532 } else {
533 assert(0 && "HandleStringLiteralInit(): Invalid array type");
534 }
535 // Set type from "char *" to "constant array of char".
536 strLiteral->setType(DeclT);
537 // For now, we always return false (meaning success).
538 return false;
539}
540
541StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000542 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000543 if (AT && AT->getElementType()->isCharType()) {
544 return dyn_cast<StringLiteral>(Init);
545 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000546 return 0;
547}
548
Steve Naroffa9960332008-01-25 00:51:06 +0000549bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000550 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
551 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000552 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000553 return Diag(VAT->getSizeExpr()->getLocStart(),
554 diag::err_variable_object_no_init,
555 VAT->getSizeExpr()->getSourceRange());
556
Steve Naroff2fdc3742007-12-10 22:44:33 +0000557 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
558 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000559 // FIXME: Handle wide strings
560 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
561 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000562
563 if (DeclType->isArrayType())
564 return Diag(Init->getLocStart(),
565 diag::err_array_init_list_required,
566 Init->getSourceRange());
567
Steve Naroffd0091aa2008-01-10 22:15:12 +0000568 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000569 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000570
Steve Naroff0cca7492008-05-01 22:18:59 +0000571 InitListChecker CheckInitList(this, InitList, DeclType);
572 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000573}
574
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000575Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000576Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000577 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000578 IdentifierInfo *II = D.getIdentifier();
579
Chris Lattnere80a59c2007-07-25 00:24:17 +0000580 // All of these full declarators require an identifier. If it doesn't have
581 // one, the ParsedFreeStandingDeclSpec action should be used.
582 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000583 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000584 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000585 D.getDeclSpec().getSourceRange(), D.getSourceRange());
586 return 0;
587 }
588
Chris Lattner31e05722007-08-26 06:24:45 +0000589 // The scope passed in may not be a decl scope. Zip up the scope tree until
590 // we find one that is.
591 while ((S->getFlags() & Scope::DeclScope) == 0)
592 S = S->getParent();
593
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000595 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000596 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000597 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000598
599 // In C++, the previous declaration we find might be a tag type
600 // (class or enum). In this case, the new declaration will hide the
601 // tag type.
602 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
603 PrevDecl = 0;
604
Chris Lattner41af0932007-11-14 06:34:38 +0000605 QualType R = GetTypeForDeclarator(D, S);
606 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
607
Reid Spencer5f016e22007-07-11 17:01:13 +0000608 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000609 // Check that there are no default arguments (C++ only).
610 if (getLangOptions().CPlusPlus)
611 CheckExtraCXXDefaultArguments(D);
612
Chris Lattner41af0932007-11-14 06:34:38 +0000613 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000614 if (!NewTD) return 0;
615
616 // Handle attributes prior to checking for duplicates in MergeVarDecl
617 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
618 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000619 // Merge the decl with the existing one if appropriate. If the decl is
620 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000621 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000622 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
623 if (NewTD == 0) return 0;
624 }
625 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000626 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000627 // C99 6.7.7p2: If a typedef name specifies a variably modified type
628 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000629 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
630 // FIXME: Diagnostic needs to be fixed.
631 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000632 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000633 }
634 }
Chris Lattner41af0932007-11-14 06:34:38 +0000635 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000636 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000637 switch (D.getDeclSpec().getStorageClassSpec()) {
638 default: assert(0 && "Unknown storage class!");
639 case DeclSpec::SCS_auto:
640 case DeclSpec::SCS_register:
641 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
642 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000643 InvalidDecl = true;
644 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
646 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
647 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000648 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000649 }
650
Chris Lattnera98e58d2008-03-15 21:24:04 +0000651 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattner0ed844b2008-04-04 06:12:32 +0000652 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
653 D.getIdentifierLoc(),
Chris Lattnera98e58d2008-03-15 21:24:04 +0000654 II, R, SC, isInline,
655 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000656 // Handle attributes.
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000657 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
658 D.getAttributes());
Chris Lattner04421082008-04-08 04:40:51 +0000659
660 // Copy the parameter declarations from the declarator D to
661 // the function declaration NewFD, if they are available.
662 if (D.getNumTypeObjects() > 0 &&
663 D.getTypeObject(0).Fun.hasPrototype) {
664 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
665
666 // Create Decl objects for each parameter, adding them to the
667 // FunctionDecl.
668 llvm::SmallVector<ParmVarDecl*, 16> Params;
669
670 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
671 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000672 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000673 // We let through "const void" here because Sema::GetTypeForDeclarator
674 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000675 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
676 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000677 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
678 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000679 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
680
Chris Lattnerdef026a2008-04-10 02:26:16 +0000681 // In C++, the empty parameter-type-list must be spelled "void"; a
682 // typedef of void is not permitted.
683 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000684 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000685 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
686 }
687
Chris Lattner04421082008-04-08 04:40:51 +0000688 } else {
689 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
690 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
691 }
692
693 NewFD->setParams(&Params[0], Params.size());
694 }
695
Steve Naroffffce4d52008-01-09 23:34:55 +0000696 // Merge the decl with the existing one if appropriate. Since C functions
697 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000698 if (PrevDecl &&
699 (!getLangOptions().CPlusPlus ||
700 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000701 bool Redeclaration = false;
702 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +0000703 if (NewFD == 0) return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +0000704 if (Redeclaration) {
Eli Friedman27424962008-05-27 05:07:37 +0000705 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregorf0097952008-04-21 02:02:58 +0000706 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 }
708 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000709
710 // In C++, check default arguments now that we have merged decls.
711 if (getLangOptions().CPlusPlus)
712 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000713 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000714 // Check that there are no default arguments (C++ only).
715 if (getLangOptions().CPlusPlus)
716 CheckExtraCXXDefaultArguments(D);
717
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000718 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000719 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
720 D.getIdentifier()->getName());
721 InvalidDecl = true;
722 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000723
724 VarDecl *NewVD;
725 VarDecl::StorageClass SC;
726 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000727 default: assert(0 && "Unknown storage class!");
728 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
729 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
730 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
731 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
732 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
733 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000735 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000736 // C99 6.9p2: The storage-class specifiers auto and register shall not
737 // appear in the declaration specifiers in an external declaration.
738 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
739 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
740 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000741 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000742 }
Steve Naroff248a7532008-04-15 22:42:06 +0000743 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
744 II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000745 } else {
Steve Naroff248a7532008-04-15 22:42:06 +0000746 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
747 II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000748 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000749 // Handle attributes prior to checking for duplicates in MergeVarDecl
750 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
751 D.getAttributes());
Nate Begemanc8e89a82008-03-14 18:07:10 +0000752
753 // Emit an error if an address space was applied to decl with local storage.
754 // This includes arrays of objects with address space qualifiers, but not
755 // automatic variables that point to other address spaces.
756 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000757 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
758 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
759 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000760 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000761 // Merge the decl with the existing one if appropriate. If the decl is
762 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000763 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 NewVD = MergeVarDecl(NewVD, PrevDecl);
765 if (NewVD == 0) return 0;
766 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000767 New = NewVD;
768 }
769
770 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000771 if (II)
772 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000773 // If any semantic error occurred, mark the decl as invalid.
774 if (D.getInvalidType() || InvalidDecl)
775 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000776
777 return New;
778}
779
Eli Friedmanc594b322008-05-20 13:48:25 +0000780bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
781 switch (Init->getStmtClass()) {
782 default:
783 Diag(Init->getExprLoc(),
784 diag::err_init_element_not_constant, Init->getSourceRange());
785 return true;
786 case Expr::ParenExprClass: {
787 const ParenExpr* PE = cast<ParenExpr>(Init);
788 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
789 }
790 case Expr::CompoundLiteralExprClass:
791 return cast<CompoundLiteralExpr>(Init)->isFileScope();
792 case Expr::DeclRefExprClass: {
793 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +0000794 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
795 if (VD->hasGlobalStorage())
796 return false;
797 Diag(Init->getExprLoc(),
798 diag::err_init_element_not_constant, Init->getSourceRange());
799 return true;
800 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000801 if (isa<FunctionDecl>(D))
802 return false;
803 Diag(Init->getExprLoc(),
804 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Naroffd0091aa2008-01-10 22:15:12 +0000805 return true;
806 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000807 case Expr::MemberExprClass: {
808 const MemberExpr *M = cast<MemberExpr>(Init);
809 if (M->isArrow())
810 return CheckAddressConstantExpression(M->getBase());
811 return CheckAddressConstantExpressionLValue(M->getBase());
812 }
813 case Expr::ArraySubscriptExprClass: {
814 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
815 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
816 return CheckAddressConstantExpression(ASE->getBase()) ||
817 CheckArithmeticConstantExpression(ASE->getIdx());
818 }
819 case Expr::StringLiteralClass:
820 case Expr::PreDefinedExprClass:
821 return false;
822 case Expr::UnaryOperatorClass: {
823 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
824
825 // C99 6.6p9
826 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +0000827 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +0000828
829 Diag(Init->getExprLoc(),
830 diag::err_init_element_not_constant, Init->getSourceRange());
831 return true;
832 }
833 }
834}
835
836bool Sema::CheckAddressConstantExpression(const Expr* Init) {
837 switch (Init->getStmtClass()) {
838 default:
839 Diag(Init->getExprLoc(),
840 diag::err_init_element_not_constant, Init->getSourceRange());
841 return true;
842 case Expr::ParenExprClass: {
843 const ParenExpr* PE = cast<ParenExpr>(Init);
844 return CheckAddressConstantExpression(PE->getSubExpr());
845 }
846 case Expr::StringLiteralClass:
847 case Expr::ObjCStringLiteralClass:
848 return false;
849 case Expr::CallExprClass: {
850 const CallExpr *CE = cast<CallExpr>(Init);
851 if (CE->isBuiltinConstantExpr())
852 return false;
853 Diag(Init->getExprLoc(),
854 diag::err_init_element_not_constant, Init->getSourceRange());
855 return true;
856 }
857 case Expr::UnaryOperatorClass: {
858 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
859
860 // C99 6.6p9
861 if (Exp->getOpcode() == UnaryOperator::AddrOf)
862 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
863
864 if (Exp->getOpcode() == UnaryOperator::Extension)
865 return CheckAddressConstantExpression(Exp->getSubExpr());
866
867 Diag(Init->getExprLoc(),
868 diag::err_init_element_not_constant, Init->getSourceRange());
869 return true;
870 }
871 case Expr::BinaryOperatorClass: {
872 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
873 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
874
875 Expr *PExp = Exp->getLHS();
876 Expr *IExp = Exp->getRHS();
877 if (IExp->getType()->isPointerType())
878 std::swap(PExp, IExp);
879
880 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
881 return CheckAddressConstantExpression(PExp) ||
882 CheckArithmeticConstantExpression(IExp);
883 }
884 case Expr::ImplicitCastExprClass: {
885 const Expr* SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
886
887 // Check for implicit promotion
888 if (SubExpr->getType()->isFunctionType() ||
889 SubExpr->getType()->isArrayType())
890 return CheckAddressConstantExpressionLValue(SubExpr);
891
892 // Check for pointer->pointer cast
893 if (SubExpr->getType()->isPointerType())
894 return CheckAddressConstantExpression(SubExpr);
895
896 if (SubExpr->getType()->isArithmeticType())
897 return CheckArithmeticConstantExpression(SubExpr);
898
899 Diag(Init->getExprLoc(),
900 diag::err_init_element_not_constant, Init->getSourceRange());
901 return true;
902 }
903 case Expr::CastExprClass: {
904 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
905
906 // Check for pointer->pointer cast
907 if (SubExpr->getType()->isPointerType())
908 return CheckAddressConstantExpression(SubExpr);
909
910 // FIXME: Should we pedwarn for (int*)(0+0)?
911 if (SubExpr->getType()->isArithmeticType())
912 return CheckArithmeticConstantExpression(SubExpr);
913
914 Diag(Init->getExprLoc(),
915 diag::err_init_element_not_constant, Init->getSourceRange());
916 return true;
917 }
918 case Expr::ConditionalOperatorClass: {
919 // FIXME: Should we pedwarn here?
920 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
921 if (!Exp->getCond()->getType()->isArithmeticType()) {
922 Diag(Init->getExprLoc(),
923 diag::err_init_element_not_constant, Init->getSourceRange());
924 return true;
925 }
926 if (CheckArithmeticConstantExpression(Exp->getCond()))
927 return true;
928 if (Exp->getLHS() &&
929 CheckAddressConstantExpression(Exp->getLHS()))
930 return true;
931 return CheckAddressConstantExpression(Exp->getRHS());
932 }
933 case Expr::AddrLabelExprClass:
934 return false;
935 }
936}
937
938bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
939 switch (Init->getStmtClass()) {
940 default:
941 Diag(Init->getExprLoc(),
942 diag::err_init_element_not_constant, Init->getSourceRange());
943 return true;
944 case Expr::ParenExprClass: {
945 const ParenExpr* PE = cast<ParenExpr>(Init);
946 return CheckArithmeticConstantExpression(PE->getSubExpr());
947 }
948 case Expr::FloatingLiteralClass:
949 case Expr::IntegerLiteralClass:
950 case Expr::CharacterLiteralClass:
951 case Expr::ImaginaryLiteralClass:
952 case Expr::TypesCompatibleExprClass:
953 case Expr::CXXBoolLiteralExprClass:
954 return false;
955 case Expr::CallExprClass: {
956 const CallExpr *CE = cast<CallExpr>(Init);
957 if (CE->isBuiltinConstantExpr())
958 return false;
959 Diag(Init->getExprLoc(),
960 diag::err_init_element_not_constant, Init->getSourceRange());
961 return true;
962 }
963 case Expr::DeclRefExprClass: {
964 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
965 if (isa<EnumConstantDecl>(D))
966 return false;
967 Diag(Init->getExprLoc(),
968 diag::err_init_element_not_constant, Init->getSourceRange());
969 return true;
970 }
971 case Expr::CompoundLiteralExprClass:
972 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
973 // but vectors are allowed to be magic.
974 if (Init->getType()->isVectorType())
975 return false;
976 Diag(Init->getExprLoc(),
977 diag::err_init_element_not_constant, Init->getSourceRange());
978 return true;
979 case Expr::UnaryOperatorClass: {
980 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
981
982 switch (Exp->getOpcode()) {
983 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
984 // See C99 6.6p3.
985 default:
986 Diag(Init->getExprLoc(),
987 diag::err_init_element_not_constant, Init->getSourceRange());
988 return true;
989 case UnaryOperator::SizeOf:
990 case UnaryOperator::AlignOf:
991 case UnaryOperator::OffsetOf:
992 // sizeof(E) is a constantexpr if and only if E is not evaluted.
993 // See C99 6.5.3.4p2 and 6.6p3.
994 if (Exp->getSubExpr()->getType()->isConstantSizeType())
995 return false;
996 Diag(Init->getExprLoc(),
997 diag::err_init_element_not_constant, Init->getSourceRange());
998 return true;
999 case UnaryOperator::Extension:
1000 case UnaryOperator::LNot:
1001 case UnaryOperator::Plus:
1002 case UnaryOperator::Minus:
1003 case UnaryOperator::Not:
1004 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1005 }
1006 }
1007 case Expr::SizeOfAlignOfTypeExprClass: {
1008 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1009 // Special check for void types, which are allowed as an extension
1010 if (Exp->getArgumentType()->isVoidType())
1011 return false;
1012 // alignof always evaluates to a constant.
1013 // FIXME: is sizeof(int[3.0]) a constant expression?
1014 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1015 Diag(Init->getExprLoc(),
1016 diag::err_init_element_not_constant, Init->getSourceRange());
1017 return true;
1018 }
1019 return false;
1020 }
1021 case Expr::BinaryOperatorClass: {
1022 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1023
1024 if (Exp->getLHS()->getType()->isArithmeticType() &&
1025 Exp->getRHS()->getType()->isArithmeticType()) {
1026 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1027 CheckArithmeticConstantExpression(Exp->getRHS());
1028 }
1029
1030 Diag(Init->getExprLoc(),
1031 diag::err_init_element_not_constant, Init->getSourceRange());
1032 return true;
1033 }
1034 case Expr::ImplicitCastExprClass:
1035 case Expr::CastExprClass: {
1036 const Expr *SubExpr;
1037 if (const CastExpr *C = dyn_cast<CastExpr>(Init)) {
1038 SubExpr = C->getSubExpr();
1039 } else {
1040 SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
1041 }
1042
1043 if (SubExpr->getType()->isArithmeticType())
1044 return CheckArithmeticConstantExpression(SubExpr);
1045
1046 Diag(Init->getExprLoc(),
1047 diag::err_init_element_not_constant, Init->getSourceRange());
1048 return true;
1049 }
1050 case Expr::ConditionalOperatorClass: {
1051 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1052 if (CheckArithmeticConstantExpression(Exp->getCond()))
1053 return true;
1054 if (Exp->getLHS() &&
1055 CheckArithmeticConstantExpression(Exp->getLHS()))
1056 return true;
1057 return CheckArithmeticConstantExpression(Exp->getRHS());
1058 }
1059 }
1060}
1061
1062bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
1063 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1064 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1065 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1066
1067 if (Init->getType()->isReferenceType()) {
1068 // FIXME: Work out how the heck reference types work
1069 return false;
1070#if 0
1071 // A reference is constant if the address of the expression
1072 // is constant
1073 // We look through initlists here to simplify
1074 // CheckAddressConstantExpressionLValue.
1075 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1076 assert(Exp->getNumInits() > 0 &&
1077 "Refernce initializer cannot be empty");
1078 Init = Exp->getInit(0);
1079 }
1080 return CheckAddressConstantExpressionLValue(Init);
1081#endif
1082 }
1083
1084 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1085 unsigned numInits = Exp->getNumInits();
1086 for (unsigned i = 0; i < numInits; i++) {
1087 // FIXME: Need to get the type of the declaration for C++,
1088 // because it could be a reference?
1089 if (CheckForConstantInitializer(Exp->getInit(i),
1090 Exp->getInit(i)->getType()))
1091 return true;
1092 }
1093 return false;
1094 }
1095
1096 if (Init->isNullPointerConstant(Context))
1097 return false;
1098 if (Init->getType()->isArithmeticType()) {
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001099 QualType InitTy = Init->getType().getCanonicalType().getUnqualifiedType();
1100 if (InitTy == Context.BoolTy) {
1101 // Special handling for pointers implicitly cast to bool;
1102 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1103 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1104 Expr* SubE = ICE->getSubExpr();
1105 if (SubE->getType()->isPointerType() ||
1106 SubE->getType()->isArrayType() ||
1107 SubE->getType()->isFunctionType()) {
1108 return CheckAddressConstantExpression(Init);
1109 }
1110 }
1111 } else if (InitTy->isIntegralType()) {
1112 Expr* SubE = 0;
1113 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init))
1114 SubE = ICE->getSubExpr();
1115 else if (CastExpr* CE = dyn_cast<CastExpr>(Init))
1116 SubE = CE->getSubExpr();
1117 // Special check for pointer cast to int; we allow as an extension
1118 // an address constant cast to an integer if the integer
1119 // is of an appropriate width (this sort of code is apparently used
1120 // in some places).
1121 // FIXME: Add pedwarn?
1122 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1123 if (SubE && (SubE->getType()->isPointerType() ||
1124 SubE->getType()->isArrayType() ||
1125 SubE->getType()->isFunctionType())) {
1126 unsigned IntWidth = Context.getTypeSize(Init->getType());
1127 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1128 if (IntWidth >= PointerWidth)
1129 return CheckAddressConstantExpression(Init);
1130 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001131 }
1132
1133 return CheckArithmeticConstantExpression(Init);
1134 }
1135
1136 if (Init->getType()->isPointerType())
1137 return CheckAddressConstantExpression(Init);
1138
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001139 // An array type at the top level that isn't an init-list must
1140 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001141 if (Init->getType()->isArrayType())
1142 return false;
1143
1144 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1145 Init->getSourceRange());
1146 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001147}
1148
Steve Naroffbb204692007-09-12 14:07:44 +00001149void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001150 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001151 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001152 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001153
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001154 // If there is no declaration, there was an error parsing it. Just ignore
1155 // the initializer.
1156 if (RealDecl == 0) {
1157 delete Init;
1158 return;
1159 }
Steve Naroffbb204692007-09-12 14:07:44 +00001160
Steve Naroff410e3e22007-09-12 20:13:48 +00001161 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1162 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001163 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1164 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001165 RealDecl->setInvalidDecl();
1166 return;
1167 }
Steve Naroffbb204692007-09-12 14:07:44 +00001168 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001169 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001170 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001171 if (VDecl->isBlockVarDecl()) {
1172 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001173 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001174 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001175 VDecl->setInvalidDecl();
1176 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +00001177 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001178 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001179 if (SC == VarDecl::Static) // C99 6.7.8p4.
1180 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001181 }
Steve Naroff248a7532008-04-15 22:42:06 +00001182 } else if (VDecl->isFileVarDecl()) {
1183 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001184 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001185 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +00001186 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001187 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001188
1189 // C99 6.7.8p4. All file scoped initializers need to be constant.
1190 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001191 }
1192 // If the type changed, it means we had an incomplete type that was
1193 // completed by the initializer. For example:
1194 // int ary[] = { 1, 3, 5 };
1195 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001196 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001197 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001198 Init->setType(DclT);
1199 }
Steve Naroffbb204692007-09-12 14:07:44 +00001200
1201 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001202 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001203 return;
1204}
1205
Reid Spencer5f016e22007-07-11 17:01:13 +00001206/// The declarators are chained together backwards, reverse the list.
1207Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1208 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001209 Decl *GroupDecl = static_cast<Decl*>(group);
1210 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001211 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001212
1213 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1214 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001215 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001216 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001217 else { // reverse the list.
1218 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001219 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001220 Group->setNextDeclarator(NewGroup);
1221 NewGroup = Group;
1222 Group = Next;
1223 }
1224 }
1225 // Perform semantic analysis that depends on having fully processed both
1226 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001227 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001228 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1229 if (!IDecl)
1230 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001231 QualType T = IDecl->getType();
1232
1233 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1234 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001235 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1236 IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +00001237 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001238 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1239 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001240 }
1241 }
1242 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1243 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001244 if (IDecl->isBlockVarDecl() &&
1245 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001246 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001247 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1248 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001249 IDecl->setInvalidDecl();
1250 }
1251 }
1252 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1253 // object that has file scope without an initializer, and without a
1254 // storage-class specifier or with the storage-class specifier "static",
1255 // constitutes a tentative definition. Note: A tentative definition with
1256 // external linkage is valid (C99 6.2.2p5).
Steve Naroff248a7532008-04-15 22:42:06 +00001257 if (IDecl && !IDecl->getInit() &&
1258 (IDecl->getStorageClass() == VarDecl::Static ||
1259 IDecl->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001260 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001261 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1262 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001263 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001264 // C99 6.9.2p3: If the declaration of an identifier for an object is
1265 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1266 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001267 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1268 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001269 IDecl->setInvalidDecl();
1270 }
1271 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001272 }
1273 return NewGroup;
1274}
Steve Naroffe1223f72007-08-28 03:03:08 +00001275
Chris Lattner04421082008-04-08 04:40:51 +00001276/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1277/// to introduce parameters into function prototype scope.
1278Sema::DeclTy *
1279Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1280 DeclSpec &DS = D.getDeclSpec();
1281
1282 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1283 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1284 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1285 Diag(DS.getStorageClassSpecLoc(),
1286 diag::err_invalid_storage_class_in_func_decl);
1287 DS.ClearStorageClassSpecs();
1288 }
1289 if (DS.isThreadSpecified()) {
1290 Diag(DS.getThreadSpecLoc(),
1291 diag::err_invalid_storage_class_in_func_decl);
1292 DS.ClearStorageClassSpecs();
1293 }
1294
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001295 // Check that there are no default arguments inside the type of this
1296 // parameter (C++ only).
1297 if (getLangOptions().CPlusPlus)
1298 CheckExtraCXXDefaultArguments(D);
1299
Chris Lattner04421082008-04-08 04:40:51 +00001300 // In this context, we *do not* check D.getInvalidType(). If the declarator
1301 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1302 // though it will not reflect the user specified type.
1303 QualType parmDeclType = GetTypeForDeclarator(D, S);
1304
1305 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1306
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1308 // Can this happen for params? We already checked that they don't conflict
1309 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001310 IdentifierInfo *II = D.getIdentifier();
1311 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1312 if (S->isDeclScope(PrevDecl)) {
1313 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1314 dyn_cast<NamedDecl>(PrevDecl)->getName());
1315
1316 // Recover by removing the name
1317 II = 0;
1318 D.SetIdentifier(0, D.getIdentifierLoc());
1319 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001320 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001321
1322 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1323 // Doing the promotion here has a win and a loss. The win is the type for
1324 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1325 // code generator). The loss is the orginal type isn't preserved. For example:
1326 //
1327 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1328 // int blockvardecl[5];
1329 // sizeof(parmvardecl); // size == 4
1330 // sizeof(blockvardecl); // size == 20
1331 // }
1332 //
1333 // For expressions, all implicit conversions are captured using the
1334 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1335 //
1336 // FIXME: If a source translation tool needs to see the original type, then
1337 // we need to consider storing both types (in ParmVarDecl)...
1338 //
Chris Lattnere6327742008-04-02 05:18:44 +00001339 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001340 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001341 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001342 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001343 parmDeclType = Context.getPointerType(parmDeclType);
1344
Chris Lattner04421082008-04-08 04:40:51 +00001345 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1346 D.getIdentifierLoc(), II,
1347 parmDeclType, VarDecl::None,
1348 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001349
Chris Lattner04421082008-04-08 04:40:51 +00001350 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001351 New->setInvalidDecl();
1352
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001353 if (II)
1354 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001355
Nate Begemanfc584522008-05-09 16:56:01 +00001356 HandleDeclAttributes(New, D.getDeclSpec().getAttributes(),
1357 D.getAttributes());
Reid Spencer5f016e22007-07-11 17:01:13 +00001358 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001359
Reid Spencer5f016e22007-07-11 17:01:13 +00001360}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001361
Chris Lattnerb652cea2007-10-09 17:14:05 +00001362Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001363 assert(CurFunctionDecl == 0 && "Function parsing confused");
1364 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1365 "Not a function declarator!");
1366 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001367
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1369 // for a K&R function.
1370 if (!FTI.hasPrototype) {
1371 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001372 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1374 FTI.ArgInfo[i].Ident->getName());
1375 // Implicitly declare the argument as type 'int' for lack of a better
1376 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001377 DeclSpec DS;
1378 const char* PrevSpec; // unused
1379 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1380 PrevSpec);
1381 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1382 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1383 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001384 }
1385 }
Chris Lattner52804082008-02-17 19:31:09 +00001386
Reid Spencer5f016e22007-07-11 17:01:13 +00001387 // Since this is a function definition, act as though we have information
1388 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001389 if (FTI.NumArgs)
1390 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001392 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 }
1394
1395 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001396
1397 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001398 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001399 GlobalScope);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001400 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1401 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1402 const FunctionDecl *Definition;
1403 if (FD->getBody(Definition)) {
1404 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1405 D.getIdentifier()->getName());
1406 Diag(Definition->getLocation(), diag::err_previous_definition);
1407 }
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001408 }
1409 }
Steve Narofffabbc342008-02-12 01:09:36 +00001410 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001411 FunctionDecl *FD = cast<FunctionDecl>(decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 CurFunctionDecl = FD;
Chris Lattnerb048c982008-04-06 04:47:34 +00001413 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001414
1415 // Check the validity of our function parameters
1416 CheckParmsForFunctionDef(FD);
1417
1418 // Introduce our parameters into the function scope
1419 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1420 ParmVarDecl *Param = FD->getParamDecl(p);
1421 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001422 if (Param->getIdentifier())
1423 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 }
Chris Lattner04421082008-04-08 04:40:51 +00001425
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 return FD;
1427}
1428
Steve Naroffd6d054d2007-11-11 23:20:51 +00001429Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1430 Decl *dcl = static_cast<Decl *>(D);
1431 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1432 FD->setBody((Stmt*)Body);
1433 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001434 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001435 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001436 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001437 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001438 }
Chris Lattnerb048c982008-04-06 04:47:34 +00001439 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001440 // Verify and clean out per-function state.
1441
1442 // Check goto/label use.
1443 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1444 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1445 // Verify that we have no forward references left. If so, there was a goto
1446 // or address of a label taken, but no definition of it. Label fwd
1447 // definitions are indicated with a null substmt.
1448 if (I->second->getSubStmt() == 0) {
1449 LabelStmt *L = I->second;
1450 // Emit error.
1451 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1452
1453 // At this point, we have gotos that use the bogus label. Stitch it into
1454 // the function body so that they aren't leaked and that the AST is well
1455 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001456 if (Body) {
1457 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1458 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1459 } else {
1460 // The whole function wasn't parsed correctly, just delete this.
1461 delete L;
1462 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001463 }
1464 }
1465 LabelMap.clear();
1466
Steve Naroffd6d054d2007-11-11 23:20:51 +00001467 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001468}
1469
Reid Spencer5f016e22007-07-11 17:01:13 +00001470/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1471/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001472ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1473 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001474 // Extension in C99. Legal in C90, but warn about it.
1475 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001477 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001478 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1479
1480 // FIXME: handle stuff like:
1481 // void foo() { extern float X(); }
1482 // void bar() { X(); } <-- implicit decl for X in another scope.
1483
1484 // Set a Declarator for the implicit definition: int foo();
1485 const char *Dummy;
1486 DeclSpec DS;
1487 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1488 Error = Error; // Silence warning.
1489 assert(!Error && "Error setting up implicit decl!");
1490 Declarator D(DS, Declarator::BlockContext);
1491 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1492 D.SetIdentifier(&II, Loc);
1493
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001494 // Insert this function into translation-unit scope.
1495
1496 DeclContext *PrevDC = CurContext;
1497 CurContext = Context.getTranslationUnitDecl();
1498
Steve Naroffe2ef8152008-04-04 14:32:09 +00001499 FunctionDecl *FD =
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001500 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001501 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001502
1503 CurContext = PrevDC;
1504
Steve Naroffe2ef8152008-04-04 14:32:09 +00001505 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001506}
1507
1508
Chris Lattner41af0932007-11-14 06:34:38 +00001509TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001510 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001511 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001512 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001513
1514 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001515 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1516 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001517 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001518 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001519 if (D.getInvalidType())
1520 NewTD->setInvalidDecl();
1521 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001522}
1523
Steve Naroff08d92e42007-09-15 18:49:24 +00001524/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001525/// former case, Name will be non-null. In the later case, Name will be null.
1526/// TagType indicates what kind of tag this is. TK indicates whether this is a
1527/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001528Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001529 SourceLocation KWLoc, IdentifierInfo *Name,
1530 SourceLocation NameLoc, AttributeList *Attr) {
1531 // If this is a use of an existing tag, it must have a name.
1532 assert((Name != 0 || TK == TK_Definition) &&
1533 "Nameless record must be a definition!");
1534
1535 Decl::Kind Kind;
1536 switch (TagType) {
1537 default: assert(0 && "Unknown tag type!");
1538 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1539 case DeclSpec::TST_union: Kind = Decl::Union; break;
Chris Lattner99dc9142008-04-13 18:59:07 +00001540 case DeclSpec::TST_class: Kind = Decl::Class; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1542 }
1543
1544 // If this is a named struct, check to see if there was a previous forward
1545 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001546 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1547 if (ScopedDecl *PrevDecl =
1548 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001549
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001550 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1551 "unexpected Decl type");
1552 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1553 // If this is a use of a previous tag, or if the tag is already declared in
1554 // the same scope (so that the definition/declaration completes or
1555 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001556 if (TK == TK_Reference ||
1557 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001558 // Make sure that this wasn't declared as an enum and now used as a struct
1559 // or something similar.
1560 if (PrevDecl->getKind() != Kind) {
1561 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1562 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1563 }
1564
1565 // If this is a use or a forward declaration, we're good.
1566 if (TK != TK_Definition)
1567 return PrevDecl;
Reid Spencer5f016e22007-07-11 17:01:13 +00001568
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001569 // Diagnose attempts to redefine a tag.
1570 if (PrevTagDecl->isDefinition()) {
1571 Diag(NameLoc, diag::err_redefinition, Name->getName());
1572 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1573 // If this is a redefinition, recover by making this struct be
1574 // anonymous, which will make any later references get the previous
1575 // definition.
1576 Name = 0;
1577 } else {
1578 // Okay, this is definition of a previously declared or referenced tag.
1579 // Move the location of the decl to be the definition site.
1580 PrevDecl->setLocation(NameLoc);
1581 return PrevDecl;
1582 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001584 // If we get here, this is a definition of a new struct type in a nested
1585 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1586 // type.
1587 } else {
1588 // The tag name clashes with a namespace name, issue an error and recover
1589 // by making this tag be anonymous.
1590 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1591 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1592 Name = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 }
1595
1596 // If there is an identifier, use the location of the identifier as the
1597 // location of the decl, otherwise use the location of the struct/union
1598 // keyword.
1599 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1600
1601 // Otherwise, if this is the first time we've seen this tag, create the decl.
1602 TagDecl *New;
1603 switch (Kind) {
1604 default: assert(0 && "Unknown tag kind!");
1605 case Decl::Enum:
1606 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1607 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001608 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 // If this is an undefined enum, warn.
1610 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1611 break;
1612 case Decl::Union:
1613 case Decl::Struct:
1614 case Decl::Class:
1615 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1616 // struct X { int A; } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001617 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 break;
1619 }
1620
1621 // If this has an identifier, add it to the scope stack.
1622 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001623 // The scope passed in may not be a decl scope. Zip up the scope tree until
1624 // we find one that is.
1625 while ((S->getFlags() & Scope::DeclScope) == 0)
1626 S = S->getParent();
1627
1628 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001629 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001631
Anders Carlssonad148062008-02-16 00:29:18 +00001632 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 return New;
1634}
1635
Eli Friedman1b76ada2008-06-03 21:01:11 +00001636static bool CalcFakeICEVal(const Expr* Expr,
1637 llvm::APSInt& Result,
1638 ASTContext& Context) {
1639 // Calculate the value of an expression that has a calculatable
1640 // value, but isn't an ICE. Currently, this only supports
1641 // a very narrow set of extensions, but it can be expanded if needed.
1642 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Expr))
1643 return CalcFakeICEVal(PE->getSubExpr(), Result, Context);
1644
1645 if (const CastExpr *CE = dyn_cast<CastExpr>(Expr)) {
1646 QualType CETy = CE->getType();
1647 if ((CETy->isIntegralType() && !CETy->isBooleanType()) ||
1648 CETy->isPointerType()) {
1649 if (CalcFakeICEVal(CE->getSubExpr(), Result, Context)) {
1650 Result.extOrTrunc(Context.getTypeSize(CETy));
1651 // FIXME: This assumes pointers are signed.
1652 Result.setIsSigned(CETy->isSignedIntegerType() ||
1653 CETy->isPointerType());
1654 return true;
1655 }
1656 }
1657 }
1658
1659 if (Expr->getType()->isIntegralType())
1660 return Expr->isIntegerConstantExpr(Result, Context);
1661
1662 return false;
1663}
1664
1665QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1666 // This method tries to turn a variable array into a constant
1667 // array even when the size isn't an ICE. This is necessary
1668 // for compatibility with code that depends on gcc's buggy
1669 // constant expression folding, like struct {char x[(int)(char*)2];}
1670 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
1671 llvm::APSInt Result(32);
1672 if (VLATy->getSizeExpr() &&
1673 CalcFakeICEVal(VLATy->getSizeExpr(), Result, Context) &&
1674 Result > llvm::APSInt(Result.getBitWidth(), Result.isUnsigned())) {
1675 return Context.getConstantArrayType(VLATy->getElementType(),
1676 Result, ArrayType::Normal, 0);
1677 }
1678 }
1679 return QualType();
1680}
1681
Steve Naroff08d92e42007-09-15 18:49:24 +00001682/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001683/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001684Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 SourceLocation DeclStart,
1686 Declarator &D, ExprTy *BitfieldWidth) {
1687 IdentifierInfo *II = D.getIdentifier();
1688 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 SourceLocation Loc = DeclStart;
1690 if (II) Loc = D.getIdentifierLoc();
1691
1692 // FIXME: Unnamed fields can be handled in various different ways, for
1693 // example, unnamed unions inject all members into the struct namespace!
1694
1695
1696 if (BitWidth) {
1697 // TODO: Validate.
1698 //printf("WARNING: BITFIELDS IGNORED!\n");
1699
1700 // 6.7.2.1p3
1701 // 6.7.2.1p4
1702
1703 } else {
1704 // Not a bitfield.
1705
1706 // validate II.
1707
1708 }
1709
1710 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001711 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1712 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001713
Reid Spencer5f016e22007-07-11 17:01:13 +00001714 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1715 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001716 if (T->isVariablyModifiedType()) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00001717 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
1718 if (!FixedTy.isNull()) {
1719 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
1720 T = FixedTy;
1721 } else {
1722 // FIXME: This diagnostic needs work
1723 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1724 InvalidDecl = true;
1725 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001726 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001727 // FIXME: Chain fielddecls together.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001728 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00001729
Anders Carlssonad148062008-02-16 00:29:18 +00001730 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1731 D.getAttributes());
1732
Steve Naroff5912a352007-08-28 20:14:24 +00001733 if (D.getInvalidType() || InvalidDecl)
1734 NewFD->setInvalidDecl();
1735 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001736}
1737
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001738/// TranslateIvarVisibility - Translate visibility from a token ID to an
1739/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001740static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001741TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001742 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001743 case tok::objc_private: return ObjCIvarDecl::Private;
1744 case tok::objc_public: return ObjCIvarDecl::Public;
1745 case tok::objc_protected: return ObjCIvarDecl::Protected;
1746 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001747 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001748 }
1749}
1750
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001751/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1752/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001753Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001754 SourceLocation DeclStart,
1755 Declarator &D, ExprTy *BitfieldWidth,
1756 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001757 IdentifierInfo *II = D.getIdentifier();
1758 Expr *BitWidth = (Expr*)BitfieldWidth;
1759 SourceLocation Loc = DeclStart;
1760 if (II) Loc = D.getIdentifierLoc();
1761
1762 // FIXME: Unnamed fields can be handled in various different ways, for
1763 // example, unnamed unions inject all members into the struct namespace!
1764
1765
1766 if (BitWidth) {
1767 // TODO: Validate.
1768 //printf("WARNING: BITFIELDS IGNORED!\n");
1769
1770 // 6.7.2.1p3
1771 // 6.7.2.1p4
1772
1773 } else {
1774 // Not a bitfield.
1775
1776 // validate II.
1777
1778 }
1779
1780 QualType T = GetTypeForDeclarator(D, S);
1781 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1782 bool InvalidDecl = false;
1783
1784 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1785 // than a variably modified type.
1786 if (T->isVariablyModifiedType()) {
1787 // FIXME: This diagnostic needs work
1788 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1789 InvalidDecl = true;
1790 }
1791
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001792 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001793
1794 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1795 D.getAttributes());
1796
1797 if (D.getInvalidType() || InvalidDecl)
1798 NewID->setInvalidDecl();
1799 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001800 if (Visibility != tok::objc_not_keyword)
1801 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001802 return NewID;
1803}
1804
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001805void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001806 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001807 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001808 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00001809 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1810 assert(EnclosingDecl && "missing record or interface decl");
1811 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1812
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001813 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001814 // Diagnose code like:
1815 // struct S { struct S {} X; };
1816 // We discover this when we complete the outer S. Reject and ignore the
1817 // outer S.
1818 Diag(Record->getLocation(), diag::err_nested_redefinition,
1819 Record->getKindName());
1820 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001821 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001822 return;
1823 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001824 // Verify that all the fields are okay.
1825 unsigned NumNamedMembers = 0;
1826 llvm::SmallVector<FieldDecl*, 32> RecFields;
1827 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001828
Reid Spencer5f016e22007-07-11 17:01:13 +00001829 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001830
Steve Naroff74216642007-09-14 22:20:54 +00001831 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1832 assert(FD && "missing field decl");
1833
1834 // Remember all fields.
1835 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001836
1837 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001838 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00001839
Reid Spencer5f016e22007-07-11 17:01:13 +00001840 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001841 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001842 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001843 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001844 FD->setInvalidDecl();
1845 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001846 continue;
1847 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001848 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1849 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001850 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001851 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001852 FD->setInvalidDecl();
1853 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001854 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001855 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001856 if (i != NumFields-1 || // ... that the last member ...
1857 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001858 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001859 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001860 FD->setInvalidDecl();
1861 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001862 continue;
1863 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001864 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001865 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1866 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001867 FD->setInvalidDecl();
1868 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001869 continue;
1870 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001871 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001872 if (Record)
1873 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001874 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001875 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1876 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001877 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001878 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1879 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001880 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001881 Record->setHasFlexibleArrayMember(true);
1882 } else {
1883 // If this is a struct/class and this is not the last element, reject
1884 // it. Note that GCC supports variable sized arrays in the middle of
1885 // structures.
1886 if (i != NumFields-1) {
1887 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1888 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001889 FD->setInvalidDecl();
1890 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001891 continue;
1892 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001893 // We support flexible arrays at the end of structs in other structs
1894 // as an extension.
1895 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1896 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001897 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001898 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 }
1900 }
1901 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001902 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001903 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001904 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1905 FD->getName());
1906 FD->setInvalidDecl();
1907 EnclosingDecl->setInvalidDecl();
1908 continue;
1909 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001910 // Keep track of the number of named members.
1911 if (IdentifierInfo *II = FD->getIdentifier()) {
1912 // Detect duplicate member names.
1913 if (!FieldIDs.insert(II)) {
1914 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1915 // Find the previous decl.
1916 SourceLocation PrevLoc;
1917 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1918 assert(i != e && "Didn't find previous def!");
1919 if (RecFields[i]->getIdentifier() == II) {
1920 PrevLoc = RecFields[i]->getLocation();
1921 break;
1922 }
1923 }
1924 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001925 FD->setInvalidDecl();
1926 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001927 continue;
1928 }
1929 ++NumNamedMembers;
1930 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001931 }
1932
Reid Spencer5f016e22007-07-11 17:01:13 +00001933 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00001934 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001935 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00001936 Consumer.HandleTagDeclDefinition(Record);
1937 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00001938 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1939 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1940 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1941 else if (ObjCImplementationDecl *IMPDecl =
1942 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001943 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1944 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001945 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001946 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001947 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001948}
1949
Steve Naroff08d92e42007-09-15 18:49:24 +00001950Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001951 DeclTy *lastEnumConst,
1952 SourceLocation IdLoc, IdentifierInfo *Id,
1953 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00001954 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 EnumConstantDecl *LastEnumConst =
1956 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1957 Expr *Val = static_cast<Expr*>(val);
1958
Chris Lattner31e05722007-08-26 06:24:45 +00001959 // The scope passed in may not be a decl scope. Zip up the scope tree until
1960 // we find one that is.
1961 while ((S->getFlags() & Scope::DeclScope) == 0)
1962 S = S->getParent();
1963
Reid Spencer5f016e22007-07-11 17:01:13 +00001964 // Verify that there isn't already something declared with this name in this
1965 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00001966 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001967 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 if (isa<EnumConstantDecl>(PrevDecl))
1969 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1970 else
1971 Diag(IdLoc, diag::err_redefinition, Id->getName());
1972 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00001973 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00001974 return 0;
1975 }
1976 }
1977
1978 llvm::APSInt EnumVal(32);
1979 QualType EltTy;
1980 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001981 // Make sure to promote the operand type to int.
1982 UsualUnaryConversions(Val);
1983
Reid Spencer5f016e22007-07-11 17:01:13 +00001984 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1985 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001986 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001987 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1988 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00001989 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001990 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001991 } else {
1992 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001993 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001994 }
1995
1996 if (!Val) {
1997 if (LastEnumConst) {
1998 // Assign the last value + 1.
1999 EnumVal = LastEnumConst->getInitVal();
2000 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002001
2002 // Check for overflow on increment.
2003 if (EnumVal < LastEnumConst->getInitVal())
2004 Diag(IdLoc, diag::warn_enum_value_overflow);
2005
Chris Lattnerb7416f92007-08-27 17:37:24 +00002006 EltTy = LastEnumConst->getType();
2007 } else {
2008 // First value, set to zero.
2009 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002010 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002011 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002012 }
2013
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002014 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002015 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2016 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002017 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002018
2019 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002020 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002021 return New;
2022}
2023
Steve Naroff08d92e42007-09-15 18:49:24 +00002024void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002025 DeclTy **Elements, unsigned NumElements) {
2026 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
2027 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
2028
Chris Lattnere37f0be2007-08-28 05:10:31 +00002029 // TODO: If the result value doesn't fit in an int, it must be a long or long
2030 // long value. ISO C does not support this, but GCC does as an extension,
2031 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002032 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002033
Chris Lattnerac609682007-08-28 06:15:15 +00002034 // Verify that all the values are okay, compute the size of the values, and
2035 // reverse the list.
2036 unsigned NumNegativeBits = 0;
2037 unsigned NumPositiveBits = 0;
2038
2039 // Keep track of whether all elements have type int.
2040 bool AllElementsInt = true;
2041
Reid Spencer5f016e22007-07-11 17:01:13 +00002042 EnumConstantDecl *EltList = 0;
2043 for (unsigned i = 0; i != NumElements; ++i) {
2044 EnumConstantDecl *ECD =
2045 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2046 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002047
2048 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002049 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002050 assert(InitVal.getBitWidth() >= IntWidth &&
2051 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002052 if (InitVal.getBitWidth() > IntWidth) {
2053 llvm::APSInt V(InitVal);
2054 V.trunc(IntWidth);
2055 V.extend(InitVal.getBitWidth());
2056 if (V != InitVal)
2057 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
2058 InitVal.toString());
2059 }
Chris Lattnerac609682007-08-28 06:15:15 +00002060
2061 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002062 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002063 NumPositiveBits = std::max(NumPositiveBits,
2064 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002065 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002066 NumNegativeBits = std::max(NumNegativeBits,
2067 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002068
Chris Lattnerac609682007-08-28 06:15:15 +00002069 // Keep track of whether every enum element has type int (very commmon).
2070 if (AllElementsInt)
2071 AllElementsInt = ECD->getType() == Context.IntTy;
2072
Reid Spencer5f016e22007-07-11 17:01:13 +00002073 ECD->setNextDeclarator(EltList);
2074 EltList = ECD;
2075 }
2076
Chris Lattnerac609682007-08-28 06:15:15 +00002077 // Figure out the type that should be used for this enum.
2078 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2079 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002080 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002081
2082 if (NumNegativeBits) {
2083 // If there is a negative value, figure out the smallest integer type (of
2084 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002085 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002086 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002087 BestWidth = IntWidth;
2088 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002089 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002090
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002091 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002092 BestType = Context.LongTy;
2093 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002094 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002095
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002096 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002097 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2098 BestType = Context.LongLongTy;
2099 }
2100 }
2101 } else {
2102 // If there is no negative value, figure out which of uint, ulong, ulonglong
2103 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002104 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002105 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002106 BestWidth = IntWidth;
2107 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002108 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002109 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002110 } else {
2111 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002112 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002113 "How could an initializer get larger than ULL?");
2114 BestType = Context.UnsignedLongLongTy;
2115 }
2116 }
2117
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002118 // Loop over all of the enumerator constants, changing their types to match
2119 // the type of the enum if needed.
2120 for (unsigned i = 0; i != NumElements; ++i) {
2121 EnumConstantDecl *ECD =
2122 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2123 if (!ECD) continue; // Already issued a diagnostic.
2124
2125 // Standard C says the enumerators have int type, but we allow, as an
2126 // extension, the enumerators to be larger than int size. If each
2127 // enumerator value fits in an int, type it as an int, otherwise type it the
2128 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2129 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002130 if (ECD->getType() == Context.IntTy) {
2131 // Make sure the init value is signed.
2132 llvm::APSInt IV = ECD->getInitVal();
2133 IV.setIsSigned(true);
2134 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002135 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002136 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002137
2138 // Determine whether the value fits into an int.
2139 llvm::APSInt InitVal = ECD->getInitVal();
2140 bool FitsInInt;
2141 if (InitVal.isUnsigned() || !InitVal.isNegative())
2142 FitsInInt = InitVal.getActiveBits() < IntWidth;
2143 else
2144 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2145
2146 // If it fits into an integer type, force it. Otherwise force it to match
2147 // the enum decl type.
2148 QualType NewTy;
2149 unsigned NewWidth;
2150 bool NewSign;
2151 if (FitsInInt) {
2152 NewTy = Context.IntTy;
2153 NewWidth = IntWidth;
2154 NewSign = true;
2155 } else if (ECD->getType() == BestType) {
2156 // Already the right type!
2157 continue;
2158 } else {
2159 NewTy = BestType;
2160 NewWidth = BestWidth;
2161 NewSign = BestType->isSignedIntegerType();
2162 }
2163
2164 // Adjust the APSInt value.
2165 InitVal.extOrTrunc(NewWidth);
2166 InitVal.setIsSigned(NewSign);
2167 ECD->setInitVal(InitVal);
2168
2169 // Adjust the Expr initializer and type.
2170 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2171 ECD->setType(NewTy);
2172 }
Chris Lattnerac609682007-08-28 06:15:15 +00002173
Chris Lattnere00b18c2007-08-28 18:24:31 +00002174 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00002175 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00002176}
2177
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002178Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2179 ExprTy *expr) {
2180 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2181
Chris Lattner8e25d862008-03-16 00:16:02 +00002182 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002183}
2184
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002185Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00002186 SourceLocation LBrace,
2187 SourceLocation RBrace,
2188 const char *Lang,
2189 unsigned StrSize,
2190 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002191 LinkageSpecDecl::LanguageIDs Language;
2192 Decl *dcl = static_cast<Decl *>(D);
2193 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2194 Language = LinkageSpecDecl::lang_c;
2195 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2196 Language = LinkageSpecDecl::lang_cxx;
2197 else {
2198 Diag(Loc, diag::err_bad_language);
2199 return 0;
2200 }
2201
2202 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00002203 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002204}
2205
Chris Lattner74788ba2008-02-21 00:48:22 +00002206void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00002207
Chris Lattner74788ba2008-02-21 00:48:22 +00002208 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00002209 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00002210 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00002211 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002212 if (!newType.isNull()) // install the new vector type into the decl
2213 vDecl->setType(newType);
2214 }
2215 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2216 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00002217 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002218 if (!newType.isNull()) // install the new vector type into the decl
2219 tDecl->setUnderlyingType(newType);
2220 }
Chris Lattner212839c2008-02-20 23:17:35 +00002221 break;
Nate Begeman213541a2008-04-18 23:10:10 +00002222 case AttributeList::AT_ext_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00002223 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Nate Begeman213541a2008-04-18 23:10:10 +00002224 HandleExtVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00002225 else
Chris Lattner74788ba2008-02-21 00:48:22 +00002226 Diag(Attr->getLoc(),
Nate Begeman213541a2008-04-18 23:10:10 +00002227 diag::err_typecheck_ext_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00002228 break;
2229 case AttributeList::AT_address_space:
Christopher Lambebb97e92008-02-04 02:31:56 +00002230 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2231 QualType newType = HandleAddressSpaceTypeAttribute(
2232 tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00002233 Attr);
2234 tDecl->setUnderlyingType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00002235 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2236 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00002237 Attr);
2238 // install the new addr spaced type into the decl
2239 vDecl->setType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00002240 }
Chris Lattner212839c2008-02-20 23:17:35 +00002241 break;
Eli Friedman3c0eb162008-05-27 03:33:27 +00002242 case AttributeList::AT_mode:
2243 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2244 QualType newType = HandleModeTypeAttribute(tDecl->getUnderlyingType(),
2245 Attr);
2246 tDecl->setUnderlyingType(newType);
2247 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2248 QualType newType = HandleModeTypeAttribute(vDecl->getType(), Attr);
2249 vDecl->setType(newType);
2250 }
2251 // FIXME: Diagnostic?
2252 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00002253 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00002254 HandleDeprecatedAttribute(New, Attr);
2255 break;
2256 case AttributeList::AT_visibility:
2257 HandleVisibilityAttribute(New, Attr);
2258 break;
2259 case AttributeList::AT_weak:
2260 HandleWeakAttribute(New, Attr);
2261 break;
2262 case AttributeList::AT_dllimport:
2263 HandleDLLImportAttribute(New, Attr);
2264 break;
2265 case AttributeList::AT_dllexport:
2266 HandleDLLExportAttribute(New, Attr);
2267 break;
2268 case AttributeList::AT_nothrow:
2269 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00002270 break;
Nate Begeman440b4562008-03-07 20:04:22 +00002271 case AttributeList::AT_stdcall:
2272 HandleStdCallAttribute(New, Attr);
2273 break;
2274 case AttributeList::AT_fastcall:
2275 HandleFastCallAttribute(New, Attr);
2276 break;
Chris Lattner212839c2008-02-20 23:17:35 +00002277 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00002278 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00002279 break;
2280 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00002281 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00002282 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00002283 case AttributeList::AT_annotate:
2284 HandleAnnotateAttribute(New, Attr);
2285 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00002286 case AttributeList::AT_noreturn:
2287 HandleNoReturnAttribute(New, Attr);
2288 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00002289 case AttributeList::AT_format:
2290 HandleFormatAttribute(New, Attr);
2291 break;
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002292 case AttributeList::AT_transparent_union:
2293 HandleTransparentUnionAttribute(New, Attr);
2294 break;
Chris Lattner212839c2008-02-20 23:17:35 +00002295 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00002296#if 0
2297 // TODO: when we have the full set of attributes, warn about unknown ones.
2298 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
2299 Attr->getName()->getName());
2300#endif
Chris Lattner212839c2008-02-20 23:17:35 +00002301 break;
2302 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002303}
2304
2305void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2306 AttributeList *declarator_postfix) {
2307 while (declspec_prefix) {
2308 HandleDeclAttribute(New, declspec_prefix);
2309 declspec_prefix = declspec_prefix->getNext();
2310 }
2311 while (declarator_postfix) {
2312 HandleDeclAttribute(New, declarator_postfix);
2313 declarator_postfix = declarator_postfix->getNext();
2314 }
2315}
2316
Nate Begeman213541a2008-04-18 23:10:10 +00002317void Sema::HandleExtVectorTypeAttribute(TypedefDecl *tDecl,
Steve Naroffbea0b342007-07-29 16:33:31 +00002318 AttributeList *rawAttr) {
2319 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00002320 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00002321 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002322 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00002323 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002324 return;
Steve Naroff73322922007-07-18 18:00:27 +00002325 }
2326 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2327 llvm::APSInt vecSize(32);
2328 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002329 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Nate Begeman213541a2008-04-18 23:10:10 +00002330 "ext_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002331 return;
Steve Naroff73322922007-07-18 18:00:27 +00002332 }
2333 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2334 // in conjunction with complex types (pointers, arrays, functions, etc.).
2335 Type *canonType = curType.getCanonicalType().getTypePtr();
2336 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002337 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00002338 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002339 return;
Steve Naroff73322922007-07-18 18:00:27 +00002340 }
2341 // unlike gcc's vector_size attribute, the size is specified as the
2342 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002343 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002344
2345 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002346 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00002347 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002348 return;
Steve Naroff73322922007-07-18 18:00:27 +00002349 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002350 // Instantiate/Install the vector type, the number of elements is > 0.
Nate Begeman213541a2008-04-18 23:10:10 +00002351 tDecl->setUnderlyingType(Context.getExtVectorType(curType, vectorSize));
Steve Naroffbea0b342007-07-29 16:33:31 +00002352 // Remember this typedef decl, we will need it later for diagnostics.
Nate Begeman213541a2008-04-18 23:10:10 +00002353 ExtVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002354}
2355
Reid Spencer5f016e22007-07-11 17:01:13 +00002356QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002357 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002358 // check the attribute arugments.
2359 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002360 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00002361 std::string("1"));
2362 return QualType();
2363 }
2364 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2365 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002366 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002367 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002368 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002369 return QualType();
2370 }
2371 // navigate to the base type - we need to provide for vector pointers,
2372 // vector arrays, and functions returning vectors.
2373 Type *canonType = curType.getCanonicalType().getTypePtr();
2374
Steve Naroff73322922007-07-18 18:00:27 +00002375 if (canonType->isPointerType() || canonType->isArrayType() ||
2376 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00002377 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00002378 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2379 do {
2380 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2381 canonType = PT->getPointeeType().getTypePtr();
2382 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2383 canonType = AT->getElementType().getTypePtr();
2384 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2385 canonType = FT->getResultType().getTypePtr();
2386 } while (canonType->isPointerType() || canonType->isArrayType() ||
2387 canonType->isFunctionType());
2388 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002389 }
2390 // the base type must be integer or float.
2391 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002392 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00002393 curType.getCanonicalType().getAsString());
2394 return QualType();
2395 }
Chris Lattner98be4942008-03-05 18:54:05 +00002396 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Reid Spencer5f016e22007-07-11 17:01:13 +00002397 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002398 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002399
2400 // the vector size needs to be an integral multiple of the type size.
2401 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00002402 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002403 sizeExpr->getSourceRange());
2404 return QualType();
2405 }
2406 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002407 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002408 sizeExpr->getSourceRange());
2409 return QualType();
2410 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00002411 // Instantiate the vector type, the number of elements is > 0, and not
2412 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00002413 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002414}
2415
Chris Lattner2070d802008-02-20 23:25:22 +00002416void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00002417 // check the attribute arguments.
2418 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002419 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00002420 std::string("0"));
2421 return;
2422 }
2423
2424 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2425 TD->addAttr(new PackedAttr);
2426 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2427 // If the alignment is less than or equal to 8 bits, the packed attribute
2428 // has no effect.
Chris Lattnerabb57582008-05-09 05:34:49 +00002429 if (!FD->getType()->isIncompleteType() &&
2430 Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00002431 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00002432 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00002433 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00002434 else
Anders Carlsson425a6092008-02-16 00:39:40 +00002435 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00002436 } else
Chris Lattner2070d802008-02-20 23:25:22 +00002437 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2438 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00002439}
Nate Begemanc398f0b2008-02-21 19:30:49 +00002440
Ted Kremenekaecb3832008-02-27 20:43:06 +00002441void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2442 // check the attribute arguments.
2443 if (rawAttr->getNumArgs() != 0) {
2444 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2445 std::string("0"));
2446 return;
2447 }
2448
Ted Kremenek3465fb32008-03-03 16:52:27 +00002449 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2450
2451 if (!Fn) {
2452 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2453 "noreturn", "function");
2454 return;
2455 }
2456
Ted Kremenekaecb3832008-02-27 20:43:06 +00002457 d->addAttr(new NoReturnAttr());
2458}
2459
Chris Lattnerddee4232008-03-03 03:28:21 +00002460void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2461 // check the attribute arguments.
2462 if (rawAttr->getNumArgs() != 0) {
2463 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2464 std::string("0"));
2465 return;
2466 }
2467
2468 d->addAttr(new DeprecatedAttr());
2469}
2470
2471void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2472 // check the attribute arguments.
Chris Lattner7b937ae2008-03-04 18:08:48 +00002473 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002474 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2475 std::string("1"));
2476 return;
2477 }
2478
Chris Lattner7b937ae2008-03-04 18:08:48 +00002479 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2480 Arg = Arg->IgnoreParenCasts();
2481 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2482
2483 if (Str == 0 || Str->isWide()) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002484 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002485 "visibility", std::string("1"));
Chris Lattnerddee4232008-03-03 03:28:21 +00002486 return;
2487 }
2488
Chris Lattner7b937ae2008-03-04 18:08:48 +00002489 const char *TypeStr = Str->getStrData();
2490 unsigned TypeLen = Str->getByteLength();
Dan Gohman4f8d1232008-05-22 00:50:06 +00002491 VisibilityAttr::VisibilityTypes type;
Chris Lattnerddee4232008-03-03 03:28:21 +00002492
Chris Lattner7b937ae2008-03-04 18:08:48 +00002493 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002494 type = VisibilityAttr::DefaultVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002495 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002496 type = VisibilityAttr::HiddenVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002497 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002498 type = VisibilityAttr::HiddenVisibility; // FIXME
Chris Lattner7b937ae2008-03-04 18:08:48 +00002499 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002500 type = VisibilityAttr::ProtectedVisibility;
Chris Lattnerddee4232008-03-03 03:28:21 +00002501 else {
2502 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002503 "visibility", TypeStr);
Chris Lattnerddee4232008-03-03 03:28:21 +00002504 return;
2505 }
2506
2507 d->addAttr(new VisibilityAttr(type));
2508}
2509
2510void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2511 // check the attribute arguments.
2512 if (rawAttr->getNumArgs() != 0) {
2513 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2514 std::string("0"));
2515 return;
2516 }
2517
2518 d->addAttr(new WeakAttr());
2519}
2520
2521void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2522 // check the attribute arguments.
2523 if (rawAttr->getNumArgs() != 0) {
2524 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2525 std::string("0"));
2526 return;
2527 }
2528
2529 d->addAttr(new DLLImportAttr());
2530}
2531
2532void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2533 // check the attribute arguments.
2534 if (rawAttr->getNumArgs() != 0) {
2535 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2536 std::string("0"));
2537 return;
2538 }
2539
2540 d->addAttr(new DLLExportAttr());
2541}
2542
Nate Begeman440b4562008-03-07 20:04:22 +00002543void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2544 // check the attribute arguments.
2545 if (rawAttr->getNumArgs() != 0) {
2546 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2547 std::string("0"));
2548 return;
2549 }
2550
2551 d->addAttr(new StdCallAttr());
2552}
2553
2554void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2555 // check the attribute arguments.
2556 if (rawAttr->getNumArgs() != 0) {
2557 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2558 std::string("0"));
2559 return;
2560 }
2561
2562 d->addAttr(new FastCallAttr());
2563}
2564
Chris Lattnerddee4232008-03-03 03:28:21 +00002565void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2566 // check the attribute arguments.
2567 if (rawAttr->getNumArgs() != 0) {
2568 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2569 std::string("0"));
2570 return;
2571 }
2572
2573 d->addAttr(new NoThrowAttr());
2574}
2575
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002576static const FunctionTypeProto *getFunctionProto(Decl *d) {
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002577 QualType Ty;
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002578
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002579 if (ValueDecl *decl = dyn_cast<ValueDecl>(d))
2580 Ty = decl->getType();
2581 else if (FieldDecl *decl = dyn_cast<FieldDecl>(d))
2582 Ty = decl->getType();
Ted Kremenek72786e02008-05-09 17:36:24 +00002583 else if (TypedefDecl* decl = dyn_cast<TypedefDecl>(d))
2584 Ty = decl->getUnderlyingType();
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002585 else
2586 return 0;
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002587
2588 if (Ty->isFunctionPointerType()) {
2589 const PointerType *PtrTy = Ty->getAsPointerType();
2590 Ty = PtrTy->getPointeeType();
2591 }
2592
2593 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2594 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2595
2596 return 0;
2597}
2598
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002599static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
2600 if (!T->isPointerType())
2601 return false;
2602
2603 T = T->getAsPointerType()->getPointeeType().getCanonicalType();
2604 ObjCInterfaceType* ClsT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
2605
2606 if (!ClsT)
2607 return false;
2608
2609 IdentifierInfo* ClsName = ClsT->getDecl()->getIdentifier();
2610
2611 // FIXME: Should we walk the chain of classes?
2612 return ClsName == &Ctx.Idents.get("NSString") ||
2613 ClsName == &Ctx.Idents.get("NSMutableString");
2614}
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002615
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002616/// Handle __attribute__((format(type,idx,firstarg))) attributes
2617/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattnerddee4232008-03-03 03:28:21 +00002618void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2619
2620 if (!rawAttr->getParameterName()) {
2621 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2622 "format", std::string("1"));
2623 return;
2624 }
2625
2626 if (rawAttr->getNumArgs() != 2) {
2627 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2628 std::string("3"));
2629 return;
2630 }
2631
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002632 // GCC ignores the format attribute on K&R style function
2633 // prototypes, so we ignore it as well
2634 const FunctionTypeProto *proto = getFunctionProto(d);
2635
2636 if (!proto) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002637 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2638 "format", "function");
2639 return;
2640 }
2641
2642 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002643 // this is needed in order to be compatible with GCC
Chris Lattnerddee4232008-03-03 03:28:21 +00002644 // the index must start in 1 and the limit is numargs+1
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002645 unsigned NumArgs = proto->getNumArgs();
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002646 unsigned FirstIdx = 1;
Chris Lattnerddee4232008-03-03 03:28:21 +00002647
2648 const char *Format = rawAttr->getParameterName()->getName();
2649 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2650
2651 // Normalize the argument, __foo__ becomes foo.
2652 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2653 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2654 Format += 2;
2655 FormatLen -= 4;
2656 }
2657
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002658 bool Supported = false;
2659 bool is_NSString = false;
2660 bool is_strftime = false;
2661
2662 switch (FormatLen) {
2663 default: break;
2664 case 5:
2665 Supported = !memcmp(Format, "scanf", 5);
2666 break;
2667 case 6:
2668 Supported = !memcmp(Format, "printf", 6);
2669 break;
2670 case 7:
2671 Supported = !memcmp(Format, "strfmon", 7);
2672 break;
2673 case 8:
2674 Supported = (is_strftime = !memcmp(Format, "strftime", 8)) ||
2675 (is_NSString = !memcmp(Format, "NSString", 8));
2676 break;
2677 }
2678
2679 if (!Supported) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002680 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2681 "format", rawAttr->getParameterName()->getName());
2682 return;
2683 }
2684
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002685 // checks for the 2nd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002686 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002687 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002688 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2689 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2690 "format", std::string("2"), IdxExpr->getSourceRange());
2691 return;
2692 }
2693
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002694 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002695 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2696 "format", std::string("2"), IdxExpr->getSourceRange());
2697 return;
2698 }
2699
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002700 // FIXME: Do we need to bounds check?
2701 unsigned ArgIdx = Idx.getZExtValue() - 1;
2702
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002703 // make sure the format string is really a string
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002704 QualType Ty = proto->getArgType(ArgIdx);
2705
2706 if (is_NSString) {
2707 // FIXME: do we need to check if the type is NSString*? What are
2708 // the semantics?
2709 if (!isNSStringType(Ty, Context)) {
2710 // FIXME: Should highlight the actual expression that has the
2711 // wrong type.
2712 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_NSString,
2713 IdxExpr->getSourceRange());
2714 return;
2715 }
2716 }
2717 else if (!Ty->isPointerType() ||
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002718 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002719 // FIXME: Should highlight the actual expression that has the
2720 // wrong type.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002721 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2722 IdxExpr->getSourceRange());
2723 return;
2724 }
2725
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002726 // check the 3rd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002727 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002728 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002729 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2730 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2731 "format", std::string("3"), FirstArgExpr->getSourceRange());
2732 return;
2733 }
2734
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002735 // check if the function is variadic if the 3rd argument non-zero
2736 if (FirstArg != 0) {
2737 if (proto->isVariadic()) {
2738 ++NumArgs; // +1 for ...
2739 } else {
2740 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2741 return;
2742 }
2743 }
2744
2745 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2746 // the input is just the current time + the format string
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002747 if (is_strftime) {
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002748 if (FirstArg != 0) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002749 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2750 FirstArgExpr->getSourceRange());
2751 return;
2752 }
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002753 // if 0 it disables parameter checking (to use with e.g. va_list)
2754 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002755 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2756 "format", std::string("3"), FirstArgExpr->getSourceRange());
2757 return;
2758 }
2759
2760 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2761 Idx.getZExtValue(), FirstArg.getZExtValue()));
2762}
2763
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002764void Sema::HandleTransparentUnionAttribute(Decl *d, AttributeList *rawAttr) {
2765 // check the attribute arguments.
2766 if (rawAttr->getNumArgs() != 0) {
2767 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2768 std::string("0"));
2769 return;
2770 }
2771
2772 TypeDecl *decl = dyn_cast<TypeDecl>(d);
2773
2774 if (!decl || !Context.getTypeDeclType(decl)->isUnionType()) {
2775 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2776 "transparent_union", "union");
2777 return;
2778 }
2779
Chris Lattner22624942008-04-30 16:04:01 +00002780 //QualType QTy = Context.getTypeDeclType(decl);
2781 //const RecordType *Ty = QTy->getAsUnionType();
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002782
2783// FIXME
2784// Ty->addAttr(new TransparentUnionAttr());
2785}
2786
Nate Begemanc398f0b2008-02-21 19:30:49 +00002787void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2788 // check the attribute arguments.
2789 if (rawAttr->getNumArgs() != 1) {
2790 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2791 std::string("1"));
2792 return;
2793 }
2794 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2795 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002796
Nate Begemanc398f0b2008-02-21 19:30:49 +00002797 // Make sure that there is a string literal as the annotation's single
2798 // argument.
2799 if (!SE) {
2800 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2801 return;
2802 }
2803 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2804 SE->getByteLength())));
2805}
2806
Anders Carlsson78aaae92007-12-19 07:19:40 +00002807void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2808{
2809 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002810 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002811 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002812 std::string("1"));
2813 return;
2814 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002815
Anders Carlsson042c4e72008-02-16 19:51:27 +00002816 unsigned Align = 0;
2817
2818 if (rawAttr->getNumArgs() == 0) {
2819 // FIXME: This should be the target specific maximum alignment.
2820 // (For now we just use 128 bits which is the maximum on X86.
2821 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002822 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002823 } else {
2824 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2825 llvm::APSInt alignment(32);
2826 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002827 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002828 "aligned", alignmentExpr->getSourceRange());
2829 return;
2830 }
2831
2832 Align = alignment.getZExtValue() * 8;
2833 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002834
Anders Carlsson042c4e72008-02-16 19:51:27 +00002835 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002836}