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