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