SemaDecl.cpp revision 1d78cc443084134428c4c333fab25148900c3ca4
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for declarations. 11// 12//===----------------------------------------------------------------------===// 13 14#include "Sema.h" 15#include "clang/AST/ASTConsumer.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/Attr.h" 18#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" 24#include "clang/Basic/LangOptions.h" 25#include "clang/Basic/TargetInfo.h" 26#include "clang/Basic/SourceManager.h" 27// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's) 28#include "clang/Lex/Preprocessor.h" 29#include "clang/Lex/HeaderSearch.h" 30#include "llvm/ADT/SmallString.h" 31#include "llvm/ADT/SmallSet.h" 32#include "llvm/ADT/DenseSet.h" 33using namespace clang; 34 35Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) { 36 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false); 37 38 if (IIDecl && (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl))) 39 return IIDecl; 40 return 0; 41} 42 43void Sema::PushDeclContext(DeclContext *CD) { 44 assert(CD->getParent() == CurContext && 45 "The next DeclContext should be directly contained in the current one."); 46 CurContext = CD; 47} 48 49void Sema::PopDeclContext() { 50 assert(CurContext && "DeclContext imbalance!"); 51 CurContext = CurContext->getParent(); 52} 53 54void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 55 if (S->decl_empty()) return; 56 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!"); 57 58 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 59 I != E; ++I) { 60 Decl *TmpD = static_cast<Decl*>(*I); 61 assert(TmpD && "This decl didn't get pushed??"); 62 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD); 63 assert(D && "This decl isn't a ScopedDecl?"); 64 65 IdentifierInfo *II = D->getIdentifier(); 66 if (!II) continue; 67 68 // Unlink this decl from the identifier. Because the scope contains decls 69 // in an unordered collection, and because we have multiple identifier 70 // namespaces (e.g. tag, normal, label),the decl may not be the first entry. 71 if (II->getFETokenInfo<Decl>() == D) { 72 // Normal case, no multiple decls in different namespaces. 73 II->setFETokenInfo(D->getNext()); 74 } else { 75 // Scan ahead. There are only three namespaces in C, so this loop can 76 // never execute more than 3 times. 77 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>(); 78 while (SomeDecl->getNext() != D) { 79 SomeDecl = SomeDecl->getNext(); 80 assert(SomeDecl && "Didn't find this decl on its identifier's chain!"); 81 } 82 SomeDecl->setNext(D->getNext()); 83 } 84 85 // This will have to be revisited for C++: there we want to nest stuff in 86 // namespace decls etc. Even for C, we might want a top-level translation 87 // unit decl or something. 88 if (!CurFunctionDecl) 89 continue; 90 91 // Chain this decl to the containing function, it now owns the memory for 92 // the decl. 93 D->setNext(CurFunctionDecl->getDeclChain()); 94 CurFunctionDecl->setDeclChain(D); 95 } 96} 97 98/// getObjCInterfaceDecl - Look up a for a class declaration in the scope. 99/// return 0 if one not found. 100ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) { 101 // The third "scope" argument is 0 since we aren't enabling lazy built-in 102 // creation from this context. 103 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false); 104 105 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 106} 107 108/// LookupDecl - Look up the inner-most declaration in the specified 109/// namespace. 110Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI, 111 Scope *S, bool enableLazyBuiltinCreation) { 112 if (II == 0) return 0; 113 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI; 114 115 // Scan up the scope chain looking for a decl that matches this identifier 116 // that is in the appropriate namespace. This search should not take long, as 117 // shadowing of names is uncommon, and deep shadowing is extremely uncommon. 118 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext()) 119 if (D->getIdentifierNamespace() == NS) 120 return D; 121 122 // If we didn't find a use of this identifier, and if the identifier 123 // corresponds to a compiler builtin, create the decl object for the builtin 124 // now, injecting it into translation unit scope, and return it. 125 if (NS == Decl::IDNS_Ordinary) { 126 if (enableLazyBuiltinCreation) { 127 // If this is a builtin on this (or all) targets, create the decl. 128 if (unsigned BuiltinID = II->getBuiltinID()) 129 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S); 130 } 131 if (getLangOptions().ObjC1) { 132 // @interface and @compatibility_alias introduce typedef-like names. 133 // Unlike typedef's, they can only be introduced at file-scope (and are 134 // therefore not scoped decls). They can, however, be shadowed by 135 // other names in IDNS_Ordinary. 136 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II); 137 if (IDI != ObjCInterfaceDecls.end()) 138 return IDI->second; 139 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II); 140 if (I != ObjCAliasDecls.end()) 141 return I->second->getClassInterface(); 142 } 143 } 144 return 0; 145} 146 147void Sema::InitBuiltinVaListType() 148{ 149 if (!Context.getBuiltinVaListType().isNull()) 150 return; 151 152 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list"); 153 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope); 154 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl); 155 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef)); 156} 157 158/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope. 159/// lazily create a decl for it. 160ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 161 Scope *S) { 162 Builtin::ID BID = (Builtin::ID)bid; 163 164 if (BID == Builtin::BI__builtin_va_start || 165 BID == Builtin::BI__builtin_va_copy || 166 BID == Builtin::BI__builtin_va_end) 167 InitBuiltinVaListType(); 168 169 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context); 170 FunctionDecl *New = FunctionDecl::Create(Context, CurContext, 171 SourceLocation(), II, R, 172 FunctionDecl::Extern, false, 0); 173 174 // Find translation-unit scope to insert this function into. 175 if (Scope *FnS = S->getFnParent()) 176 S = FnS->getParent(); // Skip all scopes in a function at once. 177 while (S->getParent()) 178 S = S->getParent(); 179 S->AddDecl(New); 180 181 // Add this decl to the end of the identifier info. 182 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) { 183 // Scan until we find the last (outermost) decl in the id chain. 184 while (LastDecl->getNext()) 185 LastDecl = LastDecl->getNext(); 186 // Insert before (outside) it. 187 LastDecl->setNext(New); 188 } else { 189 II->setFETokenInfo(New); 190 } 191 return New; 192} 193 194/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name 195/// and scope as a previous declaration 'Old'. Figure out how to resolve this 196/// situation, merging decls or emitting diagnostics as appropriate. 197/// 198TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) { 199 // Verify the old decl was also a typedef. 200 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD); 201 if (!Old) { 202 Diag(New->getLocation(), diag::err_redefinition_different_kind, 203 New->getName()); 204 Diag(OldD->getLocation(), diag::err_previous_definition); 205 return New; 206 } 207 208 // Allow multiple definitions for ObjC built-in typedefs. 209 // FIXME: Verify the underlying types are equivalent! 210 if (getLangOptions().ObjC1 && isBuiltinObjCType(New)) 211 return Old; 212 213 // Redeclaration of a type is a constraint violation (6.7.2.3p1). 214 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if 215 // *either* declaration is in a system header. The code below implements 216 // this adhoc compatibility rule. FIXME: The following code will not 217 // work properly when compiling ".i" files (containing preprocessed output). 218 SourceManager &SrcMgr = Context.getSourceManager(); 219 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation()); 220 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation()); 221 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo(); 222 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile); 223 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile); 224 225 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir. 226 if ((OldDirType != DirectoryLookup::NormalHeaderDir || 227 NewDirType != DirectoryLookup::NormalHeaderDir) || 228 getLangOptions().Microsoft) 229 return New; 230 231 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 232 // TODO: This is totally simplistic. It should handle merging functions 233 // together etc, merging extern int X; int X; ... 234 Diag(New->getLocation(), diag::err_redefinition, New->getName()); 235 Diag(Old->getLocation(), diag::err_previous_definition); 236 return New; 237} 238 239/// DeclhasAttr - returns true if decl Declaration already has the target attribute. 240static bool DeclHasAttr(const Decl *decl, const Attr *target) { 241 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext()) 242 if (attr->getKind() == target->getKind()) 243 return true; 244 245 return false; 246} 247 248/// MergeAttributes - append attributes from the Old decl to the New one. 249static void MergeAttributes(Decl *New, Decl *Old) { 250 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp; 251 252// FIXME: fix this code to cleanup the Old attrs correctly 253 while (attr) { 254 tmp = attr; 255 attr = attr->getNext(); 256 257 if (!DeclHasAttr(New, tmp)) { 258 New->addAttr(tmp); 259 } else { 260 tmp->setNext(0); 261 delete(tmp); 262 } 263 } 264} 265 266/// MergeFunctionDecl - We just parsed a function 'New' from 267/// declarator D which has the same name and scope as a previous 268/// declaration 'Old'. Figure out how to resolve this situation, 269/// merging decls or emitting diagnostics as appropriate. 270/// 271FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) { 272 // Verify the old decl was also a function. 273 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD); 274 if (!Old) { 275 Diag(New->getLocation(), diag::err_redefinition_different_kind, 276 New->getName()); 277 Diag(OldD->getLocation(), diag::err_previous_definition); 278 return New; 279 } 280 281 MergeAttributes(New, Old); 282 283 QualType OldQType = Context.getCanonicalType(Old->getType()); 284 QualType NewQType = Context.getCanonicalType(New->getType()); 285 286 // C++ [dcl.fct]p3: 287 // All declarations for a function shall agree exactly in both the 288 // return type and the parameter-type-list. 289 if (getLangOptions().CPlusPlus && OldQType == NewQType) 290 return MergeCXXFunctionDecl(New, Old); 291 292 // C: Function types need to be compatible, not identical. This handles 293 // duplicate function decls like "void f(int); void f(enum X);" properly. 294 if (!getLangOptions().CPlusPlus && 295 Context.functionTypesAreCompatible(OldQType, NewQType)) { 296 return New; 297 } 298 299 // A function that has already been declared has been redeclared or defined 300 // with a different type- show appropriate diagnostic 301 diag::kind PrevDiag; 302 if (Old->getBody()) 303 PrevDiag = diag::err_previous_definition; 304 else if (Old->isImplicit()) 305 PrevDiag = diag::err_previous_implicit_declaration; 306 else 307 PrevDiag = diag::err_previous_declaration; 308 309 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 310 // TODO: This is totally simplistic. It should handle merging functions 311 // together etc, merging extern int X; int X; ... 312 Diag(New->getLocation(), diag::err_conflicting_types, New->getName()); 313 Diag(Old->getLocation(), PrevDiag); 314 return New; 315} 316 317/// equivalentArrayTypes - Used to determine whether two array types are 318/// equivalent. 319/// We need to check this explicitly as an incomplete array definition is 320/// considered a VariableArrayType, so will not match a complete array 321/// definition that would be otherwise equivalent. 322static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) { 323 const ArrayType *NewAT = NewQType->getAsArrayType(); 324 const ArrayType *OldAT = OldQType->getAsArrayType(); 325 326 if (!NewAT || !OldAT) 327 return false; 328 329 // If either (or both) array types in incomplete we need to strip off the 330 // outer VariableArrayType. Once the outer VAT is removed the remaining 331 // types must be identical if the array types are to be considered 332 // equivalent. 333 // eg. int[][1] and int[1][1] become 334 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int)) 335 // removing the outermost VAT gives 336 // CAT(1, int) and CAT(1, int) 337 // which are equal, therefore the array types are equivalent. 338 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) { 339 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier()) 340 return false; 341 NewQType = NewAT->getElementType().getCanonicalType(); 342 OldQType = OldAT->getElementType().getCanonicalType(); 343 } 344 345 return NewQType == OldQType; 346} 347 348/// MergeVarDecl - We just parsed a variable 'New' which has the same name 349/// and scope as a previous declaration 'Old'. Figure out how to resolve this 350/// situation, merging decls or emitting diagnostics as appropriate. 351/// 352/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2). 353/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4. 354/// 355VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) { 356 // Verify the old decl was also a variable. 357 VarDecl *Old = dyn_cast<VarDecl>(OldD); 358 if (!Old) { 359 Diag(New->getLocation(), diag::err_redefinition_different_kind, 360 New->getName()); 361 Diag(OldD->getLocation(), diag::err_previous_definition); 362 return New; 363 } 364 365 MergeAttributes(New, Old); 366 367 // Verify the types match. 368 QualType OldCType = Context.getCanonicalType(Old->getType()); 369 QualType NewCType = Context.getCanonicalType(New->getType()); 370 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) { 371 Diag(New->getLocation(), diag::err_redefinition, New->getName()); 372 Diag(Old->getLocation(), diag::err_previous_definition); 373 return New; 374 } 375 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 376 if (New->getStorageClass() == VarDecl::Static && 377 (Old->getStorageClass() == VarDecl::None || 378 Old->getStorageClass() == VarDecl::Extern)) { 379 Diag(New->getLocation(), diag::err_static_non_static, New->getName()); 380 Diag(Old->getLocation(), diag::err_previous_definition); 381 return New; 382 } 383 // C99 6.2.2p4: Check if we have a non-static decl followed by a static. 384 if (New->getStorageClass() != VarDecl::Static && 385 Old->getStorageClass() == VarDecl::Static) { 386 Diag(New->getLocation(), diag::err_non_static_static, New->getName()); 387 Diag(Old->getLocation(), diag::err_previous_definition); 388 return New; 389 } 390 // We've verified the types match, now handle "tentative" definitions. 391 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old); 392 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New); 393 394 if (OldFSDecl && NewFSDecl) { 395 // Handle C "tentative" external object definitions (C99 6.9.2). 396 bool OldIsTentative = false; 397 bool NewIsTentative = false; 398 399 if (!OldFSDecl->getInit() && 400 (OldFSDecl->getStorageClass() == VarDecl::None || 401 OldFSDecl->getStorageClass() == VarDecl::Static)) 402 OldIsTentative = true; 403 404 // FIXME: this check doesn't work (since the initializer hasn't been 405 // attached yet). This check should be moved to FinalizeDeclaratorGroup. 406 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've 407 // thrown out the old decl. 408 if (!NewFSDecl->getInit() && 409 (NewFSDecl->getStorageClass() == VarDecl::None || 410 NewFSDecl->getStorageClass() == VarDecl::Static)) 411 ; // change to NewIsTentative = true; once the code is moved. 412 413 if (NewIsTentative || OldIsTentative) 414 return New; 415 } 416 if (Old->getStorageClass() != VarDecl::Extern && 417 New->getStorageClass() != VarDecl::Extern) { 418 Diag(New->getLocation(), diag::err_redefinition, New->getName()); 419 Diag(Old->getLocation(), diag::err_previous_definition); 420 } 421 return New; 422} 423 424/// CheckParmsForFunctionDef - Check that the parameters of the given 425/// function are appropriate for the definition of a function. This 426/// takes care of any checks that cannot be performed on the 427/// declaration itself, e.g., that the types of each of the function 428/// parameters are complete. 429bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) { 430 bool HasInvalidParm = false; 431 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 432 ParmVarDecl *Param = FD->getParamDecl(p); 433 434 // C99 6.7.5.3p4: the parameters in a parameter type list in a 435 // function declarator that is part of a function definition of 436 // that function shall not have incomplete type. 437 if (Param->getType()->isIncompleteType() && 438 !Param->isInvalidDecl()) { 439 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type, 440 Param->getType().getAsString()); 441 Param->setInvalidDecl(); 442 HasInvalidParm = true; 443 } 444 } 445 446 return HasInvalidParm; 447} 448 449/// CreateImplicitParameter - Creates an implicit function parameter 450/// in the scope S and with the given type. This routine is used, for 451/// example, to create the implicit "self" parameter in an Objective-C 452/// method. 453ParmVarDecl * 454Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id, 455 SourceLocation IdLoc, QualType Type) { 456 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type, 457 VarDecl::None, 0, 0); 458 if (Id) { 459 New->setNext(Id->getFETokenInfo<ScopedDecl>()); 460 Id->setFETokenInfo(New); 461 S->AddDecl(New); 462 } 463 464 return New; 465} 466 467/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 468/// no declarator (e.g. "struct foo;") is parsed. 469Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) { 470 // TODO: emit error on 'int;' or 'const enum foo;'. 471 // TODO: emit error on 'typedef int;' 472 // if (!DS.isMissingDeclaratorOk()) Diag(...); 473 474 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep())); 475} 476 477bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) { 478 // Get the type before calling CheckSingleAssignmentConstraints(), since 479 // it can promote the expression. 480 QualType InitType = Init->getType(); 481 482 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init); 483 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType, 484 InitType, Init, "initializing"); 485} 486 487bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot, 488 QualType ElementType) { 489 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer. 490 if (CheckSingleInitializer(expr, ElementType)) 491 return true; // types weren't compatible. 492 493 if (savExpr != expr) // The type was promoted, update initializer list. 494 IList->setInit(slot, expr); 495 return false; 496} 497 498bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) { 499 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) { 500 // C99 6.7.8p14. We have an array of character type with unknown size 501 // being initialized to a string literal. 502 llvm::APSInt ConstVal(32); 503 ConstVal = strLiteral->getByteLength() + 1; 504 // Return a new array type (C99 6.7.8p22). 505 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal, 506 ArrayType::Normal, 0); 507 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) { 508 // C99 6.7.8p14. We have an array of character type with known size. 509 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements()) 510 Diag(strLiteral->getSourceRange().getBegin(), 511 diag::warn_initializer_string_for_char_array_too_long, 512 strLiteral->getSourceRange()); 513 } else { 514 assert(0 && "HandleStringLiteralInit(): Invalid array type"); 515 } 516 // Set type from "char *" to "constant array of char". 517 strLiteral->setType(DeclT); 518 // For now, we always return false (meaning success). 519 return false; 520} 521 522StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) { 523 const ArrayType *AT = DeclType->getAsArrayType(); 524 if (AT && AT->getElementType()->isCharType()) { 525 return dyn_cast<StringLiteral>(Init); 526 } 527 return 0; 528} 529 530// CheckInitializerListTypes - Checks the types of elements of an initializer 531// list. This function is recursive: it calls itself to initialize subelements 532// of aggregate types. Note that the topLevel parameter essentially refers to 533// whether this expression "owns" the initializer list passed in, or if this 534// initialization is taking elements out of a parent initializer. Each 535// call to this function adds zero or more to startIndex, reports any errors, 536// and returns true if it found any inconsistent types. 537bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType, 538 bool topLevel, unsigned& startIndex) { 539 bool hadError = false; 540 541 if (DeclType->isScalarType()) { 542 // The simplest case: initializing a single scalar 543 if (topLevel) { 544 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init, 545 IList->getSourceRange()); 546 } 547 if (startIndex < IList->getNumInits()) { 548 Expr* expr = IList->getInit(startIndex); 549 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { 550 // FIXME: Should an error be reported here instead? 551 unsigned newIndex = 0; 552 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex); 553 } else { 554 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType); 555 } 556 ++startIndex; 557 } 558 // FIXME: Should an error be reported for empty initializer list + scalar? 559 } else if (DeclType->isVectorType()) { 560 if (startIndex < IList->getNumInits()) { 561 const VectorType *VT = DeclType->getAsVectorType(); 562 int maxElements = VT->getNumElements(); 563 QualType elementType = VT->getElementType(); 564 565 for (int i = 0; i < maxElements; ++i) { 566 // Don't attempt to go past the end of the init list 567 if (startIndex >= IList->getNumInits()) 568 break; 569 Expr* expr = IList->getInit(startIndex); 570 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { 571 unsigned newIndex = 0; 572 hadError |= CheckInitializerListTypes(SubInitList, elementType, 573 true, newIndex); 574 ++startIndex; 575 } else { 576 hadError |= CheckInitializerListTypes(IList, elementType, 577 false, startIndex); 578 } 579 } 580 } 581 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) { 582 if (DeclType->isStructureType() || DeclType->isUnionType()) { 583 if (startIndex < IList->getNumInits() && !topLevel && 584 Context.typesAreCompatible(IList->getInit(startIndex)->getType(), 585 DeclType)) { 586 // We found a compatible struct; per the standard, this initializes the 587 // struct. (The C standard technically says that this only applies for 588 // initializers for declarations with automatic scope; however, this 589 // construct is unambiguous anyway because a struct cannot contain 590 // a type compatible with itself. We'll output an error when we check 591 // if the initializer is constant.) 592 // FIXME: Is a call to CheckSingleInitializer required here? 593 ++startIndex; 594 } else { 595 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl(); 596 597 // If the record is invalid, some of it's members are invalid. To avoid 598 // confusion, we forgo checking the intializer for the entire record. 599 if (structDecl->isInvalidDecl()) 600 return true; 601 602 // If structDecl is a forward declaration, this loop won't do anything; 603 // That's okay, because an error should get printed out elsewhere. It 604 // might be worthwhile to skip over the rest of the initializer, though. 605 int numMembers = structDecl->getNumMembers() - 606 structDecl->hasFlexibleArrayMember(); 607 for (int i = 0; i < numMembers; i++) { 608 // Don't attempt to go past the end of the init list 609 if (startIndex >= IList->getNumInits()) 610 break; 611 FieldDecl * curField = structDecl->getMember(i); 612 if (!curField->getIdentifier()) { 613 // Don't initialize unnamed fields, e.g. "int : 20;" 614 continue; 615 } 616 QualType fieldType = curField->getType(); 617 Expr* expr = IList->getInit(startIndex); 618 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { 619 unsigned newStart = 0; 620 hadError |= CheckInitializerListTypes(SubInitList, fieldType, 621 true, newStart); 622 ++startIndex; 623 } else { 624 hadError |= CheckInitializerListTypes(IList, fieldType, 625 false, startIndex); 626 } 627 if (DeclType->isUnionType()) 628 break; 629 } 630 // FIXME: Implement flexible array initialization GCC extension (it's a 631 // really messy extension to implement, unfortunately...the necessary 632 // information isn't actually even here!) 633 } 634 } else if (DeclType->isArrayType()) { 635 // Check for the special-case of initializing an array with a string. 636 if (startIndex < IList->getNumInits()) { 637 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex), 638 DeclType)) { 639 CheckStringLiteralInit(lit, DeclType); 640 ++startIndex; 641 if (topLevel && startIndex < IList->getNumInits()) { 642 // We have leftover initializers; warn 643 Diag(IList->getInit(startIndex)->getLocStart(), 644 diag::err_excess_initializers_in_char_array_initializer, 645 IList->getInit(startIndex)->getSourceRange()); 646 } 647 return false; 648 } 649 } 650 int maxElements; 651 if (DeclType->isIncompleteArrayType()) { 652 // FIXME: use a proper constant 653 maxElements = 0x7FFFFFFF; 654 } else if (const VariableArrayType *VAT = 655 DeclType->getAsVariableArrayType()) { 656 // Check for VLAs; in standard C it would be possible to check this 657 // earlier, but I don't know where clang accepts VLAs (gcc accepts 658 // them in all sorts of strange places). 659 Diag(VAT->getSizeExpr()->getLocStart(), 660 diag::err_variable_object_no_init, 661 VAT->getSizeExpr()->getSourceRange()); 662 hadError = true; 663 maxElements = 0x7FFFFFFF; 664 } else { 665 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType(); 666 maxElements = static_cast<int>(CAT->getSize().getZExtValue()); 667 } 668 QualType elementType = DeclType->getAsArrayType()->getElementType(); 669 int numElements = 0; 670 for (int i = 0; i < maxElements; ++i, ++numElements) { 671 // Don't attempt to go past the end of the init list 672 if (startIndex >= IList->getNumInits()) 673 break; 674 Expr* expr = IList->getInit(startIndex); 675 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { 676 unsigned newIndex = 0; 677 hadError |= CheckInitializerListTypes(SubInitList, elementType, 678 true, newIndex); 679 ++startIndex; 680 } else { 681 hadError |= CheckInitializerListTypes(IList, elementType, 682 false, startIndex); 683 } 684 } 685 if (DeclType->isIncompleteArrayType()) { 686 // If this is an incomplete array type, the actual type needs to 687 // be calculated here 688 if (numElements == 0) { 689 // Sizing an array implicitly to zero is not allowed 690 // (It could in theory be allowed, but it doesn't really matter.) 691 Diag(IList->getLocStart(), 692 diag::err_at_least_one_initializer_needed_to_size_array); 693 hadError = true; 694 } else { 695 llvm::APSInt ConstVal(32); 696 ConstVal = numElements; 697 DeclType = Context.getConstantArrayType(elementType, ConstVal, 698 ArrayType::Normal, 0); 699 } 700 } 701 } else { 702 assert(0 && "Aggregate that isn't a function or array?!"); 703 } 704 } else { 705 // In C, all types are either scalars or aggregates, but 706 // additional handling is needed here for C++ (and possibly others?). 707 assert(0 && "Unsupported initializer type"); 708 } 709 710 // If this init list is a base list, we set the type; an initializer doesn't 711 // fundamentally have a type, but this makes the ASTs a bit easier to read 712 if (topLevel) 713 IList->setType(DeclType); 714 715 if (topLevel && startIndex < IList->getNumInits()) { 716 // We have leftover initializers; warn 717 Diag(IList->getInit(startIndex)->getLocStart(), 718 diag::warn_excess_initializers, 719 IList->getInit(startIndex)->getSourceRange()); 720 } 721 return hadError; 722} 723 724bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) { 725 // C99 6.7.8p3: The type of the entity to be initialized shall be an array 726 // of unknown size ("[]") or an object type that is not a variable array type. 727 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) 728 return Diag(VAT->getSizeExpr()->getLocStart(), 729 diag::err_variable_object_no_init, 730 VAT->getSizeExpr()->getSourceRange()); 731 732 InitListExpr *InitList = dyn_cast<InitListExpr>(Init); 733 if (!InitList) { 734 // FIXME: Handle wide strings 735 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType)) 736 return CheckStringLiteralInit(strLiteral, DeclType); 737 738 if (DeclType->isArrayType()) 739 return Diag(Init->getLocStart(), 740 diag::err_array_init_list_required, 741 Init->getSourceRange()); 742 743 return CheckSingleInitializer(Init, DeclType); 744 } 745 unsigned newIndex = 0; 746 return CheckInitializerListTypes(InitList, DeclType, true, newIndex); 747} 748 749Sema::DeclTy * 750Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) { 751 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl); 752 IdentifierInfo *II = D.getIdentifier(); 753 754 // All of these full declarators require an identifier. If it doesn't have 755 // one, the ParsedFreeStandingDeclSpec action should be used. 756 if (II == 0) { 757 Diag(D.getDeclSpec().getSourceRange().getBegin(), 758 diag::err_declarator_need_ident, 759 D.getDeclSpec().getSourceRange(), D.getSourceRange()); 760 return 0; 761 } 762 763 // The scope passed in may not be a decl scope. Zip up the scope tree until 764 // we find one that is. 765 while ((S->getFlags() & Scope::DeclScope) == 0) 766 S = S->getParent(); 767 768 // See if this is a redefinition of a variable in the same scope. 769 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S); 770 ScopedDecl *New; 771 bool InvalidDecl = false; 772 773 QualType R = GetTypeForDeclarator(D, S); 774 assert(!R.isNull() && "GetTypeForDeclarator() returned null type"); 775 776 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 777 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator); 778 if (!NewTD) return 0; 779 780 // Handle attributes prior to checking for duplicates in MergeVarDecl 781 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(), 782 D.getAttributes()); 783 // Merge the decl with the existing one if appropriate. If the decl is 784 // in an outer scope, it isn't the same thing. 785 if (PrevDecl && S->isDeclScope(PrevDecl)) { 786 NewTD = MergeTypeDefDecl(NewTD, PrevDecl); 787 if (NewTD == 0) return 0; 788 } 789 New = NewTD; 790 if (S->getParent() == 0) { 791 // C99 6.7.7p2: If a typedef name specifies a variably modified type 792 // then it shall have block scope. 793 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) { 794 // FIXME: Diagnostic needs to be fixed. 795 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla); 796 InvalidDecl = true; 797 } 798 } 799 } else if (R.getTypePtr()->isFunctionType()) { 800 FunctionDecl::StorageClass SC = FunctionDecl::None; 801 switch (D.getDeclSpec().getStorageClassSpec()) { 802 default: assert(0 && "Unknown storage class!"); 803 case DeclSpec::SCS_auto: 804 case DeclSpec::SCS_register: 805 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func, 806 R.getAsString()); 807 InvalidDecl = true; 808 break; 809 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break; 810 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break; 811 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break; 812 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break; 813 } 814 815 bool isInline = D.getDeclSpec().isInlineSpecified(); 816 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext, 817 D.getIdentifierLoc(), 818 II, R, SC, isInline, 819 LastDeclarator); 820 // Handle attributes. 821 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(), 822 D.getAttributes()); 823 824 // Copy the parameter declarations from the declarator D to 825 // the function declaration NewFD, if they are available. 826 if (D.getNumTypeObjects() > 0 && 827 D.getTypeObject(0).Fun.hasPrototype) { 828 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 829 830 // Create Decl objects for each parameter, adding them to the 831 // FunctionDecl. 832 llvm::SmallVector<ParmVarDecl*, 16> Params; 833 834 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 835 // function that takes no arguments, not a function that takes a 836 // single void argument. 837 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 838 FTI.ArgInfo[0].Param && 839 !((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() && 840 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 841 // empty arg list, don't push any params. 842 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param; 843 844 // In C++, the empty parameter-type-list must be spelled "void"; a 845 // typedef of void is not permitted. 846 if (getLangOptions().CPlusPlus && 847 Param->getType() != Context.VoidTy) { 848 Diag(Param->getLocation(), diag::ext_param_typedef_of_void); 849 } 850 851 } else { 852 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 853 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param); 854 } 855 856 NewFD->setParams(&Params[0], Params.size()); 857 } 858 859 // Merge the decl with the existing one if appropriate. Since C functions 860 // are in a flat namespace, make sure we consider decls in outer scopes. 861 if (PrevDecl) { 862 NewFD = MergeFunctionDecl(NewFD, PrevDecl); 863 if (NewFD == 0) return 0; 864 } 865 New = NewFD; 866 867 // In C++, check default arguments now that we have merged decls. 868 if (getLangOptions().CPlusPlus) 869 CheckCXXDefaultArguments(NewFD); 870 } else { 871 if (R.getTypePtr()->isObjCInterfaceType()) { 872 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object, 873 D.getIdentifier()->getName()); 874 InvalidDecl = true; 875 } 876 877 VarDecl *NewVD; 878 VarDecl::StorageClass SC; 879 switch (D.getDeclSpec().getStorageClassSpec()) { 880 default: assert(0 && "Unknown storage class!"); 881 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 882 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 883 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 884 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 885 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 886 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 887 } 888 if (S->getParent() == 0) { 889 // C99 6.9p2: The storage-class specifiers auto and register shall not 890 // appear in the declaration specifiers in an external declaration. 891 if (SC == VarDecl::Auto || SC == VarDecl::Register) { 892 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope, 893 R.getAsString()); 894 InvalidDecl = true; 895 } 896 NewVD = FileVarDecl::Create(Context, CurContext, D.getIdentifierLoc(), 897 II, R, SC, 898 LastDeclarator); 899 } else { 900 NewVD = BlockVarDecl::Create(Context, CurContext, D.getIdentifierLoc(), 901 II, R, SC, 902 LastDeclarator); 903 } 904 // Handle attributes prior to checking for duplicates in MergeVarDecl 905 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(), 906 D.getAttributes()); 907 908 // Emit an error if an address space was applied to decl with local storage. 909 // This includes arrays of objects with address space qualifiers, but not 910 // automatic variables that point to other address spaces. 911 // ISO/IEC TR 18037 S5.1.2 912 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) { 913 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl); 914 InvalidDecl = true; 915 } 916 // Merge the decl with the existing one if appropriate. If the decl is 917 // in an outer scope, it isn't the same thing. 918 if (PrevDecl && S->isDeclScope(PrevDecl)) { 919 NewVD = MergeVarDecl(NewVD, PrevDecl); 920 if (NewVD == 0) return 0; 921 } 922 New = NewVD; 923 } 924 925 // If this has an identifier, add it to the scope stack. 926 if (II) { 927 New->setNext(II->getFETokenInfo<ScopedDecl>()); 928 II->setFETokenInfo(New); 929 S->AddDecl(New); 930 } 931 // If any semantic error occurred, mark the decl as invalid. 932 if (D.getInvalidType() || InvalidDecl) 933 New->setInvalidDecl(); 934 935 return New; 936} 937 938bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 939 SourceLocation loc; 940 // FIXME: Remove the isReference check and handle assignment to a reference. 941 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) { 942 assert(loc.isValid() && "isConstantExpr didn't return a loc!"); 943 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange()); 944 return true; 945 } 946 return false; 947} 948 949void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) { 950 Decl *RealDecl = static_cast<Decl *>(dcl); 951 Expr *Init = static_cast<Expr *>(init); 952 assert(Init && "missing initializer"); 953 954 // If there is no declaration, there was an error parsing it. Just ignore 955 // the initializer. 956 if (RealDecl == 0) { 957 delete Init; 958 return; 959 } 960 961 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 962 if (!VDecl) { 963 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(), 964 diag::err_illegal_initializer); 965 RealDecl->setInvalidDecl(); 966 return; 967 } 968 // Get the decls type and save a reference for later, since 969 // CheckInitializerTypes may change it. 970 QualType DclT = VDecl->getType(), SavT = DclT; 971 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) { 972 VarDecl::StorageClass SC = BVD->getStorageClass(); 973 if (SC == VarDecl::Extern) { // C99 6.7.8p5 974 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 975 BVD->setInvalidDecl(); 976 } else if (!BVD->isInvalidDecl()) { 977 if (CheckInitializerTypes(Init, DclT)) 978 BVD->setInvalidDecl(); 979 if (SC == VarDecl::Static) // C99 6.7.8p4. 980 CheckForConstantInitializer(Init, DclT); 981 } 982 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) { 983 if (FVD->getStorageClass() == VarDecl::Extern) 984 Diag(VDecl->getLocation(), diag::warn_extern_init); 985 if (!FVD->isInvalidDecl()) 986 if (CheckInitializerTypes(Init, DclT)) 987 FVD->setInvalidDecl(); 988 989 // C99 6.7.8p4. All file scoped initializers need to be constant. 990 CheckForConstantInitializer(Init, DclT); 991 } 992 // If the type changed, it means we had an incomplete type that was 993 // completed by the initializer. For example: 994 // int ary[] = { 1, 3, 5 }; 995 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 996 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 997 VDecl->setType(DclT); 998 Init->setType(DclT); 999 } 1000 1001 // Attach the initializer to the decl. 1002 VDecl->setInit(Init); 1003 return; 1004} 1005 1006/// The declarators are chained together backwards, reverse the list. 1007Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) { 1008 // Often we have single declarators, handle them quickly. 1009 Decl *GroupDecl = static_cast<Decl*>(group); 1010 if (GroupDecl == 0) 1011 return 0; 1012 1013 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl); 1014 ScopedDecl *NewGroup = 0; 1015 if (Group->getNextDeclarator() == 0) 1016 NewGroup = Group; 1017 else { // reverse the list. 1018 while (Group) { 1019 ScopedDecl *Next = Group->getNextDeclarator(); 1020 Group->setNextDeclarator(NewGroup); 1021 NewGroup = Group; 1022 Group = Next; 1023 } 1024 } 1025 // Perform semantic analysis that depends on having fully processed both 1026 // the declarator and initializer. 1027 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) { 1028 VarDecl *IDecl = dyn_cast<VarDecl>(ID); 1029 if (!IDecl) 1030 continue; 1031 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl); 1032 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl); 1033 QualType T = IDecl->getType(); 1034 1035 // C99 6.7.5.2p2: If an identifier is declared to be an object with 1036 // static storage duration, it shall not have a variable length array. 1037 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) { 1038 if (T->getAsVariableArrayType()) { 1039 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla); 1040 IDecl->setInvalidDecl(); 1041 } 1042 } 1043 // Block scope. C99 6.7p7: If an identifier for an object is declared with 1044 // no linkage (C99 6.2.2p6), the type for the object shall be complete... 1045 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) { 1046 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) { 1047 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type, 1048 T.getAsString()); 1049 IDecl->setInvalidDecl(); 1050 } 1051 } 1052 // File scope. C99 6.9.2p2: A declaration of an identifier for and 1053 // object that has file scope without an initializer, and without a 1054 // storage-class specifier or with the storage-class specifier "static", 1055 // constitutes a tentative definition. Note: A tentative definition with 1056 // external linkage is valid (C99 6.2.2p5). 1057 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static || 1058 FVD->getStorageClass() == VarDecl::None)) { 1059 if (T->isIncompleteArrayType()) { 1060 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete 1061 // array to be completed. Don't issue a diagnostic. 1062 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) { 1063 // C99 6.9.2p3: If the declaration of an identifier for an object is 1064 // a tentative definition and has internal linkage (C99 6.2.2p3), the 1065 // declared type shall not be an incomplete type. 1066 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type, 1067 T.getAsString()); 1068 IDecl->setInvalidDecl(); 1069 } 1070 } 1071 } 1072 return NewGroup; 1073} 1074 1075/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 1076/// to introduce parameters into function prototype scope. 1077Sema::DeclTy * 1078Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 1079 DeclSpec &DS = D.getDeclSpec(); 1080 1081 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 1082 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 1083 DS.getStorageClassSpec() != DeclSpec::SCS_register) { 1084 Diag(DS.getStorageClassSpecLoc(), 1085 diag::err_invalid_storage_class_in_func_decl); 1086 DS.ClearStorageClassSpecs(); 1087 } 1088 if (DS.isThreadSpecified()) { 1089 Diag(DS.getThreadSpecLoc(), 1090 diag::err_invalid_storage_class_in_func_decl); 1091 DS.ClearStorageClassSpecs(); 1092 } 1093 1094 1095 // In this context, we *do not* check D.getInvalidType(). If the declarator 1096 // type was invalid, GetTypeForDeclarator() still returns a "valid" type, 1097 // though it will not reflect the user specified type. 1098 QualType parmDeclType = GetTypeForDeclarator(D, S); 1099 1100 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type"); 1101 1102 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 1103 // Can this happen for params? We already checked that they don't conflict 1104 // among each other. Here they can only shadow globals, which is ok. 1105 IdentifierInfo *II = D.getIdentifier(); 1106 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) { 1107 if (S->isDeclScope(PrevDecl)) { 1108 Diag(D.getIdentifierLoc(), diag::err_param_redefinition, 1109 dyn_cast<NamedDecl>(PrevDecl)->getName()); 1110 1111 // Recover by removing the name 1112 II = 0; 1113 D.SetIdentifier(0, D.getIdentifierLoc()); 1114 } 1115 } 1116 1117 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]). 1118 // Doing the promotion here has a win and a loss. The win is the type for 1119 // both Decl's and DeclRefExpr's will match (a convenient invariant for the 1120 // code generator). The loss is the orginal type isn't preserved. For example: 1121 // 1122 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *" 1123 // int blockvardecl[5]; 1124 // sizeof(parmvardecl); // size == 4 1125 // sizeof(blockvardecl); // size == 20 1126 // } 1127 // 1128 // For expressions, all implicit conversions are captured using the 1129 // ImplicitCastExpr AST node (we have no such mechanism for Decl's). 1130 // 1131 // FIXME: If a source translation tool needs to see the original type, then 1132 // we need to consider storing both types (in ParmVarDecl)... 1133 // 1134 if (parmDeclType->isArrayType()) { 1135 // int x[restrict 4] -> int *restrict 1136 parmDeclType = Context.getArrayDecayedType(parmDeclType); 1137 } else if (parmDeclType->isFunctionType()) 1138 parmDeclType = Context.getPointerType(parmDeclType); 1139 1140 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, 1141 D.getIdentifierLoc(), II, 1142 parmDeclType, VarDecl::None, 1143 0, 0); 1144 1145 if (D.getInvalidType()) 1146 New->setInvalidDecl(); 1147 1148 if (II) { 1149 New->setNext(II->getFETokenInfo<ScopedDecl>()); 1150 II->setFETokenInfo(New); 1151 S->AddDecl(New); 1152 } 1153 1154 HandleDeclAttributes(New, D.getAttributes(), 0); 1155 return New; 1156 1157} 1158 1159Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 1160 assert(CurFunctionDecl == 0 && "Function parsing confused"); 1161 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 1162 "Not a function declarator!"); 1163 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1164 1165 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 1166 // for a K&R function. 1167 if (!FTI.hasPrototype) { 1168 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 1169 if (FTI.ArgInfo[i].Param == 0) { 1170 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared, 1171 FTI.ArgInfo[i].Ident->getName()); 1172 // Implicitly declare the argument as type 'int' for lack of a better 1173 // type. 1174 DeclSpec DS; 1175 const char* PrevSpec; // unused 1176 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 1177 PrevSpec); 1178 Declarator ParamD(DS, Declarator::KNRTypeListContext); 1179 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 1180 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD); 1181 } 1182 } 1183 1184 // Since this is a function definition, act as though we have information 1185 // about the arguments. 1186 if (FTI.NumArgs) 1187 FTI.hasPrototype = true; 1188 } else { 1189 // FIXME: Diagnose arguments without names in C. 1190 } 1191 1192 Scope *GlobalScope = FnBodyScope->getParent(); 1193 1194 // See if this is a redefinition. 1195 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary, 1196 GlobalScope); 1197 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) { 1198 if (FD->getBody()) { 1199 Diag(D.getIdentifierLoc(), diag::err_redefinition, 1200 D.getIdentifier()->getName()); 1201 Diag(FD->getLocation(), diag::err_previous_definition); 1202 } 1203 } 1204 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0)); 1205 FunctionDecl *FD = cast<FunctionDecl>(decl); 1206 CurFunctionDecl = FD; 1207 PushDeclContext(FD); 1208 1209 // Check the validity of our function parameters 1210 CheckParmsForFunctionDef(FD); 1211 1212 // Introduce our parameters into the function scope 1213 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 1214 ParmVarDecl *Param = FD->getParamDecl(p); 1215 // If this has an identifier, add it to the scope stack. 1216 if (IdentifierInfo *II = Param->getIdentifier()) { 1217 Param->setNext(II->getFETokenInfo<ScopedDecl>()); 1218 II->setFETokenInfo(Param); 1219 FnBodyScope->AddDecl(Param); 1220 } 1221 } 1222 1223 return FD; 1224} 1225 1226Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) { 1227 Decl *dcl = static_cast<Decl *>(D); 1228 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) { 1229 FD->setBody((Stmt*)Body); 1230 assert(FD == CurFunctionDecl && "Function parsing confused"); 1231 CurFunctionDecl = 0; 1232 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) { 1233 MD->setBody((Stmt*)Body); 1234 CurMethodDecl = 0; 1235 } 1236 PopDeclContext(); 1237 // Verify and clean out per-function state. 1238 1239 // Check goto/label use. 1240 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 1241 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) { 1242 // Verify that we have no forward references left. If so, there was a goto 1243 // or address of a label taken, but no definition of it. Label fwd 1244 // definitions are indicated with a null substmt. 1245 if (I->second->getSubStmt() == 0) { 1246 LabelStmt *L = I->second; 1247 // Emit error. 1248 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName()); 1249 1250 // At this point, we have gotos that use the bogus label. Stitch it into 1251 // the function body so that they aren't leaked and that the AST is well 1252 // formed. 1253 if (Body) { 1254 L->setSubStmt(new NullStmt(L->getIdentLoc())); 1255 cast<CompoundStmt>((Stmt*)Body)->push_back(L); 1256 } else { 1257 // The whole function wasn't parsed correctly, just delete this. 1258 delete L; 1259 } 1260 } 1261 } 1262 LabelMap.clear(); 1263 1264 return D; 1265} 1266 1267/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 1268/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 1269ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 1270 IdentifierInfo &II, Scope *S) { 1271 if (getLangOptions().C99) // Extension in C99. 1272 Diag(Loc, diag::ext_implicit_function_decl, II.getName()); 1273 else // Legal in C90, but warn about it. 1274 Diag(Loc, diag::warn_implicit_function_decl, II.getName()); 1275 1276 // FIXME: handle stuff like: 1277 // void foo() { extern float X(); } 1278 // void bar() { X(); } <-- implicit decl for X in another scope. 1279 1280 // Set a Declarator for the implicit definition: int foo(); 1281 const char *Dummy; 1282 DeclSpec DS; 1283 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy); 1284 Error = Error; // Silence warning. 1285 assert(!Error && "Error setting up implicit decl!"); 1286 Declarator D(DS, Declarator::BlockContext); 1287 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc)); 1288 D.SetIdentifier(&II, Loc); 1289 1290 // Find translation-unit scope to insert this function into. 1291 if (Scope *FnS = S->getFnParent()) 1292 S = FnS->getParent(); // Skip all scopes in a function at once. 1293 while (S->getParent()) 1294 S = S->getParent(); 1295 1296 FunctionDecl *FD = 1297 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0))); 1298 FD->setImplicit(); 1299 return FD; 1300} 1301 1302 1303TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 1304 ScopedDecl *LastDeclarator) { 1305 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 1306 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 1307 1308 // Scope manipulation handled by caller. 1309 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 1310 D.getIdentifierLoc(), 1311 D.getIdentifier(), 1312 T, LastDeclarator); 1313 if (D.getInvalidType()) 1314 NewTD->setInvalidDecl(); 1315 return NewTD; 1316} 1317 1318/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 1319/// former case, Name will be non-null. In the later case, Name will be null. 1320/// TagType indicates what kind of tag this is. TK indicates whether this is a 1321/// reference/declaration/definition of a tag. 1322Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK, 1323 SourceLocation KWLoc, IdentifierInfo *Name, 1324 SourceLocation NameLoc, AttributeList *Attr) { 1325 // If this is a use of an existing tag, it must have a name. 1326 assert((Name != 0 || TK == TK_Definition) && 1327 "Nameless record must be a definition!"); 1328 1329 Decl::Kind Kind; 1330 switch (TagType) { 1331 default: assert(0 && "Unknown tag type!"); 1332 case DeclSpec::TST_struct: Kind = Decl::Struct; break; 1333 case DeclSpec::TST_union: Kind = Decl::Union; break; 1334//case DeclSpec::TST_class: Kind = Decl::Class; break; 1335 case DeclSpec::TST_enum: Kind = Decl::Enum; break; 1336 } 1337 1338 // If this is a named struct, check to see if there was a previous forward 1339 // declaration or definition. 1340 if (TagDecl *PrevDecl = 1341 dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) { 1342 1343 // If this is a use of a previous tag, or if the tag is already declared in 1344 // the same scope (so that the definition/declaration completes or 1345 // rementions the tag), reuse the decl. 1346 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) { 1347 // Make sure that this wasn't declared as an enum and now used as a struct 1348 // or something similar. 1349 if (PrevDecl->getKind() != Kind) { 1350 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName()); 1351 Diag(PrevDecl->getLocation(), diag::err_previous_use); 1352 } 1353 1354 // If this is a use or a forward declaration, we're good. 1355 if (TK != TK_Definition) 1356 return PrevDecl; 1357 1358 // Diagnose attempts to redefine a tag. 1359 if (PrevDecl->isDefinition()) { 1360 Diag(NameLoc, diag::err_redefinition, Name->getName()); 1361 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 1362 // If this is a redefinition, recover by making this struct be 1363 // anonymous, which will make any later references get the previous 1364 // definition. 1365 Name = 0; 1366 } else { 1367 // Okay, this is definition of a previously declared or referenced tag. 1368 // Move the location of the decl to be the definition site. 1369 PrevDecl->setLocation(NameLoc); 1370 return PrevDecl; 1371 } 1372 } 1373 // If we get here, this is a definition of a new struct type in a nested 1374 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new 1375 // type. 1376 } 1377 1378 // If there is an identifier, use the location of the identifier as the 1379 // location of the decl, otherwise use the location of the struct/union 1380 // keyword. 1381 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 1382 1383 // Otherwise, if this is the first time we've seen this tag, create the decl. 1384 TagDecl *New; 1385 switch (Kind) { 1386 default: assert(0 && "Unknown tag kind!"); 1387 case Decl::Enum: 1388 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 1389 // enum X { A, B, C } D; D should chain to X. 1390 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0); 1391 // If this is an undefined enum, warn. 1392 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum); 1393 break; 1394 case Decl::Union: 1395 case Decl::Struct: 1396 case Decl::Class: 1397 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 1398 // struct X { int A; } D; D should chain to X. 1399 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0); 1400 break; 1401 } 1402 1403 // If this has an identifier, add it to the scope stack. 1404 if (Name) { 1405 // The scope passed in may not be a decl scope. Zip up the scope tree until 1406 // we find one that is. 1407 while ((S->getFlags() & Scope::DeclScope) == 0) 1408 S = S->getParent(); 1409 1410 // Add it to the decl chain. 1411 New->setNext(Name->getFETokenInfo<ScopedDecl>()); 1412 Name->setFETokenInfo(New); 1413 S->AddDecl(New); 1414 } 1415 1416 HandleDeclAttributes(New, Attr, 0); 1417 return New; 1418} 1419 1420/// ActOnField - Each field of a struct/union/class is passed into this in order 1421/// to create a FieldDecl object for it. 1422Sema::DeclTy *Sema::ActOnField(Scope *S, 1423 SourceLocation DeclStart, 1424 Declarator &D, ExprTy *BitfieldWidth) { 1425 IdentifierInfo *II = D.getIdentifier(); 1426 Expr *BitWidth = (Expr*)BitfieldWidth; 1427 SourceLocation Loc = DeclStart; 1428 if (II) Loc = D.getIdentifierLoc(); 1429 1430 // FIXME: Unnamed fields can be handled in various different ways, for 1431 // example, unnamed unions inject all members into the struct namespace! 1432 1433 1434 if (BitWidth) { 1435 // TODO: Validate. 1436 //printf("WARNING: BITFIELDS IGNORED!\n"); 1437 1438 // 6.7.2.1p3 1439 // 6.7.2.1p4 1440 1441 } else { 1442 // Not a bitfield. 1443 1444 // validate II. 1445 1446 } 1447 1448 QualType T = GetTypeForDeclarator(D, S); 1449 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 1450 bool InvalidDecl = false; 1451 1452 // C99 6.7.2.1p8: A member of a structure or union may have any type other 1453 // than a variably modified type. 1454 if (T->isVariablyModifiedType()) { 1455 // FIXME: This diagnostic needs work 1456 Diag(Loc, diag::err_typecheck_illegal_vla, Loc); 1457 InvalidDecl = true; 1458 } 1459 // FIXME: Chain fielddecls together. 1460 FieldDecl *NewFD; 1461 1462 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth); 1463 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(), 1464 D.getAttributes()); 1465 1466 if (D.getInvalidType() || InvalidDecl) 1467 NewFD->setInvalidDecl(); 1468 return NewFD; 1469} 1470 1471/// TranslateIvarVisibility - Translate visibility from a token ID to an 1472/// AST enum value. 1473static ObjCIvarDecl::AccessControl 1474TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 1475 switch (ivarVisibility) { 1476 case tok::objc_private: return ObjCIvarDecl::Private; 1477 case tok::objc_public: return ObjCIvarDecl::Public; 1478 case tok::objc_protected: return ObjCIvarDecl::Protected; 1479 case tok::objc_package: return ObjCIvarDecl::Package; 1480 default: assert(false && "Unknown visitibility kind"); 1481 } 1482} 1483 1484/// ActOnIvar - Each field of a struct/union/class is passed into this in order 1485/// to create an IvarDecl object for it. 1486Sema::DeclTy *Sema::ActOnIvar(Scope *S, 1487 SourceLocation DeclStart, 1488 Declarator &D, ExprTy *BitfieldWidth, 1489 tok::ObjCKeywordKind visibility) { 1490 IdentifierInfo *II = D.getIdentifier(); 1491 Expr *BitWidth = (Expr*)BitfieldWidth; 1492 SourceLocation Loc = DeclStart; 1493 if (II) Loc = D.getIdentifierLoc(); 1494 1495 // FIXME: Unnamed fields can be handled in various different ways, for 1496 // example, unnamed unions inject all members into the struct namespace! 1497 1498 1499 if (BitWidth) { 1500 // TODO: Validate. 1501 //printf("WARNING: BITFIELDS IGNORED!\n"); 1502 1503 // 6.7.2.1p3 1504 // 6.7.2.1p4 1505 1506 } else { 1507 // Not a bitfield. 1508 1509 // validate II. 1510 1511 } 1512 1513 QualType T = GetTypeForDeclarator(D, S); 1514 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 1515 bool InvalidDecl = false; 1516 1517 // C99 6.7.2.1p8: A member of a structure or union may have any type other 1518 // than a variably modified type. 1519 if (T->isVariablyModifiedType()) { 1520 // FIXME: This diagnostic needs work 1521 Diag(Loc, diag::err_typecheck_illegal_vla, Loc); 1522 InvalidDecl = true; 1523 } 1524 1525 ObjCIvarDecl *NewID; 1526 1527 NewID = ObjCIvarDecl::Create(Context, Loc, II, T); 1528 1529 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(), 1530 D.getAttributes()); 1531 1532 if (D.getInvalidType() || InvalidDecl) 1533 NewID->setInvalidDecl(); 1534 // If we have visibility info, make sure the AST is set accordingly. 1535 if (visibility != tok::objc_not_keyword) 1536 NewID ->setAccessControl(TranslateIvarVisibility(visibility)); 1537 return NewID; 1538} 1539 1540void Sema::ActOnFields(Scope* S, 1541 SourceLocation RecLoc, DeclTy *RecDecl, 1542 DeclTy **Fields, unsigned NumFields, 1543 SourceLocation LBrac, SourceLocation RBrac) { 1544 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl); 1545 assert(EnclosingDecl && "missing record or interface decl"); 1546 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 1547 1548 if (Record && Record->isDefinition()) { 1549 // Diagnose code like: 1550 // struct S { struct S {} X; }; 1551 // We discover this when we complete the outer S. Reject and ignore the 1552 // outer S. 1553 Diag(Record->getLocation(), diag::err_nested_redefinition, 1554 Record->getKindName()); 1555 Diag(RecLoc, diag::err_previous_definition); 1556 Record->setInvalidDecl(); 1557 return; 1558 } 1559 // Verify that all the fields are okay. 1560 unsigned NumNamedMembers = 0; 1561 llvm::SmallVector<FieldDecl*, 32> RecFields; 1562 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs; 1563 1564 for (unsigned i = 0; i != NumFields; ++i) { 1565 1566 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i])); 1567 assert(FD && "missing field decl"); 1568 1569 // Remember all fields. 1570 RecFields.push_back(FD); 1571 1572 // Get the type for the field. 1573 Type *FDTy = FD->getType().getTypePtr(); 1574 1575 // C99 6.7.2.1p2 - A field may not be a function type. 1576 if (FDTy->isFunctionType()) { 1577 Diag(FD->getLocation(), diag::err_field_declared_as_function, 1578 FD->getName()); 1579 FD->setInvalidDecl(); 1580 EnclosingDecl->setInvalidDecl(); 1581 continue; 1582 } 1583 // C99 6.7.2.1p2 - A field may not be an incomplete type except... 1584 if (FDTy->isIncompleteType()) { 1585 if (!Record) { // Incomplete ivar type is always an error. 1586 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName()); 1587 FD->setInvalidDecl(); 1588 EnclosingDecl->setInvalidDecl(); 1589 continue; 1590 } 1591 if (i != NumFields-1 || // ... that the last member ... 1592 Record->getKind() != Decl::Struct || // ... of a structure ... 1593 !FDTy->isArrayType()) { //... may have incomplete array type. 1594 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName()); 1595 FD->setInvalidDecl(); 1596 EnclosingDecl->setInvalidDecl(); 1597 continue; 1598 } 1599 if (NumNamedMembers < 1) { //... must have more than named member ... 1600 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct, 1601 FD->getName()); 1602 FD->setInvalidDecl(); 1603 EnclosingDecl->setInvalidDecl(); 1604 continue; 1605 } 1606 // Okay, we have a legal flexible array member at the end of the struct. 1607 if (Record) 1608 Record->setHasFlexibleArrayMember(true); 1609 } 1610 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the 1611 /// field of another structure or the element of an array. 1612 if (const RecordType *FDTTy = FDTy->getAsRecordType()) { 1613 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 1614 // If this is a member of a union, then entire union becomes "flexible". 1615 if (Record && Record->getKind() == Decl::Union) { 1616 Record->setHasFlexibleArrayMember(true); 1617 } else { 1618 // If this is a struct/class and this is not the last element, reject 1619 // it. Note that GCC supports variable sized arrays in the middle of 1620 // structures. 1621 if (i != NumFields-1) { 1622 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct, 1623 FD->getName()); 1624 FD->setInvalidDecl(); 1625 EnclosingDecl->setInvalidDecl(); 1626 continue; 1627 } 1628 // We support flexible arrays at the end of structs in other structs 1629 // as an extension. 1630 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct, 1631 FD->getName()); 1632 if (Record) 1633 Record->setHasFlexibleArrayMember(true); 1634 } 1635 } 1636 } 1637 /// A field cannot be an Objective-c object 1638 if (FDTy->isObjCInterfaceType()) { 1639 Diag(FD->getLocation(), diag::err_statically_allocated_object, 1640 FD->getName()); 1641 FD->setInvalidDecl(); 1642 EnclosingDecl->setInvalidDecl(); 1643 continue; 1644 } 1645 // Keep track of the number of named members. 1646 if (IdentifierInfo *II = FD->getIdentifier()) { 1647 // Detect duplicate member names. 1648 if (!FieldIDs.insert(II)) { 1649 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName()); 1650 // Find the previous decl. 1651 SourceLocation PrevLoc; 1652 for (unsigned i = 0, e = RecFields.size(); ; ++i) { 1653 assert(i != e && "Didn't find previous def!"); 1654 if (RecFields[i]->getIdentifier() == II) { 1655 PrevLoc = RecFields[i]->getLocation(); 1656 break; 1657 } 1658 } 1659 Diag(PrevLoc, diag::err_previous_definition); 1660 FD->setInvalidDecl(); 1661 EnclosingDecl->setInvalidDecl(); 1662 continue; 1663 } 1664 ++NumNamedMembers; 1665 } 1666 } 1667 1668 // Okay, we successfully defined 'Record'. 1669 if (Record) { 1670 Record->defineBody(&RecFields[0], RecFields.size()); 1671 Consumer.HandleTagDeclDefinition(Record); 1672 } else { 1673 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]); 1674 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) 1675 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac); 1676 else if (ObjCImplementationDecl *IMPDecl = 1677 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 1678 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 1679 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size()); 1680 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 1681 } 1682 } 1683} 1684 1685Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl, 1686 DeclTy *lastEnumConst, 1687 SourceLocation IdLoc, IdentifierInfo *Id, 1688 SourceLocation EqualLoc, ExprTy *val) { 1689 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl)); 1690 EnumConstantDecl *LastEnumConst = 1691 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst)); 1692 Expr *Val = static_cast<Expr*>(val); 1693 1694 // The scope passed in may not be a decl scope. Zip up the scope tree until 1695 // we find one that is. 1696 while ((S->getFlags() & Scope::DeclScope) == 0) 1697 S = S->getParent(); 1698 1699 // Verify that there isn't already something declared with this name in this 1700 // scope. 1701 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) { 1702 if (S->isDeclScope(PrevDecl)) { 1703 if (isa<EnumConstantDecl>(PrevDecl)) 1704 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName()); 1705 else 1706 Diag(IdLoc, diag::err_redefinition, Id->getName()); 1707 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 1708 delete Val; 1709 return 0; 1710 } 1711 } 1712 1713 llvm::APSInt EnumVal(32); 1714 QualType EltTy; 1715 if (Val) { 1716 // Make sure to promote the operand type to int. 1717 UsualUnaryConversions(Val); 1718 1719 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 1720 SourceLocation ExpLoc; 1721 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) { 1722 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr, 1723 Id->getName()); 1724 delete Val; 1725 Val = 0; // Just forget about it. 1726 } else { 1727 EltTy = Val->getType(); 1728 } 1729 } 1730 1731 if (!Val) { 1732 if (LastEnumConst) { 1733 // Assign the last value + 1. 1734 EnumVal = LastEnumConst->getInitVal(); 1735 ++EnumVal; 1736 1737 // Check for overflow on increment. 1738 if (EnumVal < LastEnumConst->getInitVal()) 1739 Diag(IdLoc, diag::warn_enum_value_overflow); 1740 1741 EltTy = LastEnumConst->getType(); 1742 } else { 1743 // First value, set to zero. 1744 EltTy = Context.IntTy; 1745 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy))); 1746 } 1747 } 1748 1749 EnumConstantDecl *New = 1750 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy, 1751 Val, EnumVal, 1752 LastEnumConst); 1753 1754 // Register this decl in the current scope stack. 1755 New->setNext(Id->getFETokenInfo<ScopedDecl>()); 1756 Id->setFETokenInfo(New); 1757 S->AddDecl(New); 1758 return New; 1759} 1760 1761void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX, 1762 DeclTy **Elements, unsigned NumElements) { 1763 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX)); 1764 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here"); 1765 1766 // TODO: If the result value doesn't fit in an int, it must be a long or long 1767 // long value. ISO C does not support this, but GCC does as an extension, 1768 // emit a warning. 1769 unsigned IntWidth = Context.Target.getIntWidth(); 1770 1771 // Verify that all the values are okay, compute the size of the values, and 1772 // reverse the list. 1773 unsigned NumNegativeBits = 0; 1774 unsigned NumPositiveBits = 0; 1775 1776 // Keep track of whether all elements have type int. 1777 bool AllElementsInt = true; 1778 1779 EnumConstantDecl *EltList = 0; 1780 for (unsigned i = 0; i != NumElements; ++i) { 1781 EnumConstantDecl *ECD = 1782 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 1783 if (!ECD) continue; // Already issued a diagnostic. 1784 1785 // If the enum value doesn't fit in an int, emit an extension warning. 1786 const llvm::APSInt &InitVal = ECD->getInitVal(); 1787 assert(InitVal.getBitWidth() >= IntWidth && 1788 "Should have promoted value to int"); 1789 if (InitVal.getBitWidth() > IntWidth) { 1790 llvm::APSInt V(InitVal); 1791 V.trunc(IntWidth); 1792 V.extend(InitVal.getBitWidth()); 1793 if (V != InitVal) 1794 Diag(ECD->getLocation(), diag::ext_enum_value_not_int, 1795 InitVal.toString()); 1796 } 1797 1798 // Keep track of the size of positive and negative values. 1799 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 1800 NumPositiveBits = std::max(NumPositiveBits, 1801 (unsigned)InitVal.getActiveBits()); 1802 else 1803 NumNegativeBits = std::max(NumNegativeBits, 1804 (unsigned)InitVal.getMinSignedBits()); 1805 1806 // Keep track of whether every enum element has type int (very commmon). 1807 if (AllElementsInt) 1808 AllElementsInt = ECD->getType() == Context.IntTy; 1809 1810 ECD->setNextDeclarator(EltList); 1811 EltList = ECD; 1812 } 1813 1814 // Figure out the type that should be used for this enum. 1815 // FIXME: Support attribute(packed) on enums and -fshort-enums. 1816 QualType BestType; 1817 unsigned BestWidth; 1818 1819 if (NumNegativeBits) { 1820 // If there is a negative value, figure out the smallest integer type (of 1821 // int/long/longlong) that fits. 1822 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 1823 BestType = Context.IntTy; 1824 BestWidth = IntWidth; 1825 } else { 1826 BestWidth = Context.Target.getLongWidth(); 1827 1828 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) 1829 BestType = Context.LongTy; 1830 else { 1831 BestWidth = Context.Target.getLongLongWidth(); 1832 1833 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 1834 Diag(Enum->getLocation(), diag::warn_enum_too_large); 1835 BestType = Context.LongLongTy; 1836 } 1837 } 1838 } else { 1839 // If there is no negative value, figure out which of uint, ulong, ulonglong 1840 // fits. 1841 if (NumPositiveBits <= IntWidth) { 1842 BestType = Context.UnsignedIntTy; 1843 BestWidth = IntWidth; 1844 } else if (NumPositiveBits <= 1845 (BestWidth = Context.Target.getLongWidth())) { 1846 BestType = Context.UnsignedLongTy; 1847 } else { 1848 BestWidth = Context.Target.getLongLongWidth(); 1849 assert(NumPositiveBits <= BestWidth && 1850 "How could an initializer get larger than ULL?"); 1851 BestType = Context.UnsignedLongLongTy; 1852 } 1853 } 1854 1855 // Loop over all of the enumerator constants, changing their types to match 1856 // the type of the enum if needed. 1857 for (unsigned i = 0; i != NumElements; ++i) { 1858 EnumConstantDecl *ECD = 1859 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 1860 if (!ECD) continue; // Already issued a diagnostic. 1861 1862 // Standard C says the enumerators have int type, but we allow, as an 1863 // extension, the enumerators to be larger than int size. If each 1864 // enumerator value fits in an int, type it as an int, otherwise type it the 1865 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 1866 // that X has type 'int', not 'unsigned'. 1867 if (ECD->getType() == Context.IntTy) { 1868 // Make sure the init value is signed. 1869 llvm::APSInt IV = ECD->getInitVal(); 1870 IV.setIsSigned(true); 1871 ECD->setInitVal(IV); 1872 continue; // Already int type. 1873 } 1874 1875 // Determine whether the value fits into an int. 1876 llvm::APSInt InitVal = ECD->getInitVal(); 1877 bool FitsInInt; 1878 if (InitVal.isUnsigned() || !InitVal.isNegative()) 1879 FitsInInt = InitVal.getActiveBits() < IntWidth; 1880 else 1881 FitsInInt = InitVal.getMinSignedBits() <= IntWidth; 1882 1883 // If it fits into an integer type, force it. Otherwise force it to match 1884 // the enum decl type. 1885 QualType NewTy; 1886 unsigned NewWidth; 1887 bool NewSign; 1888 if (FitsInInt) { 1889 NewTy = Context.IntTy; 1890 NewWidth = IntWidth; 1891 NewSign = true; 1892 } else if (ECD->getType() == BestType) { 1893 // Already the right type! 1894 continue; 1895 } else { 1896 NewTy = BestType; 1897 NewWidth = BestWidth; 1898 NewSign = BestType->isSignedIntegerType(); 1899 } 1900 1901 // Adjust the APSInt value. 1902 InitVal.extOrTrunc(NewWidth); 1903 InitVal.setIsSigned(NewSign); 1904 ECD->setInitVal(InitVal); 1905 1906 // Adjust the Expr initializer and type. 1907 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr())); 1908 ECD->setType(NewTy); 1909 } 1910 1911 Enum->defineElements(EltList, BestType); 1912 Consumer.HandleTagDeclDefinition(Enum); 1913} 1914 1915Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, 1916 ExprTy *expr) { 1917 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr); 1918 1919 return FileScopeAsmDecl::Create(Context, Loc, AsmString); 1920} 1921 1922Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc, 1923 SourceLocation LBrace, 1924 SourceLocation RBrace, 1925 const char *Lang, 1926 unsigned StrSize, 1927 DeclTy *D) { 1928 LinkageSpecDecl::LanguageIDs Language; 1929 Decl *dcl = static_cast<Decl *>(D); 1930 if (strncmp(Lang, "\"C\"", StrSize) == 0) 1931 Language = LinkageSpecDecl::lang_c; 1932 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 1933 Language = LinkageSpecDecl::lang_cxx; 1934 else { 1935 Diag(Loc, diag::err_bad_language); 1936 return 0; 1937 } 1938 1939 // FIXME: Add all the various semantics of linkage specifications 1940 return LinkageSpecDecl::Create(Context, Loc, Language, dcl); 1941} 1942 1943void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) { 1944 1945 switch (Attr->getKind()) { 1946 case AttributeList::AT_vector_size: 1947 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) { 1948 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr); 1949 if (!newType.isNull()) // install the new vector type into the decl 1950 vDecl->setType(newType); 1951 } 1952 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) { 1953 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(), 1954 Attr); 1955 if (!newType.isNull()) // install the new vector type into the decl 1956 tDecl->setUnderlyingType(newType); 1957 } 1958 break; 1959 case AttributeList::AT_ocu_vector_type: 1960 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) 1961 HandleOCUVectorTypeAttribute(tDecl, Attr); 1962 else 1963 Diag(Attr->getLoc(), 1964 diag::err_typecheck_ocu_vector_not_typedef); 1965 break; 1966 case AttributeList::AT_address_space: 1967 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) { 1968 QualType newType = HandleAddressSpaceTypeAttribute( 1969 tDecl->getUnderlyingType(), 1970 Attr); 1971 tDecl->setUnderlyingType(newType); 1972 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) { 1973 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(), 1974 Attr); 1975 // install the new addr spaced type into the decl 1976 vDecl->setType(newType); 1977 } 1978 break; 1979 case AttributeList::AT_deprecated: 1980 HandleDeprecatedAttribute(New, Attr); 1981 break; 1982 case AttributeList::AT_visibility: 1983 HandleVisibilityAttribute(New, Attr); 1984 break; 1985 case AttributeList::AT_weak: 1986 HandleWeakAttribute(New, Attr); 1987 break; 1988 case AttributeList::AT_dllimport: 1989 HandleDLLImportAttribute(New, Attr); 1990 break; 1991 case AttributeList::AT_dllexport: 1992 HandleDLLExportAttribute(New, Attr); 1993 break; 1994 case AttributeList::AT_nothrow: 1995 HandleNothrowAttribute(New, Attr); 1996 break; 1997 case AttributeList::AT_stdcall: 1998 HandleStdCallAttribute(New, Attr); 1999 break; 2000 case AttributeList::AT_fastcall: 2001 HandleFastCallAttribute(New, Attr); 2002 break; 2003 case AttributeList::AT_aligned: 2004 HandleAlignedAttribute(New, Attr); 2005 break; 2006 case AttributeList::AT_packed: 2007 HandlePackedAttribute(New, Attr); 2008 break; 2009 case AttributeList::AT_annotate: 2010 HandleAnnotateAttribute(New, Attr); 2011 break; 2012 case AttributeList::AT_noreturn: 2013 HandleNoReturnAttribute(New, Attr); 2014 break; 2015 case AttributeList::AT_format: 2016 HandleFormatAttribute(New, Attr); 2017 break; 2018 default: 2019#if 0 2020 // TODO: when we have the full set of attributes, warn about unknown ones. 2021 Diag(Attr->getLoc(), diag::warn_attribute_ignored, 2022 Attr->getName()->getName()); 2023#endif 2024 break; 2025 } 2026} 2027 2028void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix, 2029 AttributeList *declarator_postfix) { 2030 while (declspec_prefix) { 2031 HandleDeclAttribute(New, declspec_prefix); 2032 declspec_prefix = declspec_prefix->getNext(); 2033 } 2034 while (declarator_postfix) { 2035 HandleDeclAttribute(New, declarator_postfix); 2036 declarator_postfix = declarator_postfix->getNext(); 2037 } 2038} 2039 2040void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl, 2041 AttributeList *rawAttr) { 2042 QualType curType = tDecl->getUnderlyingType(); 2043 // check the attribute arguments. 2044 if (rawAttr->getNumArgs() != 1) { 2045 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments, 2046 std::string("1")); 2047 return; 2048 } 2049 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0)); 2050 llvm::APSInt vecSize(32); 2051 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) { 2052 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int, 2053 "ocu_vector_type", sizeExpr->getSourceRange()); 2054 return; 2055 } 2056 // unlike gcc's vector_size attribute, we do not allow vectors to be defined 2057 // in conjunction with complex types (pointers, arrays, functions, etc.). 2058 Type *canonType = curType.getCanonicalType().getTypePtr(); 2059 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) { 2060 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type, 2061 curType.getCanonicalType().getAsString()); 2062 return; 2063 } 2064 // unlike gcc's vector_size attribute, the size is specified as the 2065 // number of elements, not the number of bytes. 2066 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 2067 2068 if (vectorSize == 0) { 2069 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size, 2070 sizeExpr->getSourceRange()); 2071 return; 2072 } 2073 // Instantiate/Install the vector type, the number of elements is > 0. 2074 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize)); 2075 // Remember this typedef decl, we will need it later for diagnostics. 2076 OCUVectorDecls.push_back(tDecl); 2077} 2078 2079QualType Sema::HandleVectorTypeAttribute(QualType curType, 2080 AttributeList *rawAttr) { 2081 // check the attribute arugments. 2082 if (rawAttr->getNumArgs() != 1) { 2083 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments, 2084 std::string("1")); 2085 return QualType(); 2086 } 2087 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0)); 2088 llvm::APSInt vecSize(32); 2089 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) { 2090 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int, 2091 "vector_size", sizeExpr->getSourceRange()); 2092 return QualType(); 2093 } 2094 // navigate to the base type - we need to provide for vector pointers, 2095 // vector arrays, and functions returning vectors. 2096 Type *canonType = curType.getCanonicalType().getTypePtr(); 2097 2098 if (canonType->isPointerType() || canonType->isArrayType() || 2099 canonType->isFunctionType()) { 2100 assert(0 && "HandleVector(): Complex type construction unimplemented"); 2101 /* FIXME: rebuild the type from the inside out, vectorizing the inner type. 2102 do { 2103 if (PointerType *PT = dyn_cast<PointerType>(canonType)) 2104 canonType = PT->getPointeeType().getTypePtr(); 2105 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType)) 2106 canonType = AT->getElementType().getTypePtr(); 2107 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType)) 2108 canonType = FT->getResultType().getTypePtr(); 2109 } while (canonType->isPointerType() || canonType->isArrayType() || 2110 canonType->isFunctionType()); 2111 */ 2112 } 2113 // the base type must be integer or float. 2114 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) { 2115 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type, 2116 curType.getCanonicalType().getAsString()); 2117 return QualType(); 2118 } 2119 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType)); 2120 // vecSize is specified in bytes - convert to bits. 2121 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 2122 2123 // the vector size needs to be an integral multiple of the type size. 2124 if (vectorSize % typeSize) { 2125 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size, 2126 sizeExpr->getSourceRange()); 2127 return QualType(); 2128 } 2129 if (vectorSize == 0) { 2130 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size, 2131 sizeExpr->getSourceRange()); 2132 return QualType(); 2133 } 2134 // Instantiate the vector type, the number of elements is > 0, and not 2135 // required to be a power of 2, unlike GCC. 2136 return Context.getVectorType(curType, vectorSize/typeSize); 2137} 2138 2139void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) { 2140 // check the attribute arguments. 2141 if (rawAttr->getNumArgs() > 0) { 2142 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments, 2143 std::string("0")); 2144 return; 2145 } 2146 2147 if (TagDecl *TD = dyn_cast<TagDecl>(d)) 2148 TD->addAttr(new PackedAttr); 2149 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) { 2150 // If the alignment is less than or equal to 8 bits, the packed attribute 2151 // has no effect. 2152 if (Context.getTypeAlign(FD->getType()) <= 8) 2153 Diag(rawAttr->getLoc(), 2154 diag::warn_attribute_ignored_for_field_of_type, 2155 rawAttr->getName()->getName(), FD->getType().getAsString()); 2156 else 2157 FD->addAttr(new PackedAttr); 2158 } else 2159 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored, 2160 rawAttr->getName()->getName()); 2161} 2162 2163void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) { 2164 // check the attribute arguments. 2165 if (rawAttr->getNumArgs() != 0) { 2166 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments, 2167 std::string("0")); 2168 return; 2169 } 2170 2171 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d); 2172 2173 if (!Fn) { 2174 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type, 2175 "noreturn", "function"); 2176 return; 2177 } 2178 2179 d->addAttr(new NoReturnAttr()); 2180} 2181 2182void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) { 2183 // check the attribute arguments. 2184 if (rawAttr->getNumArgs() != 0) { 2185 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments, 2186 std::string("0")); 2187 return; 2188 } 2189 2190 d->addAttr(new DeprecatedAttr()); 2191} 2192 2193void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) { 2194 // check the attribute arguments. 2195 if (rawAttr->getNumArgs() != 1) { 2196 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments, 2197 std::string("1")); 2198 return; 2199 } 2200 2201 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0)); 2202 Arg = Arg->IgnoreParenCasts(); 2203 StringLiteral *Str = dyn_cast<StringLiteral>(Arg); 2204 2205 if (Str == 0 || Str->isWide()) { 2206 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string, 2207 "visibility", std::string("1")); 2208 return; 2209 } 2210 2211 const char *TypeStr = Str->getStrData(); 2212 unsigned TypeLen = Str->getByteLength(); 2213 llvm::GlobalValue::VisibilityTypes type; 2214 2215 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7)) 2216 type = llvm::GlobalValue::DefaultVisibility; 2217 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6)) 2218 type = llvm::GlobalValue::HiddenVisibility; 2219 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8)) 2220 type = llvm::GlobalValue::HiddenVisibility; // FIXME 2221 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9)) 2222 type = llvm::GlobalValue::ProtectedVisibility; 2223 else { 2224 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported, 2225 "visibility", TypeStr); 2226 return; 2227 } 2228 2229 d->addAttr(new VisibilityAttr(type)); 2230} 2231 2232void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) { 2233 // check the attribute arguments. 2234 if (rawAttr->getNumArgs() != 0) { 2235 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments, 2236 std::string("0")); 2237 return; 2238 } 2239 2240 d->addAttr(new WeakAttr()); 2241} 2242 2243void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) { 2244 // check the attribute arguments. 2245 if (rawAttr->getNumArgs() != 0) { 2246 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments, 2247 std::string("0")); 2248 return; 2249 } 2250 2251 d->addAttr(new DLLImportAttr()); 2252} 2253 2254void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) { 2255 // check the attribute arguments. 2256 if (rawAttr->getNumArgs() != 0) { 2257 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments, 2258 std::string("0")); 2259 return; 2260 } 2261 2262 d->addAttr(new DLLExportAttr()); 2263} 2264 2265void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) { 2266 // check the attribute arguments. 2267 if (rawAttr->getNumArgs() != 0) { 2268 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments, 2269 std::string("0")); 2270 return; 2271 } 2272 2273 d->addAttr(new StdCallAttr()); 2274} 2275 2276void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) { 2277 // check the attribute arguments. 2278 if (rawAttr->getNumArgs() != 0) { 2279 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments, 2280 std::string("0")); 2281 return; 2282 } 2283 2284 d->addAttr(new FastCallAttr()); 2285} 2286 2287void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) { 2288 // check the attribute arguments. 2289 if (rawAttr->getNumArgs() != 0) { 2290 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments, 2291 std::string("0")); 2292 return; 2293 } 2294 2295 d->addAttr(new NoThrowAttr()); 2296} 2297 2298static const FunctionTypeProto *getFunctionProto(Decl *d) { 2299 ValueDecl *decl = dyn_cast<ValueDecl>(d); 2300 if (!decl) return 0; 2301 2302 QualType Ty = decl->getType(); 2303 2304 if (Ty->isFunctionPointerType()) { 2305 const PointerType *PtrTy = Ty->getAsPointerType(); 2306 Ty = PtrTy->getPointeeType(); 2307 } 2308 2309 if (const FunctionType *FnTy = Ty->getAsFunctionType()) 2310 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType()); 2311 2312 return 0; 2313} 2314 2315 2316/// Handle __attribute__((format(type,idx,firstarg))) attributes 2317/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 2318void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) { 2319 2320 if (!rawAttr->getParameterName()) { 2321 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string, 2322 "format", std::string("1")); 2323 return; 2324 } 2325 2326 if (rawAttr->getNumArgs() != 2) { 2327 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments, 2328 std::string("3")); 2329 return; 2330 } 2331 2332 // GCC ignores the format attribute on K&R style function 2333 // prototypes, so we ignore it as well 2334 const FunctionTypeProto *proto = getFunctionProto(d); 2335 2336 if (!proto) { 2337 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type, 2338 "format", "function"); 2339 return; 2340 } 2341 2342 // FIXME: in C++ the implicit 'this' function parameter also counts. 2343 // this is needed in order to be compatible with GCC 2344 // the index must start in 1 and the limit is numargs+1 2345 unsigned NumArgs = proto->getNumArgs(); 2346 unsigned FirstIdx = 1; 2347 2348 const char *Format = rawAttr->getParameterName()->getName(); 2349 unsigned FormatLen = rawAttr->getParameterName()->getLength(); 2350 2351 // Normalize the argument, __foo__ becomes foo. 2352 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' && 2353 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') { 2354 Format += 2; 2355 FormatLen -= 4; 2356 } 2357 2358 if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5)) 2359 || (FormatLen == 6 && !memcmp(Format, "printf", 6)) 2360 || (FormatLen == 7 && !memcmp(Format, "strfmon", 7)) 2361 || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) { 2362 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported, 2363 "format", rawAttr->getParameterName()->getName()); 2364 return; 2365 } 2366 2367 // checks for the 2nd argument 2368 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0)); 2369 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType())); 2370 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) { 2371 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int, 2372 "format", std::string("2"), IdxExpr->getSourceRange()); 2373 return; 2374 } 2375 2376 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) { 2377 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds, 2378 "format", std::string("2"), IdxExpr->getSourceRange()); 2379 return; 2380 } 2381 2382 // make sure the format string is really a string 2383 QualType Ty = proto->getArgType(Idx.getZExtValue()-1); 2384 if (!Ty->isPointerType() || 2385 !Ty->getAsPointerType()->getPointeeType()->isCharType()) { 2386 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string, 2387 IdxExpr->getSourceRange()); 2388 return; 2389 } 2390 2391 2392 // check the 3rd argument 2393 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1)); 2394 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType())); 2395 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) { 2396 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int, 2397 "format", std::string("3"), FirstArgExpr->getSourceRange()); 2398 return; 2399 } 2400 2401 // check if the function is variadic if the 3rd argument non-zero 2402 if (FirstArg != 0) { 2403 if (proto->isVariadic()) { 2404 ++NumArgs; // +1 for ... 2405 } else { 2406 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic); 2407 return; 2408 } 2409 } 2410 2411 // strftime requires FirstArg to be 0 because it doesn't read from any variable 2412 // the input is just the current time + the format string 2413 if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) { 2414 if (FirstArg != 0) { 2415 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter, 2416 FirstArgExpr->getSourceRange()); 2417 return; 2418 } 2419 // if 0 it disables parameter checking (to use with e.g. va_list) 2420 } else if (FirstArg != 0 && FirstArg != NumArgs) { 2421 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds, 2422 "format", std::string("3"), FirstArgExpr->getSourceRange()); 2423 return; 2424 } 2425 2426 d->addAttr(new FormatAttr(std::string(Format, FormatLen), 2427 Idx.getZExtValue(), FirstArg.getZExtValue())); 2428} 2429 2430void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) { 2431 // check the attribute arguments. 2432 if (rawAttr->getNumArgs() != 1) { 2433 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments, 2434 std::string("1")); 2435 return; 2436 } 2437 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0)); 2438 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr); 2439 2440 // Make sure that there is a string literal as the annotation's single 2441 // argument. 2442 if (!SE) { 2443 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string); 2444 return; 2445 } 2446 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(), 2447 SE->getByteLength()))); 2448} 2449 2450void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr) 2451{ 2452 // check the attribute arguments. 2453 if (rawAttr->getNumArgs() > 1) { 2454 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments, 2455 std::string("1")); 2456 return; 2457 } 2458 2459 unsigned Align = 0; 2460 2461 if (rawAttr->getNumArgs() == 0) { 2462 // FIXME: This should be the target specific maximum alignment. 2463 // (For now we just use 128 bits which is the maximum on X86. 2464 Align = 128; 2465 return; 2466 } else { 2467 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0)); 2468 llvm::APSInt alignment(32); 2469 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) { 2470 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int, 2471 "aligned", alignmentExpr->getSourceRange()); 2472 return; 2473 } 2474 2475 Align = alignment.getZExtValue() * 8; 2476 } 2477 2478 d->addAttr(new AlignedAttr(Align)); 2479} 2480