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