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