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