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