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