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