SemaDecl.cpp revision 8365223e5498255a1285b6bb206f5894fe5b83c6
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/DeclObjC.h" 19#include "clang/AST/ExprCXX.h" 20#include "clang/Parse/DeclSpec.h" 21#include "clang/Basic/Diagnostic.h" 22#include "clang/Basic/TargetInfo.h" 23#include "clang/Basic/SourceManager.h" 24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's) 25#include "clang/Lex/Preprocessor.h" 26#include "clang/Lex/HeaderSearch.h" 27#include "llvm/ADT/SmallSet.h" 28using namespace clang; 29 30Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S, 31 const CXXScopeSpec *SS) { 32 DeclContext *DC = 0; 33 if (SS) { 34 if (SS->isInvalid()) 35 return 0; 36 DC = static_cast<DeclContext*>(SS->getScopeRep()); 37 } 38 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false); 39 40 if (IIDecl && (isa<TypedefDecl>(IIDecl) || 41 isa<ObjCInterfaceDecl>(IIDecl) || 42 isa<TagDecl>(IIDecl))) 43 return IIDecl; 44 return 0; 45} 46 47DeclContext *Sema::getContainingDC(DeclContext *DC) { 48 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 49 // A C++ out-of-line method will return to the file declaration context. 50 if (MD->isOutOfLineDefinition()) 51 return MD->getLexicalDeclContext(); 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 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record."); 58 DC = MD->getParent(); 59 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 60 DC = RD; 61 62 // Return the declaration context of the topmost class the inline method is 63 // declared in. 64 return DC; 65 } 66 67 if (isa<ObjCMethodDecl>(DC)) 68 return Context.getTranslationUnitDecl(); 69 70 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC)) 71 return SD->getLexicalDeclContext(); 72 73 return DC->getParent(); 74} 75 76void Sema::PushDeclContext(DeclContext *DC) { 77 assert(getContainingDC(DC) == CurContext && 78 "The next DeclContext should be lexically contained in the current one."); 79 CurContext = DC; 80} 81 82void Sema::PopDeclContext() { 83 assert(CurContext && "DeclContext imbalance!"); 84 CurContext = getContainingDC(CurContext); 85} 86 87/// Add this decl to the scope shadowed decl chains. 88void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) { 89 S->AddDecl(D); 90 91 // C++ [basic.scope]p4: 92 // -- exactly one declaration shall declare a class name or 93 // enumeration name that is not a typedef name and the other 94 // declarations shall all refer to the same object or 95 // enumerator, or all refer to functions and function templates; 96 // in this case the class name or enumeration name is hidden. 97 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 98 // We are pushing the name of a tag (enum or class). 99 IdentifierResolver::iterator 100 I = IdResolver.begin(TD->getIdentifier(), 101 TD->getDeclContext(), false/*LookInParentCtx*/); 102 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) { 103 // There is already a declaration with the same name in the same 104 // scope. It must be found before we find the new declaration, 105 // so swap the order on the shadowed declaration chain. 106 107 IdResolver.AddShadowedDecl(TD, *I); 108 return; 109 } 110 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) { 111 FunctionDecl *FD = cast<FunctionDecl>(D); 112 // We are pushing the name of a function, which might be an 113 // overloaded name. 114 IdentifierResolver::iterator 115 I = IdResolver.begin(FD->getDeclName(), 116 FD->getDeclContext(), false/*LookInParentCtx*/); 117 if (I != IdResolver.end() && 118 IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) && 119 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) { 120 // There is already a declaration with the same name in the same 121 // scope. It must be a function or an overloaded function. 122 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I); 123 if (!Ovl) { 124 // We haven't yet overloaded this function. Take the existing 125 // FunctionDecl and put it into an OverloadedFunctionDecl. 126 Ovl = OverloadedFunctionDecl::Create(Context, 127 FD->getDeclContext(), 128 FD->getDeclName()); 129 Ovl->addOverload(dyn_cast<FunctionDecl>(*I)); 130 131 // Remove the name binding to the existing FunctionDecl... 132 IdResolver.RemoveDecl(*I); 133 134 // ... and put the OverloadedFunctionDecl in its place. 135 IdResolver.AddDecl(Ovl); 136 } 137 138 // We have an OverloadedFunctionDecl. Add the new FunctionDecl 139 // to its list of overloads. 140 Ovl->addOverload(FD); 141 142 return; 143 } 144 } 145 146 IdResolver.AddDecl(D); 147} 148 149void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 150 if (S->decl_empty()) return; 151 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!"); 152 153 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 154 I != E; ++I) { 155 Decl *TmpD = static_cast<Decl*>(*I); 156 assert(TmpD && "This decl didn't get pushed??"); 157 158 if (isa<CXXFieldDecl>(TmpD)) continue; 159 160 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?"); 161 ScopedDecl *D = cast<ScopedDecl>(TmpD); 162 163 IdentifierInfo *II = D->getIdentifier(); 164 if (!II) continue; 165 166 // We only want to remove the decls from the identifier decl chains for 167 // local scopes, when inside a function/method. 168 if (S->getFnParent() != 0) 169 IdResolver.RemoveDecl(D); 170 171 // Chain this decl to the containing DeclContext. 172 D->setNext(CurContext->getDeclChain()); 173 CurContext->setDeclChain(D); 174 } 175} 176 177/// getObjCInterfaceDecl - Look up a for a class declaration in the scope. 178/// return 0 if one not found. 179ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) { 180 // The third "scope" argument is 0 since we aren't enabling lazy built-in 181 // creation from this context. 182 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false); 183 184 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 185} 186 187/// LookupDecl - Look up the inner-most declaration in the specified 188/// namespace. 189Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S, 190 const DeclContext *LookupCtx, 191 bool enableLazyBuiltinCreation) { 192 if (!Name) return 0; 193 unsigned NS = NSI; 194 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary)) 195 NS |= Decl::IDNS_Tag; 196 197 IdentifierResolver::iterator 198 I = LookupCtx ? IdResolver.begin(Name, LookupCtx, false/*LookInParentCtx*/) 199 : IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/); 200 // Scan up the scope chain looking for a decl that matches this identifier 201 // that is in the appropriate namespace. This search should not take long, as 202 // shadowing of names is uncommon, and deep shadowing is extremely uncommon. 203 for (; I != IdResolver.end(); ++I) 204 if ((*I)->getIdentifierNamespace() & NS) 205 return *I; 206 207 // If we didn't find a use of this identifier, and if the identifier 208 // corresponds to a compiler builtin, create the decl object for the builtin 209 // now, injecting it into translation unit scope, and return it. 210 if (NS & Decl::IDNS_Ordinary) { 211 IdentifierInfo *II = Name.getAsIdentifierInfo(); 212 if (enableLazyBuiltinCreation && II && 213 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) { 214 // If this is a builtin on this (or all) targets, create the decl. 215 if (unsigned BuiltinID = II->getBuiltinID()) 216 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S); 217 } 218 if (getLangOptions().ObjC1 && II) { 219 // @interface and @compatibility_alias introduce typedef-like names. 220 // Unlike typedef's, they can only be introduced at file-scope (and are 221 // therefore not scoped decls). They can, however, be shadowed by 222 // other names in IDNS_Ordinary. 223 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II); 224 if (IDI != ObjCInterfaceDecls.end()) 225 return IDI->second; 226 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II); 227 if (I != ObjCAliasDecls.end()) 228 return I->second->getClassInterface(); 229 } 230 } 231 return 0; 232} 233 234void Sema::InitBuiltinVaListType() { 235 if (!Context.getBuiltinVaListType().isNull()) 236 return; 237 238 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list"); 239 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope); 240 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl); 241 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef)); 242} 243 244/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope. 245/// lazily create a decl for it. 246ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 247 Scope *S) { 248 Builtin::ID BID = (Builtin::ID)bid; 249 250 if (Context.BuiltinInfo.hasVAListUse(BID)) 251 InitBuiltinVaListType(); 252 253 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context); 254 FunctionDecl *New = FunctionDecl::Create(Context, 255 Context.getTranslationUnitDecl(), 256 SourceLocation(), II, R, 257 FunctionDecl::Extern, false, 0); 258 259 // Create Decl objects for each parameter, adding them to the 260 // FunctionDecl. 261 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) { 262 llvm::SmallVector<ParmVarDecl*, 16> Params; 263 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) 264 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0, 265 FT->getArgType(i), VarDecl::None, 0, 266 0)); 267 New->setParams(&Params[0], Params.size()); 268 } 269 270 271 272 // TUScope is the translation-unit scope to insert this function into. 273 PushOnScopeChains(New, TUScope); 274 return New; 275} 276 277/// GetStdNamespace - This method gets the C++ "std" namespace. This is where 278/// everything from the standard library is defined. 279NamespaceDecl *Sema::GetStdNamespace() { 280 if (!StdNamespace) { 281 DeclContext *Global = Context.getTranslationUnitDecl(); 282 Decl *Std = LookupDecl(Ident_StdNs, Decl::IDNS_Tag | Decl::IDNS_Ordinary, 283 0, Global, /*enableLazyBuiltinCreation=*/false); 284 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std); 285 } 286 return StdNamespace; 287} 288 289/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name 290/// and scope as a previous declaration 'Old'. Figure out how to resolve this 291/// situation, merging decls or emitting diagnostics as appropriate. 292/// 293TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) { 294 // Allow multiple definitions for ObjC built-in typedefs. 295 // FIXME: Verify the underlying types are equivalent! 296 if (getLangOptions().ObjC1) { 297 const IdentifierInfo *typeIdent = New->getIdentifier(); 298 if (typeIdent == Ident_id) { 299 Context.setObjCIdType(New); 300 return New; 301 } else if (typeIdent == Ident_Class) { 302 Context.setObjCClassType(New); 303 return New; 304 } else if (typeIdent == Ident_SEL) { 305 Context.setObjCSelType(New); 306 return New; 307 } else if (typeIdent == Ident_Protocol) { 308 Context.setObjCProtoType(New->getUnderlyingType()); 309 return New; 310 } 311 // Fall through - the typedef name was not a builtin type. 312 } 313 // Verify the old decl was also a typedef. 314 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD); 315 if (!Old) { 316 Diag(New->getLocation(), diag::err_redefinition_different_kind, 317 New->getName()); 318 Diag(OldD->getLocation(), diag::err_previous_definition); 319 return New; 320 } 321 322 // If the typedef types are not identical, reject them in all languages and 323 // with any extensions enabled. 324 if (Old->getUnderlyingType() != New->getUnderlyingType() && 325 Context.getCanonicalType(Old->getUnderlyingType()) != 326 Context.getCanonicalType(New->getUnderlyingType())) { 327 Diag(New->getLocation(), diag::err_redefinition_different_typedef, 328 New->getUnderlyingType().getAsString(), 329 Old->getUnderlyingType().getAsString()); 330 Diag(Old->getLocation(), diag::err_previous_definition); 331 return Old; 332 } 333 334 if (getLangOptions().Microsoft) return New; 335 336 // Redeclaration of a type is a constraint violation (6.7.2.3p1). 337 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if 338 // *either* declaration is in a system header. The code below implements 339 // this adhoc compatibility rule. FIXME: The following code will not 340 // work properly when compiling ".i" files (containing preprocessed output). 341 if (PP.getDiagnostics().getSuppressSystemWarnings()) { 342 SourceManager &SrcMgr = Context.getSourceManager(); 343 if (SrcMgr.isInSystemHeader(Old->getLocation())) 344 return New; 345 if (SrcMgr.isInSystemHeader(New->getLocation())) 346 return New; 347 } 348 349 Diag(New->getLocation(), diag::err_redefinition, New->getName()); 350 Diag(Old->getLocation(), diag::err_previous_definition); 351 return New; 352} 353 354/// DeclhasAttr - returns true if decl Declaration already has the target 355/// attribute. 356static bool DeclHasAttr(const Decl *decl, const Attr *target) { 357 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext()) 358 if (attr->getKind() == target->getKind()) 359 return true; 360 361 return false; 362} 363 364/// MergeAttributes - append attributes from the Old decl to the New one. 365static void MergeAttributes(Decl *New, Decl *Old) { 366 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp; 367 368 while (attr) { 369 tmp = attr; 370 attr = attr->getNext(); 371 372 if (!DeclHasAttr(New, tmp)) { 373 New->addAttr(tmp); 374 } else { 375 tmp->setNext(0); 376 delete(tmp); 377 } 378 } 379 380 Old->invalidateAttrs(); 381} 382 383/// MergeFunctionDecl - We just parsed a function 'New' from 384/// declarator D which has the same name and scope as a previous 385/// declaration 'Old'. Figure out how to resolve this situation, 386/// merging decls or emitting diagnostics as appropriate. 387/// Redeclaration will be set true if this New is a redeclaration OldD. 388/// 389/// In C++, New and Old must be declarations that are not 390/// overloaded. Use IsOverload to determine whether New and Old are 391/// overloaded, and to select the Old declaration that New should be 392/// merged with. 393FunctionDecl * 394Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) { 395 assert(!isa<OverloadedFunctionDecl>(OldD) && 396 "Cannot merge with an overloaded function declaration"); 397 398 Redeclaration = false; 399 // Verify the old decl was also a function. 400 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD); 401 if (!Old) { 402 Diag(New->getLocation(), diag::err_redefinition_different_kind, 403 New->getName()); 404 Diag(OldD->getLocation(), diag::err_previous_definition); 405 return New; 406 } 407 408 // Determine whether the previous declaration was a definition, 409 // implicit declaration, or a declaration. 410 diag::kind PrevDiag; 411 if (Old->isThisDeclarationADefinition()) 412 PrevDiag = diag::err_previous_definition; 413 else if (Old->isImplicit()) 414 PrevDiag = diag::err_previous_implicit_declaration; 415 else 416 PrevDiag = diag::err_previous_declaration; 417 418 QualType OldQType = Context.getCanonicalType(Old->getType()); 419 QualType NewQType = Context.getCanonicalType(New->getType()); 420 421 if (getLangOptions().CPlusPlus) { 422 // (C++98 13.1p2): 423 // Certain function declarations cannot be overloaded: 424 // -- Function declarations that differ only in the return type 425 // cannot be overloaded. 426 QualType OldReturnType 427 = cast<FunctionType>(OldQType.getTypePtr())->getResultType(); 428 QualType NewReturnType 429 = cast<FunctionType>(NewQType.getTypePtr())->getResultType(); 430 if (OldReturnType != NewReturnType) { 431 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 432 Diag(Old->getLocation(), PrevDiag); 433 return New; 434 } 435 436 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 437 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 438 if (OldMethod && NewMethod) { 439 // -- Member function declarations with the same name and the 440 // same parameter types cannot be overloaded if any of them 441 // is a static member function declaration. 442 if (OldMethod->isStatic() || NewMethod->isStatic()) { 443 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 444 Diag(Old->getLocation(), PrevDiag); 445 return New; 446 } 447 } 448 449 // (C++98 8.3.5p3): 450 // All declarations for a function shall agree exactly in both the 451 // return type and the parameter-type-list. 452 if (OldQType == NewQType) { 453 // We have a redeclaration. 454 MergeAttributes(New, Old); 455 Redeclaration = true; 456 return MergeCXXFunctionDecl(New, Old); 457 } 458 459 // Fall through for conflicting redeclarations and redefinitions. 460 } 461 462 // C: Function types need to be compatible, not identical. This handles 463 // duplicate function decls like "void f(int); void f(enum X);" properly. 464 if (!getLangOptions().CPlusPlus && 465 Context.typesAreCompatible(OldQType, NewQType)) { 466 MergeAttributes(New, Old); 467 Redeclaration = true; 468 return New; 469 } 470 471 // A function that has already been declared has been redeclared or defined 472 // with a different type- show appropriate diagnostic 473 474 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 475 // TODO: This is totally simplistic. It should handle merging functions 476 // together etc, merging extern int X; int X; ... 477 Diag(New->getLocation(), diag::err_conflicting_types, New->getName()); 478 Diag(Old->getLocation(), PrevDiag); 479 return New; 480} 481 482/// Predicate for C "tentative" external object definitions (C99 6.9.2). 483static bool isTentativeDefinition(VarDecl *VD) { 484 if (VD->isFileVarDecl()) 485 return (!VD->getInit() && 486 (VD->getStorageClass() == VarDecl::None || 487 VD->getStorageClass() == VarDecl::Static)); 488 return false; 489} 490 491/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors 492/// when dealing with C "tentative" external object definitions (C99 6.9.2). 493void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) { 494 bool VDIsTentative = isTentativeDefinition(VD); 495 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType(); 496 497 for (IdentifierResolver::iterator 498 I = IdResolver.begin(VD->getIdentifier(), 499 VD->getDeclContext(), false/*LookInParentCtx*/), 500 E = IdResolver.end(); I != E; ++I) { 501 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) { 502 VarDecl *OldDecl = dyn_cast<VarDecl>(*I); 503 504 // Handle the following case: 505 // int a[10]; 506 // int a[]; - the code below makes sure we set the correct type. 507 // int a[11]; - this is an error, size isn't 10. 508 if (OldDecl && VDIsTentative && VDIsIncompleteArray && 509 OldDecl->getType()->isConstantArrayType()) 510 VD->setType(OldDecl->getType()); 511 512 // Check for "tentative" definitions. We can't accomplish this in 513 // MergeVarDecl since the initializer hasn't been attached. 514 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative) 515 continue; 516 517 // Handle __private_extern__ just like extern. 518 if (OldDecl->getStorageClass() != VarDecl::Extern && 519 OldDecl->getStorageClass() != VarDecl::PrivateExtern && 520 VD->getStorageClass() != VarDecl::Extern && 521 VD->getStorageClass() != VarDecl::PrivateExtern) { 522 Diag(VD->getLocation(), diag::err_redefinition, VD->getName()); 523 Diag(OldDecl->getLocation(), diag::err_previous_definition); 524 } 525 } 526 } 527} 528 529/// MergeVarDecl - We just parsed a variable 'New' which has the same name 530/// and scope as a previous declaration 'Old'. Figure out how to resolve this 531/// situation, merging decls or emitting diagnostics as appropriate. 532/// 533/// Tentative definition rules (C99 6.9.2p2) are checked by 534/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 535/// definitions here, since the initializer hasn't been attached. 536/// 537VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) { 538 // Verify the old decl was also a variable. 539 VarDecl *Old = dyn_cast<VarDecl>(OldD); 540 if (!Old) { 541 Diag(New->getLocation(), diag::err_redefinition_different_kind, 542 New->getName()); 543 Diag(OldD->getLocation(), diag::err_previous_definition); 544 return New; 545 } 546 547 MergeAttributes(New, Old); 548 549 // Verify the types match. 550 QualType OldCType = Context.getCanonicalType(Old->getType()); 551 QualType NewCType = Context.getCanonicalType(New->getType()); 552 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) { 553 Diag(New->getLocation(), diag::err_redefinition, New->getName()); 554 Diag(Old->getLocation(), diag::err_previous_definition); 555 return New; 556 } 557 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 558 if (New->getStorageClass() == VarDecl::Static && 559 (Old->getStorageClass() == VarDecl::None || 560 Old->getStorageClass() == VarDecl::Extern)) { 561 Diag(New->getLocation(), diag::err_static_non_static, New->getName()); 562 Diag(Old->getLocation(), diag::err_previous_definition); 563 return New; 564 } 565 // C99 6.2.2p4: Check if we have a non-static decl followed by a static. 566 if (New->getStorageClass() != VarDecl::Static && 567 Old->getStorageClass() == VarDecl::Static) { 568 Diag(New->getLocation(), diag::err_non_static_static, New->getName()); 569 Diag(Old->getLocation(), diag::err_previous_definition); 570 return New; 571 } 572 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 573 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) { 574 Diag(New->getLocation(), diag::err_redefinition, New->getName()); 575 Diag(Old->getLocation(), diag::err_previous_definition); 576 } 577 return New; 578} 579 580/// CheckParmsForFunctionDef - Check that the parameters of the given 581/// function are appropriate for the definition of a function. This 582/// takes care of any checks that cannot be performed on the 583/// declaration itself, e.g., that the types of each of the function 584/// parameters are complete. 585bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) { 586 bool HasInvalidParm = false; 587 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 588 ParmVarDecl *Param = FD->getParamDecl(p); 589 590 // C99 6.7.5.3p4: the parameters in a parameter type list in a 591 // function declarator that is part of a function definition of 592 // that function shall not have incomplete type. 593 if (Param->getType()->isIncompleteType() && 594 !Param->isInvalidDecl()) { 595 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type, 596 Param->getType().getAsString()); 597 Param->setInvalidDecl(); 598 HasInvalidParm = true; 599 } 600 } 601 602 return HasInvalidParm; 603} 604 605/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 606/// no declarator (e.g. "struct foo;") is parsed. 607Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) { 608 // TODO: emit error on 'int;' or 'const enum foo;'. 609 // TODO: emit error on 'typedef int;' 610 // if (!DS.isMissingDeclaratorOk()) Diag(...); 611 612 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep())); 613} 614 615bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) { 616 // Get the type before calling CheckSingleAssignmentConstraints(), since 617 // it can promote the expression. 618 QualType InitType = Init->getType(); 619 620 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init); 621 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType, 622 InitType, Init, "initializing"); 623} 624 625bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) { 626 const ArrayType *AT = Context.getAsArrayType(DeclT); 627 628 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 629 // C99 6.7.8p14. We have an array of character type with unknown size 630 // being initialized to a string literal. 631 llvm::APSInt ConstVal(32); 632 ConstVal = strLiteral->getByteLength() + 1; 633 // Return a new array type (C99 6.7.8p22). 634 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal, 635 ArrayType::Normal, 0); 636 } else { 637 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); 638 // C99 6.7.8p14. We have an array of character type with known size. 639 // FIXME: Avoid truncation for 64-bit length strings. 640 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue()) 641 Diag(strLiteral->getSourceRange().getBegin(), 642 diag::warn_initializer_string_for_char_array_too_long) 643 << strLiteral->getSourceRange(); 644 } 645 // Set type from "char *" to "constant array of char". 646 strLiteral->setType(DeclT); 647 // For now, we always return false (meaning success). 648 return false; 649} 650 651StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) { 652 const ArrayType *AT = Context.getAsArrayType(DeclType); 653 if (AT && AT->getElementType()->isCharType()) { 654 return dyn_cast<StringLiteral>(Init); 655 } 656 return 0; 657} 658 659bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType, 660 SourceLocation InitLoc, 661 std::string InitEntity) { 662 // C++ [dcl.init.ref]p1: 663 // A variable declared to be a T&, that is “reference to type T” 664 // (8.3.2), shall be initialized by an object, or function, of 665 // type T or by an object that can be converted into a T. 666 if (DeclType->isReferenceType()) 667 return CheckReferenceInit(Init, DeclType); 668 669 // C99 6.7.8p3: The type of the entity to be initialized shall be an array 670 // of unknown size ("[]") or an object type that is not a variable array type. 671 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType)) 672 return Diag(InitLoc, diag::err_variable_object_no_init) 673 << VAT->getSizeExpr()->getSourceRange(); 674 675 InitListExpr *InitList = dyn_cast<InitListExpr>(Init); 676 if (!InitList) { 677 // FIXME: Handle wide strings 678 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType)) 679 return CheckStringLiteralInit(strLiteral, DeclType); 680 681 // C++ [dcl.init]p14: 682 // -- If the destination type is a (possibly cv-qualified) class 683 // type: 684 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) { 685 QualType DeclTypeC = Context.getCanonicalType(DeclType); 686 QualType InitTypeC = Context.getCanonicalType(Init->getType()); 687 688 // -- If the initialization is direct-initialization, or if it is 689 // copy-initialization where the cv-unqualified version of the 690 // source type is the same class as, or a derived class of, the 691 // class of the destination, constructors are considered. 692 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) || 693 IsDerivedFrom(InitTypeC, DeclTypeC)) { 694 CXXConstructorDecl *Constructor 695 = PerformInitializationByConstructor(DeclType, &Init, 1, 696 InitLoc, Init->getSourceRange(), 697 InitEntity, IK_Copy); 698 return Constructor == 0; 699 } 700 701 // -- Otherwise (i.e., for the remaining copy-initialization 702 // cases), user-defined conversion sequences that can 703 // convert from the source type to the destination type or 704 // (when a conversion function is used) to a derived class 705 // thereof are enumerated as described in 13.3.1.4, and the 706 // best one is chosen through overload resolution 707 // (13.3). If the conversion cannot be done or is 708 // ambiguous, the initialization is ill-formed. The 709 // function selected is called with the initializer 710 // expression as its argument; if the function is a 711 // constructor, the call initializes a temporary of the 712 // destination type. 713 // FIXME: We're pretending to do copy elision here; return to 714 // this when we have ASTs for such things. 715 if (!PerformImplicitConversion(Init, DeclType)) 716 return false; 717 718 return Diag(InitLoc, diag::err_typecheck_convert_incompatible) 719 << DeclType.getAsString() << InitEntity << "initializing" 720 << Init->getSourceRange(); 721 } 722 723 // C99 6.7.8p16. 724 if (DeclType->isArrayType()) 725 return Diag(Init->getLocStart(), diag::err_array_init_list_required) 726 << Init->getSourceRange(); 727 728 return CheckSingleInitializer(Init, DeclType); 729 } else if (getLangOptions().CPlusPlus) { 730 // C++ [dcl.init]p14: 731 // [...] If the class is an aggregate (8.5.1), and the initializer 732 // is a brace-enclosed list, see 8.5.1. 733 // 734 // Note: 8.5.1 is handled below; here, we diagnose the case where 735 // we have an initializer list and a destination type that is not 736 // an aggregate. 737 // FIXME: In C++0x, this is yet another form of initialization. 738 if (const RecordType *ClassRec = DeclType->getAsRecordType()) { 739 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 740 if (!ClassDecl->isAggregate()) 741 return Diag(InitLoc, diag::err_init_non_aggr_init_list) 742 << DeclType.getAsString() << Init->getSourceRange(); 743 } 744 } 745 746 InitListChecker CheckInitList(this, InitList, DeclType); 747 return CheckInitList.HadError(); 748} 749 750/// GetNameForDeclarator - Determine the full declaration name for the 751/// given Declarator. 752DeclarationName Sema::GetNameForDeclarator(Declarator &D) { 753 switch (D.getKind()) { 754 case Declarator::DK_Abstract: 755 assert(D.getIdentifier() == 0 && "abstract declarators have no name"); 756 return DeclarationName(); 757 758 case Declarator::DK_Normal: 759 assert (D.getIdentifier() != 0 && "normal declarators have an identifier"); 760 return DeclarationName(D.getIdentifier()); 761 762 case Declarator::DK_Constructor: { 763 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType()); 764 Ty = Context.getCanonicalType(Ty); 765 return Context.DeclarationNames.getCXXConstructorName(Ty); 766 } 767 768 case Declarator::DK_Destructor: { 769 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType()); 770 Ty = Context.getCanonicalType(Ty); 771 return Context.DeclarationNames.getCXXDestructorName(Ty); 772 } 773 774 case Declarator::DK_Conversion: { 775 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType()); 776 Ty = Context.getCanonicalType(Ty); 777 return Context.DeclarationNames.getCXXConversionFunctionName(Ty); 778 } 779 780 case Declarator::DK_Operator: 781 assert(D.getIdentifier() == 0 && "operator names have no identifier"); 782 return Context.DeclarationNames.getCXXOperatorName( 783 D.getOverloadedOperator()); 784 } 785 786 assert(false && "Unknown name kind"); 787 return DeclarationName(); 788} 789 790Sema::DeclTy * 791Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) { 792 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl); 793 DeclarationName Name = GetNameForDeclarator(D); 794 795 // All of these full declarators require an identifier. If it doesn't have 796 // one, the ParsedFreeStandingDeclSpec action should be used. 797 if (!Name) { 798 if (!D.getInvalidType()) // Reject this if we think it is valid. 799 Diag(D.getDeclSpec().getSourceRange().getBegin(), 800 diag::err_declarator_need_ident) 801 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 802 return 0; 803 } 804 805 // The scope passed in may not be a decl scope. Zip up the scope tree until 806 // we find one that is. 807 while ((S->getFlags() & Scope::DeclScope) == 0) 808 S = S->getParent(); 809 810 DeclContext *DC; 811 Decl *PrevDecl; 812 ScopedDecl *New; 813 bool InvalidDecl = false; 814 815 // See if this is a redefinition of a variable in the same scope. 816 if (!D.getCXXScopeSpec().isSet()) { 817 DC = CurContext; 818 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S); 819 } else { // Something like "int foo::x;" 820 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep()); 821 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC); 822 823 // C++ 7.3.1.2p2: 824 // Members (including explicit specializations of templates) of a named 825 // namespace can also be defined outside that namespace by explicit 826 // qualification of the name being defined, provided that the entity being 827 // defined was already declared in the namespace and the definition appears 828 // after the point of declaration in a namespace that encloses the 829 // declarations namespace. 830 // 831 if (PrevDecl == 0) { 832 // No previous declaration in the qualifying scope. 833 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member, 834 Name.getAsString(), D.getCXXScopeSpec().getRange()); 835 } else if (!CurContext->Encloses(DC)) { 836 // The qualifying scope doesn't enclose the original declaration. 837 // Emit diagnostic based on current scope. 838 SourceLocation L = D.getIdentifierLoc(); 839 SourceRange R = D.getCXXScopeSpec().getRange(); 840 if (isa<FunctionDecl>(CurContext)) { 841 Diag(L, diag::err_invalid_declarator_in_function, Name.getAsString(), 842 R); 843 } else { 844 Diag(L, diag::err_invalid_declarator_scope) 845 << Name.getAsString() << cast<NamedDecl>(DC)->getName() << R; 846 } 847 } 848 } 849 850 // In C++, the previous declaration we find might be a tag type 851 // (class or enum). In this case, the new declaration will hide the 852 // tag type. 853 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) 854 PrevDecl = 0; 855 856 QualType R = GetTypeForDeclarator(D, S); 857 assert(!R.isNull() && "GetTypeForDeclarator() returned null type"); 858 859 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 860 // Check that there are no default arguments (C++ only). 861 if (getLangOptions().CPlusPlus) 862 CheckExtraCXXDefaultArguments(D); 863 864 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator); 865 if (!NewTD) return 0; 866 867 // Handle attributes prior to checking for duplicates in MergeVarDecl 868 ProcessDeclAttributes(NewTD, D); 869 // Merge the decl with the existing one if appropriate. If the decl is 870 // in an outer scope, it isn't the same thing. 871 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) { 872 NewTD = MergeTypeDefDecl(NewTD, PrevDecl); 873 if (NewTD == 0) return 0; 874 } 875 New = NewTD; 876 if (S->getFnParent() == 0) { 877 // C99 6.7.7p2: If a typedef name specifies a variably modified type 878 // then it shall have block scope. 879 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) { 880 // FIXME: Diagnostic needs to be fixed. 881 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla); 882 InvalidDecl = true; 883 } 884 } 885 } else if (R.getTypePtr()->isFunctionType()) { 886 FunctionDecl::StorageClass SC = FunctionDecl::None; 887 switch (D.getDeclSpec().getStorageClassSpec()) { 888 default: assert(0 && "Unknown storage class!"); 889 case DeclSpec::SCS_auto: 890 case DeclSpec::SCS_register: 891 case DeclSpec::SCS_mutable: 892 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func, 893 R.getAsString()); 894 InvalidDecl = true; 895 break; 896 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break; 897 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break; 898 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break; 899 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break; 900 } 901 902 bool isInline = D.getDeclSpec().isInlineSpecified(); 903 // bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 904 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 905 906 FunctionDecl *NewFD; 907 if (D.getKind() == Declarator::DK_Constructor) { 908 // This is a C++ constructor declaration. 909 assert(DC->isCXXRecord() && 910 "Constructors can only be declared in a member context"); 911 912 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC); 913 914 // Create the new declaration 915 NewFD = CXXConstructorDecl::Create(Context, 916 cast<CXXRecordDecl>(DC), 917 D.getIdentifierLoc(), Name, R, 918 isExplicit, isInline, 919 /*isImplicitlyDeclared=*/false); 920 921 if (isInvalidDecl) 922 NewFD->setInvalidDecl(); 923 } else if (D.getKind() == Declarator::DK_Destructor) { 924 // This is a C++ destructor declaration. 925 if (DC->isCXXRecord()) { 926 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC); 927 928 NewFD = CXXDestructorDecl::Create(Context, 929 cast<CXXRecordDecl>(DC), 930 D.getIdentifierLoc(), Name, R, 931 isInline, 932 /*isImplicitlyDeclared=*/false); 933 934 if (isInvalidDecl) 935 NewFD->setInvalidDecl(); 936 } else { 937 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 938 // Create a FunctionDecl to satisfy the function definition parsing 939 // code path. 940 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(), 941 Name, R, SC, isInline, LastDeclarator, 942 // FIXME: Move to DeclGroup... 943 D.getDeclSpec().getSourceRange().getBegin()); 944 NewFD->setInvalidDecl(); 945 } 946 } else if (D.getKind() == Declarator::DK_Conversion) { 947 if (!DC->isCXXRecord()) { 948 Diag(D.getIdentifierLoc(), 949 diag::err_conv_function_not_member); 950 return 0; 951 } else { 952 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC); 953 954 NewFD = CXXConversionDecl::Create(Context, 955 cast<CXXRecordDecl>(DC), 956 D.getIdentifierLoc(), Name, R, 957 isInline, isExplicit); 958 959 if (isInvalidDecl) 960 NewFD->setInvalidDecl(); 961 } 962 } else if (DC->isCXXRecord()) { 963 // This is a C++ method declaration. 964 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC), 965 D.getIdentifierLoc(), Name, R, 966 (SC == FunctionDecl::Static), isInline, 967 LastDeclarator); 968 } else { 969 NewFD = FunctionDecl::Create(Context, DC, 970 D.getIdentifierLoc(), 971 Name, R, SC, isInline, LastDeclarator, 972 // FIXME: Move to DeclGroup... 973 D.getDeclSpec().getSourceRange().getBegin()); 974 } 975 // Handle attributes. 976 ProcessDeclAttributes(NewFD, D); 977 978 // Handle GNU asm-label extension (encoded as an attribute). 979 if (Expr *E = (Expr*) D.getAsmLabel()) { 980 // The parser guarantees this is a string. 981 StringLiteral *SE = cast<StringLiteral>(E); 982 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(), 983 SE->getByteLength()))); 984 } 985 986 // Copy the parameter declarations from the declarator D to 987 // the function declaration NewFD, if they are available. 988 if (D.getNumTypeObjects() > 0) { 989 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 990 991 // Create Decl objects for each parameter, adding them to the 992 // FunctionDecl. 993 llvm::SmallVector<ParmVarDecl*, 16> Params; 994 995 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 996 // function that takes no arguments, not a function that takes a 997 // single void argument. 998 // We let through "const void" here because Sema::GetTypeForDeclarator 999 // already checks for that case. 1000 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 1001 FTI.ArgInfo[0].Param && 1002 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 1003 // empty arg list, don't push any params. 1004 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param; 1005 1006 // In C++, the empty parameter-type-list must be spelled "void"; a 1007 // typedef of void is not permitted. 1008 if (getLangOptions().CPlusPlus && 1009 Param->getType().getUnqualifiedType() != Context.VoidTy) { 1010 Diag(Param->getLocation(), diag::ext_param_typedef_of_void); 1011 } 1012 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 1013 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 1014 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param); 1015 } 1016 1017 NewFD->setParams(&Params[0], Params.size()); 1018 } else if (R->getAsTypedefType()) { 1019 // When we're declaring a function with a typedef, as in the 1020 // following example, we'll need to synthesize (unnamed) 1021 // parameters for use in the declaration. 1022 // 1023 // @code 1024 // typedef void fn(int); 1025 // fn f; 1026 // @endcode 1027 const FunctionTypeProto *FT = R->getAsFunctionTypeProto(); 1028 if (!FT) { 1029 // This is a typedef of a function with no prototype, so we 1030 // don't need to do anything. 1031 } else if ((FT->getNumArgs() == 0) || 1032 (FT->getNumArgs() == 1 && !FT->isVariadic() && 1033 FT->getArgType(0)->isVoidType())) { 1034 // This is a zero-argument function. We don't need to do anything. 1035 } else { 1036 // Synthesize a parameter for each argument type. 1037 llvm::SmallVector<ParmVarDecl*, 16> Params; 1038 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin(); 1039 ArgType != FT->arg_type_end(); ++ArgType) { 1040 Params.push_back(ParmVarDecl::Create(Context, DC, 1041 SourceLocation(), 0, 1042 *ArgType, VarDecl::None, 1043 0, 0)); 1044 } 1045 1046 NewFD->setParams(&Params[0], Params.size()); 1047 } 1048 } 1049 1050 // C++ constructors and destructors are handled by separate 1051 // routines, since they don't require any declaration merging (C++ 1052 // [class.mfct]p2) and they aren't ever pushed into scope, because 1053 // they can't be found by name lookup anyway (C++ [class.ctor]p2). 1054 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) 1055 return ActOnConstructorDeclarator(Constructor); 1056 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD)) 1057 return ActOnDestructorDeclarator(Destructor); 1058 1059 // Extra checking for conversion functions, including recording 1060 // the conversion function in its class. 1061 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 1062 ActOnConversionDeclarator(Conversion); 1063 1064 // Extra checking for C++ overloaded operators (C++ [over.oper]). 1065 if (NewFD->isOverloadedOperator() && 1066 CheckOverloadedOperatorDeclaration(NewFD)) 1067 NewFD->setInvalidDecl(); 1068 1069 // Merge the decl with the existing one if appropriate. Since C functions 1070 // are in a flat namespace, make sure we consider decls in outer scopes. 1071 if (PrevDecl && 1072 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) { 1073 bool Redeclaration = false; 1074 1075 // If C++, determine whether NewFD is an overload of PrevDecl or 1076 // a declaration that requires merging. If it's an overload, 1077 // there's no more work to do here; we'll just add the new 1078 // function to the scope. 1079 OverloadedFunctionDecl::function_iterator MatchedDecl; 1080 if (!getLangOptions().CPlusPlus || 1081 !IsOverload(NewFD, PrevDecl, MatchedDecl)) { 1082 Decl *OldDecl = PrevDecl; 1083 1084 // If PrevDecl was an overloaded function, extract the 1085 // FunctionDecl that matched. 1086 if (isa<OverloadedFunctionDecl>(PrevDecl)) 1087 OldDecl = *MatchedDecl; 1088 1089 // NewFD and PrevDecl represent declarations that need to be 1090 // merged. 1091 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration); 1092 1093 if (NewFD == 0) return 0; 1094 if (Redeclaration) { 1095 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 1096 1097 if (OldDecl == PrevDecl) { 1098 // Remove the name binding for the previous 1099 // declaration. We'll add the binding back later, but then 1100 // it will refer to the new declaration (which will 1101 // contain more information). 1102 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl)); 1103 } else { 1104 // We need to update the OverloadedFunctionDecl with the 1105 // latest declaration of this function, so that name 1106 // lookup will always refer to the latest declaration of 1107 // this function. 1108 *MatchedDecl = NewFD; 1109 1110 // Add the redeclaration to the current scope, since we'll 1111 // be skipping PushOnScopeChains. 1112 S->AddDecl(NewFD); 1113 1114 return NewFD; 1115 } 1116 } 1117 } 1118 } 1119 New = NewFD; 1120 1121 // In C++, check default arguments now that we have merged decls. 1122 if (getLangOptions().CPlusPlus) 1123 CheckCXXDefaultArguments(NewFD); 1124 } else { 1125 // Check that there are no default arguments (C++ only). 1126 if (getLangOptions().CPlusPlus) 1127 CheckExtraCXXDefaultArguments(D); 1128 1129 if (R.getTypePtr()->isObjCInterfaceType()) { 1130 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object, 1131 D.getIdentifier()->getName()); 1132 InvalidDecl = true; 1133 } 1134 1135 VarDecl *NewVD; 1136 VarDecl::StorageClass SC; 1137 switch (D.getDeclSpec().getStorageClassSpec()) { 1138 default: assert(0 && "Unknown storage class!"); 1139 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 1140 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 1141 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 1142 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 1143 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 1144 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 1145 case DeclSpec::SCS_mutable: 1146 // mutable can only appear on non-static class members, so it's always 1147 // an error here 1148 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 1149 InvalidDecl = true; 1150 break; 1151 } 1152 1153 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1154 if (!II) { 1155 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name, 1156 Name.getAsString()); 1157 return 0; 1158 } 1159 1160 if (DC->isCXXRecord()) { 1161 assert(SC == VarDecl::Static && "Invalid storage class for member!"); 1162 // This is a static data member for a C++ class. 1163 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC), 1164 D.getIdentifierLoc(), II, 1165 R, LastDeclarator); 1166 } else { 1167 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified(); 1168 if (S->getFnParent() == 0) { 1169 // C99 6.9p2: The storage-class specifiers auto and register shall not 1170 // appear in the declaration specifiers in an external declaration. 1171 if (SC == VarDecl::Auto || SC == VarDecl::Register) { 1172 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope, 1173 R.getAsString()); 1174 InvalidDecl = true; 1175 } 1176 } 1177 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(), 1178 II, R, SC, LastDeclarator, 1179 // FIXME: Move to DeclGroup... 1180 D.getDeclSpec().getSourceRange().getBegin()); 1181 NewVD->setThreadSpecified(ThreadSpecified); 1182 } 1183 // Handle attributes prior to checking for duplicates in MergeVarDecl 1184 ProcessDeclAttributes(NewVD, D); 1185 1186 // Handle GNU asm-label extension (encoded as an attribute). 1187 if (Expr *E = (Expr*) D.getAsmLabel()) { 1188 // The parser guarantees this is a string. 1189 StringLiteral *SE = cast<StringLiteral>(E); 1190 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(), 1191 SE->getByteLength()))); 1192 } 1193 1194 // Emit an error if an address space was applied to decl with local storage. 1195 // This includes arrays of objects with address space qualifiers, but not 1196 // automatic variables that point to other address spaces. 1197 // ISO/IEC TR 18037 S5.1.2 1198 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) { 1199 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl); 1200 InvalidDecl = true; 1201 } 1202 // Merge the decl with the existing one if appropriate. If the decl is 1203 // in an outer scope, it isn't the same thing. 1204 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) { 1205 NewVD = MergeVarDecl(NewVD, PrevDecl); 1206 if (NewVD == 0) return 0; 1207 } 1208 New = NewVD; 1209 } 1210 1211 // Set the lexical context. If the declarator has a C++ scope specifier, the 1212 // lexical context will be different from the semantic context. 1213 New->setLexicalDeclContext(CurContext); 1214 1215 // If this has an identifier, add it to the scope stack. 1216 if (Name) 1217 PushOnScopeChains(New, S); 1218 // If any semantic error occurred, mark the decl as invalid. 1219 if (D.getInvalidType() || InvalidDecl) 1220 New->setInvalidDecl(); 1221 1222 return New; 1223} 1224 1225void Sema::InitializerElementNotConstant(const Expr *Init) { 1226 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 1227 << Init->getSourceRange(); 1228} 1229 1230bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) { 1231 switch (Init->getStmtClass()) { 1232 default: 1233 InitializerElementNotConstant(Init); 1234 return true; 1235 case Expr::ParenExprClass: { 1236 const ParenExpr* PE = cast<ParenExpr>(Init); 1237 return CheckAddressConstantExpressionLValue(PE->getSubExpr()); 1238 } 1239 case Expr::CompoundLiteralExprClass: 1240 return cast<CompoundLiteralExpr>(Init)->isFileScope(); 1241 case Expr::DeclRefExprClass: { 1242 const Decl *D = cast<DeclRefExpr>(Init)->getDecl(); 1243 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1244 if (VD->hasGlobalStorage()) 1245 return false; 1246 InitializerElementNotConstant(Init); 1247 return true; 1248 } 1249 if (isa<FunctionDecl>(D)) 1250 return false; 1251 InitializerElementNotConstant(Init); 1252 return true; 1253 } 1254 case Expr::MemberExprClass: { 1255 const MemberExpr *M = cast<MemberExpr>(Init); 1256 if (M->isArrow()) 1257 return CheckAddressConstantExpression(M->getBase()); 1258 return CheckAddressConstantExpressionLValue(M->getBase()); 1259 } 1260 case Expr::ArraySubscriptExprClass: { 1261 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)? 1262 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init); 1263 return CheckAddressConstantExpression(ASE->getBase()) || 1264 CheckArithmeticConstantExpression(ASE->getIdx()); 1265 } 1266 case Expr::StringLiteralClass: 1267 case Expr::PredefinedExprClass: 1268 return false; 1269 case Expr::UnaryOperatorClass: { 1270 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1271 1272 // C99 6.6p9 1273 if (Exp->getOpcode() == UnaryOperator::Deref) 1274 return CheckAddressConstantExpression(Exp->getSubExpr()); 1275 1276 InitializerElementNotConstant(Init); 1277 return true; 1278 } 1279 } 1280} 1281 1282bool Sema::CheckAddressConstantExpression(const Expr* Init) { 1283 switch (Init->getStmtClass()) { 1284 default: 1285 InitializerElementNotConstant(Init); 1286 return true; 1287 case Expr::ParenExprClass: 1288 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr()); 1289 case Expr::StringLiteralClass: 1290 case Expr::ObjCStringLiteralClass: 1291 return false; 1292 case Expr::CallExprClass: 1293 case Expr::CXXOperatorCallExprClass: 1294 // __builtin___CFStringMakeConstantString is a valid constant l-value. 1295 if (cast<CallExpr>(Init)->isBuiltinCall() == 1296 Builtin::BI__builtin___CFStringMakeConstantString) 1297 return false; 1298 1299 InitializerElementNotConstant(Init); 1300 return true; 1301 1302 case Expr::UnaryOperatorClass: { 1303 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1304 1305 // C99 6.6p9 1306 if (Exp->getOpcode() == UnaryOperator::AddrOf) 1307 return CheckAddressConstantExpressionLValue(Exp->getSubExpr()); 1308 1309 if (Exp->getOpcode() == UnaryOperator::Extension) 1310 return CheckAddressConstantExpression(Exp->getSubExpr()); 1311 1312 InitializerElementNotConstant(Init); 1313 return true; 1314 } 1315 case Expr::BinaryOperatorClass: { 1316 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"? 1317 const BinaryOperator *Exp = cast<BinaryOperator>(Init); 1318 1319 Expr *PExp = Exp->getLHS(); 1320 Expr *IExp = Exp->getRHS(); 1321 if (IExp->getType()->isPointerType()) 1322 std::swap(PExp, IExp); 1323 1324 // FIXME: Should we pedwarn if IExp isn't an integer constant expression? 1325 return CheckAddressConstantExpression(PExp) || 1326 CheckArithmeticConstantExpression(IExp); 1327 } 1328 case Expr::ImplicitCastExprClass: 1329 case Expr::CStyleCastExprClass: { 1330 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr(); 1331 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) { 1332 // Check for implicit promotion 1333 if (SubExpr->getType()->isFunctionType() || 1334 SubExpr->getType()->isArrayType()) 1335 return CheckAddressConstantExpressionLValue(SubExpr); 1336 } 1337 1338 // Check for pointer->pointer cast 1339 if (SubExpr->getType()->isPointerType()) 1340 return CheckAddressConstantExpression(SubExpr); 1341 1342 if (SubExpr->getType()->isIntegralType()) { 1343 // Check for the special-case of a pointer->int->pointer cast; 1344 // this isn't standard, but some code requires it. See 1345 // PR2720 for an example. 1346 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) { 1347 if (SubCast->getSubExpr()->getType()->isPointerType()) { 1348 unsigned IntWidth = Context.getIntWidth(SubCast->getType()); 1349 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy); 1350 if (IntWidth >= PointerWidth) { 1351 return CheckAddressConstantExpression(SubCast->getSubExpr()); 1352 } 1353 } 1354 } 1355 } 1356 if (SubExpr->getType()->isArithmeticType()) { 1357 return CheckArithmeticConstantExpression(SubExpr); 1358 } 1359 1360 InitializerElementNotConstant(Init); 1361 return true; 1362 } 1363 case Expr::ConditionalOperatorClass: { 1364 // FIXME: Should we pedwarn here? 1365 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init); 1366 if (!Exp->getCond()->getType()->isArithmeticType()) { 1367 InitializerElementNotConstant(Init); 1368 return true; 1369 } 1370 if (CheckArithmeticConstantExpression(Exp->getCond())) 1371 return true; 1372 if (Exp->getLHS() && 1373 CheckAddressConstantExpression(Exp->getLHS())) 1374 return true; 1375 return CheckAddressConstantExpression(Exp->getRHS()); 1376 } 1377 case Expr::AddrLabelExprClass: 1378 return false; 1379 } 1380} 1381 1382static const Expr* FindExpressionBaseAddress(const Expr* E); 1383 1384static const Expr* FindExpressionBaseAddressLValue(const Expr* E) { 1385 switch (E->getStmtClass()) { 1386 default: 1387 return E; 1388 case Expr::ParenExprClass: { 1389 const ParenExpr* PE = cast<ParenExpr>(E); 1390 return FindExpressionBaseAddressLValue(PE->getSubExpr()); 1391 } 1392 case Expr::MemberExprClass: { 1393 const MemberExpr *M = cast<MemberExpr>(E); 1394 if (M->isArrow()) 1395 return FindExpressionBaseAddress(M->getBase()); 1396 return FindExpressionBaseAddressLValue(M->getBase()); 1397 } 1398 case Expr::ArraySubscriptExprClass: { 1399 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E); 1400 return FindExpressionBaseAddress(ASE->getBase()); 1401 } 1402 case Expr::UnaryOperatorClass: { 1403 const UnaryOperator *Exp = cast<UnaryOperator>(E); 1404 1405 if (Exp->getOpcode() == UnaryOperator::Deref) 1406 return FindExpressionBaseAddress(Exp->getSubExpr()); 1407 1408 return E; 1409 } 1410 } 1411} 1412 1413static const Expr* FindExpressionBaseAddress(const Expr* E) { 1414 switch (E->getStmtClass()) { 1415 default: 1416 return E; 1417 case Expr::ParenExprClass: { 1418 const ParenExpr* PE = cast<ParenExpr>(E); 1419 return FindExpressionBaseAddress(PE->getSubExpr()); 1420 } 1421 case Expr::UnaryOperatorClass: { 1422 const UnaryOperator *Exp = cast<UnaryOperator>(E); 1423 1424 // C99 6.6p9 1425 if (Exp->getOpcode() == UnaryOperator::AddrOf) 1426 return FindExpressionBaseAddressLValue(Exp->getSubExpr()); 1427 1428 if (Exp->getOpcode() == UnaryOperator::Extension) 1429 return FindExpressionBaseAddress(Exp->getSubExpr()); 1430 1431 return E; 1432 } 1433 case Expr::BinaryOperatorClass: { 1434 const BinaryOperator *Exp = cast<BinaryOperator>(E); 1435 1436 Expr *PExp = Exp->getLHS(); 1437 Expr *IExp = Exp->getRHS(); 1438 if (IExp->getType()->isPointerType()) 1439 std::swap(PExp, IExp); 1440 1441 return FindExpressionBaseAddress(PExp); 1442 } 1443 case Expr::ImplicitCastExprClass: { 1444 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr(); 1445 1446 // Check for implicit promotion 1447 if (SubExpr->getType()->isFunctionType() || 1448 SubExpr->getType()->isArrayType()) 1449 return FindExpressionBaseAddressLValue(SubExpr); 1450 1451 // Check for pointer->pointer cast 1452 if (SubExpr->getType()->isPointerType()) 1453 return FindExpressionBaseAddress(SubExpr); 1454 1455 // We assume that we have an arithmetic expression here; 1456 // if we don't, we'll figure it out later 1457 return 0; 1458 } 1459 case Expr::CStyleCastExprClass: { 1460 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 1461 1462 // Check for pointer->pointer cast 1463 if (SubExpr->getType()->isPointerType()) 1464 return FindExpressionBaseAddress(SubExpr); 1465 1466 // We assume that we have an arithmetic expression here; 1467 // if we don't, we'll figure it out later 1468 return 0; 1469 } 1470 } 1471} 1472 1473bool Sema::CheckArithmeticConstantExpression(const Expr* Init) { 1474 switch (Init->getStmtClass()) { 1475 default: 1476 InitializerElementNotConstant(Init); 1477 return true; 1478 case Expr::ParenExprClass: { 1479 const ParenExpr* PE = cast<ParenExpr>(Init); 1480 return CheckArithmeticConstantExpression(PE->getSubExpr()); 1481 } 1482 case Expr::FloatingLiteralClass: 1483 case Expr::IntegerLiteralClass: 1484 case Expr::CharacterLiteralClass: 1485 case Expr::ImaginaryLiteralClass: 1486 case Expr::TypesCompatibleExprClass: 1487 case Expr::CXXBoolLiteralExprClass: 1488 return false; 1489 case Expr::CallExprClass: 1490 case Expr::CXXOperatorCallExprClass: { 1491 const CallExpr *CE = cast<CallExpr>(Init); 1492 1493 // Allow any constant foldable calls to builtins. 1494 if (CE->isBuiltinCall() && CE->isEvaluatable(Context)) 1495 return false; 1496 1497 InitializerElementNotConstant(Init); 1498 return true; 1499 } 1500 case Expr::DeclRefExprClass: { 1501 const Decl *D = cast<DeclRefExpr>(Init)->getDecl(); 1502 if (isa<EnumConstantDecl>(D)) 1503 return false; 1504 InitializerElementNotConstant(Init); 1505 return true; 1506 } 1507 case Expr::CompoundLiteralExprClass: 1508 // Allow "(vector type){2,4}"; normal C constraints don't allow this, 1509 // but vectors are allowed to be magic. 1510 if (Init->getType()->isVectorType()) 1511 return false; 1512 InitializerElementNotConstant(Init); 1513 return true; 1514 case Expr::UnaryOperatorClass: { 1515 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1516 1517 switch (Exp->getOpcode()) { 1518 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 1519 // See C99 6.6p3. 1520 default: 1521 InitializerElementNotConstant(Init); 1522 return true; 1523 case UnaryOperator::OffsetOf: 1524 if (Exp->getSubExpr()->getType()->isConstantSizeType()) 1525 return false; 1526 InitializerElementNotConstant(Init); 1527 return true; 1528 case UnaryOperator::Extension: 1529 case UnaryOperator::LNot: 1530 case UnaryOperator::Plus: 1531 case UnaryOperator::Minus: 1532 case UnaryOperator::Not: 1533 return CheckArithmeticConstantExpression(Exp->getSubExpr()); 1534 } 1535 } 1536 case Expr::SizeOfAlignOfExprClass: { 1537 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init); 1538 // Special check for void types, which are allowed as an extension 1539 if (Exp->getTypeOfArgument()->isVoidType()) 1540 return false; 1541 // alignof always evaluates to a constant. 1542 // FIXME: is sizeof(int[3.0]) a constant expression? 1543 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) { 1544 InitializerElementNotConstant(Init); 1545 return true; 1546 } 1547 return false; 1548 } 1549 case Expr::BinaryOperatorClass: { 1550 const BinaryOperator *Exp = cast<BinaryOperator>(Init); 1551 1552 if (Exp->getLHS()->getType()->isArithmeticType() && 1553 Exp->getRHS()->getType()->isArithmeticType()) { 1554 return CheckArithmeticConstantExpression(Exp->getLHS()) || 1555 CheckArithmeticConstantExpression(Exp->getRHS()); 1556 } 1557 1558 if (Exp->getLHS()->getType()->isPointerType() && 1559 Exp->getRHS()->getType()->isPointerType()) { 1560 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS()); 1561 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS()); 1562 1563 // Only allow a null (constant integer) base; we could 1564 // allow some additional cases if necessary, but this 1565 // is sufficient to cover offsetof-like constructs. 1566 if (!LHSBase && !RHSBase) { 1567 return CheckAddressConstantExpression(Exp->getLHS()) || 1568 CheckAddressConstantExpression(Exp->getRHS()); 1569 } 1570 } 1571 1572 InitializerElementNotConstant(Init); 1573 return true; 1574 } 1575 case Expr::ImplicitCastExprClass: 1576 case Expr::CStyleCastExprClass: { 1577 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr(); 1578 if (SubExpr->getType()->isArithmeticType()) 1579 return CheckArithmeticConstantExpression(SubExpr); 1580 1581 if (SubExpr->getType()->isPointerType()) { 1582 const Expr* Base = FindExpressionBaseAddress(SubExpr); 1583 // If the pointer has a null base, this is an offsetof-like construct 1584 if (!Base) 1585 return CheckAddressConstantExpression(SubExpr); 1586 } 1587 1588 InitializerElementNotConstant(Init); 1589 return true; 1590 } 1591 case Expr::ConditionalOperatorClass: { 1592 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init); 1593 1594 // If GNU extensions are disabled, we require all operands to be arithmetic 1595 // constant expressions. 1596 if (getLangOptions().NoExtensions) { 1597 return CheckArithmeticConstantExpression(Exp->getCond()) || 1598 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) || 1599 CheckArithmeticConstantExpression(Exp->getRHS()); 1600 } 1601 1602 // Otherwise, we have to emulate some of the behavior of fold here. 1603 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant 1604 // because it can constant fold things away. To retain compatibility with 1605 // GCC code, we see if we can fold the condition to a constant (which we 1606 // should always be able to do in theory). If so, we only require the 1607 // specified arm of the conditional to be a constant. This is a horrible 1608 // hack, but is require by real world code that uses __builtin_constant_p. 1609 APValue Val; 1610 if (!Exp->getCond()->Evaluate(Val, Context)) { 1611 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression 1612 // won't be able to either. Use it to emit the diagnostic though. 1613 bool Res = CheckArithmeticConstantExpression(Exp->getCond()); 1614 assert(Res && "Evaluate couldn't evaluate this constant?"); 1615 return Res; 1616 } 1617 1618 // Verify that the side following the condition is also a constant. 1619 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS(); 1620 if (Val.getInt() == 0) 1621 std::swap(TrueSide, FalseSide); 1622 1623 if (TrueSide && CheckArithmeticConstantExpression(TrueSide)) 1624 return true; 1625 1626 // Okay, the evaluated side evaluates to a constant, so we accept this. 1627 // Check to see if the other side is obviously not a constant. If so, 1628 // emit a warning that this is a GNU extension. 1629 if (FalseSide && !FalseSide->isEvaluatable(Context)) 1630 Diag(Init->getExprLoc(), 1631 diag::ext_typecheck_expression_not_constant_but_accepted) 1632 << FalseSide->getSourceRange(); 1633 return false; 1634 } 1635 } 1636} 1637 1638bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 1639 Init = Init->IgnoreParens(); 1640 1641 // Look through CXXDefaultArgExprs; they have no meaning in this context. 1642 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init)) 1643 return CheckForConstantInitializer(DAE->getExpr(), DclT); 1644 1645 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init)) 1646 return CheckForConstantInitializer(e->getInitializer(), DclT); 1647 1648 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) { 1649 unsigned numInits = Exp->getNumInits(); 1650 for (unsigned i = 0; i < numInits; i++) { 1651 // FIXME: Need to get the type of the declaration for C++, 1652 // because it could be a reference? 1653 if (CheckForConstantInitializer(Exp->getInit(i), 1654 Exp->getInit(i)->getType())) 1655 return true; 1656 } 1657 return false; 1658 } 1659 1660 if (Init->isNullPointerConstant(Context)) 1661 return false; 1662 if (Init->getType()->isArithmeticType()) { 1663 QualType InitTy = Context.getCanonicalType(Init->getType()) 1664 .getUnqualifiedType(); 1665 if (InitTy == Context.BoolTy) { 1666 // Special handling for pointers implicitly cast to bool; 1667 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level. 1668 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) { 1669 Expr* SubE = ICE->getSubExpr(); 1670 if (SubE->getType()->isPointerType() || 1671 SubE->getType()->isArrayType() || 1672 SubE->getType()->isFunctionType()) { 1673 return CheckAddressConstantExpression(Init); 1674 } 1675 } 1676 } else if (InitTy->isIntegralType()) { 1677 Expr* SubE = 0; 1678 if (CastExpr* CE = dyn_cast<CastExpr>(Init)) 1679 SubE = CE->getSubExpr(); 1680 // Special check for pointer cast to int; we allow as an extension 1681 // an address constant cast to an integer if the integer 1682 // is of an appropriate width (this sort of code is apparently used 1683 // in some places). 1684 // FIXME: Add pedwarn? 1685 // FIXME: Don't allow bitfields here! Need the FieldDecl for that. 1686 if (SubE && (SubE->getType()->isPointerType() || 1687 SubE->getType()->isArrayType() || 1688 SubE->getType()->isFunctionType())) { 1689 unsigned IntWidth = Context.getTypeSize(Init->getType()); 1690 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy); 1691 if (IntWidth >= PointerWidth) 1692 return CheckAddressConstantExpression(Init); 1693 } 1694 } 1695 1696 return CheckArithmeticConstantExpression(Init); 1697 } 1698 1699 if (Init->getType()->isPointerType()) 1700 return CheckAddressConstantExpression(Init); 1701 1702 // An array type at the top level that isn't an init-list must 1703 // be a string literal 1704 if (Init->getType()->isArrayType()) 1705 return false; 1706 1707 if (Init->getType()->isFunctionType()) 1708 return false; 1709 1710 // Allow block exprs at top level. 1711 if (Init->getType()->isBlockPointerType()) 1712 return false; 1713 1714 InitializerElementNotConstant(Init); 1715 return true; 1716} 1717 1718void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) { 1719 Decl *RealDecl = static_cast<Decl *>(dcl); 1720 Expr *Init = static_cast<Expr *>(init); 1721 assert(Init && "missing initializer"); 1722 1723 // If there is no declaration, there was an error parsing it. Just ignore 1724 // the initializer. 1725 if (RealDecl == 0) { 1726 delete Init; 1727 return; 1728 } 1729 1730 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 1731 if (!VDecl) { 1732 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(), 1733 diag::err_illegal_initializer); 1734 RealDecl->setInvalidDecl(); 1735 return; 1736 } 1737 // Get the decls type and save a reference for later, since 1738 // CheckInitializerTypes may change it. 1739 QualType DclT = VDecl->getType(), SavT = DclT; 1740 if (VDecl->isBlockVarDecl()) { 1741 VarDecl::StorageClass SC = VDecl->getStorageClass(); 1742 if (SC == VarDecl::Extern) { // C99 6.7.8p5 1743 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 1744 VDecl->setInvalidDecl(); 1745 } else if (!VDecl->isInvalidDecl()) { 1746 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(), 1747 VDecl->getName())) 1748 VDecl->setInvalidDecl(); 1749 1750 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 1751 if (!getLangOptions().CPlusPlus) { 1752 if (SC == VarDecl::Static) // C99 6.7.8p4. 1753 CheckForConstantInitializer(Init, DclT); 1754 } 1755 } 1756 } else if (VDecl->isFileVarDecl()) { 1757 if (VDecl->getStorageClass() == VarDecl::Extern) 1758 Diag(VDecl->getLocation(), diag::warn_extern_init); 1759 if (!VDecl->isInvalidDecl()) 1760 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(), 1761 VDecl->getName())) 1762 VDecl->setInvalidDecl(); 1763 1764 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 1765 if (!getLangOptions().CPlusPlus) { 1766 // C99 6.7.8p4. All file scoped initializers need to be constant. 1767 CheckForConstantInitializer(Init, DclT); 1768 } 1769 } 1770 // If the type changed, it means we had an incomplete type that was 1771 // completed by the initializer. For example: 1772 // int ary[] = { 1, 3, 5 }; 1773 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 1774 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 1775 VDecl->setType(DclT); 1776 Init->setType(DclT); 1777 } 1778 1779 // Attach the initializer to the decl. 1780 VDecl->setInit(Init); 1781 return; 1782} 1783 1784void Sema::ActOnUninitializedDecl(DeclTy *dcl) { 1785 Decl *RealDecl = static_cast<Decl *>(dcl); 1786 1787 // If there is no declaration, there was an error parsing it. Just ignore it. 1788 if (RealDecl == 0) 1789 return; 1790 1791 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 1792 QualType Type = Var->getType(); 1793 // C++ [dcl.init.ref]p3: 1794 // The initializer can be omitted for a reference only in a 1795 // parameter declaration (8.3.5), in the declaration of a 1796 // function return type, in the declaration of a class member 1797 // within its class declaration (9.2), and where the extern 1798 // specifier is explicitly used. 1799 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) { 1800 Diag(Var->getLocation(), 1801 diag::err_reference_var_requires_init, 1802 Var->getName(), 1803 SourceRange(Var->getLocation(), Var->getLocation())); 1804 Var->setInvalidDecl(); 1805 return; 1806 } 1807 1808 // C++ [dcl.init]p9: 1809 // 1810 // If no initializer is specified for an object, and the object 1811 // is of (possibly cv-qualified) non-POD class type (or array 1812 // thereof), the object shall be default-initialized; if the 1813 // object is of const-qualified type, the underlying class type 1814 // shall have a user-declared default constructor. 1815 if (getLangOptions().CPlusPlus) { 1816 QualType InitType = Type; 1817 if (const ArrayType *Array = Context.getAsArrayType(Type)) 1818 InitType = Array->getElementType(); 1819 if (InitType->isRecordType()) { 1820 const CXXConstructorDecl *Constructor 1821 = PerformInitializationByConstructor(InitType, 0, 0, 1822 Var->getLocation(), 1823 SourceRange(Var->getLocation(), 1824 Var->getLocation()), 1825 Var->getName(), 1826 IK_Default); 1827 if (!Constructor) 1828 Var->setInvalidDecl(); 1829 } 1830 } 1831 1832#if 0 1833 // FIXME: Temporarily disabled because we are not properly parsing 1834 // linkage specifications on declarations, e.g., 1835 // 1836 // extern "C" const CGPoint CGPointerZero; 1837 // 1838 // C++ [dcl.init]p9: 1839 // 1840 // If no initializer is specified for an object, and the 1841 // object is of (possibly cv-qualified) non-POD class type (or 1842 // array thereof), the object shall be default-initialized; if 1843 // the object is of const-qualified type, the underlying class 1844 // type shall have a user-declared default 1845 // constructor. Otherwise, if no initializer is specified for 1846 // an object, the object and its subobjects, if any, have an 1847 // indeterminate initial value; if the object or any of its 1848 // subobjects are of const-qualified type, the program is 1849 // ill-formed. 1850 // 1851 // This isn't technically an error in C, so we don't diagnose it. 1852 // 1853 // FIXME: Actually perform the POD/user-defined default 1854 // constructor check. 1855 if (getLangOptions().CPlusPlus && 1856 Context.getCanonicalType(Type).isConstQualified() && 1857 Var->getStorageClass() != VarDecl::Extern) 1858 Diag(Var->getLocation(), 1859 diag::err_const_var_requires_init, 1860 Var->getName(), 1861 SourceRange(Var->getLocation(), Var->getLocation())); 1862#endif 1863 } 1864} 1865 1866/// The declarators are chained together backwards, reverse the list. 1867Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) { 1868 // Often we have single declarators, handle them quickly. 1869 Decl *GroupDecl = static_cast<Decl*>(group); 1870 if (GroupDecl == 0) 1871 return 0; 1872 1873 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl); 1874 ScopedDecl *NewGroup = 0; 1875 if (Group->getNextDeclarator() == 0) 1876 NewGroup = Group; 1877 else { // reverse the list. 1878 while (Group) { 1879 ScopedDecl *Next = Group->getNextDeclarator(); 1880 Group->setNextDeclarator(NewGroup); 1881 NewGroup = Group; 1882 Group = Next; 1883 } 1884 } 1885 // Perform semantic analysis that depends on having fully processed both 1886 // the declarator and initializer. 1887 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) { 1888 VarDecl *IDecl = dyn_cast<VarDecl>(ID); 1889 if (!IDecl) 1890 continue; 1891 QualType T = IDecl->getType(); 1892 1893 // C99 6.7.5.2p2: If an identifier is declared to be an object with 1894 // static storage duration, it shall not have a variable length array. 1895 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) && 1896 IDecl->getStorageClass() == VarDecl::Static) { 1897 if (T->isVariableArrayType()) { 1898 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla); 1899 IDecl->setInvalidDecl(); 1900 } 1901 } 1902 // Block scope. C99 6.7p7: If an identifier for an object is declared with 1903 // no linkage (C99 6.2.2p6), the type for the object shall be complete... 1904 if (IDecl->isBlockVarDecl() && 1905 IDecl->getStorageClass() != VarDecl::Extern) { 1906 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) { 1907 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type, 1908 T.getAsString()); 1909 IDecl->setInvalidDecl(); 1910 } 1911 } 1912 // File scope. C99 6.9.2p2: A declaration of an identifier for and 1913 // object that has file scope without an initializer, and without a 1914 // storage-class specifier or with the storage-class specifier "static", 1915 // constitutes a tentative definition. Note: A tentative definition with 1916 // external linkage is valid (C99 6.2.2p5). 1917 if (isTentativeDefinition(IDecl)) { 1918 if (T->isIncompleteArrayType()) { 1919 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete 1920 // array to be completed. Don't issue a diagnostic. 1921 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) { 1922 // C99 6.9.2p3: If the declaration of an identifier for an object is 1923 // a tentative definition and has internal linkage (C99 6.2.2p3), the 1924 // declared type shall not be an incomplete type. 1925 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type, 1926 T.getAsString()); 1927 IDecl->setInvalidDecl(); 1928 } 1929 } 1930 if (IDecl->isFileVarDecl()) 1931 CheckForFileScopedRedefinitions(S, IDecl); 1932 } 1933 return NewGroup; 1934} 1935 1936/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 1937/// to introduce parameters into function prototype scope. 1938Sema::DeclTy * 1939Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 1940 // FIXME: disallow CXXScopeSpec for param declarators. 1941 const DeclSpec &DS = D.getDeclSpec(); 1942 1943 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 1944 VarDecl::StorageClass StorageClass = VarDecl::None; 1945 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 1946 StorageClass = VarDecl::Register; 1947 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 1948 Diag(DS.getStorageClassSpecLoc(), 1949 diag::err_invalid_storage_class_in_func_decl); 1950 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1951 } 1952 if (DS.isThreadSpecified()) { 1953 Diag(DS.getThreadSpecLoc(), 1954 diag::err_invalid_storage_class_in_func_decl); 1955 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1956 } 1957 1958 // Check that there are no default arguments inside the type of this 1959 // parameter (C++ only). 1960 if (getLangOptions().CPlusPlus) 1961 CheckExtraCXXDefaultArguments(D); 1962 1963 // In this context, we *do not* check D.getInvalidType(). If the declarator 1964 // type was invalid, GetTypeForDeclarator() still returns a "valid" type, 1965 // though it will not reflect the user specified type. 1966 QualType parmDeclType = GetTypeForDeclarator(D, S); 1967 1968 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type"); 1969 1970 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 1971 // Can this happen for params? We already checked that they don't conflict 1972 // among each other. Here they can only shadow globals, which is ok. 1973 IdentifierInfo *II = D.getIdentifier(); 1974 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) { 1975 if (S->isDeclScope(PrevDecl)) { 1976 Diag(D.getIdentifierLoc(), diag::err_param_redefinition, 1977 dyn_cast<NamedDecl>(PrevDecl)->getName()); 1978 1979 // Recover by removing the name 1980 II = 0; 1981 D.SetIdentifier(0, D.getIdentifierLoc()); 1982 } 1983 } 1984 1985 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]). 1986 // Doing the promotion here has a win and a loss. The win is the type for 1987 // both Decl's and DeclRefExpr's will match (a convenient invariant for the 1988 // code generator). The loss is the orginal type isn't preserved. For example: 1989 // 1990 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *" 1991 // int blockvardecl[5]; 1992 // sizeof(parmvardecl); // size == 4 1993 // sizeof(blockvardecl); // size == 20 1994 // } 1995 // 1996 // For expressions, all implicit conversions are captured using the 1997 // ImplicitCastExpr AST node (we have no such mechanism for Decl's). 1998 // 1999 // FIXME: If a source translation tool needs to see the original type, then 2000 // we need to consider storing both types (in ParmVarDecl)... 2001 // 2002 if (parmDeclType->isArrayType()) { 2003 // int x[restrict 4] -> int *restrict 2004 parmDeclType = Context.getArrayDecayedType(parmDeclType); 2005 } else if (parmDeclType->isFunctionType()) 2006 parmDeclType = Context.getPointerType(parmDeclType); 2007 2008 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, 2009 D.getIdentifierLoc(), II, 2010 parmDeclType, StorageClass, 2011 0, 0); 2012 2013 if (D.getInvalidType()) 2014 New->setInvalidDecl(); 2015 2016 if (II) 2017 PushOnScopeChains(New, S); 2018 2019 ProcessDeclAttributes(New, D); 2020 return New; 2021 2022} 2023 2024Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 2025 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 2026 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 2027 "Not a function declarator!"); 2028 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2029 2030 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 2031 // for a K&R function. 2032 if (!FTI.hasPrototype) { 2033 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 2034 if (FTI.ArgInfo[i].Param == 0) { 2035 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared, 2036 FTI.ArgInfo[i].Ident->getName()); 2037 // Implicitly declare the argument as type 'int' for lack of a better 2038 // type. 2039 DeclSpec DS; 2040 const char* PrevSpec; // unused 2041 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 2042 PrevSpec); 2043 Declarator ParamD(DS, Declarator::KNRTypeListContext); 2044 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 2045 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD); 2046 } 2047 } 2048 } else { 2049 // FIXME: Diagnose arguments without names in C. 2050 } 2051 2052 Scope *GlobalScope = FnBodyScope->getParent(); 2053 2054 return ActOnStartOfFunctionDef(FnBodyScope, 2055 ActOnDeclarator(GlobalScope, D, 0)); 2056} 2057 2058Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) { 2059 Decl *decl = static_cast<Decl*>(D); 2060 FunctionDecl *FD = cast<FunctionDecl>(decl); 2061 2062 // See if this is a redefinition. 2063 const FunctionDecl *Definition; 2064 if (FD->getBody(Definition)) { 2065 Diag(FD->getLocation(), diag::err_redefinition, 2066 FD->getName()); 2067 Diag(Definition->getLocation(), diag::err_previous_definition); 2068 } 2069 2070 PushDeclContext(FD); 2071 2072 // Check the validity of our function parameters 2073 CheckParmsForFunctionDef(FD); 2074 2075 // Introduce our parameters into the function scope 2076 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 2077 ParmVarDecl *Param = FD->getParamDecl(p); 2078 // If this has an identifier, add it to the scope stack. 2079 if (Param->getIdentifier()) 2080 PushOnScopeChains(Param, FnBodyScope); 2081 } 2082 2083 return FD; 2084} 2085 2086Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) { 2087 Decl *dcl = static_cast<Decl *>(D); 2088 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) { 2089 FD->setBody((Stmt*)Body); 2090 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 2091 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 2092 MD->setBody((Stmt*)Body); 2093 } else 2094 return 0; 2095 PopDeclContext(); 2096 // Verify and clean out per-function state. 2097 2098 // Check goto/label use. 2099 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 2100 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) { 2101 // Verify that we have no forward references left. If so, there was a goto 2102 // or address of a label taken, but no definition of it. Label fwd 2103 // definitions are indicated with a null substmt. 2104 if (I->second->getSubStmt() == 0) { 2105 LabelStmt *L = I->second; 2106 // Emit error. 2107 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName()); 2108 2109 // At this point, we have gotos that use the bogus label. Stitch it into 2110 // the function body so that they aren't leaked and that the AST is well 2111 // formed. 2112 if (Body) { 2113 L->setSubStmt(new NullStmt(L->getIdentLoc())); 2114 cast<CompoundStmt>((Stmt*)Body)->push_back(L); 2115 } else { 2116 // The whole function wasn't parsed correctly, just delete this. 2117 delete L; 2118 } 2119 } 2120 } 2121 LabelMap.clear(); 2122 2123 return D; 2124} 2125 2126/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 2127/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 2128ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 2129 IdentifierInfo &II, Scope *S) { 2130 // Extension in C99. Legal in C90, but warn about it. 2131 if (getLangOptions().C99) 2132 Diag(Loc, diag::ext_implicit_function_decl, II.getName()); 2133 else 2134 Diag(Loc, diag::warn_implicit_function_decl, II.getName()); 2135 2136 // FIXME: handle stuff like: 2137 // void foo() { extern float X(); } 2138 // void bar() { X(); } <-- implicit decl for X in another scope. 2139 2140 // Set a Declarator for the implicit definition: int foo(); 2141 const char *Dummy; 2142 DeclSpec DS; 2143 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy); 2144 Error = Error; // Silence warning. 2145 assert(!Error && "Error setting up implicit decl!"); 2146 Declarator D(DS, Declarator::BlockContext); 2147 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc)); 2148 D.SetIdentifier(&II, Loc); 2149 2150 // Insert this function into translation-unit scope. 2151 2152 DeclContext *PrevDC = CurContext; 2153 CurContext = Context.getTranslationUnitDecl(); 2154 2155 FunctionDecl *FD = 2156 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0))); 2157 FD->setImplicit(); 2158 2159 CurContext = PrevDC; 2160 2161 return FD; 2162} 2163 2164 2165TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 2166 ScopedDecl *LastDeclarator) { 2167 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 2168 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 2169 2170 // Scope manipulation handled by caller. 2171 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 2172 D.getIdentifierLoc(), 2173 D.getIdentifier(), 2174 T, LastDeclarator); 2175 if (D.getInvalidType()) 2176 NewTD->setInvalidDecl(); 2177 return NewTD; 2178} 2179 2180/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 2181/// former case, Name will be non-null. In the later case, Name will be null. 2182/// TagType indicates what kind of tag this is. TK indicates whether this is a 2183/// reference/declaration/definition of a tag. 2184Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK, 2185 SourceLocation KWLoc, const CXXScopeSpec &SS, 2186 IdentifierInfo *Name, SourceLocation NameLoc, 2187 AttributeList *Attr) { 2188 // If this is a use of an existing tag, it must have a name. 2189 assert((Name != 0 || TK == TK_Definition) && 2190 "Nameless record must be a definition!"); 2191 2192 TagDecl::TagKind Kind; 2193 switch (TagType) { 2194 default: assert(0 && "Unknown tag type!"); 2195 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 2196 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 2197 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 2198 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break; 2199 } 2200 2201 // Two code paths: a new one for structs/unions/classes where we create 2202 // separate decls for forward declarations, and an old (eventually to 2203 // be removed) code path for enums. 2204 if (Kind != TagDecl::TK_enum) 2205 return ActOnTagStruct(S, Kind, TK, KWLoc, SS, Name, NameLoc, Attr); 2206 2207 DeclContext *DC = CurContext; 2208 ScopedDecl *PrevDecl = 0; 2209 2210 if (Name && SS.isNotEmpty()) { 2211 // We have a nested-name tag ('struct foo::bar'). 2212 2213 // Check for invalid 'foo::'. 2214 if (SS.isInvalid()) { 2215 Name = 0; 2216 goto CreateNewDecl; 2217 } 2218 2219 DC = static_cast<DeclContext*>(SS.getScopeRep()); 2220 // Look-up name inside 'foo::'. 2221 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC)); 2222 2223 // A tag 'foo::bar' must already exist. 2224 if (PrevDecl == 0) { 2225 Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(), 2226 SS.getRange()); 2227 Name = 0; 2228 goto CreateNewDecl; 2229 } 2230 } else { 2231 // If this is a named struct, check to see if there was a previous forward 2232 // declaration or definition. 2233 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up. 2234 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S)); 2235 } 2236 2237 if (PrevDecl) { 2238 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) && 2239 "unexpected Decl type"); 2240 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 2241 // If this is a use of a previous tag, or if the tag is already declared 2242 // in the same scope (so that the definition/declaration completes or 2243 // rementions the tag), reuse the decl. 2244 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) { 2245 // Make sure that this wasn't declared as an enum and now used as a 2246 // struct or something similar. 2247 if (PrevTagDecl->getTagKind() != Kind) { 2248 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName()); 2249 Diag(PrevDecl->getLocation(), diag::err_previous_use); 2250 // Recover by making this an anonymous redefinition. 2251 Name = 0; 2252 PrevDecl = 0; 2253 } else { 2254 // If this is a use or a forward declaration, we're good. 2255 if (TK != TK_Definition) 2256 return PrevDecl; 2257 2258 // Diagnose attempts to redefine a tag. 2259 if (PrevTagDecl->isDefinition()) { 2260 Diag(NameLoc, diag::err_redefinition, Name->getName()); 2261 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 2262 // If this is a redefinition, recover by making this struct be 2263 // anonymous, which will make any later references get the previous 2264 // definition. 2265 Name = 0; 2266 } else { 2267 // Okay, this is definition of a previously declared or referenced 2268 // tag. Move the location of the decl to be the definition site. 2269 PrevDecl->setLocation(NameLoc); 2270 return PrevDecl; 2271 } 2272 } 2273 } 2274 // If we get here, this is a definition of a new struct type in a nested 2275 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new 2276 // type. 2277 } else { 2278 // PrevDecl is a namespace. 2279 if (isDeclInScope(PrevDecl, DC, S)) { 2280 // The tag name clashes with a namespace name, issue an error and 2281 // recover by making this tag be anonymous. 2282 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName()); 2283 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 2284 Name = 0; 2285 } 2286 } 2287 } 2288 2289 CreateNewDecl: 2290 2291 // If there is an identifier, use the location of the identifier as the 2292 // location of the decl, otherwise use the location of the struct/union 2293 // keyword. 2294 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 2295 2296 // Otherwise, if this is the first time we've seen this tag, create the decl. 2297 TagDecl *New; 2298 if (Kind == TagDecl::TK_enum) { 2299 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 2300 // enum X { A, B, C } D; D should chain to X. 2301 New = EnumDecl::Create(Context, DC, Loc, Name, 0); 2302 // If this is an undefined enum, warn. 2303 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum); 2304 } else { 2305 // struct/union/class 2306 2307 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 2308 // struct X { int A; } D; D should chain to X. 2309 if (getLangOptions().CPlusPlus) 2310 // FIXME: Look for a way to use RecordDecl for simple structs. 2311 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name); 2312 else 2313 New = RecordDecl::Create(Context, Kind, DC, Loc, Name); 2314 } 2315 2316 // If this has an identifier, add it to the scope stack. 2317 if (Name) { 2318 // The scope passed in may not be a decl scope. Zip up the scope tree until 2319 // we find one that is. 2320 while ((S->getFlags() & Scope::DeclScope) == 0) 2321 S = S->getParent(); 2322 2323 // Add it to the decl chain. 2324 PushOnScopeChains(New, S); 2325 } 2326 2327 if (Attr) 2328 ProcessDeclAttributeList(New, Attr); 2329 2330 // Set the lexical context. If the tag has a C++ scope specifier, the 2331 // lexical context will be different from the semantic context. 2332 New->setLexicalDeclContext(CurContext); 2333 2334 return New; 2335} 2336 2337/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike 2338/// the logic for enums, we create separate decls for forward declarations. 2339/// This is called by ActOnTag, but eventually will replace its logic. 2340Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK, 2341 SourceLocation KWLoc, const CXXScopeSpec &SS, 2342 IdentifierInfo *Name, SourceLocation NameLoc, 2343 AttributeList *Attr) { 2344 DeclContext *DC = CurContext; 2345 ScopedDecl *PrevDecl = 0; 2346 2347 if (Name && SS.isNotEmpty()) { 2348 // We have a nested-name tag ('struct foo::bar'). 2349 2350 // Check for invalid 'foo::'. 2351 if (SS.isInvalid()) { 2352 Name = 0; 2353 goto CreateNewDecl; 2354 } 2355 2356 DC = static_cast<DeclContext*>(SS.getScopeRep()); 2357 // Look-up name inside 'foo::'. 2358 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC)); 2359 2360 // A tag 'foo::bar' must already exist. 2361 if (PrevDecl == 0) { 2362 Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(), 2363 SS.getRange()); 2364 Name = 0; 2365 goto CreateNewDecl; 2366 } 2367 } else { 2368 // If this is a named struct, check to see if there was a previous forward 2369 // declaration or definition. 2370 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up. 2371 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S)); 2372 } 2373 2374 if (PrevDecl) { 2375 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) && 2376 "unexpected Decl type"); 2377 2378 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 2379 // If this is a use of a previous tag, or if the tag is already declared 2380 // in the same scope (so that the definition/declaration completes or 2381 // rementions the tag), reuse the decl. 2382 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) { 2383 // Make sure that this wasn't declared as an enum and now used as a 2384 // struct or something similar. 2385 if (PrevTagDecl->getTagKind() != Kind) { 2386 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName()); 2387 Diag(PrevDecl->getLocation(), diag::err_previous_use); 2388 // Recover by making this an anonymous redefinition. 2389 Name = 0; 2390 PrevDecl = 0; 2391 } else { 2392 // If this is a use, return the original decl. 2393 2394 // FIXME: In the future, return a variant or some other clue 2395 // for the consumer of this Decl to know it doesn't own it. 2396 // For our current ASTs this shouldn't be a problem, but will 2397 // need to be changed with DeclGroups. 2398 if (TK == TK_Reference) 2399 return PrevDecl; 2400 2401 // The new decl is a definition? 2402 if (TK == TK_Definition) { 2403 // Diagnose attempts to redefine a tag. 2404 if (RecordDecl* DefRecord = 2405 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) { 2406 Diag(NameLoc, diag::err_redefinition, Name->getName()); 2407 Diag(DefRecord->getLocation(), diag::err_previous_definition); 2408 // If this is a redefinition, recover by making this struct be 2409 // anonymous, which will make any later references get the previous 2410 // definition. 2411 Name = 0; 2412 PrevDecl = 0; 2413 } 2414 // Okay, this is definition of a previously declared or referenced 2415 // tag. We're going to create a new Decl. 2416 } 2417 } 2418 // If we get here we have (another) forward declaration. Just create 2419 // a new decl. 2420 } 2421 else { 2422 // If we get here, this is a definition of a new struct type in a nested 2423 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 2424 // new decl/type. We set PrevDecl to NULL so that the Records 2425 // have distinct types. 2426 PrevDecl = 0; 2427 } 2428 } else { 2429 // PrevDecl is a namespace. 2430 if (isDeclInScope(PrevDecl, DC, S)) { 2431 // The tag name clashes with a namespace name, issue an error and 2432 // recover by making this tag be anonymous. 2433 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName()); 2434 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 2435 Name = 0; 2436 } 2437 } 2438 } 2439 2440 CreateNewDecl: 2441 2442 // If there is an identifier, use the location of the identifier as the 2443 // location of the decl, otherwise use the location of the struct/union 2444 // keyword. 2445 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 2446 2447 // Otherwise, if this is the first time we've seen this tag, create the decl. 2448 TagDecl *New; 2449 2450 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 2451 // struct X { int A; } D; D should chain to X. 2452 if (getLangOptions().CPlusPlus) 2453 // FIXME: Look for a way to use RecordDecl for simple structs. 2454 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name, 2455 dyn_cast_or_null<CXXRecordDecl>(PrevDecl)); 2456 else 2457 New = RecordDecl::Create(Context, Kind, DC, Loc, Name, 2458 dyn_cast_or_null<RecordDecl>(PrevDecl)); 2459 2460 // If this has an identifier, add it to the scope stack. 2461 if ((TK == TK_Definition || !PrevDecl) && Name) { 2462 // The scope passed in may not be a decl scope. Zip up the scope tree until 2463 // we find one that is. 2464 while ((S->getFlags() & Scope::DeclScope) == 0) 2465 S = S->getParent(); 2466 2467 // Add it to the decl chain. 2468 PushOnScopeChains(New, S); 2469 } 2470 2471 // Handle #pragma pack: if the #pragma pack stack has non-default 2472 // alignment, make up a packed attribute for this decl. These 2473 // attributes are checked when the ASTContext lays out the 2474 // structure. 2475 // 2476 // It is important for implementing the correct semantics that this 2477 // happen here (in act on tag decl). The #pragma pack stack is 2478 // maintained as a result of parser callbacks which can occur at 2479 // many points during the parsing of a struct declaration (because 2480 // the #pragma tokens are effectively skipped over during the 2481 // parsing of the struct). 2482 if (unsigned Alignment = PackContext.getAlignment()) 2483 New->addAttr(new PackedAttr(Alignment * 8)); 2484 2485 if (Attr) 2486 ProcessDeclAttributeList(New, Attr); 2487 2488 // Set the lexical context. If the tag has a C++ scope specifier, the 2489 // lexical context will be different from the semantic context. 2490 New->setLexicalDeclContext(CurContext); 2491 2492 return New; 2493} 2494 2495 2496/// Collect the instance variables declared in an Objective-C object. Used in 2497/// the creation of structures from objects using the @defs directive. 2498static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx, 2499 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) { 2500 if (Class->getSuperClass()) 2501 CollectIvars(Class->getSuperClass(), Ctx, ivars); 2502 2503 // For each ivar, create a fresh ObjCAtDefsFieldDecl. 2504 for (ObjCInterfaceDecl::ivar_iterator 2505 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) { 2506 2507 ObjCIvarDecl* ID = *I; 2508 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(), 2509 ID->getIdentifier(), 2510 ID->getType(), 2511 ID->getBitWidth())); 2512 } 2513} 2514 2515/// Called whenever @defs(ClassName) is encountered in the source. Inserts the 2516/// instance variables of ClassName into Decls. 2517void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart, 2518 IdentifierInfo *ClassName, 2519 llvm::SmallVectorImpl<DeclTy*> &Decls) { 2520 // Check that ClassName is a valid class 2521 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName); 2522 if (!Class) { 2523 Diag(DeclStart, diag::err_undef_interface, ClassName->getName()); 2524 return; 2525 } 2526 // Collect the instance variables 2527 CollectIvars(Class, Context, Decls); 2528} 2529 2530/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array 2531/// types into constant array types in certain situations which would otherwise 2532/// be errors (for GCC compatibility). 2533static QualType TryToFixInvalidVariablyModifiedType(QualType T, 2534 ASTContext &Context) { 2535 // This method tries to turn a variable array into a constant 2536 // array even when the size isn't an ICE. This is necessary 2537 // for compatibility with code that depends on gcc's buggy 2538 // constant expression folding, like struct {char x[(int)(char*)2];} 2539 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 2540 if (!VLATy) return QualType(); 2541 2542 APValue Result; 2543 if (!VLATy->getSizeExpr() || 2544 !VLATy->getSizeExpr()->Evaluate(Result, Context)) 2545 return QualType(); 2546 2547 assert(Result.isInt() && "Size expressions must be integers!"); 2548 llvm::APSInt &Res = Result.getInt(); 2549 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) 2550 return Context.getConstantArrayType(VLATy->getElementType(), 2551 Res, ArrayType::Normal, 0); 2552 return QualType(); 2553} 2554 2555/// ActOnField - Each field of a struct/union/class is passed into this in order 2556/// to create a FieldDecl object for it. 2557Sema::DeclTy *Sema::ActOnField(Scope *S, 2558 SourceLocation DeclStart, 2559 Declarator &D, ExprTy *BitfieldWidth) { 2560 IdentifierInfo *II = D.getIdentifier(); 2561 Expr *BitWidth = (Expr*)BitfieldWidth; 2562 SourceLocation Loc = DeclStart; 2563 if (II) Loc = D.getIdentifierLoc(); 2564 2565 // FIXME: Unnamed fields can be handled in various different ways, for 2566 // example, unnamed unions inject all members into the struct namespace! 2567 2568 if (BitWidth) { 2569 // TODO: Validate. 2570 //printf("WARNING: BITFIELDS IGNORED!\n"); 2571 2572 // 6.7.2.1p3 2573 // 6.7.2.1p4 2574 2575 } else { 2576 // Not a bitfield. 2577 2578 // validate II. 2579 2580 } 2581 2582 QualType T = GetTypeForDeclarator(D, S); 2583 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 2584 bool InvalidDecl = false; 2585 2586 // C99 6.7.2.1p8: A member of a structure or union may have any type other 2587 // than a variably modified type. 2588 if (T->isVariablyModifiedType()) { 2589 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context); 2590 if (!FixedTy.isNull()) { 2591 Diag(Loc, diag::warn_illegal_constant_array_size); 2592 T = FixedTy; 2593 } else { 2594 Diag(Loc, diag::err_typecheck_field_variable_size); 2595 T = Context.IntTy; 2596 InvalidDecl = true; 2597 } 2598 } 2599 // FIXME: Chain fielddecls together. 2600 FieldDecl *NewFD; 2601 2602 if (getLangOptions().CPlusPlus) { 2603 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs. 2604 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext), 2605 Loc, II, T, 2606 D.getDeclSpec().getStorageClassSpec() == 2607 DeclSpec::SCS_mutable, BitWidth); 2608 if (II) 2609 PushOnScopeChains(NewFD, S); 2610 } 2611 else 2612 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth); 2613 2614 ProcessDeclAttributes(NewFD, D); 2615 2616 if (D.getInvalidType() || InvalidDecl) 2617 NewFD->setInvalidDecl(); 2618 return NewFD; 2619} 2620 2621/// TranslateIvarVisibility - Translate visibility from a token ID to an 2622/// AST enum value. 2623static ObjCIvarDecl::AccessControl 2624TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 2625 switch (ivarVisibility) { 2626 default: assert(0 && "Unknown visitibility kind"); 2627 case tok::objc_private: return ObjCIvarDecl::Private; 2628 case tok::objc_public: return ObjCIvarDecl::Public; 2629 case tok::objc_protected: return ObjCIvarDecl::Protected; 2630 case tok::objc_package: return ObjCIvarDecl::Package; 2631 } 2632} 2633 2634/// ActOnIvar - Each ivar field of an objective-c class is passed into this 2635/// in order to create an IvarDecl object for it. 2636Sema::DeclTy *Sema::ActOnIvar(Scope *S, 2637 SourceLocation DeclStart, 2638 Declarator &D, ExprTy *BitfieldWidth, 2639 tok::ObjCKeywordKind Visibility) { 2640 IdentifierInfo *II = D.getIdentifier(); 2641 Expr *BitWidth = (Expr*)BitfieldWidth; 2642 SourceLocation Loc = DeclStart; 2643 if (II) Loc = D.getIdentifierLoc(); 2644 2645 // FIXME: Unnamed fields can be handled in various different ways, for 2646 // example, unnamed unions inject all members into the struct namespace! 2647 2648 2649 if (BitWidth) { 2650 // TODO: Validate. 2651 //printf("WARNING: BITFIELDS IGNORED!\n"); 2652 2653 // 6.7.2.1p3 2654 // 6.7.2.1p4 2655 2656 } else { 2657 // Not a bitfield. 2658 2659 // validate II. 2660 2661 } 2662 2663 QualType T = GetTypeForDeclarator(D, S); 2664 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 2665 bool InvalidDecl = false; 2666 2667 // C99 6.7.2.1p8: A member of a structure or union may have any type other 2668 // than a variably modified type. 2669 if (T->isVariablyModifiedType()) { 2670 // FIXME: This diagnostic needs work 2671 Diag(Loc, diag::err_typecheck_illegal_vla) << SourceRange(Loc); 2672 InvalidDecl = true; 2673 } 2674 2675 // Get the visibility (access control) for this ivar. 2676 ObjCIvarDecl::AccessControl ac = 2677 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 2678 : ObjCIvarDecl::None; 2679 2680 // Construct the decl. 2681 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac, 2682 (Expr *)BitfieldWidth); 2683 2684 // Process attributes attached to the ivar. 2685 ProcessDeclAttributes(NewID, D); 2686 2687 if (D.getInvalidType() || InvalidDecl) 2688 NewID->setInvalidDecl(); 2689 2690 return NewID; 2691} 2692 2693void Sema::ActOnFields(Scope* S, 2694 SourceLocation RecLoc, DeclTy *RecDecl, 2695 DeclTy **Fields, unsigned NumFields, 2696 SourceLocation LBrac, SourceLocation RBrac, 2697 AttributeList *Attr) { 2698 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl); 2699 assert(EnclosingDecl && "missing record or interface decl"); 2700 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 2701 2702 if (Record) 2703 if (RecordDecl* DefRecord = Record->getDefinition(Context)) { 2704 // Diagnose code like: 2705 // struct S { struct S {} X; }; 2706 // We discover this when we complete the outer S. Reject and ignore the 2707 // outer S. 2708 Diag(DefRecord->getLocation(), diag::err_nested_redefinition, 2709 DefRecord->getKindName()); 2710 Diag(RecLoc, diag::err_previous_definition); 2711 Record->setInvalidDecl(); 2712 return; 2713 } 2714 2715 // Verify that all the fields are okay. 2716 unsigned NumNamedMembers = 0; 2717 llvm::SmallVector<FieldDecl*, 32> RecFields; 2718 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs; 2719 2720 for (unsigned i = 0; i != NumFields; ++i) { 2721 2722 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i])); 2723 assert(FD && "missing field decl"); 2724 2725 // Remember all fields. 2726 RecFields.push_back(FD); 2727 2728 // Get the type for the field. 2729 Type *FDTy = FD->getType().getTypePtr(); 2730 2731 // C99 6.7.2.1p2 - A field may not be a function type. 2732 if (FDTy->isFunctionType()) { 2733 Diag(FD->getLocation(), diag::err_field_declared_as_function, 2734 FD->getName()); 2735 FD->setInvalidDecl(); 2736 EnclosingDecl->setInvalidDecl(); 2737 continue; 2738 } 2739 // C99 6.7.2.1p2 - A field may not be an incomplete type except... 2740 if (FDTy->isIncompleteType()) { 2741 if (!Record) { // Incomplete ivar type is always an error. 2742 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName()); 2743 FD->setInvalidDecl(); 2744 EnclosingDecl->setInvalidDecl(); 2745 continue; 2746 } 2747 if (i != NumFields-1 || // ... that the last member ... 2748 !Record->isStruct() || // ... of a structure ... 2749 !FDTy->isArrayType()) { //... may have incomplete array type. 2750 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName()); 2751 FD->setInvalidDecl(); 2752 EnclosingDecl->setInvalidDecl(); 2753 continue; 2754 } 2755 if (NumNamedMembers < 1) { //... must have more than named member ... 2756 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct, 2757 FD->getName()); 2758 FD->setInvalidDecl(); 2759 EnclosingDecl->setInvalidDecl(); 2760 continue; 2761 } 2762 // Okay, we have a legal flexible array member at the end of the struct. 2763 if (Record) 2764 Record->setHasFlexibleArrayMember(true); 2765 } 2766 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the 2767 /// field of another structure or the element of an array. 2768 if (const RecordType *FDTTy = FDTy->getAsRecordType()) { 2769 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 2770 // If this is a member of a union, then entire union becomes "flexible". 2771 if (Record && Record->isUnion()) { 2772 Record->setHasFlexibleArrayMember(true); 2773 } else { 2774 // If this is a struct/class and this is not the last element, reject 2775 // it. Note that GCC supports variable sized arrays in the middle of 2776 // structures. 2777 if (i != NumFields-1) { 2778 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct, 2779 FD->getName()); 2780 FD->setInvalidDecl(); 2781 EnclosingDecl->setInvalidDecl(); 2782 continue; 2783 } 2784 // We support flexible arrays at the end of structs in other structs 2785 // as an extension. 2786 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct, 2787 FD->getName()); 2788 if (Record) 2789 Record->setHasFlexibleArrayMember(true); 2790 } 2791 } 2792 } 2793 /// A field cannot be an Objective-c object 2794 if (FDTy->isObjCInterfaceType()) { 2795 Diag(FD->getLocation(), diag::err_statically_allocated_object, 2796 FD->getName()); 2797 FD->setInvalidDecl(); 2798 EnclosingDecl->setInvalidDecl(); 2799 continue; 2800 } 2801 // Keep track of the number of named members. 2802 if (IdentifierInfo *II = FD->getIdentifier()) { 2803 // Detect duplicate member names. 2804 if (!FieldIDs.insert(II)) { 2805 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName()); 2806 // Find the previous decl. 2807 SourceLocation PrevLoc; 2808 for (unsigned i = 0; ; ++i) { 2809 assert(i != RecFields.size() && "Didn't find previous def!"); 2810 if (RecFields[i]->getIdentifier() == II) { 2811 PrevLoc = RecFields[i]->getLocation(); 2812 break; 2813 } 2814 } 2815 Diag(PrevLoc, diag::err_previous_definition); 2816 FD->setInvalidDecl(); 2817 EnclosingDecl->setInvalidDecl(); 2818 continue; 2819 } 2820 ++NumNamedMembers; 2821 } 2822 } 2823 2824 // Okay, we successfully defined 'Record'. 2825 if (Record) { 2826 Record->defineBody(Context, &RecFields[0], RecFields.size()); 2827 // If this is a C++ record, HandleTagDeclDefinition will be invoked in 2828 // Sema::ActOnFinishCXXClassDef. 2829 if (!isa<CXXRecordDecl>(Record)) 2830 Consumer.HandleTagDeclDefinition(Record); 2831 } else { 2832 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]); 2833 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) 2834 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac); 2835 else if (ObjCImplementationDecl *IMPDecl = 2836 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 2837 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 2838 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size()); 2839 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 2840 } 2841 } 2842 2843 if (Attr) 2844 ProcessDeclAttributeList(Record, Attr); 2845} 2846 2847Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl, 2848 DeclTy *lastEnumConst, 2849 SourceLocation IdLoc, IdentifierInfo *Id, 2850 SourceLocation EqualLoc, ExprTy *val) { 2851 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl)); 2852 EnumConstantDecl *LastEnumConst = 2853 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst)); 2854 Expr *Val = static_cast<Expr*>(val); 2855 2856 // The scope passed in may not be a decl scope. Zip up the scope tree until 2857 // we find one that is. 2858 while ((S->getFlags() & Scope::DeclScope) == 0) 2859 S = S->getParent(); 2860 2861 // Verify that there isn't already something declared with this name in this 2862 // scope. 2863 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) { 2864 // When in C++, we may get a TagDecl with the same name; in this case the 2865 // enum constant will 'hide' the tag. 2866 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 2867 "Received TagDecl when not in C++!"); 2868 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 2869 if (isa<EnumConstantDecl>(PrevDecl)) 2870 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName()); 2871 else 2872 Diag(IdLoc, diag::err_redefinition, Id->getName()); 2873 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 2874 delete Val; 2875 return 0; 2876 } 2877 } 2878 2879 llvm::APSInt EnumVal(32); 2880 QualType EltTy; 2881 if (Val) { 2882 // Make sure to promote the operand type to int. 2883 UsualUnaryConversions(Val); 2884 2885 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 2886 SourceLocation ExpLoc; 2887 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) { 2888 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr, 2889 Id->getName()); 2890 delete Val; 2891 Val = 0; // Just forget about it. 2892 } else { 2893 EltTy = Val->getType(); 2894 } 2895 } 2896 2897 if (!Val) { 2898 if (LastEnumConst) { 2899 // Assign the last value + 1. 2900 EnumVal = LastEnumConst->getInitVal(); 2901 ++EnumVal; 2902 2903 // Check for overflow on increment. 2904 if (EnumVal < LastEnumConst->getInitVal()) 2905 Diag(IdLoc, diag::warn_enum_value_overflow); 2906 2907 EltTy = LastEnumConst->getType(); 2908 } else { 2909 // First value, set to zero. 2910 EltTy = Context.IntTy; 2911 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy))); 2912 } 2913 } 2914 2915 EnumConstantDecl *New = 2916 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy, 2917 Val, EnumVal, 2918 LastEnumConst); 2919 2920 // Register this decl in the current scope stack. 2921 PushOnScopeChains(New, S); 2922 return New; 2923} 2924 2925// FIXME: For consistency with ActOnFields(), we should have the parser 2926// pass in the source location for the left/right braces. 2927void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX, 2928 DeclTy **Elements, unsigned NumElements) { 2929 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX)); 2930 2931 if (Enum && Enum->isDefinition()) { 2932 // Diagnose code like: 2933 // enum e0 { 2934 // E0 = sizeof(enum e0 { E1 }) 2935 // }; 2936 Diag(Enum->getLocation(), diag::err_nested_redefinition, 2937 Enum->getName()); 2938 Diag(EnumLoc, diag::err_previous_definition); 2939 Enum->setInvalidDecl(); 2940 return; 2941 } 2942 // TODO: If the result value doesn't fit in an int, it must be a long or long 2943 // long value. ISO C does not support this, but GCC does as an extension, 2944 // emit a warning. 2945 unsigned IntWidth = Context.Target.getIntWidth(); 2946 2947 // Verify that all the values are okay, compute the size of the values, and 2948 // reverse the list. 2949 unsigned NumNegativeBits = 0; 2950 unsigned NumPositiveBits = 0; 2951 2952 // Keep track of whether all elements have type int. 2953 bool AllElementsInt = true; 2954 2955 EnumConstantDecl *EltList = 0; 2956 for (unsigned i = 0; i != NumElements; ++i) { 2957 EnumConstantDecl *ECD = 2958 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 2959 if (!ECD) continue; // Already issued a diagnostic. 2960 2961 // If the enum value doesn't fit in an int, emit an extension warning. 2962 const llvm::APSInt &InitVal = ECD->getInitVal(); 2963 assert(InitVal.getBitWidth() >= IntWidth && 2964 "Should have promoted value to int"); 2965 if (InitVal.getBitWidth() > IntWidth) { 2966 llvm::APSInt V(InitVal); 2967 V.trunc(IntWidth); 2968 V.extend(InitVal.getBitWidth()); 2969 if (V != InitVal) 2970 Diag(ECD->getLocation(), diag::ext_enum_value_not_int, 2971 InitVal.toString(10)); 2972 } 2973 2974 // Keep track of the size of positive and negative values. 2975 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 2976 NumPositiveBits = std::max(NumPositiveBits, 2977 (unsigned)InitVal.getActiveBits()); 2978 else 2979 NumNegativeBits = std::max(NumNegativeBits, 2980 (unsigned)InitVal.getMinSignedBits()); 2981 2982 // Keep track of whether every enum element has type int (very commmon). 2983 if (AllElementsInt) 2984 AllElementsInt = ECD->getType() == Context.IntTy; 2985 2986 ECD->setNextDeclarator(EltList); 2987 EltList = ECD; 2988 } 2989 2990 // Figure out the type that should be used for this enum. 2991 // FIXME: Support attribute(packed) on enums and -fshort-enums. 2992 QualType BestType; 2993 unsigned BestWidth; 2994 2995 if (NumNegativeBits) { 2996 // If there is a negative value, figure out the smallest integer type (of 2997 // int/long/longlong) that fits. 2998 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 2999 BestType = Context.IntTy; 3000 BestWidth = IntWidth; 3001 } else { 3002 BestWidth = Context.Target.getLongWidth(); 3003 3004 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) 3005 BestType = Context.LongTy; 3006 else { 3007 BestWidth = Context.Target.getLongLongWidth(); 3008 3009 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 3010 Diag(Enum->getLocation(), diag::warn_enum_too_large); 3011 BestType = Context.LongLongTy; 3012 } 3013 } 3014 } else { 3015 // If there is no negative value, figure out which of uint, ulong, ulonglong 3016 // fits. 3017 if (NumPositiveBits <= IntWidth) { 3018 BestType = Context.UnsignedIntTy; 3019 BestWidth = IntWidth; 3020 } else if (NumPositiveBits <= 3021 (BestWidth = Context.Target.getLongWidth())) { 3022 BestType = Context.UnsignedLongTy; 3023 } else { 3024 BestWidth = Context.Target.getLongLongWidth(); 3025 assert(NumPositiveBits <= BestWidth && 3026 "How could an initializer get larger than ULL?"); 3027 BestType = Context.UnsignedLongLongTy; 3028 } 3029 } 3030 3031 // Loop over all of the enumerator constants, changing their types to match 3032 // the type of the enum if needed. 3033 for (unsigned i = 0; i != NumElements; ++i) { 3034 EnumConstantDecl *ECD = 3035 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 3036 if (!ECD) continue; // Already issued a diagnostic. 3037 3038 // Standard C says the enumerators have int type, but we allow, as an 3039 // extension, the enumerators to be larger than int size. If each 3040 // enumerator value fits in an int, type it as an int, otherwise type it the 3041 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 3042 // that X has type 'int', not 'unsigned'. 3043 if (ECD->getType() == Context.IntTy) { 3044 // Make sure the init value is signed. 3045 llvm::APSInt IV = ECD->getInitVal(); 3046 IV.setIsSigned(true); 3047 ECD->setInitVal(IV); 3048 continue; // Already int type. 3049 } 3050 3051 // Determine whether the value fits into an int. 3052 llvm::APSInt InitVal = ECD->getInitVal(); 3053 bool FitsInInt; 3054 if (InitVal.isUnsigned() || !InitVal.isNegative()) 3055 FitsInInt = InitVal.getActiveBits() < IntWidth; 3056 else 3057 FitsInInt = InitVal.getMinSignedBits() <= IntWidth; 3058 3059 // If it fits into an integer type, force it. Otherwise force it to match 3060 // the enum decl type. 3061 QualType NewTy; 3062 unsigned NewWidth; 3063 bool NewSign; 3064 if (FitsInInt) { 3065 NewTy = Context.IntTy; 3066 NewWidth = IntWidth; 3067 NewSign = true; 3068 } else if (ECD->getType() == BestType) { 3069 // Already the right type! 3070 continue; 3071 } else { 3072 NewTy = BestType; 3073 NewWidth = BestWidth; 3074 NewSign = BestType->isSignedIntegerType(); 3075 } 3076 3077 // Adjust the APSInt value. 3078 InitVal.extOrTrunc(NewWidth); 3079 InitVal.setIsSigned(NewSign); 3080 ECD->setInitVal(InitVal); 3081 3082 // Adjust the Expr initializer and type. 3083 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(), 3084 /*isLvalue=*/false)); 3085 ECD->setType(NewTy); 3086 } 3087 3088 Enum->defineElements(EltList, BestType); 3089 Consumer.HandleTagDeclDefinition(Enum); 3090} 3091 3092Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, 3093 ExprTy *expr) { 3094 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr); 3095 3096 return FileScopeAsmDecl::Create(Context, Loc, AsmString); 3097} 3098 3099Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc, 3100 SourceLocation LBrace, 3101 SourceLocation RBrace, 3102 const char *Lang, 3103 unsigned StrSize, 3104 DeclTy *D) { 3105 LinkageSpecDecl::LanguageIDs Language; 3106 Decl *dcl = static_cast<Decl *>(D); 3107 if (strncmp(Lang, "\"C\"", StrSize) == 0) 3108 Language = LinkageSpecDecl::lang_c; 3109 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 3110 Language = LinkageSpecDecl::lang_cxx; 3111 else { 3112 Diag(Loc, diag::err_bad_language); 3113 return 0; 3114 } 3115 3116 // FIXME: Add all the various semantics of linkage specifications 3117 return LinkageSpecDecl::Create(Context, Loc, Language, dcl); 3118} 3119 3120void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name, 3121 ExprTy *alignment, SourceLocation PragmaLoc, 3122 SourceLocation LParenLoc, SourceLocation RParenLoc) { 3123 Expr *Alignment = static_cast<Expr *>(alignment); 3124 3125 // If specified then alignment must be a "small" power of two. 3126 unsigned AlignmentVal = 0; 3127 if (Alignment) { 3128 llvm::APSInt Val; 3129 if (!Alignment->isIntegerConstantExpr(Val, Context) || 3130 !Val.isPowerOf2() || 3131 Val.getZExtValue() > 16) { 3132 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment); 3133 delete Alignment; 3134 return; // Ignore 3135 } 3136 3137 AlignmentVal = (unsigned) Val.getZExtValue(); 3138 } 3139 3140 switch (Kind) { 3141 case Action::PPK_Default: // pack([n]) 3142 PackContext.setAlignment(AlignmentVal); 3143 break; 3144 3145 case Action::PPK_Show: // pack(show) 3146 // Show the current alignment, making sure to show the right value 3147 // for the default. 3148 AlignmentVal = PackContext.getAlignment(); 3149 // FIXME: This should come from the target. 3150 if (AlignmentVal == 0) 3151 AlignmentVal = 8; 3152 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal; 3153 break; 3154 3155 case Action::PPK_Push: // pack(push [, id] [, [n]) 3156 PackContext.push(Name); 3157 // Set the new alignment if specified. 3158 if (Alignment) 3159 PackContext.setAlignment(AlignmentVal); 3160 break; 3161 3162 case Action::PPK_Pop: // pack(pop [, id] [, n]) 3163 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack: 3164 // "#pragma pack(pop, identifier, n) is undefined" 3165 if (Alignment && Name) 3166 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment); 3167 3168 // Do the pop. 3169 if (!PackContext.pop(Name)) { 3170 // If a name was specified then failure indicates the name 3171 // wasn't found. Otherwise failure indicates the stack was 3172 // empty. 3173 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed, 3174 Name ? "no record matching name" : "stack empty"); 3175 3176 // FIXME: Warn about popping named records as MSVC does. 3177 } else { 3178 // Pop succeeded, set the new alignment if specified. 3179 if (Alignment) 3180 PackContext.setAlignment(AlignmentVal); 3181 } 3182 break; 3183 3184 default: 3185 assert(0 && "Invalid #pragma pack kind."); 3186 } 3187} 3188 3189bool PragmaPackStack::pop(IdentifierInfo *Name) { 3190 if (Stack.empty()) 3191 return false; 3192 3193 // If name is empty just pop top. 3194 if (!Name) { 3195 Alignment = Stack.back().first; 3196 Stack.pop_back(); 3197 return true; 3198 } 3199 3200 // Otherwise, find the named record. 3201 for (unsigned i = Stack.size(); i != 0; ) { 3202 --i; 3203 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) { 3204 // Found it, pop up to and including this record. 3205 Alignment = Stack[i].first; 3206 Stack.erase(Stack.begin() + i, Stack.end()); 3207 return true; 3208 } 3209 } 3210 3211 return false; 3212} 3213