SemaDecl.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file was developed by Chris Lattner and is distributed under
  6. // the University of Illinois Open Source License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for declarations.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "Sema.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Builtins.h"
  16. #include "clang/AST/Decl.h"
  17. #include "clang/AST/Expr.h"
  18. #include "clang/AST/Type.h"
  19. #include "clang/Parse/DeclSpec.h"
  20. #include "clang/Parse/Scope.h"
  21. #include "clang/Lex/IdentifierTable.h"
  22. #include "clang/Basic/LangOptions.h"
  23. #include "clang/Basic/TargetInfo.h"
  24. #include "llvm/ADT/SmallSet.h"
  25. using namespace clang;
  26. // C99: 6.7.5p3: Used by ParseDeclarator/ParseField to make sure we have
  27. // a constant expression of type int with a value greater than zero.
  28. bool Sema::VerifyConstantArrayType(const ArrayType *Array,
  29. SourceLocation DeclLoc) {
  30. const Expr *Size = Array->getSize();
  31. if (Size == 0) return false; // incomplete type.
  32. if (!Size->getType()->isIntegerType()) {
  33. Diag(Size->getLocStart(), diag::err_array_size_non_int,
  34. Size->getType().getAsString(), Size->getSourceRange());
  35. return true;
  36. }
  37. // Verify that the size of the array is an integer constant expr.
  38. SourceLocation Loc;
  39. llvm::APSInt SizeVal(32);
  40. if (!Size->isIntegerConstantExpr(SizeVal, &Loc)) {
  41. // FIXME: This emits the diagnostic to enforce 6.7.2.1p8, but the message
  42. // is wrong. It is also wrong for static variables.
  43. // FIXME: This is also wrong for:
  44. // int sub1(int i, char *pi) { typedef int foo[i];
  45. // struct bar {foo f1; int f2:3; int f3:4} *p; }
  46. Diag(DeclLoc, diag::err_typecheck_illegal_vla, Size->getSourceRange());
  47. return true;
  48. }
  49. // We have a constant expression with an integer type, now make sure
  50. // value greater than zero (C99 6.7.5.2p1).
  51. // FIXME: This check isn't specific to static VLAs, this should be moved
  52. // elsewhere or replicated. 'int X[-1];' inside a function should emit an
  53. // error.
  54. if (SizeVal.isSigned()) {
  55. llvm::APSInt Zero(SizeVal.getBitWidth());
  56. Zero.setIsUnsigned(false);
  57. if (SizeVal < Zero) {
  58. Diag(DeclLoc, diag::err_typecheck_negative_array_size,
  59. Size->getSourceRange());
  60. return true;
  61. } else if (SizeVal == 0) {
  62. // GCC accepts zero sized static arrays.
  63. Diag(DeclLoc, diag::err_typecheck_zero_array_size,
  64. Size->getSourceRange());
  65. }
  66. }
  67. return false;
  68. }
  69. Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
  70. return dyn_cast_or_null<TypedefDecl>(II.getFETokenInfo<Decl>());
  71. }
  72. void Sema::PopScope(SourceLocation Loc, Scope *S) {
  73. for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
  74. I != E; ++I) {
  75. Decl *D = static_cast<Decl*>(*I);
  76. assert(D && "This decl didn't get pushed??");
  77. IdentifierInfo *II = D->getIdentifier();
  78. if (!II) continue;
  79. // Unlink this decl from the identifier. Because the scope contains decls
  80. // in an unordered collection, and because we have multiple identifier
  81. // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
  82. if (II->getFETokenInfo<Decl>() == D) {
  83. // Normal case, no multiple decls in different namespaces.
  84. II->setFETokenInfo(D->getNext());
  85. } else {
  86. // Scan ahead. There are only three namespaces in C, so this loop can
  87. // never execute more than 3 times.
  88. Decl *SomeDecl = II->getFETokenInfo<Decl>();
  89. while (SomeDecl->getNext() != D) {
  90. SomeDecl = SomeDecl->getNext();
  91. assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
  92. }
  93. SomeDecl->setNext(D->getNext());
  94. }
  95. // This will have to be revisited for C++: there we want to nest stuff in
  96. // namespace decls etc. Even for C, we might want a top-level translation
  97. // unit decl or something.
  98. if (!CurFunctionDecl)
  99. continue;
  100. // Chain this decl to the containing function, it now owns the memory for
  101. // the decl.
  102. D->setNext(CurFunctionDecl->getDeclChain());
  103. CurFunctionDecl->setDeclChain(D);
  104. }
  105. }
  106. /// LookupScopedDecl - Look up the inner-most declaration in the specified
  107. /// namespace.
  108. Decl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
  109. SourceLocation IdLoc, Scope *S) {
  110. if (II == 0) return 0;
  111. Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
  112. // Scan up the scope chain looking for a decl that matches this identifier
  113. // that is in the appropriate namespace. This search should not take long, as
  114. // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
  115. for (Decl *D = II->getFETokenInfo<Decl>(); D; D = D->getNext())
  116. if (D->getIdentifierNamespace() == NS)
  117. return D;
  118. // If we didn't find a use of this identifier, and if the identifier
  119. // corresponds to a compiler builtin, create the decl object for the builtin
  120. // now, injecting it into translation unit scope, and return it.
  121. if (NS == Decl::IDNS_Ordinary) {
  122. // If this is a builtin on some other target, or if this builtin varies
  123. // across targets (e.g. in type), emit a diagnostic and mark the translation
  124. // unit non-portable for using it.
  125. if (II->isNonPortableBuiltin()) {
  126. // Only emit this diagnostic once for this builtin.
  127. II->setNonPortableBuiltin(false);
  128. Context.Target.DiagnoseNonPortability(IdLoc,
  129. diag::port_target_builtin_use);
  130. }
  131. // If this is a builtin on this (or all) targets, create the decl.
  132. if (unsigned BuiltinID = II->getBuiltinID())
  133. return LazilyCreateBuiltin(II, BuiltinID, S);
  134. }
  135. return 0;
  136. }
  137. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
  138. /// lazily create a decl for it.
  139. Decl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
  140. Builtin::ID BID = (Builtin::ID)bid;
  141. QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
  142. FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
  143. FunctionDecl::Extern, 0);
  144. // Find translation-unit scope to insert this function into.
  145. while (S->getParent())
  146. S = S->getParent();
  147. S->AddDecl(New);
  148. // Add this decl to the end of the identifier info.
  149. if (Decl *LastDecl = II->getFETokenInfo<Decl>()) {
  150. // Scan until we find the last (outermost) decl in the id chain.
  151. while (LastDecl->getNext())
  152. LastDecl = LastDecl->getNext();
  153. // Insert before (outside) it.
  154. LastDecl->setNext(New);
  155. } else {
  156. II->setFETokenInfo(New);
  157. }
  158. // Make sure clients iterating over decls see this.
  159. LastInGroupList.push_back(New);
  160. return New;
  161. }
  162. /// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
  163. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  164. /// situation, merging decls or emitting diagnostics as appropriate.
  165. ///
  166. TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
  167. // Verify the old decl was also a typedef.
  168. TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
  169. if (!Old) {
  170. Diag(New->getLocation(), diag::err_redefinition_different_kind,
  171. New->getName());
  172. Diag(OldD->getLocation(), diag::err_previous_definition);
  173. return New;
  174. }
  175. // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
  176. // TODO: This is totally simplistic. It should handle merging functions
  177. // together etc, merging extern int X; int X; ...
  178. Diag(New->getLocation(), diag::err_redefinition, New->getName());
  179. Diag(Old->getLocation(), diag::err_previous_definition);
  180. return New;
  181. }
  182. /// MergeFunctionDecl - We just parsed a function 'New' which has the same name
  183. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  184. /// situation, merging decls or emitting diagnostics as appropriate.
  185. ///
  186. FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
  187. // Verify the old decl was also a function.
  188. FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
  189. if (!Old) {
  190. Diag(New->getLocation(), diag::err_redefinition_different_kind,
  191. New->getName());
  192. Diag(OldD->getLocation(), diag::err_previous_definition);
  193. return New;
  194. }
  195. // This is not right, but it's a start. If 'Old' is a function prototype with
  196. // the same type as 'New', silently allow this. FIXME: We should link up decl
  197. // objects here.
  198. if (Old->getBody() == 0 &&
  199. Old->getCanonicalType() == New->getCanonicalType()) {
  200. return New;
  201. }
  202. // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
  203. // TODO: This is totally simplistic. It should handle merging functions
  204. // together etc, merging extern int X; int X; ...
  205. Diag(New->getLocation(), diag::err_redefinition, New->getName());
  206. Diag(Old->getLocation(), diag::err_previous_definition);
  207. return New;
  208. }
  209. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  210. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  211. /// situation, merging decls or emitting diagnostics as appropriate.
  212. ///
  213. /// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
  214. /// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
  215. ///
  216. VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
  217. // Verify the old decl was also a variable.
  218. VarDecl *Old = dyn_cast<VarDecl>(OldD);
  219. if (!Old) {
  220. Diag(New->getLocation(), diag::err_redefinition_different_kind,
  221. New->getName());
  222. Diag(OldD->getLocation(), diag::err_previous_definition);
  223. return New;
  224. }
  225. // Verify the types match.
  226. if (Old->getCanonicalType() != New->getCanonicalType()) {
  227. Diag(New->getLocation(), diag::err_redefinition, New->getName());
  228. Diag(Old->getLocation(), diag::err_previous_definition);
  229. return New;
  230. }
  231. // We've verified the types match, now check if Old is "extern".
  232. if (Old->getStorageClass() != VarDecl::Extern) {
  233. Diag(New->getLocation(), diag::err_redefinition, New->getName());
  234. Diag(Old->getLocation(), diag::err_previous_definition);
  235. }
  236. return New;
  237. }
  238. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  239. /// no declarator (e.g. "struct foo;") is parsed.
  240. Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
  241. // TODO: emit error on 'int;' or 'const enum foo;'.
  242. // TODO: emit error on 'typedef int;'
  243. // if (!DS.isMissingDeclaratorOk()) Diag(...);
  244. return 0;
  245. }
  246. Sema::DeclTy *
  247. Sema::ParseDeclarator(Scope *S, Declarator &D, ExprTy *Init,
  248. DeclTy *lastDeclarator) {
  249. Decl *LastDeclarator = (Decl*)lastDeclarator;
  250. IdentifierInfo *II = D.getIdentifier();
  251. // See if this is a redefinition of a variable in the same scope.
  252. Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
  253. D.getIdentifierLoc(), S);
  254. if (PrevDecl && !S->isDeclScope(PrevDecl))
  255. PrevDecl = 0; // If in outer scope, it isn't the same thing.
  256. Decl *New;
  257. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  258. TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
  259. if (!NewTD) return 0;
  260. // Handle attributes prior to checking for duplicates in MergeVarDecl
  261. HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
  262. D.getAttributes());
  263. // Merge the decl with the existing one if appropriate.
  264. if (PrevDecl) {
  265. NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
  266. if (NewTD == 0) return 0;
  267. }
  268. New = NewTD;
  269. if (S->getParent() == 0) {
  270. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  271. // then it shall have block scope.
  272. if (ArrayType *ary = dyn_cast<ArrayType>(NewTD->getUnderlyingType())) {
  273. if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
  274. return 0;
  275. }
  276. }
  277. } else if (D.isFunctionDeclarator()) {
  278. QualType R = GetTypeForDeclarator(D, S);
  279. if (R.isNull()) return 0; // FIXME: "auto func();" passes through...
  280. FunctionDecl::StorageClass SC;
  281. switch (D.getDeclSpec().getStorageClassSpec()) {
  282. default: assert(0 && "Unknown storage class!");
  283. case DeclSpec::SCS_auto:
  284. case DeclSpec::SCS_register:
  285. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
  286. R.getAsString());
  287. return 0;
  288. case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
  289. case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
  290. case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
  291. }
  292. FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
  293. LastDeclarator);
  294. // Merge the decl with the existing one if appropriate.
  295. if (PrevDecl) {
  296. NewFD = MergeFunctionDecl(NewFD, PrevDecl);
  297. if (NewFD == 0) return 0;
  298. }
  299. New = NewFD;
  300. } else {
  301. QualType R = GetTypeForDeclarator(D, S);
  302. if (R.isNull()) return 0;
  303. VarDecl *NewVD;
  304. VarDecl::StorageClass SC;
  305. switch (D.getDeclSpec().getStorageClassSpec()) {
  306. default: assert(0 && "Unknown storage class!");
  307. case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
  308. case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
  309. case DeclSpec::SCS_static: SC = VarDecl::Static; break;
  310. case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
  311. case DeclSpec::SCS_register: SC = VarDecl::Register; break;
  312. }
  313. if (S->getParent() == 0) {
  314. // File scope. C99 6.9.2p2: A declaration of an identifier for and
  315. // object that has file scope without an initializer, and without a
  316. // storage-class specifier or with the storage-class specifier "static",
  317. // constitutes a tentative definition. Note: A tentative definition with
  318. // external linkage is valid (C99 6.2.2p5).
  319. if (!Init && SC == VarDecl::Static) {
  320. // C99 6.9.2p3: If the declaration of an identifier for an object is
  321. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  322. // declared type shall not be an incomplete type.
  323. if (R->isIncompleteType()) {
  324. Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
  325. R.getAsString());
  326. return 0;
  327. }
  328. }
  329. // C99 6.9p2: The storage-class specifiers auto and register shall not
  330. // appear in the declaration specifiers in an external declaration.
  331. if (SC == VarDecl::Auto || SC == VarDecl::Register) {
  332. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
  333. R.getAsString());
  334. return 0;
  335. }
  336. // C99 6.7.5.2p2: If an identifier is declared to be an object with
  337. // static storage duration, it shall not have a variable length array.
  338. if (ArrayType *ary = dyn_cast<ArrayType>(R.getCanonicalType())) {
  339. if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
  340. return 0;
  341. }
  342. NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
  343. } else {
  344. // Block scope. C99 6.7p7: If an identifier for an object is declared with
  345. // no linkage (C99 6.2.2p6), the type for the object shall be complete...
  346. if (SC != VarDecl::Extern) {
  347. if (R->isIncompleteType()) {
  348. Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
  349. R.getAsString());
  350. return 0;
  351. }
  352. }
  353. if (SC == VarDecl::Static) {
  354. // C99 6.7.5.2p2: If an identifier is declared to be an object with
  355. // static storage duration, it shall not have a variable length array.
  356. if (ArrayType *ary = dyn_cast<ArrayType>(R.getCanonicalType())) {
  357. if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
  358. return 0;
  359. }
  360. }
  361. NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
  362. }
  363. // Handle attributes prior to checking for duplicates in MergeVarDecl
  364. HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
  365. D.getAttributes());
  366. // Merge the decl with the existing one if appropriate.
  367. if (PrevDecl) {
  368. NewVD = MergeVarDecl(NewVD, PrevDecl);
  369. if (NewVD == 0) return 0;
  370. }
  371. New = NewVD;
  372. }
  373. // If this has an identifier, add it to the scope stack.
  374. if (II) {
  375. New->setNext(II->getFETokenInfo<Decl>());
  376. II->setFETokenInfo(New);
  377. S->AddDecl(New);
  378. }
  379. if (S->getParent() == 0)
  380. AddTopLevelDecl(New, LastDeclarator);
  381. return New;
  382. }
  383. /// The declarators are chained together backwards, reverse the list.
  384. Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
  385. // Often we have single declarators, handle them quickly.
  386. Decl *Group = static_cast<Decl*>(group);
  387. if (Group == 0 || Group->getNextDeclarator() == 0) return Group;
  388. Decl *NewGroup = 0;
  389. while (Group) {
  390. Decl *Next = Group->getNextDeclarator();
  391. Group->setNextDeclarator(NewGroup);
  392. NewGroup = Group;
  393. Group = Next;
  394. }
  395. return NewGroup;
  396. }
  397. ParmVarDecl *
  398. Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
  399. Scope *FnScope) {
  400. const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
  401. IdentifierInfo *II = PI.Ident;
  402. // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
  403. // Can this happen for params? We already checked that they don't conflict
  404. // among each other. Here they can only shadow globals, which is ok.
  405. if (Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
  406. PI.IdentLoc, FnScope)) {
  407. }
  408. // FIXME: Handle storage class (auto, register). No declarator?
  409. // TODO: Chain to previous parameter with the prevdeclarator chain?
  410. ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II,
  411. QualType::getFromOpaquePtr(PI.TypeInfo),
  412. VarDecl::None, 0);
  413. // If this has an identifier, add it to the scope stack.
  414. if (II) {
  415. New->setNext(II->getFETokenInfo<Decl>());
  416. II->setFETokenInfo(New);
  417. FnScope->AddDecl(New);
  418. }
  419. return New;
  420. }
  421. Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
  422. assert(CurFunctionDecl == 0 && "Function parsing confused");
  423. assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
  424. "Not a function declarator!");
  425. DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
  426. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  427. // for a K&R function.
  428. if (!FTI.hasPrototype) {
  429. for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
  430. if (FTI.ArgInfo[i].TypeInfo == 0) {
  431. Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
  432. FTI.ArgInfo[i].Ident->getName());
  433. // Implicitly declare the argument as type 'int' for lack of a better
  434. // type.
  435. FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
  436. }
  437. }
  438. // Since this is a function definition, act as though we have information
  439. // about the arguments.
  440. FTI.hasPrototype = true;
  441. } else {
  442. // FIXME: Diagnose arguments without names in C.
  443. }
  444. Scope *GlobalScope = FnBodyScope->getParent();
  445. FunctionDecl *FD =
  446. static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0, 0));
  447. CurFunctionDecl = FD;
  448. // Create Decl objects for each parameter, adding them to the FunctionDecl.
  449. llvm::SmallVector<ParmVarDecl*, 16> Params;
  450. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
  451. // no arguments, not a function that takes a single void argument.
  452. if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
  453. FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
  454. // empty arg list, don't push any params.
  455. } else {
  456. for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
  457. Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
  458. }
  459. FD->setParams(&Params[0], Params.size());
  460. return FD;
  461. }
  462. Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
  463. FunctionDecl *FD = static_cast<FunctionDecl*>(D);
  464. FD->setBody((Stmt*)Body);
  465. assert(FD == CurFunctionDecl && "Function parsing confused");
  466. CurFunctionDecl = 0;
  467. // Verify and clean out per-function state.
  468. // Check goto/label use.
  469. for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
  470. I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
  471. // Verify that we have no forward references left. If so, there was a goto
  472. // or address of a label taken, but no definition of it. Label fwd
  473. // definitions are indicated with a null substmt.
  474. if (I->second->getSubStmt() == 0) {
  475. LabelStmt *L = I->second;
  476. // Emit error.
  477. Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
  478. // At this point, we have gotos that use the bogus label. Stitch it into
  479. // the function body so that they aren't leaked and that the AST is well
  480. // formed.
  481. L->setSubStmt(new NullStmt(L->getIdentLoc()));
  482. cast<CompoundStmt>((Stmt*)Body)->push_back(L);
  483. }
  484. }
  485. LabelMap.clear();
  486. return FD;
  487. }
  488. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  489. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  490. Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
  491. Scope *S) {
  492. if (getLangOptions().C99) // Extension in C99.
  493. Diag(Loc, diag::ext_implicit_function_decl, II.getName());
  494. else // Legal in C90, but warn about it.
  495. Diag(Loc, diag::warn_implicit_function_decl, II.getName());
  496. // FIXME: handle stuff like:
  497. // void foo() { extern float X(); }
  498. // void bar() { X(); } <-- implicit decl for X in another scope.
  499. // Set a Declarator for the implicit definition: int foo();
  500. const char *Dummy;
  501. DeclSpec DS;
  502. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
  503. Error = Error; // Silence warning.
  504. assert(!Error && "Error setting up implicit decl!");
  505. Declarator D(DS, Declarator::BlockContext);
  506. D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
  507. D.SetIdentifier(&II, Loc);
  508. // Find translation-unit scope to insert this function into.
  509. while (S->getParent())
  510. S = S->getParent();
  511. return static_cast<Decl*>(ParseDeclarator(S, D, 0, 0));
  512. }
  513. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
  514. Decl *LastDeclarator) {
  515. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  516. QualType T = GetTypeForDeclarator(D, S);
  517. if (T.isNull()) return 0;
  518. // Scope manipulation handled by caller.
  519. return new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(), T,
  520. LastDeclarator);
  521. }
  522. /// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
  523. /// former case, Name will be non-null. In the later case, Name will be null.
  524. /// TagType indicates what kind of tag this is. TK indicates whether this is a
  525. /// reference/declaration/definition of a tag.
  526. Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
  527. SourceLocation KWLoc, IdentifierInfo *Name,
  528. SourceLocation NameLoc, AttributeList *Attr) {
  529. // If this is a use of an existing tag, it must have a name.
  530. assert((Name != 0 || TK == TK_Definition) &&
  531. "Nameless record must be a definition!");
  532. Decl::Kind Kind;
  533. switch (TagType) {
  534. default: assert(0 && "Unknown tag type!");
  535. case DeclSpec::TST_struct: Kind = Decl::Struct; break;
  536. case DeclSpec::TST_union: Kind = Decl::Union; break;
  537. //case DeclSpec::TST_class: Kind = Decl::Class; break;
  538. case DeclSpec::TST_enum: Kind = Decl::Enum; break;
  539. }
  540. // If this is a named struct, check to see if there was a previous forward
  541. // declaration or definition.
  542. if (TagDecl *PrevDecl =
  543. dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
  544. NameLoc, S))) {
  545. // If this is a use of a previous tag, or if the tag is already declared in
  546. // the same scope (so that the definition/declaration completes or
  547. // rementions the tag), reuse the decl.
  548. if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
  549. // Make sure that this wasn't declared as an enum and now used as a struct
  550. // or something similar.
  551. if (PrevDecl->getKind() != Kind) {
  552. Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
  553. Diag(PrevDecl->getLocation(), diag::err_previous_use);
  554. }
  555. // If this is a use or a forward declaration, we're good.
  556. if (TK != TK_Definition)
  557. return PrevDecl;
  558. // Diagnose attempts to redefine a tag.
  559. if (PrevDecl->isDefinition()) {
  560. Diag(NameLoc, diag::err_redefinition, Name->getName());
  561. Diag(PrevDecl->getLocation(), diag::err_previous_definition);
  562. // If this is a redefinition, recover by making this struct be
  563. // anonymous, which will make any later references get the previous
  564. // definition.
  565. Name = 0;
  566. } else {
  567. // Okay, this is definition of a previously declared or referenced tag.
  568. // Move the location of the decl to be the definition site.
  569. PrevDecl->setLocation(NameLoc);
  570. return PrevDecl;
  571. }
  572. }
  573. // If we get here, this is a definition of a new struct type in a nested
  574. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
  575. // type.
  576. }
  577. // If there is an identifier, use the location of the identifier as the
  578. // location of the decl, otherwise use the location of the struct/union
  579. // keyword.
  580. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  581. // Otherwise, if this is the first time we've seen this tag, create the decl.
  582. TagDecl *New;
  583. switch (Kind) {
  584. default: assert(0 && "Unknown tag kind!");
  585. case Decl::Enum:
  586. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  587. // enum X { A, B, C } D; D should chain to X.
  588. New = new EnumDecl(Loc, Name, 0);
  589. // If this is an undefined enum, warn.
  590. if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
  591. break;
  592. case Decl::Union:
  593. case Decl::Struct:
  594. case Decl::Class:
  595. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  596. // struct X { int A; } D; D should chain to X.
  597. New = new RecordDecl(Kind, Loc, Name, 0);
  598. break;
  599. }
  600. // If this has an identifier, add it to the scope stack.
  601. if (Name) {
  602. New->setNext(Name->getFETokenInfo<Decl>());
  603. Name->setFETokenInfo(New);
  604. S->AddDecl(New);
  605. }
  606. return New;
  607. }
  608. /// ParseField - Each field of a struct/union/class is passed into this in order
  609. /// to create a FieldDecl object for it.
  610. Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
  611. SourceLocation DeclStart,
  612. Declarator &D, ExprTy *BitfieldWidth) {
  613. IdentifierInfo *II = D.getIdentifier();
  614. Expr *BitWidth = (Expr*)BitfieldWidth;
  615. SourceLocation Loc = DeclStart;
  616. if (II) Loc = D.getIdentifierLoc();
  617. // FIXME: Unnamed fields can be handled in various different ways, for
  618. // example, unnamed unions inject all members into the struct namespace!
  619. if (BitWidth) {
  620. // TODO: Validate.
  621. //printf("WARNING: BITFIELDS IGNORED!\n");
  622. // 6.7.2.1p3
  623. // 6.7.2.1p4
  624. } else {
  625. // Not a bitfield.
  626. // validate II.
  627. }
  628. QualType T = GetTypeForDeclarator(D, S);
  629. if (T.isNull()) return 0;
  630. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  631. // than a variably modified type.
  632. if (ArrayType *ary = dyn_cast<ArrayType>(T.getCanonicalType())) {
  633. if (VerifyConstantArrayType(ary, Loc))
  634. return 0;
  635. }
  636. // FIXME: Chain fielddecls together.
  637. return new FieldDecl(Loc, II, T, 0);
  638. }
  639. void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
  640. DeclTy **Fields, unsigned NumFields) {
  641. RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
  642. if (Record->isDefinition()) {
  643. // Diagnose code like:
  644. // struct S { struct S {} X; };
  645. // We discover this when we complete the outer S. Reject and ignore the
  646. // outer S.
  647. Diag(Record->getLocation(), diag::err_nested_redefinition,
  648. Record->getKindName());
  649. Diag(RecLoc, diag::err_previous_definition);
  650. return;
  651. }
  652. // Verify that all the fields are okay.
  653. unsigned NumNamedMembers = 0;
  654. llvm::SmallVector<FieldDecl*, 32> RecFields;
  655. llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
  656. for (unsigned i = 0; i != NumFields; ++i) {
  657. FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
  658. if (!FD) continue; // Already issued a diagnostic.
  659. // Get the type for the field.
  660. Type *FDTy = FD->getType().getCanonicalType().getTypePtr();
  661. // C99 6.7.2.1p2 - A field may not be a function type.
  662. if (isa<FunctionType>(FDTy)) {
  663. Diag(FD->getLocation(), diag::err_field_declared_as_function,
  664. FD->getName());
  665. delete FD;
  666. continue;
  667. }
  668. // C99 6.7.2.1p2 - A field may not be an incomplete type except...
  669. if (FDTy->isIncompleteType()) {
  670. if (i != NumFields-1 || // ... that the last member ...
  671. Record->getKind() != Decl::Struct || // ... of a structure ...
  672. !isa<ArrayType>(FDTy)) { //... may have incomplete array type.
  673. Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
  674. delete FD;
  675. continue;
  676. }
  677. if (NumNamedMembers < 1) { //... must have more than named member ...
  678. Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
  679. FD->getName());
  680. delete FD;
  681. continue;
  682. }
  683. // Okay, we have a legal flexible array member at the end of the struct.
  684. Record->setHasFlexibleArrayMember(true);
  685. }
  686. /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
  687. /// field of another structure or the element of an array.
  688. if (RecordType *FDTTy = dyn_cast<RecordType>(FDTy)) {
  689. if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
  690. // If this is a member of a union, then entire union becomes "flexible".
  691. if (Record->getKind() == Decl::Union) {
  692. Record->setHasFlexibleArrayMember(true);
  693. } else {
  694. // If this is a struct/class and this is not the last element, reject
  695. // it. Note that GCC supports variable sized arrays in the middle of
  696. // structures.
  697. if (i != NumFields-1) {
  698. Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
  699. FD->getName());
  700. delete FD;
  701. continue;
  702. }
  703. // We support flexible arrays at the end of structs in other structs
  704. // as an extension.
  705. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
  706. FD->getName());
  707. Record->setHasFlexibleArrayMember(true);
  708. }
  709. }
  710. }
  711. // Keep track of the number of named members.
  712. if (IdentifierInfo *II = FD->getIdentifier()) {
  713. // Detect duplicate member names.
  714. if (!FieldIDs.insert(II)) {
  715. Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
  716. // Find the previous decl.
  717. SourceLocation PrevLoc;
  718. for (unsigned i = 0, e = RecFields.size(); ; ++i) {
  719. assert(i != e && "Didn't find previous def!");
  720. if (RecFields[i]->getIdentifier() == II) {
  721. PrevLoc = RecFields[i]->getLocation();
  722. break;
  723. }
  724. }
  725. Diag(PrevLoc, diag::err_previous_definition);
  726. delete FD;
  727. continue;
  728. }
  729. ++NumNamedMembers;
  730. }
  731. // Remember good fields.
  732. RecFields.push_back(FD);
  733. }
  734. // Okay, we successfully defined 'Record'.
  735. Record->defineBody(&RecFields[0], RecFields.size());
  736. }
  737. Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
  738. DeclTy *lastEnumConst,
  739. SourceLocation IdLoc, IdentifierInfo *Id,
  740. SourceLocation EqualLoc, ExprTy *val) {
  741. theEnumDecl = theEnumDecl; // silence unused warning.
  742. EnumConstantDecl *LastEnumConst =
  743. cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
  744. Expr *Val = static_cast<Expr*>(val);
  745. // Verify that there isn't already something declared with this name in this
  746. // scope.
  747. if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
  748. if (S->isDeclScope(PrevDecl)) {
  749. if (isa<EnumConstantDecl>(PrevDecl))
  750. Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
  751. else
  752. Diag(IdLoc, diag::err_redefinition, Id->getName());
  753. Diag(PrevDecl->getLocation(), diag::err_previous_definition);
  754. // FIXME: Don't leak memory: delete Val;
  755. return 0;
  756. }
  757. }
  758. llvm::APSInt EnumVal(32);
  759. QualType EltTy;
  760. if (Val) {
  761. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  762. SourceLocation ExpLoc;
  763. if (!Val->isIntegerConstantExpr(EnumVal, &ExpLoc)) {
  764. Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
  765. Id->getName());
  766. // FIXME: Don't leak memory: delete Val;
  767. return 0;
  768. }
  769. EltTy = Val->getType();
  770. } else if (LastEnumConst) {
  771. // Assign the last value + 1.
  772. EnumVal = LastEnumConst->getInitVal();
  773. ++EnumVal;
  774. // FIXME: detect overflow!
  775. EltTy = LastEnumConst->getType();
  776. } else {
  777. // First value, set to zero.
  778. EltTy = Context.IntTy;
  779. // FIXME: Resize EnumVal to the size of int.
  780. }
  781. // TODO: Default promotions to int/uint.
  782. // TODO: If the result value doesn't fit in an int, it must be a long or long
  783. // long value. ISO C does not support this, but GCC does as an extension,
  784. // emit a warning.
  785. EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
  786. LastEnumConst);
  787. // Register this decl in the current scope stack.
  788. New->setNext(Id->getFETokenInfo<Decl>());
  789. Id->setFETokenInfo(New);
  790. S->AddDecl(New);
  791. return New;
  792. }
  793. void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
  794. DeclTy **Elements, unsigned NumElements) {
  795. EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
  796. assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
  797. // Verify that all the values are okay, and reverse the list.
  798. EnumConstantDecl *EltList = 0;
  799. for (unsigned i = 0; i != NumElements; ++i) {
  800. EnumConstantDecl *ECD =
  801. cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
  802. if (!ECD) continue; // Already issued a diagnostic.
  803. ECD->setNextDeclarator(EltList);
  804. EltList = ECD;
  805. }
  806. Enum->defineElements(EltList);
  807. }
  808. void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
  809. if (!current) return;
  810. // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
  811. // remember this in the LastInGroupList list.
  812. if (last)
  813. LastInGroupList.push_back((Decl*)last);
  814. }
  815. void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
  816. if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
  817. if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
  818. QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
  819. if (!newType.isNull()) // install the new vector type into the decl
  820. vDecl->setType(newType);
  821. }
  822. if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
  823. QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
  824. rawAttr);
  825. if (!newType.isNull()) // install the new vector type into the decl
  826. tDecl->setUnderlyingType(newType);
  827. }
  828. }
  829. // FIXME: add other attributes...
  830. }
  831. void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
  832. AttributeList *declarator_postfix) {
  833. while (declspec_prefix) {
  834. HandleDeclAttribute(New, declspec_prefix);
  835. declspec_prefix = declspec_prefix->getNext();
  836. }
  837. while (declarator_postfix) {
  838. HandleDeclAttribute(New, declarator_postfix);
  839. declarator_postfix = declarator_postfix->getNext();
  840. }
  841. }
  842. QualType Sema::HandleVectorTypeAttribute(QualType curType,
  843. AttributeList *rawAttr) {
  844. // check the attribute arugments.
  845. if (rawAttr->getNumArgs() != 1) {
  846. Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
  847. std::string("1"));
  848. return QualType();
  849. }
  850. Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
  851. llvm::APSInt vecSize(32);
  852. if (!sizeExpr->isIntegerConstantExpr(vecSize)) {
  853. Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
  854. sizeExpr->getSourceRange());
  855. return QualType();
  856. }
  857. // navigate to the base type - we need to provide for vector pointers,
  858. // vector arrays, and functions returning vectors.
  859. Type *canonType = curType.getCanonicalType().getTypePtr();
  860. while (canonType->isPointerType() || canonType->isArrayType() ||
  861. canonType->isFunctionType()) {
  862. if (PointerType *PT = dyn_cast<PointerType>(canonType))
  863. canonType = PT->getPointeeType().getTypePtr();
  864. else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
  865. canonType = AT->getElementType().getTypePtr();
  866. else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
  867. canonType = FT->getResultType().getTypePtr();
  868. }
  869. // the base type must be integer or float.
  870. if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
  871. Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
  872. curType.getCanonicalType().getAsString());
  873. return QualType();
  874. }
  875. BuiltinType *baseType = cast<BuiltinType>(canonType);
  876. unsigned typeSize = baseType->getSize();
  877. // vecSize is specified in bytes - convert to bits.
  878. unsigned vectorSize = vecSize.getZExtValue() * 8;
  879. // the vector size needs to be an integral multiple of the type size.
  880. if (vectorSize % typeSize) {
  881. Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
  882. sizeExpr->getSourceRange());
  883. return QualType();
  884. }
  885. if (vectorSize == 0) {
  886. Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
  887. sizeExpr->getSourceRange());
  888. return QualType();
  889. }
  890. // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
  891. // the number of elements to be a power of two (unlike GCC).
  892. // Instantiate the vector type, the number of elements is > 0.
  893. return Context.convertToVectorType(curType, vectorSize/typeSize);
  894. }