SemaDecl.cpp revision 27a84d01614609c094029a49f7a86f0f7f8fe7f1
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 "SemaInherit.h" 16#include "clang/AST/APValue.h" 17#include "clang/AST/ASTConsumer.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/Analysis/CFG.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/AST/DeclTemplate.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/StmtCXX.h" 24#include "clang/AST/StmtObjC.h" 25#include "clang/Parse/DeclSpec.h" 26#include "clang/Basic/PartialDiagnostic.h" 27#include "clang/Basic/SourceManager.h" 28#include "clang/Basic/TargetInfo.h" 29// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's) 30#include "clang/Lex/Preprocessor.h" 31#include "clang/Lex/HeaderSearch.h" 32#include "llvm/ADT/BitVector.h" 33#include "llvm/ADT/STLExtras.h" 34#include <algorithm> 35#include <cstring> 36#include <functional> 37#include <queue> 38using namespace clang; 39 40/// getDeclName - Return a pretty name for the specified decl if possible, or 41/// an empty string if not. This is used for pretty crash reporting. 42std::string Sema::getDeclName(DeclPtrTy d) { 43 Decl *D = d.getAs<Decl>(); 44 if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D)) 45 return DN->getQualifiedNameAsString(); 46 return ""; 47} 48 49Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) { 50 return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>())); 51} 52 53/// \brief If the identifier refers to a type name within this scope, 54/// return the declaration of that type. 55/// 56/// This routine performs ordinary name lookup of the identifier II 57/// within the given scope, with optional C++ scope specifier SS, to 58/// determine whether the name refers to a type. If so, returns an 59/// opaque pointer (actually a QualType) corresponding to that 60/// type. Otherwise, returns NULL. 61/// 62/// If name lookup results in an ambiguity, this routine will complain 63/// and then return NULL. 64Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 65 Scope *S, const CXXScopeSpec *SS, 66 bool isClassName) { 67 // C++ [temp.res]p3: 68 // A qualified-id that refers to a type and in which the 69 // nested-name-specifier depends on a template-parameter (14.6.2) 70 // shall be prefixed by the keyword typename to indicate that the 71 // qualified-id denotes a type, forming an 72 // elaborated-type-specifier (7.1.5.3). 73 // 74 // We therefore do not perform any name lookup if the result would 75 // refer to a member of an unknown specialization. 76 if (SS && isUnknownSpecialization(*SS)) { 77 if (!isClassName) 78 return 0; 79 80 // We know from the grammar that this name refers to a type, so build a 81 // TypenameType node to describe the type. 82 // FIXME: Record somewhere that this TypenameType node has no "typename" 83 // keyword associated with it. 84 return CheckTypenameType((NestedNameSpecifier *)SS->getScopeRep(), 85 II, SS->getRange()).getAsOpaquePtr(); 86 } 87 88 LookupResult Result 89 = LookupParsedName(S, SS, &II, LookupOrdinaryName, false, false); 90 91 NamedDecl *IIDecl = 0; 92 switch (Result.getKind()) { 93 case LookupResult::NotFound: 94 case LookupResult::FoundOverloaded: 95 return 0; 96 97 case LookupResult::AmbiguousBaseSubobjectTypes: 98 case LookupResult::AmbiguousBaseSubobjects: 99 case LookupResult::AmbiguousReference: { 100 // Look to see if we have a type anywhere in the list of results. 101 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 102 Res != ResEnd; ++Res) { 103 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 104 if (!IIDecl || 105 (*Res)->getLocation().getRawEncoding() < 106 IIDecl->getLocation().getRawEncoding()) 107 IIDecl = *Res; 108 } 109 } 110 111 if (!IIDecl) { 112 // None of the entities we found is a type, so there is no way 113 // to even assume that the result is a type. In this case, don't 114 // complain about the ambiguity. The parser will either try to 115 // perform this lookup again (e.g., as an object name), which 116 // will produce the ambiguity, or will complain that it expected 117 // a type name. 118 Result.Destroy(); 119 return 0; 120 } 121 122 // We found a type within the ambiguous lookup; diagnose the 123 // ambiguity and then return that type. This might be the right 124 // answer, or it might not be, but it suppresses any attempt to 125 // perform the name lookup again. 126 DiagnoseAmbiguousLookup(Result, DeclarationName(&II), NameLoc); 127 break; 128 } 129 130 case LookupResult::Found: 131 IIDecl = Result.getAsDecl(); 132 break; 133 } 134 135 if (IIDecl) { 136 QualType T; 137 138 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 139 // Check whether we can use this type 140 (void)DiagnoseUseOfDecl(IIDecl, NameLoc); 141 142 if (getLangOptions().CPlusPlus) { 143 // C++ [temp.local]p2: 144 // Within the scope of a class template specialization or 145 // partial specialization, when the injected-class-name is 146 // not followed by a <, it is equivalent to the 147 // injected-class-name followed by the template-argument s 148 // of the class template specialization or partial 149 // specialization enclosed in <>. 150 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) 151 if (RD->isInjectedClassName()) 152 if (ClassTemplateDecl *Template = RD->getDescribedClassTemplate()) 153 T = Template->getInjectedClassNameType(Context); 154 } 155 156 if (T.isNull()) 157 T = Context.getTypeDeclType(TD); 158 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 159 // Check whether we can use this interface. 160 (void)DiagnoseUseOfDecl(IIDecl, NameLoc); 161 162 T = Context.getObjCInterfaceType(IDecl); 163 } else 164 return 0; 165 166 if (SS) 167 T = getQualifiedNameType(*SS, T); 168 169 return T.getAsOpaquePtr(); 170 } 171 172 return 0; 173} 174 175/// isTagName() - This method is called *for error recovery purposes only* 176/// to determine if the specified name is a valid tag name ("struct foo"). If 177/// so, this returns the TST for the tag corresponding to it (TST_enum, 178/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C 179/// where the user forgot to specify the tag. 180DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 181 // Do a tag name lookup in this scope. 182 LookupResult R = LookupName(S, &II, LookupTagName, false, false); 183 if (R.getKind() == LookupResult::Found) 184 if (const TagDecl *TD = dyn_cast<TagDecl>(R.getAsDecl())) { 185 switch (TD->getTagKind()) { 186 case TagDecl::TK_struct: return DeclSpec::TST_struct; 187 case TagDecl::TK_union: return DeclSpec::TST_union; 188 case TagDecl::TK_class: return DeclSpec::TST_class; 189 case TagDecl::TK_enum: return DeclSpec::TST_enum; 190 } 191 } 192 193 return DeclSpec::TST_unspecified; 194} 195 196 197// Determines the context to return to after temporarily entering a 198// context. This depends in an unnecessarily complicated way on the 199// exact ordering of callbacks from the parser. 200DeclContext *Sema::getContainingDC(DeclContext *DC) { 201 202 // Functions defined inline within classes aren't parsed until we've 203 // finished parsing the top-level class, so the top-level class is 204 // the context we'll need to return to. 205 if (isa<FunctionDecl>(DC)) { 206 DC = DC->getLexicalParent(); 207 208 // A function not defined within a class will always return to its 209 // lexical context. 210 if (!isa<CXXRecordDecl>(DC)) 211 return DC; 212 213 // A C++ inline method/friend is parsed *after* the topmost class 214 // it was declared in is fully parsed ("complete"); the topmost 215 // class is the context we need to return to. 216 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 217 DC = RD; 218 219 // Return the declaration context of the topmost class the inline method is 220 // declared in. 221 return DC; 222 } 223 224 if (isa<ObjCMethodDecl>(DC)) 225 return Context.getTranslationUnitDecl(); 226 227 return DC->getLexicalParent(); 228} 229 230void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 231 assert(getContainingDC(DC) == CurContext && 232 "The next DeclContext should be lexically contained in the current one."); 233 CurContext = DC; 234 S->setEntity(DC); 235} 236 237void Sema::PopDeclContext() { 238 assert(CurContext && "DeclContext imbalance!"); 239 240 CurContext = getContainingDC(CurContext); 241} 242 243/// EnterDeclaratorContext - Used when we must lookup names in the context 244/// of a declarator's nested name specifier. 245void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 246 assert(PreDeclaratorDC == 0 && "Previous declarator context not popped?"); 247 PreDeclaratorDC = static_cast<DeclContext*>(S->getEntity()); 248 CurContext = DC; 249 assert(CurContext && "No context?"); 250 S->setEntity(CurContext); 251} 252 253void Sema::ExitDeclaratorContext(Scope *S) { 254 S->setEntity(PreDeclaratorDC); 255 PreDeclaratorDC = 0; 256 257 // Reset CurContext to the nearest enclosing context. 258 while (!S->getEntity() && S->getParent()) 259 S = S->getParent(); 260 CurContext = static_cast<DeclContext*>(S->getEntity()); 261 assert(CurContext && "No context?"); 262} 263 264/// \brief Determine whether we allow overloading of the function 265/// PrevDecl with another declaration. 266/// 267/// This routine determines whether overloading is possible, not 268/// whether some new function is actually an overload. It will return 269/// true in C++ (where we can always provide overloads) or, as an 270/// extension, in C when the previous function is already an 271/// overloaded function declaration or has the "overloadable" 272/// attribute. 273static bool AllowOverloadingOfFunction(Decl *PrevDecl, ASTContext &Context) { 274 if (Context.getLangOptions().CPlusPlus) 275 return true; 276 277 if (isa<OverloadedFunctionDecl>(PrevDecl)) 278 return true; 279 280 return PrevDecl->getAttr<OverloadableAttr>() != 0; 281} 282 283/// Add this decl to the scope shadowed decl chains. 284void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 285 // Move up the scope chain until we find the nearest enclosing 286 // non-transparent context. The declaration will be introduced into this 287 // scope. 288 while (S->getEntity() && 289 ((DeclContext *)S->getEntity())->isTransparentContext()) 290 S = S->getParent(); 291 292 // Add scoped declarations into their context, so that they can be 293 // found later. Declarations without a context won't be inserted 294 // into any context. 295 if (AddToContext) 296 CurContext->addDecl(D); 297 298 // Out-of-line function and variable definitions should not be pushed into 299 // scope. 300 if ((isa<FunctionTemplateDecl>(D) && 301 cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->isOutOfLine()) || 302 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isOutOfLine()) || 303 (isa<VarDecl>(D) && cast<VarDecl>(D)->isOutOfLine())) 304 return; 305 306 S->AddDecl(DeclPtrTy::make(D)); 307 308 // C++ [basic.scope]p4: 309 // -- exactly one declaration shall declare a class name or 310 // enumeration name that is not a typedef name and the other 311 // declarations shall all refer to the same object or 312 // enumerator, or all refer to functions and function templates; 313 // in this case the class name or enumeration name is hidden. 314 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 315 // We are pushing the name of a tag (enum or class). 316 if (CurContext->getLookupContext() 317 == TD->getDeclContext()->getLookupContext()) { 318 // We're pushing the tag into the current context, which might 319 // require some reshuffling in the identifier resolver. 320 IdentifierResolver::iterator 321 I = IdResolver.begin(TD->getDeclName()), 322 IEnd = IdResolver.end(); 323 NamedDecl *ID = *I; 324 if (I != IEnd && isDeclInScope(ID, CurContext, S)) { 325 NamedDecl *PrevDecl = *I; 326 for (; I != IEnd && isDeclInScope(ID, CurContext, S); 327 PrevDecl = *I, ++I) { 328 if (TD->declarationReplaces(*I)) { 329 // This is a redeclaration. Remove it from the chain and 330 // break out, so that we'll add in the shadowed 331 // declaration. 332 S->RemoveDecl(DeclPtrTy::make(*I)); 333 if (PrevDecl == *I) { 334 IdResolver.RemoveDecl(*I); 335 IdResolver.AddDecl(TD); 336 return; 337 } else { 338 IdResolver.RemoveDecl(*I); 339 break; 340 } 341 } 342 } 343 344 // There is already a declaration with the same name in the same 345 // scope, which is not a tag declaration. It must be found 346 // before we find the new declaration, so insert the new 347 // declaration at the end of the chain. 348 IdResolver.AddShadowedDecl(TD, PrevDecl); 349 350 return; 351 } 352 } 353 } else if ((isa<FunctionDecl>(D) && 354 AllowOverloadingOfFunction(D, Context)) || 355 isa<FunctionTemplateDecl>(D)) { 356 // We are pushing the name of a function or function template, 357 // which might be an overloaded name. 358 IdentifierResolver::iterator Redecl 359 = std::find_if(IdResolver.begin(D->getDeclName()), 360 IdResolver.end(), 361 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces), 362 D)); 363 if (Redecl != IdResolver.end() && 364 S->isDeclScope(DeclPtrTy::make(*Redecl))) { 365 // There is already a declaration of a function on our 366 // IdResolver chain. Replace it with this declaration. 367 S->RemoveDecl(DeclPtrTy::make(*Redecl)); 368 IdResolver.RemoveDecl(*Redecl); 369 } 370 } else if (isa<ObjCInterfaceDecl>(D)) { 371 // We're pushing an Objective-C interface into the current 372 // context. If there is already an alias declaration, remove it first. 373 for (IdentifierResolver::iterator 374 I = IdResolver.begin(D->getDeclName()), IEnd = IdResolver.end(); 375 I != IEnd; ++I) { 376 if (isa<ObjCCompatibleAliasDecl>(*I)) { 377 S->RemoveDecl(DeclPtrTy::make(*I)); 378 IdResolver.RemoveDecl(*I); 379 break; 380 } 381 } 382 } 383 384 IdResolver.AddDecl(D); 385} 386 387bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) { 388 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) { 389 // Look inside the overload set to determine if any of the declarations 390 // are in scope. (Possibly) build a new overload set containing only 391 // those declarations that are in scope. 392 OverloadedFunctionDecl *NewOvl = 0; 393 bool FoundInScope = false; 394 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 395 FEnd = Ovl->function_end(); 396 F != FEnd; ++F) { 397 NamedDecl *FD = F->get(); 398 if (!isDeclInScope(FD, Ctx, S)) { 399 if (!NewOvl && F != Ovl->function_begin()) { 400 NewOvl = OverloadedFunctionDecl::Create(Context, 401 F->get()->getDeclContext(), 402 F->get()->getDeclName()); 403 D = NewOvl; 404 for (OverloadedFunctionDecl::function_iterator 405 First = Ovl->function_begin(); 406 First != F; ++First) 407 NewOvl->addOverload(*First); 408 } 409 } else { 410 FoundInScope = true; 411 if (NewOvl) 412 NewOvl->addOverload(*F); 413 } 414 } 415 416 return FoundInScope; 417 } 418 419 return IdResolver.isDeclInScope(D, Ctx, Context, S); 420} 421 422void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 423 if (S->decl_empty()) return; 424 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 425 "Scope shouldn't contain decls!"); 426 427 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 428 I != E; ++I) { 429 Decl *TmpD = (*I).getAs<Decl>(); 430 assert(TmpD && "This decl didn't get pushed??"); 431 432 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 433 NamedDecl *D = cast<NamedDecl>(TmpD); 434 435 if (!D->getDeclName()) continue; 436 437 // Remove this name from our lexical scope. 438 IdResolver.RemoveDecl(D); 439 } 440} 441 442/// getObjCInterfaceDecl - Look up a for a class declaration in the scope. 443/// return 0 if one not found. 444ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) { 445 // The third "scope" argument is 0 since we aren't enabling lazy built-in 446 // creation from this context. 447 NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName); 448 449 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 450} 451 452/// getNonFieldDeclScope - Retrieves the innermost scope, starting 453/// from S, where a non-field would be declared. This routine copes 454/// with the difference between C and C++ scoping rules in structs and 455/// unions. For example, the following code is well-formed in C but 456/// ill-formed in C++: 457/// @code 458/// struct S6 { 459/// enum { BAR } e; 460/// }; 461/// 462/// void test_S6() { 463/// struct S6 a; 464/// a.e = BAR; 465/// } 466/// @endcode 467/// For the declaration of BAR, this routine will return a different 468/// scope. The scope S will be the scope of the unnamed enumeration 469/// within S6. In C++, this routine will return the scope associated 470/// with S6, because the enumeration's scope is a transparent 471/// context but structures can contain non-field names. In C, this 472/// routine will return the translation unit scope, since the 473/// enumeration's scope is a transparent context and structures cannot 474/// contain non-field names. 475Scope *Sema::getNonFieldDeclScope(Scope *S) { 476 while (((S->getFlags() & Scope::DeclScope) == 0) || 477 (S->getEntity() && 478 ((DeclContext *)S->getEntity())->isTransparentContext()) || 479 (S->isClassScope() && !getLangOptions().CPlusPlus)) 480 S = S->getParent(); 481 return S; 482} 483 484void Sema::InitBuiltinVaListType() { 485 if (!Context.getBuiltinVaListType().isNull()) 486 return; 487 488 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list"); 489 NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName); 490 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl); 491 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef)); 492} 493 494/// LazilyCreateBuiltin - The specified Builtin-ID was first used at 495/// file scope. lazily create a decl for it. ForRedeclaration is true 496/// if we're creating this built-in in anticipation of redeclaring the 497/// built-in. 498NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 499 Scope *S, bool ForRedeclaration, 500 SourceLocation Loc) { 501 Builtin::ID BID = (Builtin::ID)bid; 502 503 if (Context.BuiltinInfo.hasVAListUse(BID)) 504 InitBuiltinVaListType(); 505 506 ASTContext::GetBuiltinTypeError Error; 507 QualType R = Context.GetBuiltinType(BID, Error); 508 switch (Error) { 509 case ASTContext::GE_None: 510 // Okay 511 break; 512 513 case ASTContext::GE_Missing_stdio: 514 if (ForRedeclaration) 515 Diag(Loc, diag::err_implicit_decl_requires_stdio) 516 << Context.BuiltinInfo.GetName(BID); 517 return 0; 518 519 case ASTContext::GE_Missing_setjmp: 520 if (ForRedeclaration) 521 Diag(Loc, diag::err_implicit_decl_requires_setjmp) 522 << Context.BuiltinInfo.GetName(BID); 523 return 0; 524 } 525 526 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 527 Diag(Loc, diag::ext_implicit_lib_function_decl) 528 << Context.BuiltinInfo.GetName(BID) 529 << R; 530 if (Context.BuiltinInfo.getHeaderName(BID) && 531 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl) 532 != Diagnostic::Ignored) 533 Diag(Loc, diag::note_please_include_header) 534 << Context.BuiltinInfo.getHeaderName(BID) 535 << Context.BuiltinInfo.GetName(BID); 536 } 537 538 FunctionDecl *New = FunctionDecl::Create(Context, 539 Context.getTranslationUnitDecl(), 540 Loc, II, R, /*DInfo=*/0, 541 FunctionDecl::Extern, false, 542 /*hasPrototype=*/true); 543 New->setImplicit(); 544 545 // Create Decl objects for each parameter, adding them to the 546 // FunctionDecl. 547 if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 548 llvm::SmallVector<ParmVarDecl*, 16> Params; 549 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) 550 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0, 551 FT->getArgType(i), /*DInfo=*/0, 552 VarDecl::None, 0)); 553 New->setParams(Context, Params.data(), Params.size()); 554 } 555 556 AddKnownFunctionAttributes(New); 557 558 // TUScope is the translation-unit scope to insert this function into. 559 // FIXME: This is hideous. We need to teach PushOnScopeChains to 560 // relate Scopes to DeclContexts, and probably eliminate CurContext 561 // entirely, but we're not there yet. 562 DeclContext *SavedContext = CurContext; 563 CurContext = Context.getTranslationUnitDecl(); 564 PushOnScopeChains(New, TUScope); 565 CurContext = SavedContext; 566 return New; 567} 568 569/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the 570/// same name and scope as a previous declaration 'Old'. Figure out 571/// how to resolve this situation, merging decls or emitting 572/// diagnostics as appropriate. If there was an error, set New to be invalid. 573/// 574void Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) { 575 // If either decl is known invalid already, set the new one to be invalid and 576 // don't bother doing any merging checks. 577 if (New->isInvalidDecl() || OldD->isInvalidDecl()) 578 return New->setInvalidDecl(); 579 580 // Allow multiple definitions for ObjC built-in typedefs. 581 // FIXME: Verify the underlying types are equivalent! 582 if (getLangOptions().ObjC1) { 583 const IdentifierInfo *TypeID = New->getIdentifier(); 584 switch (TypeID->getLength()) { 585 default: break; 586 case 2: 587 if (!TypeID->isStr("id")) 588 break; 589 Context.ObjCIdRedefinitionType = New->getUnderlyingType(); 590 // Install the built-in type for 'id', ignoring the current definition. 591 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 592 return; 593 case 5: 594 if (!TypeID->isStr("Class")) 595 break; 596 Context.ObjCClassRedefinitionType = New->getUnderlyingType(); 597 // Install the built-in type for 'Class', ignoring the current definition. 598 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 599 return; 600 case 3: 601 if (!TypeID->isStr("SEL")) 602 break; 603 Context.setObjCSelType(Context.getTypeDeclType(New)); 604 return; 605 case 8: 606 if (!TypeID->isStr("Protocol")) 607 break; 608 Context.setObjCProtoType(New->getUnderlyingType()); 609 return; 610 } 611 // Fall through - the typedef name was not a builtin type. 612 } 613 // Verify the old decl was also a type. 614 TypeDecl *Old = dyn_cast<TypeDecl>(OldD); 615 if (!Old) { 616 Diag(New->getLocation(), diag::err_redefinition_different_kind) 617 << New->getDeclName(); 618 if (OldD->getLocation().isValid()) 619 Diag(OldD->getLocation(), diag::note_previous_definition); 620 return New->setInvalidDecl(); 621 } 622 623 // Determine the "old" type we'll use for checking and diagnostics. 624 QualType OldType; 625 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old)) 626 OldType = OldTypedef->getUnderlyingType(); 627 else 628 OldType = Context.getTypeDeclType(Old); 629 630 // If the typedef types are not identical, reject them in all languages and 631 // with any extensions enabled. 632 633 if (OldType != New->getUnderlyingType() && 634 Context.getCanonicalType(OldType) != 635 Context.getCanonicalType(New->getUnderlyingType())) { 636 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 637 << New->getUnderlyingType() << OldType; 638 if (Old->getLocation().isValid()) 639 Diag(Old->getLocation(), diag::note_previous_definition); 640 return New->setInvalidDecl(); 641 } 642 643 if (getLangOptions().Microsoft) 644 return; 645 646 // C++ [dcl.typedef]p2: 647 // In a given non-class scope, a typedef specifier can be used to 648 // redefine the name of any type declared in that scope to refer 649 // to the type to which it already refers. 650 if (getLangOptions().CPlusPlus) { 651 if (!isa<CXXRecordDecl>(CurContext)) 652 return; 653 Diag(New->getLocation(), diag::err_redefinition) 654 << New->getDeclName(); 655 Diag(Old->getLocation(), diag::note_previous_definition); 656 return New->setInvalidDecl(); 657 } 658 659 // If we have a redefinition of a typedef in C, emit a warning. This warning 660 // is normally mapped to an error, but can be controlled with 661 // -Wtypedef-redefinition. If either the original or the redefinition is 662 // in a system header, don't emit this for compatibility with GCC. 663 if (PP.getDiagnostics().getSuppressSystemWarnings() && 664 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 665 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 666 return; 667 668 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 669 << New->getDeclName(); 670 Diag(Old->getLocation(), diag::note_previous_definition); 671 return; 672} 673 674/// DeclhasAttr - returns true if decl Declaration already has the target 675/// attribute. 676static bool 677DeclHasAttr(const Decl *decl, const Attr *target) { 678 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext()) 679 if (attr->getKind() == target->getKind()) 680 return true; 681 682 return false; 683} 684 685/// MergeAttributes - append attributes from the Old decl to the New one. 686static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) { 687 for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) { 688 if (!DeclHasAttr(New, attr) && attr->isMerged()) { 689 Attr *NewAttr = attr->clone(C); 690 NewAttr->setInherited(true); 691 New->addAttr(NewAttr); 692 } 693 } 694} 695 696/// Used in MergeFunctionDecl to keep track of function parameters in 697/// C. 698struct GNUCompatibleParamWarning { 699 ParmVarDecl *OldParm; 700 ParmVarDecl *NewParm; 701 QualType PromotedType; 702}; 703 704/// MergeFunctionDecl - We just parsed a function 'New' from 705/// declarator D which has the same name and scope as a previous 706/// declaration 'Old'. Figure out how to resolve this situation, 707/// merging decls or emitting diagnostics as appropriate. 708/// 709/// In C++, New and Old must be declarations that are not 710/// overloaded. Use IsOverload to determine whether New and Old are 711/// overloaded, and to select the Old declaration that New should be 712/// merged with. 713/// 714/// Returns true if there was an error, false otherwise. 715bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) { 716 assert(!isa<OverloadedFunctionDecl>(OldD) && 717 "Cannot merge with an overloaded function declaration"); 718 719 // Verify the old decl was also a function. 720 FunctionDecl *Old = 0; 721 if (FunctionTemplateDecl *OldFunctionTemplate 722 = dyn_cast<FunctionTemplateDecl>(OldD)) 723 Old = OldFunctionTemplate->getTemplatedDecl(); 724 else 725 Old = dyn_cast<FunctionDecl>(OldD); 726 if (!Old) { 727 Diag(New->getLocation(), diag::err_redefinition_different_kind) 728 << New->getDeclName(); 729 Diag(OldD->getLocation(), diag::note_previous_definition); 730 return true; 731 } 732 733 // Determine whether the previous declaration was a definition, 734 // implicit declaration, or a declaration. 735 diag::kind PrevDiag; 736 if (Old->isThisDeclarationADefinition()) 737 PrevDiag = diag::note_previous_definition; 738 else if (Old->isImplicit()) 739 PrevDiag = diag::note_previous_implicit_declaration; 740 else 741 PrevDiag = diag::note_previous_declaration; 742 743 QualType OldQType = Context.getCanonicalType(Old->getType()); 744 QualType NewQType = Context.getCanonicalType(New->getType()); 745 746 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 747 New->getStorageClass() == FunctionDecl::Static && 748 Old->getStorageClass() != FunctionDecl::Static) { 749 Diag(New->getLocation(), diag::err_static_non_static) 750 << New; 751 Diag(Old->getLocation(), PrevDiag); 752 return true; 753 } 754 755 if (getLangOptions().CPlusPlus) { 756 // (C++98 13.1p2): 757 // Certain function declarations cannot be overloaded: 758 // -- Function declarations that differ only in the return type 759 // cannot be overloaded. 760 QualType OldReturnType 761 = cast<FunctionType>(OldQType.getTypePtr())->getResultType(); 762 QualType NewReturnType 763 = cast<FunctionType>(NewQType.getTypePtr())->getResultType(); 764 if (OldReturnType != NewReturnType) { 765 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 766 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 767 return true; 768 } 769 770 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 771 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 772 if (OldMethod && NewMethod && !NewMethod->getFriendObjectKind() && 773 NewMethod->getLexicalDeclContext()->isRecord()) { 774 // -- Member function declarations with the same name and the 775 // same parameter types cannot be overloaded if any of them 776 // is a static member function declaration. 777 if (OldMethod->isStatic() || NewMethod->isStatic()) { 778 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 779 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 780 return true; 781 } 782 783 // C++ [class.mem]p1: 784 // [...] A member shall not be declared twice in the 785 // member-specification, except that a nested class or member 786 // class template can be declared and then later defined. 787 unsigned NewDiag; 788 if (isa<CXXConstructorDecl>(OldMethod)) 789 NewDiag = diag::err_constructor_redeclared; 790 else if (isa<CXXDestructorDecl>(NewMethod)) 791 NewDiag = diag::err_destructor_redeclared; 792 else if (isa<CXXConversionDecl>(NewMethod)) 793 NewDiag = diag::err_conv_function_redeclared; 794 else 795 NewDiag = diag::err_member_redeclared; 796 797 Diag(New->getLocation(), NewDiag); 798 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 799 } 800 801 // (C++98 8.3.5p3): 802 // All declarations for a function shall agree exactly in both the 803 // return type and the parameter-type-list. 804 if (OldQType == NewQType) 805 return MergeCompatibleFunctionDecls(New, Old); 806 807 // Fall through for conflicting redeclarations and redefinitions. 808 } 809 810 // C: Function types need to be compatible, not identical. This handles 811 // duplicate function decls like "void f(int); void f(enum X);" properly. 812 if (!getLangOptions().CPlusPlus && 813 Context.typesAreCompatible(OldQType, NewQType)) { 814 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 815 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 816 const FunctionProtoType *OldProto = 0; 817 if (isa<FunctionNoProtoType>(NewFuncType) && 818 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 819 // The old declaration provided a function prototype, but the 820 // new declaration does not. Merge in the prototype. 821 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 822 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 823 OldProto->arg_type_end()); 824 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 825 ParamTypes.data(), ParamTypes.size(), 826 OldProto->isVariadic(), 827 OldProto->getTypeQuals()); 828 New->setType(NewQType); 829 New->setHasInheritedPrototype(); 830 831 // Synthesize a parameter for each argument type. 832 llvm::SmallVector<ParmVarDecl*, 16> Params; 833 for (FunctionProtoType::arg_type_iterator 834 ParamType = OldProto->arg_type_begin(), 835 ParamEnd = OldProto->arg_type_end(); 836 ParamType != ParamEnd; ++ParamType) { 837 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 838 SourceLocation(), 0, 839 *ParamType, /*DInfo=*/0, 840 VarDecl::None, 0); 841 Param->setImplicit(); 842 Params.push_back(Param); 843 } 844 845 New->setParams(Context, Params.data(), Params.size()); 846 } 847 848 return MergeCompatibleFunctionDecls(New, Old); 849 } 850 851 // GNU C permits a K&R definition to follow a prototype declaration 852 // if the declared types of the parameters in the K&R definition 853 // match the types in the prototype declaration, even when the 854 // promoted types of the parameters from the K&R definition differ 855 // from the types in the prototype. GCC then keeps the types from 856 // the prototype. 857 // 858 // If a variadic prototype is followed by a non-variadic K&R definition, 859 // the K&R definition becomes variadic. This is sort of an edge case, but 860 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 861 // C99 6.9.1p8. 862 if (!getLangOptions().CPlusPlus && 863 Old->hasPrototype() && !New->hasPrototype() && 864 New->getType()->getAs<FunctionProtoType>() && 865 Old->getNumParams() == New->getNumParams()) { 866 llvm::SmallVector<QualType, 16> ArgTypes; 867 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings; 868 const FunctionProtoType *OldProto 869 = Old->getType()->getAs<FunctionProtoType>(); 870 const FunctionProtoType *NewProto 871 = New->getType()->getAs<FunctionProtoType>(); 872 873 // Determine whether this is the GNU C extension. 874 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 875 NewProto->getResultType()); 876 bool LooseCompatible = !MergedReturn.isNull(); 877 for (unsigned Idx = 0, End = Old->getNumParams(); 878 LooseCompatible && Idx != End; ++Idx) { 879 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 880 ParmVarDecl *NewParm = New->getParamDecl(Idx); 881 if (Context.typesAreCompatible(OldParm->getType(), 882 NewProto->getArgType(Idx))) { 883 ArgTypes.push_back(NewParm->getType()); 884 } else if (Context.typesAreCompatible(OldParm->getType(), 885 NewParm->getType())) { 886 GNUCompatibleParamWarning Warn 887 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 888 Warnings.push_back(Warn); 889 ArgTypes.push_back(NewParm->getType()); 890 } else 891 LooseCompatible = false; 892 } 893 894 if (LooseCompatible) { 895 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 896 Diag(Warnings[Warn].NewParm->getLocation(), 897 diag::ext_param_promoted_not_compatible_with_prototype) 898 << Warnings[Warn].PromotedType 899 << Warnings[Warn].OldParm->getType(); 900 Diag(Warnings[Warn].OldParm->getLocation(), 901 diag::note_previous_declaration); 902 } 903 904 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0], 905 ArgTypes.size(), 906 OldProto->isVariadic(), 0)); 907 return MergeCompatibleFunctionDecls(New, Old); 908 } 909 910 // Fall through to diagnose conflicting types. 911 } 912 913 // A function that has already been declared has been redeclared or defined 914 // with a different type- show appropriate diagnostic 915 if (unsigned BuiltinID = Old->getBuiltinID()) { 916 // The user has declared a builtin function with an incompatible 917 // signature. 918 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 919 // The function the user is redeclaring is a library-defined 920 // function like 'malloc' or 'printf'. Warn about the 921 // redeclaration, then pretend that we don't know about this 922 // library built-in. 923 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 924 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 925 << Old << Old->getType(); 926 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 927 Old->setInvalidDecl(); 928 return false; 929 } 930 931 PrevDiag = diag::note_previous_builtin_declaration; 932 } 933 934 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 935 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 936 return true; 937} 938 939/// \brief Completes the merge of two function declarations that are 940/// known to be compatible. 941/// 942/// This routine handles the merging of attributes and other 943/// properties of function declarations form the old declaration to 944/// the new declaration, once we know that New is in fact a 945/// redeclaration of Old. 946/// 947/// \returns false 948bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) { 949 // Merge the attributes 950 MergeAttributes(New, Old, Context); 951 952 // Merge the storage class. 953 if (Old->getStorageClass() != FunctionDecl::Extern && 954 Old->getStorageClass() != FunctionDecl::None) 955 New->setStorageClass(Old->getStorageClass()); 956 957 // Merge "pure" flag. 958 if (Old->isPure()) 959 New->setPure(); 960 961 // Merge the "deleted" flag. 962 if (Old->isDeleted()) 963 New->setDeleted(); 964 965 if (getLangOptions().CPlusPlus) 966 return MergeCXXFunctionDecl(New, Old); 967 968 return false; 969} 970 971/// MergeVarDecl - We just parsed a variable 'New' which has the same name 972/// and scope as a previous declaration 'Old'. Figure out how to resolve this 973/// situation, merging decls or emitting diagnostics as appropriate. 974/// 975/// Tentative definition rules (C99 6.9.2p2) are checked by 976/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 977/// definitions here, since the initializer hasn't been attached. 978/// 979void Sema::MergeVarDecl(VarDecl *New, Decl *OldD) { 980 // If either decl is invalid, make sure the new one is marked invalid and 981 // don't do any other checking. 982 if (New->isInvalidDecl() || OldD->isInvalidDecl()) 983 return New->setInvalidDecl(); 984 985 // Verify the old decl was also a variable. 986 VarDecl *Old = dyn_cast<VarDecl>(OldD); 987 if (!Old) { 988 Diag(New->getLocation(), diag::err_redefinition_different_kind) 989 << New->getDeclName(); 990 Diag(OldD->getLocation(), diag::note_previous_definition); 991 return New->setInvalidDecl(); 992 } 993 994 MergeAttributes(New, Old, Context); 995 996 // Merge the types 997 QualType MergedT; 998 if (getLangOptions().CPlusPlus) { 999 if (Context.hasSameType(New->getType(), Old->getType())) 1000 MergedT = New->getType(); 1001 // C++ [basic.types]p7: 1002 // [...] The declared type of an array object might be an array of 1003 // unknown size and therefore be incomplete at one point in a 1004 // translation unit and complete later on; [...] 1005 else if (Old->getType()->isIncompleteArrayType() && 1006 New->getType()->isArrayType()) { 1007 CanQual<ArrayType> OldArray 1008 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 1009 CanQual<ArrayType> NewArray 1010 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 1011 if (OldArray->getElementType() == NewArray->getElementType()) 1012 MergedT = New->getType(); 1013 } 1014 } else { 1015 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 1016 } 1017 if (MergedT.isNull()) { 1018 Diag(New->getLocation(), diag::err_redefinition_different_type) 1019 << New->getDeclName(); 1020 Diag(Old->getLocation(), diag::note_previous_definition); 1021 return New->setInvalidDecl(); 1022 } 1023 New->setType(MergedT); 1024 1025 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 1026 if (New->getStorageClass() == VarDecl::Static && 1027 (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) { 1028 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 1029 Diag(Old->getLocation(), diag::note_previous_definition); 1030 return New->setInvalidDecl(); 1031 } 1032 // C99 6.2.2p4: 1033 // For an identifier declared with the storage-class specifier 1034 // extern in a scope in which a prior declaration of that 1035 // identifier is visible,23) if the prior declaration specifies 1036 // internal or external linkage, the linkage of the identifier at 1037 // the later declaration is the same as the linkage specified at 1038 // the prior declaration. If no prior declaration is visible, or 1039 // if the prior declaration specifies no linkage, then the 1040 // identifier has external linkage. 1041 if (New->hasExternalStorage() && Old->hasLinkage()) 1042 /* Okay */; 1043 else if (New->getStorageClass() != VarDecl::Static && 1044 Old->getStorageClass() == VarDecl::Static) { 1045 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 1046 Diag(Old->getLocation(), diag::note_previous_definition); 1047 return New->setInvalidDecl(); 1048 } 1049 1050 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 1051 1052 // FIXME: The test for external storage here seems wrong? We still 1053 // need to check for mismatches. 1054 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 1055 // Don't complain about out-of-line definitions of static members. 1056 !(Old->getLexicalDeclContext()->isRecord() && 1057 !New->getLexicalDeclContext()->isRecord())) { 1058 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 1059 Diag(Old->getLocation(), diag::note_previous_definition); 1060 return New->setInvalidDecl(); 1061 } 1062 1063 if (New->isThreadSpecified() && !Old->isThreadSpecified()) { 1064 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 1065 Diag(Old->getLocation(), diag::note_previous_definition); 1066 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) { 1067 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 1068 Diag(Old->getLocation(), diag::note_previous_definition); 1069 } 1070 1071 // Keep a chain of previous declarations. 1072 New->setPreviousDeclaration(Old); 1073} 1074 1075/// CheckFallThrough - Check that we don't fall off the end of a 1076/// Statement that should return a value. 1077/// 1078/// \returns AlwaysFallThrough iff we always fall off the end of the statement, 1079/// MaybeFallThrough iff we might or might not fall off the end and 1080/// NeverFallThrough iff we never fall off the end of the statement. We assume 1081/// that functions not marked noreturn will return. 1082Sema::ControlFlowKind Sema::CheckFallThrough(Stmt *Root) { 1083 llvm::OwningPtr<CFG> cfg (CFG::buildCFG(Root, &Context)); 1084 1085 // FIXME: They should never return 0, fix that, delete this code. 1086 if (cfg == 0) 1087 return NeverFallThrough; 1088 // The CFG leaves in dead things, and we don't want to dead code paths to 1089 // confuse us, so we mark all live things first. 1090 std::queue<CFGBlock*> workq; 1091 llvm::BitVector live(cfg->getNumBlockIDs()); 1092 // Prep work queue 1093 workq.push(&cfg->getEntry()); 1094 // Solve 1095 while (!workq.empty()) { 1096 CFGBlock *item = workq.front(); 1097 workq.pop(); 1098 live.set(item->getBlockID()); 1099 for (CFGBlock::succ_iterator I=item->succ_begin(), 1100 E=item->succ_end(); 1101 I != E; 1102 ++I) { 1103 if ((*I) && !live[(*I)->getBlockID()]) { 1104 live.set((*I)->getBlockID()); 1105 workq.push(*I); 1106 } 1107 } 1108 } 1109 1110 // Now we know what is live, we check the live precessors of the exit block 1111 // and look for fall through paths, being careful to ignore normal returns, 1112 // and exceptional paths. 1113 bool HasLiveReturn = false; 1114 bool HasFakeEdge = false; 1115 bool HasPlainEdge = false; 1116 for (CFGBlock::succ_iterator I=cfg->getExit().pred_begin(), 1117 E = cfg->getExit().pred_end(); 1118 I != E; 1119 ++I) { 1120 CFGBlock& B = **I; 1121 if (!live[B.getBlockID()]) 1122 continue; 1123 if (B.size() == 0) { 1124 // A labeled empty statement, or the entry block... 1125 HasPlainEdge = true; 1126 continue; 1127 } 1128 Stmt *S = B[B.size()-1]; 1129 if (isa<ReturnStmt>(S)) { 1130 HasLiveReturn = true; 1131 continue; 1132 } 1133 if (isa<ObjCAtThrowStmt>(S)) { 1134 HasFakeEdge = true; 1135 continue; 1136 } 1137 if (isa<CXXThrowExpr>(S)) { 1138 HasFakeEdge = true; 1139 continue; 1140 } 1141 bool NoReturnEdge = false; 1142 if (CallExpr *C = dyn_cast<CallExpr>(S)) { 1143 Expr *CEE = C->getCallee()->IgnoreParenCasts(); 1144 if (CEE->getType().getNoReturnAttr()) { 1145 NoReturnEdge = true; 1146 HasFakeEdge = true; 1147 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) { 1148 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 1149 if (FD->hasAttr<NoReturnAttr>()) { 1150 NoReturnEdge = true; 1151 HasFakeEdge = true; 1152 } 1153 } 1154 } 1155 } 1156 // FIXME: Add noreturn message sends. 1157 if (NoReturnEdge == false) 1158 HasPlainEdge = true; 1159 } 1160 if (!HasPlainEdge) 1161 return NeverFallThrough; 1162 if (HasFakeEdge || HasLiveReturn) 1163 return MaybeFallThrough; 1164 // This says AlwaysFallThrough for calls to functions that are not marked 1165 // noreturn, that don't return. If people would like this warning to be more 1166 // accurate, such functions should be marked as noreturn. 1167 return AlwaysFallThrough; 1168} 1169 1170/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a 1171/// function that should return a value. Check that we don't fall off the end 1172/// of a noreturn function. We assume that functions and blocks not marked 1173/// noreturn will return. 1174void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body) { 1175 // FIXME: Would be nice if we had a better way to control cascading errors, 1176 // but for now, avoid them. The problem is that when Parse sees: 1177 // int foo() { return a; } 1178 // The return is eaten and the Sema code sees just: 1179 // int foo() { } 1180 // which this code would then warn about. 1181 if (getDiagnostics().hasErrorOccurred()) 1182 return; 1183 bool ReturnsVoid = false; 1184 bool HasNoReturn = false; 1185 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1186 if (FD->getResultType()->isVoidType()) 1187 ReturnsVoid = true; 1188 if (FD->hasAttr<NoReturnAttr>()) 1189 HasNoReturn = true; 1190 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 1191 if (MD->getResultType()->isVoidType()) 1192 ReturnsVoid = true; 1193 if (MD->hasAttr<NoReturnAttr>()) 1194 HasNoReturn = true; 1195 } 1196 1197 // Short circuit for compilation speed. 1198 if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function) 1199 == Diagnostic::Ignored || ReturnsVoid) 1200 && (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr) 1201 == Diagnostic::Ignored || !HasNoReturn) 1202 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block) 1203 == Diagnostic::Ignored || !ReturnsVoid)) 1204 return; 1205 // FIXME: Funtion try block 1206 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) { 1207 switch (CheckFallThrough(Body)) { 1208 case MaybeFallThrough: 1209 if (HasNoReturn) 1210 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function); 1211 else if (!ReturnsVoid) 1212 Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function); 1213 break; 1214 case AlwaysFallThrough: 1215 if (HasNoReturn) 1216 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function); 1217 else if (!ReturnsVoid) 1218 Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function); 1219 break; 1220 case NeverFallThrough: 1221 if (ReturnsVoid) 1222 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function); 1223 break; 1224 } 1225 } 1226} 1227 1228/// CheckFallThroughForBlock - Check that we don't fall off the end of a block 1229/// that should return a value. Check that we don't fall off the end of a 1230/// noreturn block. We assume that functions and blocks not marked noreturn 1231/// will return. 1232void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body) { 1233 // FIXME: Would be nice if we had a better way to control cascading errors, 1234 // but for now, avoid them. The problem is that when Parse sees: 1235 // int foo() { return a; } 1236 // The return is eaten and the Sema code sees just: 1237 // int foo() { } 1238 // which this code would then warn about. 1239 if (getDiagnostics().hasErrorOccurred()) 1240 return; 1241 bool ReturnsVoid = false; 1242 bool HasNoReturn = false; 1243 if (const FunctionType *FT = BlockTy->getPointeeType()->getAs<FunctionType>()) { 1244 if (FT->getResultType()->isVoidType()) 1245 ReturnsVoid = true; 1246 if (FT->getNoReturnAttr()) 1247 HasNoReturn = true; 1248 } 1249 1250 // Short circuit for compilation speed. 1251 if (ReturnsVoid 1252 && !HasNoReturn 1253 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block) 1254 == Diagnostic::Ignored || !ReturnsVoid)) 1255 return; 1256 // FIXME: Funtion try block 1257 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) { 1258 switch (CheckFallThrough(Body)) { 1259 case MaybeFallThrough: 1260 if (HasNoReturn) 1261 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr); 1262 else if (!ReturnsVoid) 1263 Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block); 1264 break; 1265 case AlwaysFallThrough: 1266 if (HasNoReturn) 1267 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr); 1268 else if (!ReturnsVoid) 1269 Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block); 1270 break; 1271 case NeverFallThrough: 1272 if (ReturnsVoid) 1273 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block); 1274 break; 1275 } 1276 } 1277} 1278 1279/// CheckParmsForFunctionDef - Check that the parameters of the given 1280/// function are appropriate for the definition of a function. This 1281/// takes care of any checks that cannot be performed on the 1282/// declaration itself, e.g., that the types of each of the function 1283/// parameters are complete. 1284bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) { 1285 bool HasInvalidParm = false; 1286 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 1287 ParmVarDecl *Param = FD->getParamDecl(p); 1288 1289 // C99 6.7.5.3p4: the parameters in a parameter type list in a 1290 // function declarator that is part of a function definition of 1291 // that function shall not have incomplete type. 1292 // 1293 // This is also C++ [dcl.fct]p6. 1294 if (!Param->isInvalidDecl() && 1295 RequireCompleteType(Param->getLocation(), Param->getType(), 1296 diag::err_typecheck_decl_incomplete_type)) { 1297 Param->setInvalidDecl(); 1298 HasInvalidParm = true; 1299 } 1300 1301 // C99 6.9.1p5: If the declarator includes a parameter type list, the 1302 // declaration of each parameter shall include an identifier. 1303 if (Param->getIdentifier() == 0 && 1304 !Param->isImplicit() && 1305 !getLangOptions().CPlusPlus) 1306 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 1307 } 1308 1309 return HasInvalidParm; 1310} 1311 1312/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 1313/// no declarator (e.g. "struct foo;") is parsed. 1314Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) { 1315 // FIXME: Error on auto/register at file scope 1316 // FIXME: Error on inline/virtual/explicit 1317 // FIXME: Error on invalid restrict 1318 // FIXME: Warn on useless __thread 1319 // FIXME: Warn on useless const/volatile 1320 // FIXME: Warn on useless static/extern/typedef/private_extern/mutable 1321 // FIXME: Warn on useless attributes 1322 TagDecl *Tag = 0; 1323 if (DS.getTypeSpecType() == DeclSpec::TST_class || 1324 DS.getTypeSpecType() == DeclSpec::TST_struct || 1325 DS.getTypeSpecType() == DeclSpec::TST_union || 1326 DS.getTypeSpecType() == DeclSpec::TST_enum) { 1327 if (!DS.getTypeRep()) // We probably had an error 1328 return DeclPtrTy(); 1329 1330 // Note that the above type specs guarantee that the 1331 // type rep is a Decl, whereas in many of the others 1332 // it's a Type. 1333 Tag = dyn_cast<TagDecl>(static_cast<Decl *>(DS.getTypeRep())); 1334 } 1335 1336 if (DS.isFriendSpecified()) { 1337 // We have a "friend" declaration that does not have a declarator. 1338 // Look at the type to see if the friend declaration was handled 1339 // elsewhere (e.g., for friend classes and friend class templates). 1340 // If not, produce a suitable diagnostic or go try to befriend the 1341 // type itself. 1342 QualType T; 1343 if (DS.getTypeSpecType() == DeclSpec::TST_typename || 1344 DS.getTypeSpecType() == DeclSpec::TST_typeofType) 1345 T = QualType::getFromOpaquePtr(DS.getTypeRep()); 1346 else if (DS.getTypeSpecType() == DeclSpec::TST_typeofExpr || 1347 DS.getTypeSpecType() == DeclSpec::TST_decltype) 1348 T = ((Expr *)DS.getTypeRep())->getType(); 1349 else if (DS.getTypeSpecType() == DeclSpec::TST_class || 1350 DS.getTypeSpecType() == DeclSpec::TST_struct || 1351 DS.getTypeSpecType() == DeclSpec::TST_union) 1352 return DeclPtrTy::make(Tag); 1353 1354 if (T.isNull()) { 1355 // Fall through to diagnose this error, below. 1356 } else if (const RecordType *RecordT = T->getAs<RecordType>()) { 1357 // C++ [class.friend]p2: 1358 // An elaborated-type-specifier shall be used in a friend declaration 1359 // for a class. 1360 1361 // We have something like "friend C;", where C is the name of a 1362 // class type but is missing an elaborated type specifier. Complain, 1363 // but tell the user exactly how to fix the problem. 1364 RecordDecl *RecordD = RecordT->getDecl(); 1365 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type) 1366 << (unsigned)RecordD->getTagKind() 1367 << QualType(RecordT, 0) 1368 << SourceRange(DS.getFriendSpecLoc()) 1369 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(), 1370 RecordD->getKindName() + std::string(" ")); 1371 1372 // FIXME: We could go into ActOnTag to actually make the friend 1373 // declaration happen at this point. 1374 return DeclPtrTy(); 1375 } 1376 1377 if (!T.isNull() && T->isDependentType()) { 1378 // Since T is a dependent type, handle it as a friend type 1379 // declaration. 1380 return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0)); 1381 } 1382 1383 // Complain about any non-dependent friend type here. 1384 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend) 1385 << DS.getSourceRange(); 1386 return DeclPtrTy(); 1387 } 1388 1389 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 1390 if (!Record->getDeclName() && Record->isDefinition() && 1391 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 1392 if (getLangOptions().CPlusPlus || 1393 Record->getDeclContext()->isRecord()) 1394 return BuildAnonymousStructOrUnion(S, DS, Record); 1395 1396 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators) 1397 << DS.getSourceRange(); 1398 } 1399 1400 // Microsoft allows unnamed struct/union fields. Don't complain 1401 // about them. 1402 // FIXME: Should we support Microsoft's extensions in this area? 1403 if (Record->getDeclName() && getLangOptions().Microsoft) 1404 return DeclPtrTy::make(Tag); 1405 } 1406 1407 if (!DS.isMissingDeclaratorOk() && 1408 DS.getTypeSpecType() != DeclSpec::TST_error) { 1409 // Warn about typedefs of enums without names, since this is an 1410 // extension in both Microsoft an GNU. 1411 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef && 1412 Tag && isa<EnumDecl>(Tag)) { 1413 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name) 1414 << DS.getSourceRange(); 1415 return DeclPtrTy::make(Tag); 1416 } 1417 1418 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators) 1419 << DS.getSourceRange(); 1420 return DeclPtrTy(); 1421 } 1422 1423 return DeclPtrTy::make(Tag); 1424} 1425 1426/// InjectAnonymousStructOrUnionMembers - Inject the members of the 1427/// anonymous struct or union AnonRecord into the owning context Owner 1428/// and scope S. This routine will be invoked just after we realize 1429/// that an unnamed union or struct is actually an anonymous union or 1430/// struct, e.g., 1431/// 1432/// @code 1433/// union { 1434/// int i; 1435/// float f; 1436/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 1437/// // f into the surrounding scope.x 1438/// @endcode 1439/// 1440/// This routine is recursive, injecting the names of nested anonymous 1441/// structs/unions into the owning context and scope as well. 1442bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner, 1443 RecordDecl *AnonRecord) { 1444 bool Invalid = false; 1445 for (RecordDecl::field_iterator F = AnonRecord->field_begin(), 1446 FEnd = AnonRecord->field_end(); 1447 F != FEnd; ++F) { 1448 if ((*F)->getDeclName()) { 1449 NamedDecl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(), 1450 LookupOrdinaryName, true); 1451 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 1452 // C++ [class.union]p2: 1453 // The names of the members of an anonymous union shall be 1454 // distinct from the names of any other entity in the 1455 // scope in which the anonymous union is declared. 1456 unsigned diagKind 1457 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl 1458 : diag::err_anonymous_struct_member_redecl; 1459 Diag((*F)->getLocation(), diagKind) 1460 << (*F)->getDeclName(); 1461 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 1462 Invalid = true; 1463 } else { 1464 // C++ [class.union]p2: 1465 // For the purpose of name lookup, after the anonymous union 1466 // definition, the members of the anonymous union are 1467 // considered to have been defined in the scope in which the 1468 // anonymous union is declared. 1469 Owner->makeDeclVisibleInContext(*F); 1470 S->AddDecl(DeclPtrTy::make(*F)); 1471 IdResolver.AddDecl(*F); 1472 } 1473 } else if (const RecordType *InnerRecordType 1474 = (*F)->getType()->getAs<RecordType>()) { 1475 RecordDecl *InnerRecord = InnerRecordType->getDecl(); 1476 if (InnerRecord->isAnonymousStructOrUnion()) 1477 Invalid = Invalid || 1478 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord); 1479 } 1480 } 1481 1482 return Invalid; 1483} 1484 1485/// ActOnAnonymousStructOrUnion - Handle the declaration of an 1486/// anonymous structure or union. Anonymous unions are a C++ feature 1487/// (C++ [class.union]) and a GNU C extension; anonymous structures 1488/// are a GNU C and GNU C++ extension. 1489Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 1490 RecordDecl *Record) { 1491 DeclContext *Owner = Record->getDeclContext(); 1492 1493 // Diagnose whether this anonymous struct/union is an extension. 1494 if (Record->isUnion() && !getLangOptions().CPlusPlus) 1495 Diag(Record->getLocation(), diag::ext_anonymous_union); 1496 else if (!Record->isUnion()) 1497 Diag(Record->getLocation(), diag::ext_anonymous_struct); 1498 1499 // C and C++ require different kinds of checks for anonymous 1500 // structs/unions. 1501 bool Invalid = false; 1502 if (getLangOptions().CPlusPlus) { 1503 const char* PrevSpec = 0; 1504 unsigned DiagID; 1505 // C++ [class.union]p3: 1506 // Anonymous unions declared in a named namespace or in the 1507 // global namespace shall be declared static. 1508 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 1509 (isa<TranslationUnitDecl>(Owner) || 1510 (isa<NamespaceDecl>(Owner) && 1511 cast<NamespaceDecl>(Owner)->getDeclName()))) { 1512 Diag(Record->getLocation(), diag::err_anonymous_union_not_static); 1513 Invalid = true; 1514 1515 // Recover by adding 'static'. 1516 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), 1517 PrevSpec, DiagID); 1518 } 1519 // C++ [class.union]p3: 1520 // A storage class is not allowed in a declaration of an 1521 // anonymous union in a class scope. 1522 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 1523 isa<RecordDecl>(Owner)) { 1524 Diag(DS.getStorageClassSpecLoc(), 1525 diag::err_anonymous_union_with_storage_spec); 1526 Invalid = true; 1527 1528 // Recover by removing the storage specifier. 1529 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(), 1530 PrevSpec, DiagID); 1531 } 1532 1533 // C++ [class.union]p2: 1534 // The member-specification of an anonymous union shall only 1535 // define non-static data members. [Note: nested types and 1536 // functions cannot be declared within an anonymous union. ] 1537 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 1538 MemEnd = Record->decls_end(); 1539 Mem != MemEnd; ++Mem) { 1540 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 1541 // C++ [class.union]p3: 1542 // An anonymous union shall not have private or protected 1543 // members (clause 11). 1544 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) { 1545 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 1546 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 1547 Invalid = true; 1548 } 1549 } else if ((*Mem)->isImplicit()) { 1550 // Any implicit members are fine. 1551 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 1552 // This is a type that showed up in an 1553 // elaborated-type-specifier inside the anonymous struct or 1554 // union, but which actually declares a type outside of the 1555 // anonymous struct or union. It's okay. 1556 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 1557 if (!MemRecord->isAnonymousStructOrUnion() && 1558 MemRecord->getDeclName()) { 1559 // This is a nested type declaration. 1560 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 1561 << (int)Record->isUnion(); 1562 Invalid = true; 1563 } 1564 } else { 1565 // We have something that isn't a non-static data 1566 // member. Complain about it. 1567 unsigned DK = diag::err_anonymous_record_bad_member; 1568 if (isa<TypeDecl>(*Mem)) 1569 DK = diag::err_anonymous_record_with_type; 1570 else if (isa<FunctionDecl>(*Mem)) 1571 DK = diag::err_anonymous_record_with_function; 1572 else if (isa<VarDecl>(*Mem)) 1573 DK = diag::err_anonymous_record_with_static; 1574 Diag((*Mem)->getLocation(), DK) 1575 << (int)Record->isUnion(); 1576 Invalid = true; 1577 } 1578 } 1579 } 1580 1581 if (!Record->isUnion() && !Owner->isRecord()) { 1582 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 1583 << (int)getLangOptions().CPlusPlus; 1584 Invalid = true; 1585 } 1586 1587 // Create a declaration for this anonymous struct/union. 1588 NamedDecl *Anon = 0; 1589 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 1590 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(), 1591 /*IdentifierInfo=*/0, 1592 Context.getTypeDeclType(Record), 1593 // FIXME: Type source info. 1594 /*DInfo=*/0, 1595 /*BitWidth=*/0, /*Mutable=*/false); 1596 Anon->setAccess(AS_public); 1597 if (getLangOptions().CPlusPlus) 1598 FieldCollector->Add(cast<FieldDecl>(Anon)); 1599 } else { 1600 VarDecl::StorageClass SC; 1601 switch (DS.getStorageClassSpec()) { 1602 default: assert(0 && "Unknown storage class!"); 1603 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 1604 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 1605 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 1606 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 1607 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 1608 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 1609 case DeclSpec::SCS_mutable: 1610 // mutable can only appear on non-static class members, so it's always 1611 // an error here 1612 Diag(Record->getLocation(), diag::err_mutable_nonmember); 1613 Invalid = true; 1614 SC = VarDecl::None; 1615 break; 1616 } 1617 1618 Anon = VarDecl::Create(Context, Owner, Record->getLocation(), 1619 /*IdentifierInfo=*/0, 1620 Context.getTypeDeclType(Record), 1621 // FIXME: Type source info. 1622 /*DInfo=*/0, 1623 SC); 1624 } 1625 Anon->setImplicit(); 1626 1627 // Add the anonymous struct/union object to the current 1628 // context. We'll be referencing this object when we refer to one of 1629 // its members. 1630 Owner->addDecl(Anon); 1631 1632 // Inject the members of the anonymous struct/union into the owning 1633 // context and into the identifier resolver chain for name lookup 1634 // purposes. 1635 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record)) 1636 Invalid = true; 1637 1638 // Mark this as an anonymous struct/union type. Note that we do not 1639 // do this until after we have already checked and injected the 1640 // members of this anonymous struct/union type, because otherwise 1641 // the members could be injected twice: once by DeclContext when it 1642 // builds its lookup table, and once by 1643 // InjectAnonymousStructOrUnionMembers. 1644 Record->setAnonymousStructOrUnion(true); 1645 1646 if (Invalid) 1647 Anon->setInvalidDecl(); 1648 1649 return DeclPtrTy::make(Anon); 1650} 1651 1652 1653/// GetNameForDeclarator - Determine the full declaration name for the 1654/// given Declarator. 1655DeclarationName Sema::GetNameForDeclarator(Declarator &D) { 1656 switch (D.getKind()) { 1657 case Declarator::DK_Abstract: 1658 assert(D.getIdentifier() == 0 && "abstract declarators have no name"); 1659 return DeclarationName(); 1660 1661 case Declarator::DK_Normal: 1662 assert (D.getIdentifier() != 0 && "normal declarators have an identifier"); 1663 return DeclarationName(D.getIdentifier()); 1664 1665 case Declarator::DK_Constructor: { 1666 QualType Ty = GetTypeFromParser(D.getDeclaratorIdType()); 1667 return Context.DeclarationNames.getCXXConstructorName( 1668 Context.getCanonicalType(Ty)); 1669 } 1670 1671 case Declarator::DK_Destructor: { 1672 QualType Ty = GetTypeFromParser(D.getDeclaratorIdType()); 1673 return Context.DeclarationNames.getCXXDestructorName( 1674 Context.getCanonicalType(Ty)); 1675 } 1676 1677 case Declarator::DK_Conversion: { 1678 // FIXME: We'd like to keep the non-canonical type for diagnostics! 1679 QualType Ty = GetTypeFromParser(D.getDeclaratorIdType()); 1680 return Context.DeclarationNames.getCXXConversionFunctionName( 1681 Context.getCanonicalType(Ty)); 1682 } 1683 1684 case Declarator::DK_Operator: 1685 assert(D.getIdentifier() == 0 && "operator names have no identifier"); 1686 return Context.DeclarationNames.getCXXOperatorName( 1687 D.getOverloadedOperator()); 1688 1689 case Declarator::DK_TemplateId: { 1690 TemplateName Name 1691 = TemplateName::getFromVoidPointer(D.getTemplateId()->Template); 1692 if (TemplateDecl *Template = Name.getAsTemplateDecl()) 1693 return Template->getDeclName(); 1694 if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) 1695 return Ovl->getDeclName(); 1696 1697 return DeclarationName(); 1698 } 1699 } 1700 1701 assert(false && "Unknown name kind"); 1702 return DeclarationName(); 1703} 1704 1705/// isNearlyMatchingFunction - Determine whether the C++ functions 1706/// Declaration and Definition are "nearly" matching. This heuristic 1707/// is used to improve diagnostics in the case where an out-of-line 1708/// function definition doesn't match any declaration within 1709/// the class or namespace. 1710static bool isNearlyMatchingFunction(ASTContext &Context, 1711 FunctionDecl *Declaration, 1712 FunctionDecl *Definition) { 1713 if (Declaration->param_size() != Definition->param_size()) 1714 return false; 1715 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 1716 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 1717 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 1718 1719 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType()); 1720 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType()); 1721 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType()) 1722 return false; 1723 } 1724 1725 return true; 1726} 1727 1728Sema::DeclPtrTy 1729Sema::HandleDeclarator(Scope *S, Declarator &D, 1730 MultiTemplateParamsArg TemplateParamLists, 1731 bool IsFunctionDefinition) { 1732 DeclarationName Name = GetNameForDeclarator(D); 1733 1734 // All of these full declarators require an identifier. If it doesn't have 1735 // one, the ParsedFreeStandingDeclSpec action should be used. 1736 if (!Name) { 1737 if (!D.isInvalidType()) // Reject this if we think it is valid. 1738 Diag(D.getDeclSpec().getSourceRange().getBegin(), 1739 diag::err_declarator_need_ident) 1740 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 1741 return DeclPtrTy(); 1742 } 1743 1744 // The scope passed in may not be a decl scope. Zip up the scope tree until 1745 // we find one that is. 1746 while ((S->getFlags() & Scope::DeclScope) == 0 || 1747 (S->getFlags() & Scope::TemplateParamScope) != 0) 1748 S = S->getParent(); 1749 1750 // If this is an out-of-line definition of a member of a class template 1751 // or class template partial specialization, we may need to rebuild the 1752 // type specifier in the declarator. See RebuildTypeInCurrentInstantiation() 1753 // for more information. 1754 // FIXME: cope with decltype(expr) and typeof(expr) once the rebuilder can 1755 // handle expressions properly. 1756 DeclSpec &DS = const_cast<DeclSpec&>(D.getDeclSpec()); 1757 if (D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid() && 1758 isDependentScopeSpecifier(D.getCXXScopeSpec()) && 1759 (DS.getTypeSpecType() == DeclSpec::TST_typename || 1760 DS.getTypeSpecType() == DeclSpec::TST_typeofType || 1761 DS.getTypeSpecType() == DeclSpec::TST_typeofExpr || 1762 DS.getTypeSpecType() == DeclSpec::TST_decltype)) { 1763 if (DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(), true)) { 1764 // FIXME: Preserve type source info. 1765 QualType T = GetTypeFromParser(DS.getTypeRep()); 1766 EnterDeclaratorContext(S, DC); 1767 T = RebuildTypeInCurrentInstantiation(T, D.getIdentifierLoc(), Name); 1768 ExitDeclaratorContext(S); 1769 if (T.isNull()) 1770 return DeclPtrTy(); 1771 DS.UpdateTypeRep(T.getAsOpaquePtr()); 1772 } 1773 } 1774 1775 DeclContext *DC; 1776 NamedDecl *PrevDecl; 1777 NamedDecl *New; 1778 1779 DeclaratorInfo *DInfo = 0; 1780 QualType R = GetTypeForDeclarator(D, S, &DInfo); 1781 1782 // See if this is a redefinition of a variable in the same scope. 1783 if (D.getCXXScopeSpec().isInvalid()) { 1784 DC = CurContext; 1785 PrevDecl = 0; 1786 D.setInvalidType(); 1787 } else if (!D.getCXXScopeSpec().isSet()) { 1788 LookupNameKind NameKind = LookupOrdinaryName; 1789 1790 // If the declaration we're planning to build will be a function 1791 // or object with linkage, then look for another declaration with 1792 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 1793 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 1794 /* Do nothing*/; 1795 else if (R->isFunctionType()) { 1796 if (CurContext->isFunctionOrMethod() || 1797 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 1798 NameKind = LookupRedeclarationWithLinkage; 1799 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 1800 NameKind = LookupRedeclarationWithLinkage; 1801 else if (CurContext->getLookupContext()->isTranslationUnit() && 1802 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 1803 NameKind = LookupRedeclarationWithLinkage; 1804 1805 DC = CurContext; 1806 PrevDecl = LookupName(S, Name, NameKind, true, 1807 NameKind == LookupRedeclarationWithLinkage, 1808 D.getIdentifierLoc()); 1809 } else { // Something like "int foo::x;" 1810 DC = computeDeclContext(D.getCXXScopeSpec(), true); 1811 1812 if (!DC) { 1813 // If we could not compute the declaration context, it's because the 1814 // declaration context is dependent but does not refer to a class, 1815 // class template, or class template partial specialization. Complain 1816 // and return early, to avoid the coming semantic disaster. 1817 Diag(D.getIdentifierLoc(), 1818 diag::err_template_qualified_declarator_no_match) 1819 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 1820 << D.getCXXScopeSpec().getRange(); 1821 return DeclPtrTy(); 1822 } 1823 1824 PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName, true); 1825 1826 // C++ 7.3.1.2p2: 1827 // Members (including explicit specializations of templates) of a named 1828 // namespace can also be defined outside that namespace by explicit 1829 // qualification of the name being defined, provided that the entity being 1830 // defined was already declared in the namespace and the definition appears 1831 // after the point of declaration in a namespace that encloses the 1832 // declarations namespace. 1833 // 1834 // Note that we only check the context at this point. We don't yet 1835 // have enough information to make sure that PrevDecl is actually 1836 // the declaration we want to match. For example, given: 1837 // 1838 // class X { 1839 // void f(); 1840 // void f(float); 1841 // }; 1842 // 1843 // void X::f(int) { } // ill-formed 1844 // 1845 // In this case, PrevDecl will point to the overload set 1846 // containing the two f's declared in X, but neither of them 1847 // matches. 1848 1849 // First check whether we named the global scope. 1850 if (isa<TranslationUnitDecl>(DC)) { 1851 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope) 1852 << Name << D.getCXXScopeSpec().getRange(); 1853 } else if (!CurContext->Encloses(DC)) { 1854 // The qualifying scope doesn't enclose the original declaration. 1855 // Emit diagnostic based on current scope. 1856 SourceLocation L = D.getIdentifierLoc(); 1857 SourceRange R = D.getCXXScopeSpec().getRange(); 1858 if (isa<FunctionDecl>(CurContext)) 1859 Diag(L, diag::err_invalid_declarator_in_function) << Name << R; 1860 else 1861 Diag(L, diag::err_invalid_declarator_scope) 1862 << Name << cast<NamedDecl>(DC) << R; 1863 D.setInvalidType(); 1864 } 1865 } 1866 1867 if (PrevDecl && PrevDecl->isTemplateParameter()) { 1868 // Maybe we will complain about the shadowed template parameter. 1869 if (!D.isInvalidType()) 1870 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl)) 1871 D.setInvalidType(); 1872 1873 // Just pretend that we didn't see the previous declaration. 1874 PrevDecl = 0; 1875 } 1876 1877 // In C++, the previous declaration we find might be a tag type 1878 // (class or enum). In this case, the new declaration will hide the 1879 // tag type. Note that this does does not apply if we're declaring a 1880 // typedef (C++ [dcl.typedef]p4). 1881 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag && 1882 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 1883 PrevDecl = 0; 1884 1885 bool Redeclaration = false; 1886 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 1887 if (TemplateParamLists.size()) { 1888 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 1889 return DeclPtrTy(); 1890 } 1891 1892 New = ActOnTypedefDeclarator(S, D, DC, R, DInfo, PrevDecl, Redeclaration); 1893 } else if (R->isFunctionType()) { 1894 New = ActOnFunctionDeclarator(S, D, DC, R, DInfo, PrevDecl, 1895 move(TemplateParamLists), 1896 IsFunctionDefinition, Redeclaration); 1897 } else { 1898 New = ActOnVariableDeclarator(S, D, DC, R, DInfo, PrevDecl, 1899 move(TemplateParamLists), 1900 Redeclaration); 1901 } 1902 1903 if (New == 0) 1904 return DeclPtrTy(); 1905 1906 // If this has an identifier and is not an invalid redeclaration or 1907 // function template specialization, add it to the scope stack. 1908 if (Name && !(Redeclaration && New->isInvalidDecl()) && 1909 !(isa<FunctionDecl>(New) && 1910 cast<FunctionDecl>(New)->isFunctionTemplateSpecialization())) 1911 PushOnScopeChains(New, S); 1912 1913 return DeclPtrTy::make(New); 1914} 1915 1916/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array 1917/// types into constant array types in certain situations which would otherwise 1918/// be errors (for GCC compatibility). 1919static QualType TryToFixInvalidVariablyModifiedType(QualType T, 1920 ASTContext &Context, 1921 bool &SizeIsNegative) { 1922 // This method tries to turn a variable array into a constant 1923 // array even when the size isn't an ICE. This is necessary 1924 // for compatibility with code that depends on gcc's buggy 1925 // constant expression folding, like struct {char x[(int)(char*)2];} 1926 SizeIsNegative = false; 1927 1928 QualifierCollector Qs; 1929 const Type *Ty = Qs.strip(T); 1930 1931 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 1932 QualType Pointee = PTy->getPointeeType(); 1933 QualType FixedType = 1934 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative); 1935 if (FixedType.isNull()) return FixedType; 1936 FixedType = Context.getPointerType(FixedType); 1937 return Qs.apply(FixedType); 1938 } 1939 1940 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 1941 if (!VLATy) 1942 return QualType(); 1943 // FIXME: We should probably handle this case 1944 if (VLATy->getElementType()->isVariablyModifiedType()) 1945 return QualType(); 1946 1947 Expr::EvalResult EvalResult; 1948 if (!VLATy->getSizeExpr() || 1949 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) || 1950 !EvalResult.Val.isInt()) 1951 return QualType(); 1952 1953 llvm::APSInt &Res = EvalResult.Val.getInt(); 1954 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) { 1955 Expr* ArySizeExpr = VLATy->getSizeExpr(); 1956 // FIXME: here we could "steal" (how?) ArySizeExpr from the VLA, 1957 // so as to transfer ownership to the ConstantArrayWithExpr. 1958 // Alternatively, we could "clone" it (how?). 1959 // Since we don't know how to do things above, we just use the 1960 // very same Expr*. 1961 return Context.getConstantArrayWithExprType(VLATy->getElementType(), 1962 Res, ArySizeExpr, 1963 ArrayType::Normal, 0, 1964 VLATy->getBracketsRange()); 1965 } 1966 1967 SizeIsNegative = true; 1968 return QualType(); 1969} 1970 1971/// \brief Register the given locally-scoped external C declaration so 1972/// that it can be found later for redeclarations 1973void 1974Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, NamedDecl *PrevDecl, 1975 Scope *S) { 1976 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 1977 "Decl is not a locally-scoped decl!"); 1978 // Note that we have a locally-scoped external with this name. 1979 LocallyScopedExternalDecls[ND->getDeclName()] = ND; 1980 1981 if (!PrevDecl) 1982 return; 1983 1984 // If there was a previous declaration of this variable, it may be 1985 // in our identifier chain. Update the identifier chain with the new 1986 // declaration. 1987 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 1988 // The previous declaration was found on the identifer resolver 1989 // chain, so remove it from its scope. 1990 while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl))) 1991 S = S->getParent(); 1992 1993 if (S) 1994 S->RemoveDecl(DeclPtrTy::make(PrevDecl)); 1995 } 1996} 1997 1998/// \brief Diagnose function specifiers on a declaration of an identifier that 1999/// does not identify a function. 2000void Sema::DiagnoseFunctionSpecifiers(Declarator& D) { 2001 // FIXME: We should probably indicate the identifier in question to avoid 2002 // confusion for constructs like "inline int a(), b;" 2003 if (D.getDeclSpec().isInlineSpecified()) 2004 Diag(D.getDeclSpec().getInlineSpecLoc(), 2005 diag::err_inline_non_function); 2006 2007 if (D.getDeclSpec().isVirtualSpecified()) 2008 Diag(D.getDeclSpec().getVirtualSpecLoc(), 2009 diag::err_virtual_non_function); 2010 2011 if (D.getDeclSpec().isExplicitSpecified()) 2012 Diag(D.getDeclSpec().getExplicitSpecLoc(), 2013 diag::err_explicit_non_function); 2014} 2015 2016NamedDecl* 2017Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2018 QualType R, DeclaratorInfo *DInfo, 2019 NamedDecl* PrevDecl, bool &Redeclaration) { 2020 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 2021 if (D.getCXXScopeSpec().isSet()) { 2022 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 2023 << D.getCXXScopeSpec().getRange(); 2024 D.setInvalidType(); 2025 // Pretend we didn't see the scope specifier. 2026 DC = 0; 2027 } 2028 2029 if (getLangOptions().CPlusPlus) { 2030 // Check that there are no default arguments (C++ only). 2031 CheckExtraCXXDefaultArguments(D); 2032 } 2033 2034 DiagnoseFunctionSpecifiers(D); 2035 2036 if (D.getDeclSpec().isThreadSpecified()) 2037 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 2038 2039 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R); 2040 if (!NewTD) return 0; 2041 2042 if (D.isInvalidType()) 2043 NewTD->setInvalidDecl(); 2044 2045 // Handle attributes prior to checking for duplicates in MergeVarDecl 2046 ProcessDeclAttributes(S, NewTD, D); 2047 // Merge the decl with the existing one if appropriate. If the decl is 2048 // in an outer scope, it isn't the same thing. 2049 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) { 2050 Redeclaration = true; 2051 MergeTypeDefDecl(NewTD, PrevDecl); 2052 } 2053 2054 // C99 6.7.7p2: If a typedef name specifies a variably modified type 2055 // then it shall have block scope. 2056 QualType T = NewTD->getUnderlyingType(); 2057 if (T->isVariablyModifiedType()) { 2058 CurFunctionNeedsScopeChecking = true; 2059 2060 if (S->getFnParent() == 0) { 2061 bool SizeIsNegative; 2062 QualType FixedTy = 2063 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative); 2064 if (!FixedTy.isNull()) { 2065 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size); 2066 NewTD->setUnderlyingType(FixedTy); 2067 } else { 2068 if (SizeIsNegative) 2069 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size); 2070 else if (T->isVariableArrayType()) 2071 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope); 2072 else 2073 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope); 2074 NewTD->setInvalidDecl(); 2075 } 2076 } 2077 } 2078 2079 // If this is the C FILE type, notify the AST context. 2080 if (IdentifierInfo *II = NewTD->getIdentifier()) 2081 if (!NewTD->isInvalidDecl() && 2082 NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) { 2083 if (II->isStr("FILE")) 2084 Context.setFILEDecl(NewTD); 2085 else if (II->isStr("jmp_buf")) 2086 Context.setjmp_bufDecl(NewTD); 2087 else if (II->isStr("sigjmp_buf")) 2088 Context.setsigjmp_bufDecl(NewTD); 2089 } 2090 2091 return NewTD; 2092} 2093 2094/// \brief Determines whether the given declaration is an out-of-scope 2095/// previous declaration. 2096/// 2097/// This routine should be invoked when name lookup has found a 2098/// previous declaration (PrevDecl) that is not in the scope where a 2099/// new declaration by the same name is being introduced. If the new 2100/// declaration occurs in a local scope, previous declarations with 2101/// linkage may still be considered previous declarations (C99 2102/// 6.2.2p4-5, C++ [basic.link]p6). 2103/// 2104/// \param PrevDecl the previous declaration found by name 2105/// lookup 2106/// 2107/// \param DC the context in which the new declaration is being 2108/// declared. 2109/// 2110/// \returns true if PrevDecl is an out-of-scope previous declaration 2111/// for a new delcaration with the same name. 2112static bool 2113isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 2114 ASTContext &Context) { 2115 if (!PrevDecl) 2116 return 0; 2117 2118 // FIXME: PrevDecl could be an OverloadedFunctionDecl, in which 2119 // case we need to check each of the overloaded functions. 2120 if (!PrevDecl->hasLinkage()) 2121 return false; 2122 2123 if (Context.getLangOptions().CPlusPlus) { 2124 // C++ [basic.link]p6: 2125 // If there is a visible declaration of an entity with linkage 2126 // having the same name and type, ignoring entities declared 2127 // outside the innermost enclosing namespace scope, the block 2128 // scope declaration declares that same entity and receives the 2129 // linkage of the previous declaration. 2130 DeclContext *OuterContext = DC->getLookupContext(); 2131 if (!OuterContext->isFunctionOrMethod()) 2132 // This rule only applies to block-scope declarations. 2133 return false; 2134 else { 2135 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 2136 if (PrevOuterContext->isRecord()) 2137 // We found a member function: ignore it. 2138 return false; 2139 else { 2140 // Find the innermost enclosing namespace for the new and 2141 // previous declarations. 2142 while (!OuterContext->isFileContext()) 2143 OuterContext = OuterContext->getParent(); 2144 while (!PrevOuterContext->isFileContext()) 2145 PrevOuterContext = PrevOuterContext->getParent(); 2146 2147 // The previous declaration is in a different namespace, so it 2148 // isn't the same function. 2149 if (OuterContext->getPrimaryContext() != 2150 PrevOuterContext->getPrimaryContext()) 2151 return false; 2152 } 2153 } 2154 } 2155 2156 return true; 2157} 2158 2159NamedDecl* 2160Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2161 QualType R, DeclaratorInfo *DInfo, 2162 NamedDecl* PrevDecl, 2163 MultiTemplateParamsArg TemplateParamLists, 2164 bool &Redeclaration) { 2165 DeclarationName Name = GetNameForDeclarator(D); 2166 2167 // Check that there are no default arguments (C++ only). 2168 if (getLangOptions().CPlusPlus) 2169 CheckExtraCXXDefaultArguments(D); 2170 2171 VarDecl *NewVD; 2172 VarDecl::StorageClass SC; 2173 switch (D.getDeclSpec().getStorageClassSpec()) { 2174 default: assert(0 && "Unknown storage class!"); 2175 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 2176 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 2177 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 2178 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 2179 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 2180 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 2181 case DeclSpec::SCS_mutable: 2182 // mutable can only appear on non-static class members, so it's always 2183 // an error here 2184 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 2185 D.setInvalidType(); 2186 SC = VarDecl::None; 2187 break; 2188 } 2189 2190 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2191 if (!II) { 2192 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 2193 << Name.getAsString(); 2194 return 0; 2195 } 2196 2197 DiagnoseFunctionSpecifiers(D); 2198 2199 if (!DC->isRecord() && S->getFnParent() == 0) { 2200 // C99 6.9p2: The storage-class specifiers auto and register shall not 2201 // appear in the declaration specifiers in an external declaration. 2202 if (SC == VarDecl::Auto || SC == VarDecl::Register) { 2203 2204 // If this is a register variable with an asm label specified, then this 2205 // is a GNU extension. 2206 if (SC == VarDecl::Register && D.getAsmLabel()) 2207 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 2208 else 2209 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 2210 D.setInvalidType(); 2211 } 2212 } 2213 if (DC->isRecord() && !CurContext->isRecord()) { 2214 // This is an out-of-line definition of a static data member. 2215 if (SC == VarDecl::Static) { 2216 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 2217 diag::err_static_out_of_line) 2218 << CodeModificationHint::CreateRemoval( 2219 SourceRange(D.getDeclSpec().getStorageClassSpecLoc())); 2220 } else if (SC == VarDecl::None) 2221 SC = VarDecl::Static; 2222 } 2223 if (SC == VarDecl::Static) { 2224 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 2225 if (RD->isLocalClass()) 2226 Diag(D.getIdentifierLoc(), 2227 diag::err_static_data_member_not_allowed_in_local_class) 2228 << Name << RD->getDeclName(); 2229 } 2230 } 2231 2232 // Match up the template parameter lists with the scope specifier, then 2233 // determine whether we have a template or a template specialization. 2234 if (TemplateParameterList *TemplateParams 2235 = MatchTemplateParametersToScopeSpecifier( 2236 D.getDeclSpec().getSourceRange().getBegin(), 2237 D.getCXXScopeSpec(), 2238 (TemplateParameterList**)TemplateParamLists.get(), 2239 TemplateParamLists.size())) { 2240 if (TemplateParams->size() > 0) { 2241 // There is no such thing as a variable template. 2242 Diag(D.getIdentifierLoc(), diag::err_template_variable) 2243 << II 2244 << SourceRange(TemplateParams->getTemplateLoc(), 2245 TemplateParams->getRAngleLoc()); 2246 return 0; 2247 } else { 2248 // There is an extraneous 'template<>' for this variable. Complain 2249 // about it, but allow the declaration of the variable. 2250 Diag(TemplateParams->getTemplateLoc(), 2251 diag::err_template_variable_noparams) 2252 << II 2253 << SourceRange(TemplateParams->getTemplateLoc(), 2254 TemplateParams->getRAngleLoc()); 2255 } 2256 } 2257 2258 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(), 2259 II, R, DInfo, SC); 2260 2261 if (D.isInvalidType()) 2262 NewVD->setInvalidDecl(); 2263 2264 if (D.getDeclSpec().isThreadSpecified()) { 2265 if (NewVD->hasLocalStorage()) 2266 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 2267 else if (!Context.Target.isTLSSupported()) 2268 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 2269 else 2270 NewVD->setThreadSpecified(true); 2271 } 2272 2273 // Set the lexical context. If the declarator has a C++ scope specifier, the 2274 // lexical context will be different from the semantic context. 2275 NewVD->setLexicalDeclContext(CurContext); 2276 2277 // Handle attributes prior to checking for duplicates in MergeVarDecl 2278 ProcessDeclAttributes(S, NewVD, D); 2279 2280 // Handle GNU asm-label extension (encoded as an attribute). 2281 if (Expr *E = (Expr*) D.getAsmLabel()) { 2282 // The parser guarantees this is a string. 2283 StringLiteral *SE = cast<StringLiteral>(E); 2284 NewVD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(), 2285 SE->getByteLength()))); 2286 } 2287 2288 // If name lookup finds a previous declaration that is not in the 2289 // same scope as the new declaration, this may still be an 2290 // acceptable redeclaration. 2291 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) && 2292 !(NewVD->hasLinkage() && 2293 isOutOfScopePreviousDeclaration(PrevDecl, DC, Context))) 2294 PrevDecl = 0; 2295 2296 // Merge the decl with the existing one if appropriate. 2297 if (PrevDecl) { 2298 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) { 2299 // The user tried to define a non-static data member 2300 // out-of-line (C++ [dcl.meaning]p1). 2301 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 2302 << D.getCXXScopeSpec().getRange(); 2303 PrevDecl = 0; 2304 NewVD->setInvalidDecl(); 2305 } 2306 } else if (D.getCXXScopeSpec().isSet()) { 2307 // No previous declaration in the qualifying scope. 2308 NestedNameSpecifier *NNS = 2309 (NestedNameSpecifier *)D.getCXXScopeSpec().getScopeRep(); 2310 DiagnoseMissingMember(D.getIdentifierLoc(), Name, NNS, 2311 D.getCXXScopeSpec().getRange()); 2312 NewVD->setInvalidDecl(); 2313 } 2314 2315 CheckVariableDeclaration(NewVD, PrevDecl, Redeclaration); 2316 2317 // attributes declared post-definition are currently ignored 2318 if (PrevDecl) { 2319 const VarDecl *Def = 0, *PrevVD = dyn_cast<VarDecl>(PrevDecl); 2320 if (PrevVD->getDefinition(Def) && D.hasAttributes()) { 2321 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition); 2322 Diag(Def->getLocation(), diag::note_previous_definition); 2323 } 2324 } 2325 2326 // If this is a locally-scoped extern C variable, update the map of 2327 // such variables. 2328 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() && 2329 !NewVD->isInvalidDecl()) 2330 RegisterLocallyScopedExternCDecl(NewVD, PrevDecl, S); 2331 2332 return NewVD; 2333} 2334 2335/// \brief Perform semantic checking on a newly-created variable 2336/// declaration. 2337/// 2338/// This routine performs all of the type-checking required for a 2339/// variable declaration once it has been built. It is used both to 2340/// check variables after they have been parsed and their declarators 2341/// have been translated into a declaration, and to check variables 2342/// that have been instantiated from a template. 2343/// 2344/// Sets NewVD->isInvalidDecl() if an error was encountered. 2345void Sema::CheckVariableDeclaration(VarDecl *NewVD, NamedDecl *PrevDecl, 2346 bool &Redeclaration) { 2347 // If the decl is already known invalid, don't check it. 2348 if (NewVD->isInvalidDecl()) 2349 return; 2350 2351 QualType T = NewVD->getType(); 2352 2353 if (T->isObjCInterfaceType()) { 2354 Diag(NewVD->getLocation(), diag::err_statically_allocated_object); 2355 return NewVD->setInvalidDecl(); 2356 } 2357 2358 // The variable can not have an abstract class type. 2359 if (RequireNonAbstractType(NewVD->getLocation(), T, 2360 diag::err_abstract_type_in_decl, 2361 AbstractVariableType)) 2362 return NewVD->setInvalidDecl(); 2363 2364 // Emit an error if an address space was applied to decl with local storage. 2365 // This includes arrays of objects with address space qualifiers, but not 2366 // automatic variables that point to other address spaces. 2367 // ISO/IEC TR 18037 S5.1.2 2368 if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) { 2369 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 2370 return NewVD->setInvalidDecl(); 2371 } 2372 2373 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 2374 && !NewVD->hasAttr<BlocksAttr>()) 2375 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 2376 2377 bool isVM = T->isVariablyModifiedType(); 2378 if (isVM || NewVD->hasAttr<CleanupAttr>() || 2379 NewVD->hasAttr<BlocksAttr>()) 2380 CurFunctionNeedsScopeChecking = true; 2381 2382 if ((isVM && NewVD->hasLinkage()) || 2383 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 2384 bool SizeIsNegative; 2385 QualType FixedTy = 2386 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative); 2387 2388 if (FixedTy.isNull() && T->isVariableArrayType()) { 2389 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 2390 // FIXME: This won't give the correct result for 2391 // int a[10][n]; 2392 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 2393 2394 if (NewVD->isFileVarDecl()) 2395 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 2396 << SizeRange; 2397 else if (NewVD->getStorageClass() == VarDecl::Static) 2398 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 2399 << SizeRange; 2400 else 2401 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 2402 << SizeRange; 2403 return NewVD->setInvalidDecl(); 2404 } 2405 2406 if (FixedTy.isNull()) { 2407 if (NewVD->isFileVarDecl()) 2408 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 2409 else 2410 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 2411 return NewVD->setInvalidDecl(); 2412 } 2413 2414 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 2415 NewVD->setType(FixedTy); 2416 } 2417 2418 if (!PrevDecl && NewVD->isExternC()) { 2419 // Since we did not find anything by this name and we're declaring 2420 // an extern "C" variable, look for a non-visible extern "C" 2421 // declaration with the same name. 2422 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 2423 = LocallyScopedExternalDecls.find(NewVD->getDeclName()); 2424 if (Pos != LocallyScopedExternalDecls.end()) 2425 PrevDecl = Pos->second; 2426 } 2427 2428 if (T->isVoidType() && !NewVD->hasExternalStorage()) { 2429 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 2430 << T; 2431 return NewVD->setInvalidDecl(); 2432 } 2433 2434 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 2435 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 2436 return NewVD->setInvalidDecl(); 2437 } 2438 2439 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 2440 Diag(NewVD->getLocation(), diag::err_block_on_vm); 2441 return NewVD->setInvalidDecl(); 2442 } 2443 2444 if (PrevDecl) { 2445 Redeclaration = true; 2446 MergeVarDecl(NewVD, PrevDecl); 2447 } 2448} 2449 2450static bool isUsingDecl(Decl *D) { 2451 return isa<UsingDecl>(D) || isa<UnresolvedUsingDecl>(D); 2452} 2453 2454NamedDecl* 2455Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2456 QualType R, DeclaratorInfo *DInfo, 2457 NamedDecl* PrevDecl, 2458 MultiTemplateParamsArg TemplateParamLists, 2459 bool IsFunctionDefinition, bool &Redeclaration) { 2460 assert(R.getTypePtr()->isFunctionType()); 2461 2462 DeclarationName Name = GetNameForDeclarator(D); 2463 FunctionDecl::StorageClass SC = FunctionDecl::None; 2464 switch (D.getDeclSpec().getStorageClassSpec()) { 2465 default: assert(0 && "Unknown storage class!"); 2466 case DeclSpec::SCS_auto: 2467 case DeclSpec::SCS_register: 2468 case DeclSpec::SCS_mutable: 2469 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 2470 diag::err_typecheck_sclass_func); 2471 D.setInvalidType(); 2472 break; 2473 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break; 2474 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break; 2475 case DeclSpec::SCS_static: { 2476 if (CurContext->getLookupContext()->isFunctionOrMethod()) { 2477 // C99 6.7.1p5: 2478 // The declaration of an identifier for a function that has 2479 // block scope shall have no explicit storage-class specifier 2480 // other than extern 2481 // See also (C++ [dcl.stc]p4). 2482 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 2483 diag::err_static_block_func); 2484 SC = FunctionDecl::None; 2485 } else 2486 SC = FunctionDecl::Static; 2487 break; 2488 } 2489 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break; 2490 } 2491 2492 if (D.getDeclSpec().isThreadSpecified()) 2493 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 2494 2495 bool isFriend = D.getDeclSpec().isFriendSpecified(); 2496 bool isInline = D.getDeclSpec().isInlineSpecified(); 2497 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 2498 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 2499 2500 // Check that the return type is not an abstract class type. 2501 // For record types, this is done by the AbstractClassUsageDiagnoser once 2502 // the class has been completely parsed. 2503 if (!DC->isRecord() && 2504 RequireNonAbstractType(D.getIdentifierLoc(), 2505 R->getAs<FunctionType>()->getResultType(), 2506 diag::err_abstract_type_in_decl, 2507 AbstractReturnType)) 2508 D.setInvalidType(); 2509 2510 // Do not allow returning a objc interface by-value. 2511 if (R->getAs<FunctionType>()->getResultType()->isObjCInterfaceType()) { 2512 Diag(D.getIdentifierLoc(), 2513 diag::err_object_cannot_be_passed_returned_by_value) << 0 2514 << R->getAs<FunctionType>()->getResultType(); 2515 D.setInvalidType(); 2516 } 2517 2518 bool isVirtualOkay = false; 2519 FunctionDecl *NewFD; 2520 2521 if (isFriend) { 2522 // DC is the namespace in which the function is being declared. 2523 assert((DC->isFileContext() || PrevDecl) && "previously-undeclared " 2524 "friend function being created in a non-namespace context"); 2525 2526 // C++ [class.friend]p5 2527 // A function can be defined in a friend declaration of a 2528 // class . . . . Such a function is implicitly inline. 2529 isInline |= IsFunctionDefinition; 2530 } 2531 2532 if (D.getKind() == Declarator::DK_Constructor) { 2533 // This is a C++ constructor declaration. 2534 assert(DC->isRecord() && 2535 "Constructors can only be declared in a member context"); 2536 2537 R = CheckConstructorDeclarator(D, R, SC); 2538 2539 // Create the new declaration 2540 NewFD = CXXConstructorDecl::Create(Context, 2541 cast<CXXRecordDecl>(DC), 2542 D.getIdentifierLoc(), Name, R, DInfo, 2543 isExplicit, isInline, 2544 /*isImplicitlyDeclared=*/false); 2545 } else if (D.getKind() == Declarator::DK_Destructor) { 2546 // This is a C++ destructor declaration. 2547 if (DC->isRecord()) { 2548 R = CheckDestructorDeclarator(D, SC); 2549 2550 NewFD = CXXDestructorDecl::Create(Context, 2551 cast<CXXRecordDecl>(DC), 2552 D.getIdentifierLoc(), Name, R, 2553 isInline, 2554 /*isImplicitlyDeclared=*/false); 2555 2556 isVirtualOkay = true; 2557 } else { 2558 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 2559 2560 // Create a FunctionDecl to satisfy the function definition parsing 2561 // code path. 2562 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(), 2563 Name, R, DInfo, SC, isInline, 2564 /*hasPrototype=*/true); 2565 D.setInvalidType(); 2566 } 2567 } else if (D.getKind() == Declarator::DK_Conversion) { 2568 if (!DC->isRecord()) { 2569 Diag(D.getIdentifierLoc(), 2570 diag::err_conv_function_not_member); 2571 return 0; 2572 } 2573 2574 CheckConversionDeclarator(D, R, SC); 2575 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC), 2576 D.getIdentifierLoc(), Name, R, DInfo, 2577 isInline, isExplicit); 2578 2579 isVirtualOkay = true; 2580 } else if (DC->isRecord()) { 2581 // If the of the function is the same as the name of the record, then this 2582 // must be an invalid constructor that has a return type. 2583 // (The parser checks for a return type and makes the declarator a 2584 // constructor if it has no return type). 2585 // must have an invalid constructor that has a return type 2586 if (Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 2587 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 2588 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2589 << SourceRange(D.getIdentifierLoc()); 2590 return 0; 2591 } 2592 2593 // This is a C++ method declaration. 2594 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC), 2595 D.getIdentifierLoc(), Name, R, DInfo, 2596 (SC == FunctionDecl::Static), isInline); 2597 2598 isVirtualOkay = (SC != FunctionDecl::Static); 2599 } else { 2600 // Determine whether the function was written with a 2601 // prototype. This true when: 2602 // - we're in C++ (where every function has a prototype), 2603 // - there is a prototype in the declarator, or 2604 // - the type R of the function is some kind of typedef or other reference 2605 // to a type name (which eventually refers to a function type). 2606 bool HasPrototype = 2607 getLangOptions().CPlusPlus || 2608 (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) || 2609 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 2610 2611 NewFD = FunctionDecl::Create(Context, DC, 2612 D.getIdentifierLoc(), 2613 Name, R, DInfo, SC, isInline, HasPrototype); 2614 } 2615 2616 if (D.isInvalidType()) 2617 NewFD->setInvalidDecl(); 2618 2619 // Set the lexical context. If the declarator has a C++ 2620 // scope specifier, or is the object of a friend declaration, the 2621 // lexical context will be different from the semantic context. 2622 NewFD->setLexicalDeclContext(CurContext); 2623 2624 if (isFriend) 2625 NewFD->setObjectOfFriendDecl(/* PreviouslyDeclared= */ PrevDecl != NULL); 2626 2627 // Match up the template parameter lists with the scope specifier, then 2628 // determine whether we have a template or a template specialization. 2629 FunctionTemplateDecl *FunctionTemplate = 0; 2630 bool isFunctionTemplateSpecialization = false; 2631 if (TemplateParameterList *TemplateParams 2632 = MatchTemplateParametersToScopeSpecifier( 2633 D.getDeclSpec().getSourceRange().getBegin(), 2634 D.getCXXScopeSpec(), 2635 (TemplateParameterList**)TemplateParamLists.get(), 2636 TemplateParamLists.size())) { 2637 if (TemplateParams->size() > 0) { 2638 // This is a function template 2639 2640 // Check that we can declare a template here. 2641 if (CheckTemplateDeclScope(S, TemplateParams)) 2642 return 0; 2643 2644 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 2645 NewFD->getLocation(), 2646 Name, TemplateParams, 2647 NewFD); 2648 FunctionTemplate->setLexicalDeclContext(CurContext); 2649 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 2650 } else { 2651 // This is a function template specialization. 2652 isFunctionTemplateSpecialization = true; 2653 } 2654 2655 // FIXME: Free this memory properly. 2656 TemplateParamLists.release(); 2657 } 2658 2659 // C++ [dcl.fct.spec]p5: 2660 // The virtual specifier shall only be used in declarations of 2661 // nonstatic class member functions that appear within a 2662 // member-specification of a class declaration; see 10.3. 2663 // 2664 if (isVirtual && !NewFD->isInvalidDecl()) { 2665 if (!isVirtualOkay) { 2666 Diag(D.getDeclSpec().getVirtualSpecLoc(), 2667 diag::err_virtual_non_function); 2668 } else if (!CurContext->isRecord()) { 2669 // 'virtual' was specified outside of the class. 2670 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class) 2671 << CodeModificationHint::CreateRemoval( 2672 SourceRange(D.getDeclSpec().getVirtualSpecLoc())); 2673 } else { 2674 // Okay: Add virtual to the method. 2675 cast<CXXMethodDecl>(NewFD)->setVirtualAsWritten(true); 2676 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC); 2677 CurClass->setAggregate(false); 2678 CurClass->setPOD(false); 2679 CurClass->setEmpty(false); 2680 CurClass->setPolymorphic(true); 2681 CurClass->setHasTrivialConstructor(false); 2682 CurClass->setHasTrivialCopyConstructor(false); 2683 CurClass->setHasTrivialCopyAssignment(false); 2684 } 2685 } 2686 2687 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) { 2688 // Look for virtual methods in base classes that this method might override. 2689 2690 BasePaths Paths; 2691 if (LookupInBases(cast<CXXRecordDecl>(DC), 2692 MemberLookupCriteria(NewMD), Paths)) { 2693 for (BasePaths::decl_iterator I = Paths.found_decls_begin(), 2694 E = Paths.found_decls_end(); I != E; ++I) { 2695 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 2696 if (!CheckOverridingFunctionReturnType(NewMD, OldMD) && 2697 !CheckOverridingFunctionExceptionSpec(NewMD, OldMD)) 2698 NewMD->addOverriddenMethod(OldMD); 2699 } 2700 } 2701 } 2702 } 2703 2704 if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) && 2705 !CurContext->isRecord()) { 2706 // C++ [class.static]p1: 2707 // A data or function member of a class may be declared static 2708 // in a class definition, in which case it is a static member of 2709 // the class. 2710 2711 // Complain about the 'static' specifier if it's on an out-of-line 2712 // member function definition. 2713 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 2714 diag::err_static_out_of_line) 2715 << CodeModificationHint::CreateRemoval( 2716 SourceRange(D.getDeclSpec().getStorageClassSpecLoc())); 2717 } 2718 2719 // Handle GNU asm-label extension (encoded as an attribute). 2720 if (Expr *E = (Expr*) D.getAsmLabel()) { 2721 // The parser guarantees this is a string. 2722 StringLiteral *SE = cast<StringLiteral>(E); 2723 NewFD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(), 2724 SE->getByteLength()))); 2725 } 2726 2727 // Copy the parameter declarations from the declarator D to the function 2728 // declaration NewFD, if they are available. First scavenge them into Params. 2729 llvm::SmallVector<ParmVarDecl*, 16> Params; 2730 if (D.getNumTypeObjects() > 0) { 2731 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2732 2733 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 2734 // function that takes no arguments, not a function that takes a 2735 // single void argument. 2736 // We let through "const void" here because Sema::GetTypeForDeclarator 2737 // already checks for that case. 2738 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 2739 FTI.ArgInfo[0].Param && 2740 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) { 2741 // Empty arg list, don't push any params. 2742 ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>(); 2743 2744 // In C++, the empty parameter-type-list must be spelled "void"; a 2745 // typedef of void is not permitted. 2746 if (getLangOptions().CPlusPlus && 2747 Param->getType().getUnqualifiedType() != Context.VoidTy) 2748 Diag(Param->getLocation(), diag::err_param_typedef_of_void); 2749 // FIXME: Leaks decl? 2750 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 2751 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 2752 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>(); 2753 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 2754 Param->setDeclContext(NewFD); 2755 Params.push_back(Param); 2756 } 2757 } 2758 2759 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 2760 // When we're declaring a function with a typedef, typeof, etc as in the 2761 // following example, we'll need to synthesize (unnamed) 2762 // parameters for use in the declaration. 2763 // 2764 // @code 2765 // typedef void fn(int); 2766 // fn f; 2767 // @endcode 2768 2769 // Synthesize a parameter for each argument type. 2770 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 2771 AE = FT->arg_type_end(); AI != AE; ++AI) { 2772 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, 2773 SourceLocation(), 0, 2774 *AI, /*DInfo=*/0, 2775 VarDecl::None, 0); 2776 Param->setImplicit(); 2777 Params.push_back(Param); 2778 } 2779 } else { 2780 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 2781 "Should not need args for typedef of non-prototype fn"); 2782 } 2783 // Finally, we know we have the right number of parameters, install them. 2784 NewFD->setParams(Context, Params.data(), Params.size()); 2785 2786 // If name lookup finds a previous declaration that is not in the 2787 // same scope as the new declaration, this may still be an 2788 // acceptable redeclaration. 2789 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) && 2790 !(NewFD->hasLinkage() && 2791 isOutOfScopePreviousDeclaration(PrevDecl, DC, Context))) 2792 PrevDecl = 0; 2793 2794 // If the declarator is a template-id, translate the parser's template 2795 // argument list into our AST format. 2796 bool HasExplicitTemplateArgs = false; 2797 llvm::SmallVector<TemplateArgument, 16> TemplateArgs; 2798 SourceLocation LAngleLoc, RAngleLoc; 2799 if (D.getKind() == Declarator::DK_TemplateId) { 2800 TemplateIdAnnotation *TemplateId = D.getTemplateId(); 2801 ASTTemplateArgsPtr TemplateArgsPtr(*this, 2802 TemplateId->getTemplateArgs(), 2803 TemplateId->getTemplateArgIsType(), 2804 TemplateId->NumArgs); 2805 translateTemplateArguments(TemplateArgsPtr, 2806 TemplateId->getTemplateArgLocations(), 2807 TemplateArgs); 2808 TemplateArgsPtr.release(); 2809 2810 HasExplicitTemplateArgs = true; 2811 LAngleLoc = TemplateId->LAngleLoc; 2812 RAngleLoc = TemplateId->RAngleLoc; 2813 2814 if (FunctionTemplate) { 2815 // FIXME: Diagnostic function template with explicit template 2816 // arguments. 2817 HasExplicitTemplateArgs = false; 2818 } else if (!isFunctionTemplateSpecialization && 2819 !D.getDeclSpec().isFriendSpecified()) { 2820 // We have encountered something that the user meant to be a 2821 // specialization (because it has explicitly-specified template 2822 // arguments) but that was not introduced with a "template<>" (or had 2823 // too few of them). 2824 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 2825 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 2826 << CodeModificationHint::CreateInsertion( 2827 D.getDeclSpec().getSourceRange().getBegin(), 2828 "template<> "); 2829 isFunctionTemplateSpecialization = true; 2830 } 2831 } 2832 2833 if (isFunctionTemplateSpecialization && 2834 CheckFunctionTemplateSpecialization(NewFD, HasExplicitTemplateArgs, 2835 LAngleLoc, TemplateArgs.data(), 2836 TemplateArgs.size(), RAngleLoc, 2837 PrevDecl)) 2838 NewFD->setInvalidDecl(); 2839 2840 // Perform semantic checking on the function declaration. 2841 bool OverloadableAttrRequired = false; // FIXME: HACK! 2842 CheckFunctionDeclaration(NewFD, PrevDecl, Redeclaration, 2843 /*FIXME:*/OverloadableAttrRequired); 2844 2845 if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) { 2846 // An out-of-line member function declaration must also be a 2847 // definition (C++ [dcl.meaning]p1). 2848 // FIXME: Find a better way to recognize out-of-line specializations! 2849 if (!IsFunctionDefinition && !isFriend && 2850 !(TemplateParamLists.size() && !FunctionTemplate)) { 2851 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration) 2852 << D.getCXXScopeSpec().getRange(); 2853 NewFD->setInvalidDecl(); 2854 } else if (!Redeclaration && (!PrevDecl || !isUsingDecl(PrevDecl))) { 2855 // The user tried to provide an out-of-line definition for a 2856 // function that is a member of a class or namespace, but there 2857 // was no such member function declared (C++ [class.mfct]p2, 2858 // C++ [namespace.memdef]p2). For example: 2859 // 2860 // class X { 2861 // void f() const; 2862 // }; 2863 // 2864 // void X::f() { } // ill-formed 2865 // 2866 // Complain about this problem, and attempt to suggest close 2867 // matches (e.g., those that differ only in cv-qualifiers and 2868 // whether the parameter types are references). 2869 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match) 2870 << cast<NamedDecl>(DC) << D.getCXXScopeSpec().getRange(); 2871 NewFD->setInvalidDecl(); 2872 2873 LookupResult Prev = LookupQualifiedName(DC, Name, LookupOrdinaryName, 2874 true); 2875 assert(!Prev.isAmbiguous() && 2876 "Cannot have an ambiguity in previous-declaration lookup"); 2877 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 2878 Func != FuncEnd; ++Func) { 2879 if (isa<FunctionDecl>(*Func) && 2880 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD)) 2881 Diag((*Func)->getLocation(), diag::note_member_def_close_match); 2882 } 2883 2884 PrevDecl = 0; 2885 } 2886 } 2887 2888 // Handle attributes. We need to have merged decls when handling attributes 2889 // (for example to check for conflicts, etc). 2890 // FIXME: This needs to happen before we merge declarations. Then, 2891 // let attribute merging cope with attribute conflicts. 2892 ProcessDeclAttributes(S, NewFD, D); 2893 2894 // attributes declared post-definition are currently ignored 2895 if (Redeclaration && PrevDecl) { 2896 const FunctionDecl *Def, *PrevFD = dyn_cast<FunctionDecl>(PrevDecl); 2897 if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) { 2898 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition); 2899 Diag(Def->getLocation(), diag::note_previous_definition); 2900 } 2901 } 2902 2903 AddKnownFunctionAttributes(NewFD); 2904 2905 if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) { 2906 // If a function name is overloadable in C, then every function 2907 // with that name must be marked "overloadable". 2908 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 2909 << Redeclaration << NewFD; 2910 if (PrevDecl) 2911 Diag(PrevDecl->getLocation(), 2912 diag::note_attribute_overloadable_prev_overload); 2913 NewFD->addAttr(::new (Context) OverloadableAttr()); 2914 } 2915 2916 // If this is a locally-scoped extern C function, update the 2917 // map of such names. 2918 if (CurContext->isFunctionOrMethod() && NewFD->isExternC() 2919 && !NewFD->isInvalidDecl()) 2920 RegisterLocallyScopedExternCDecl(NewFD, PrevDecl, S); 2921 2922 // Set this FunctionDecl's range up to the right paren. 2923 NewFD->setLocEnd(D.getSourceRange().getEnd()); 2924 2925 if (FunctionTemplate && NewFD->isInvalidDecl()) 2926 FunctionTemplate->setInvalidDecl(); 2927 2928 if (FunctionTemplate) 2929 return FunctionTemplate; 2930 2931 return NewFD; 2932} 2933 2934/// \brief Perform semantic checking of a new function declaration. 2935/// 2936/// Performs semantic analysis of the new function declaration 2937/// NewFD. This routine performs all semantic checking that does not 2938/// require the actual declarator involved in the declaration, and is 2939/// used both for the declaration of functions as they are parsed 2940/// (called via ActOnDeclarator) and for the declaration of functions 2941/// that have been instantiated via C++ template instantiation (called 2942/// via InstantiateDecl). 2943/// 2944/// This sets NewFD->isInvalidDecl() to true if there was an error. 2945void Sema::CheckFunctionDeclaration(FunctionDecl *NewFD, NamedDecl *&PrevDecl, 2946 bool &Redeclaration, 2947 bool &OverloadableAttrRequired) { 2948 // If NewFD is already known erroneous, don't do any of this checking. 2949 if (NewFD->isInvalidDecl()) 2950 return; 2951 2952 if (NewFD->getResultType()->isVariablyModifiedType()) { 2953 // Functions returning a variably modified type violate C99 6.7.5.2p2 2954 // because all functions have linkage. 2955 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 2956 return NewFD->setInvalidDecl(); 2957 } 2958 2959 if (NewFD->isMain()) 2960 CheckMain(NewFD); 2961 2962 // Check for a previous declaration of this name. 2963 if (!PrevDecl && NewFD->isExternC()) { 2964 // Since we did not find anything by this name and we're declaring 2965 // an extern "C" function, look for a non-visible extern "C" 2966 // declaration with the same name. 2967 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 2968 = LocallyScopedExternalDecls.find(NewFD->getDeclName()); 2969 if (Pos != LocallyScopedExternalDecls.end()) 2970 PrevDecl = Pos->second; 2971 } 2972 2973 // Merge or overload the declaration with an existing declaration of 2974 // the same name, if appropriate. 2975 if (PrevDecl) { 2976 // Determine whether NewFD is an overload of PrevDecl or 2977 // a declaration that requires merging. If it's an overload, 2978 // there's no more work to do here; we'll just add the new 2979 // function to the scope. 2980 OverloadedFunctionDecl::function_iterator MatchedDecl; 2981 2982 if (!getLangOptions().CPlusPlus && 2983 AllowOverloadingOfFunction(PrevDecl, Context)) { 2984 OverloadableAttrRequired = true; 2985 2986 // Functions marked "overloadable" must have a prototype (that 2987 // we can't get through declaration merging). 2988 if (!NewFD->getType()->getAs<FunctionProtoType>()) { 2989 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_no_prototype) 2990 << NewFD; 2991 Redeclaration = true; 2992 2993 // Turn this into a variadic function with no parameters. 2994 QualType R = Context.getFunctionType( 2995 NewFD->getType()->getAs<FunctionType>()->getResultType(), 2996 0, 0, true, 0); 2997 NewFD->setType(R); 2998 return NewFD->setInvalidDecl(); 2999 } 3000 } 3001 3002 if (PrevDecl && 3003 (!AllowOverloadingOfFunction(PrevDecl, Context) || 3004 !IsOverload(NewFD, PrevDecl, MatchedDecl)) && !isUsingDecl(PrevDecl)) { 3005 Redeclaration = true; 3006 Decl *OldDecl = PrevDecl; 3007 3008 // If PrevDecl was an overloaded function, extract the 3009 // FunctionDecl that matched. 3010 if (isa<OverloadedFunctionDecl>(PrevDecl)) 3011 OldDecl = *MatchedDecl; 3012 3013 // NewFD and OldDecl represent declarations that need to be 3014 // merged. 3015 if (MergeFunctionDecl(NewFD, OldDecl)) 3016 return NewFD->setInvalidDecl(); 3017 3018 if (FunctionTemplateDecl *OldTemplateDecl 3019 = dyn_cast<FunctionTemplateDecl>(OldDecl)) 3020 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 3021 else { 3022 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions 3023 NewFD->setAccess(OldDecl->getAccess()); 3024 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 3025 } 3026 } 3027 } 3028 3029 // Semantic checking for this function declaration (in isolation). 3030 if (getLangOptions().CPlusPlus) { 3031 // C++-specific checks. 3032 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 3033 CheckConstructor(Constructor); 3034 } else if (isa<CXXDestructorDecl>(NewFD)) { 3035 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent()); 3036 QualType ClassType = Context.getTypeDeclType(Record); 3037 if (!ClassType->isDependentType()) { 3038 DeclarationName Name 3039 = Context.DeclarationNames.getCXXDestructorName( 3040 Context.getCanonicalType(ClassType)); 3041 if (NewFD->getDeclName() != Name) { 3042 Diag(NewFD->getLocation(), diag::err_destructor_name); 3043 return NewFD->setInvalidDecl(); 3044 } 3045 } 3046 Record->setUserDeclaredDestructor(true); 3047 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no 3048 // user-defined destructor. 3049 Record->setPOD(false); 3050 3051 // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly- 3052 // declared destructor. 3053 // FIXME: C++0x: don't do this for "= default" destructors 3054 Record->setHasTrivialDestructor(false); 3055 } else if (CXXConversionDecl *Conversion 3056 = dyn_cast<CXXConversionDecl>(NewFD)) 3057 ActOnConversionDeclarator(Conversion); 3058 3059 // Extra checking for C++ overloaded operators (C++ [over.oper]). 3060 if (NewFD->isOverloadedOperator() && 3061 CheckOverloadedOperatorDeclaration(NewFD)) 3062 return NewFD->setInvalidDecl(); 3063 3064 // In C++, check default arguments now that we have merged decls. Unless 3065 // the lexical context is the class, because in this case this is done 3066 // during delayed parsing anyway. 3067 if (!CurContext->isRecord()) 3068 CheckCXXDefaultArguments(NewFD); 3069 } 3070} 3071 3072void Sema::CheckMain(FunctionDecl* FD) { 3073 // C++ [basic.start.main]p3: A program that declares main to be inline 3074 // or static is ill-formed. 3075 // C99 6.7.4p4: In a hosted environment, the inline function specifier 3076 // shall not appear in a declaration of main. 3077 // static main is not an error under C99, but we should warn about it. 3078 bool isInline = FD->isInline(); 3079 bool isStatic = FD->getStorageClass() == FunctionDecl::Static; 3080 if (isInline || isStatic) { 3081 unsigned diagID = diag::warn_unusual_main_decl; 3082 if (isInline || getLangOptions().CPlusPlus) 3083 diagID = diag::err_unusual_main_decl; 3084 3085 int which = isStatic + (isInline << 1) - 1; 3086 Diag(FD->getLocation(), diagID) << which; 3087 } 3088 3089 QualType T = FD->getType(); 3090 assert(T->isFunctionType() && "function decl is not of function type"); 3091 const FunctionType* FT = T->getAs<FunctionType>(); 3092 3093 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 3094 // TODO: add a replacement fixit to turn the return type into 'int'. 3095 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 3096 FD->setInvalidDecl(true); 3097 } 3098 3099 // Treat protoless main() as nullary. 3100 if (isa<FunctionNoProtoType>(FT)) return; 3101 3102 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 3103 unsigned nparams = FTP->getNumArgs(); 3104 assert(FD->getNumParams() == nparams); 3105 3106 if (nparams > 3) { 3107 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 3108 FD->setInvalidDecl(true); 3109 nparams = 3; 3110 } 3111 3112 // FIXME: a lot of the following diagnostics would be improved 3113 // if we had some location information about types. 3114 3115 QualType CharPP = 3116 Context.getPointerType(Context.getPointerType(Context.CharTy)); 3117 QualType Expected[] = { Context.IntTy, CharPP, CharPP }; 3118 3119 for (unsigned i = 0; i < nparams; ++i) { 3120 QualType AT = FTP->getArgType(i); 3121 3122 bool mismatch = true; 3123 3124 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 3125 mismatch = false; 3126 else if (Expected[i] == CharPP) { 3127 // As an extension, the following forms are okay: 3128 // char const ** 3129 // char const * const * 3130 // char * const * 3131 3132 QualifierCollector qs; 3133 const PointerType* PT; 3134 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 3135 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 3136 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) { 3137 qs.removeConst(); 3138 mismatch = !qs.empty(); 3139 } 3140 } 3141 3142 if (mismatch) { 3143 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 3144 // TODO: suggest replacing given type with expected type 3145 FD->setInvalidDecl(true); 3146 } 3147 } 3148 3149 if (nparams == 1 && !FD->isInvalidDecl()) { 3150 Diag(FD->getLocation(), diag::warn_main_one_arg); 3151 } 3152} 3153 3154bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 3155 // FIXME: Need strict checking. In C89, we need to check for 3156 // any assignment, increment, decrement, function-calls, or 3157 // commas outside of a sizeof. In C99, it's the same list, 3158 // except that the aforementioned are allowed in unevaluated 3159 // expressions. Everything else falls under the 3160 // "may accept other forms of constant expressions" exception. 3161 // (We never end up here for C++, so the constant expression 3162 // rules there don't matter.) 3163 if (Init->isConstantInitializer(Context)) 3164 return false; 3165 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 3166 << Init->getSourceRange(); 3167 return true; 3168} 3169 3170void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) { 3171 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false); 3172} 3173 3174/// AddInitializerToDecl - Adds the initializer Init to the 3175/// declaration dcl. If DirectInit is true, this is C++ direct 3176/// initialization rather than copy initialization. 3177void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) { 3178 Decl *RealDecl = dcl.getAs<Decl>(); 3179 // If there is no declaration, there was an error parsing it. Just ignore 3180 // the initializer. 3181 if (RealDecl == 0) 3182 return; 3183 3184 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 3185 // With declarators parsed the way they are, the parser cannot 3186 // distinguish between a normal initializer and a pure-specifier. 3187 // Thus this grotesque test. 3188 IntegerLiteral *IL; 3189 Expr *Init = static_cast<Expr *>(init.get()); 3190 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 3191 Context.getCanonicalType(IL->getType()) == Context.IntTy) { 3192 if (Method->isVirtualAsWritten()) { 3193 Method->setPure(); 3194 3195 // A class is abstract if at least one function is pure virtual. 3196 cast<CXXRecordDecl>(CurContext)->setAbstract(true); 3197 } else if (!Method->isInvalidDecl()) { 3198 Diag(Method->getLocation(), diag::err_non_virtual_pure) 3199 << Method->getDeclName() << Init->getSourceRange(); 3200 Method->setInvalidDecl(); 3201 } 3202 } else { 3203 Diag(Method->getLocation(), diag::err_member_function_initialization) 3204 << Method->getDeclName() << Init->getSourceRange(); 3205 Method->setInvalidDecl(); 3206 } 3207 return; 3208 } 3209 3210 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 3211 if (!VDecl) { 3212 if (getLangOptions().CPlusPlus && 3213 RealDecl->getLexicalDeclContext()->isRecord() && 3214 isa<NamedDecl>(RealDecl)) 3215 Diag(RealDecl->getLocation(), diag::err_member_initialization) 3216 << cast<NamedDecl>(RealDecl)->getDeclName(); 3217 else 3218 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 3219 RealDecl->setInvalidDecl(); 3220 return; 3221 } 3222 3223 if (!VDecl->getType()->isArrayType() && 3224 RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 3225 diag::err_typecheck_decl_incomplete_type)) { 3226 RealDecl->setInvalidDecl(); 3227 return; 3228 } 3229 3230 const VarDecl *Def = 0; 3231 if (VDecl->getDefinition(Def)) { 3232 Diag(VDecl->getLocation(), diag::err_redefinition) 3233 << VDecl->getDeclName(); 3234 Diag(Def->getLocation(), diag::note_previous_definition); 3235 VDecl->setInvalidDecl(); 3236 return; 3237 } 3238 3239 // Take ownership of the expression, now that we're sure we have somewhere 3240 // to put it. 3241 Expr *Init = init.takeAs<Expr>(); 3242 assert(Init && "missing initializer"); 3243 3244 // Get the decls type and save a reference for later, since 3245 // CheckInitializerTypes may change it. 3246 QualType DclT = VDecl->getType(), SavT = DclT; 3247 if (VDecl->isBlockVarDecl()) { 3248 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5 3249 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 3250 VDecl->setInvalidDecl(); 3251 } else if (!VDecl->isInvalidDecl()) { 3252 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(), 3253 VDecl->getDeclName(), DirectInit)) 3254 VDecl->setInvalidDecl(); 3255 3256 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 3257 // Don't check invalid declarations to avoid emitting useless diagnostics. 3258 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 3259 if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4. 3260 CheckForConstantInitializer(Init, DclT); 3261 } 3262 } 3263 } else if (VDecl->isStaticDataMember() && 3264 VDecl->getLexicalDeclContext()->isRecord()) { 3265 // This is an in-class initialization for a static data member, e.g., 3266 // 3267 // struct S { 3268 // static const int value = 17; 3269 // }; 3270 3271 // Attach the initializer 3272 VDecl->setInit(Context, Init); 3273 3274 // C++ [class.mem]p4: 3275 // A member-declarator can contain a constant-initializer only 3276 // if it declares a static member (9.4) of const integral or 3277 // const enumeration type, see 9.4.2. 3278 QualType T = VDecl->getType(); 3279 if (!T->isDependentType() && 3280 (!Context.getCanonicalType(T).isConstQualified() || 3281 !T->isIntegralType())) { 3282 Diag(VDecl->getLocation(), diag::err_member_initialization) 3283 << VDecl->getDeclName() << Init->getSourceRange(); 3284 VDecl->setInvalidDecl(); 3285 } else { 3286 // C++ [class.static.data]p4: 3287 // If a static data member is of const integral or const 3288 // enumeration type, its declaration in the class definition 3289 // can specify a constant-initializer which shall be an 3290 // integral constant expression (5.19). 3291 if (!Init->isTypeDependent() && 3292 !Init->getType()->isIntegralType()) { 3293 // We have a non-dependent, non-integral or enumeration type. 3294 Diag(Init->getSourceRange().getBegin(), 3295 diag::err_in_class_initializer_non_integral_type) 3296 << Init->getType() << Init->getSourceRange(); 3297 VDecl->setInvalidDecl(); 3298 } else if (!Init->isTypeDependent() && !Init->isValueDependent()) { 3299 // Check whether the expression is a constant expression. 3300 llvm::APSInt Value; 3301 SourceLocation Loc; 3302 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) { 3303 Diag(Loc, diag::err_in_class_initializer_non_constant) 3304 << Init->getSourceRange(); 3305 VDecl->setInvalidDecl(); 3306 } else if (!VDecl->getType()->isDependentType()) 3307 ImpCastExprToType(Init, VDecl->getType()); 3308 } 3309 } 3310 } else if (VDecl->isFileVarDecl()) { 3311 if (VDecl->getStorageClass() == VarDecl::Extern) 3312 Diag(VDecl->getLocation(), diag::warn_extern_init); 3313 if (!VDecl->isInvalidDecl()) 3314 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(), 3315 VDecl->getDeclName(), DirectInit)) 3316 VDecl->setInvalidDecl(); 3317 3318 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 3319 // Don't check invalid declarations to avoid emitting useless diagnostics. 3320 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 3321 // C99 6.7.8p4. All file scoped initializers need to be constant. 3322 CheckForConstantInitializer(Init, DclT); 3323 } 3324 } 3325 // If the type changed, it means we had an incomplete type that was 3326 // completed by the initializer. For example: 3327 // int ary[] = { 1, 3, 5 }; 3328 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 3329 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 3330 VDecl->setType(DclT); 3331 Init->setType(DclT); 3332 } 3333 3334 Init = MaybeCreateCXXExprWithTemporaries(Init, 3335 /*ShouldDestroyTemporaries=*/true); 3336 // Attach the initializer to the decl. 3337 VDecl->setInit(Context, Init); 3338 3339 // If the previous declaration of VDecl was a tentative definition, 3340 // remove it from the set of tentative definitions. 3341 if (VDecl->getPreviousDeclaration() && 3342 VDecl->getPreviousDeclaration()->isTentativeDefinition(Context)) { 3343 bool Deleted = TentativeDefinitions.erase(VDecl->getDeclName()); 3344 assert(Deleted && "Unrecorded tentative definition?"); Deleted=Deleted; 3345 } 3346 3347 return; 3348} 3349 3350void Sema::ActOnUninitializedDecl(DeclPtrTy dcl, 3351 bool TypeContainsUndeducedAuto) { 3352 Decl *RealDecl = dcl.getAs<Decl>(); 3353 3354 // If there is no declaration, there was an error parsing it. Just ignore it. 3355 if (RealDecl == 0) 3356 return; 3357 3358 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 3359 QualType Type = Var->getType(); 3360 3361 // Record tentative definitions. 3362 if (Var->isTentativeDefinition(Context)) { 3363 std::pair<llvm::DenseMap<DeclarationName, VarDecl *>::iterator, bool> 3364 InsertPair = 3365 TentativeDefinitions.insert(std::make_pair(Var->getDeclName(), Var)); 3366 3367 // Keep the latest definition in the map. If we see 'int i; int i;' we 3368 // want the second one in the map. 3369 InsertPair.first->second = Var; 3370 3371 // However, for the list, we don't care about the order, just make sure 3372 // that there are no dupes for a given declaration name. 3373 if (InsertPair.second) 3374 TentativeDefinitionList.push_back(Var->getDeclName()); 3375 } 3376 3377 // C++ [dcl.init.ref]p3: 3378 // The initializer can be omitted for a reference only in a 3379 // parameter declaration (8.3.5), in the declaration of a 3380 // function return type, in the declaration of a class member 3381 // within its class declaration (9.2), and where the extern 3382 // specifier is explicitly used. 3383 if (Type->isReferenceType() && !Var->hasExternalStorage()) { 3384 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 3385 << Var->getDeclName() 3386 << SourceRange(Var->getLocation(), Var->getLocation()); 3387 Var->setInvalidDecl(); 3388 return; 3389 } 3390 3391 // C++0x [dcl.spec.auto]p3 3392 if (TypeContainsUndeducedAuto) { 3393 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 3394 << Var->getDeclName() << Type; 3395 Var->setInvalidDecl(); 3396 return; 3397 } 3398 3399 // C++ [dcl.init]p9: 3400 // If no initializer is specified for an object, and the object 3401 // is of (possibly cv-qualified) non-POD class type (or array 3402 // thereof), the object shall be default-initialized; if the 3403 // object is of const-qualified type, the underlying class type 3404 // shall have a user-declared default constructor. 3405 // 3406 // FIXME: Diagnose the "user-declared default constructor" bit. 3407 if (getLangOptions().CPlusPlus) { 3408 QualType InitType = Type; 3409 if (const ArrayType *Array = Context.getAsArrayType(Type)) 3410 InitType = Array->getElementType(); 3411 if ((!Var->hasExternalStorage() && !Var->isExternC()) && 3412 InitType->isRecordType() && !InitType->isDependentType()) { 3413 if (!RequireCompleteType(Var->getLocation(), InitType, 3414 diag::err_invalid_incomplete_type_use)) { 3415 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 3416 3417 CXXConstructorDecl *Constructor 3418 = PerformInitializationByConstructor(InitType, 3419 MultiExprArg(*this, 0, 0), 3420 Var->getLocation(), 3421 SourceRange(Var->getLocation(), 3422 Var->getLocation()), 3423 Var->getDeclName(), 3424 IK_Default, 3425 ConstructorArgs); 3426 3427 // FIXME: Location info for the variable initialization? 3428 if (!Constructor) 3429 Var->setInvalidDecl(); 3430 else { 3431 // FIXME: Cope with initialization of arrays 3432 if (!Constructor->isTrivial() && 3433 InitializeVarWithConstructor(Var, Constructor, InitType, 3434 move_arg(ConstructorArgs))) 3435 Var->setInvalidDecl(); 3436 3437 FinalizeVarWithDestructor(Var, InitType); 3438 } 3439 } 3440 } 3441 } 3442 3443#if 0 3444 // FIXME: Temporarily disabled because we are not properly parsing 3445 // linkage specifications on declarations, e.g., 3446 // 3447 // extern "C" const CGPoint CGPointerZero; 3448 // 3449 // C++ [dcl.init]p9: 3450 // 3451 // If no initializer is specified for an object, and the 3452 // object is of (possibly cv-qualified) non-POD class type (or 3453 // array thereof), the object shall be default-initialized; if 3454 // the object is of const-qualified type, the underlying class 3455 // type shall have a user-declared default 3456 // constructor. Otherwise, if no initializer is specified for 3457 // an object, the object and its subobjects, if any, have an 3458 // indeterminate initial value; if the object or any of its 3459 // subobjects are of const-qualified type, the program is 3460 // ill-formed. 3461 // 3462 // This isn't technically an error in C, so we don't diagnose it. 3463 // 3464 // FIXME: Actually perform the POD/user-defined default 3465 // constructor check. 3466 if (getLangOptions().CPlusPlus && 3467 Context.getCanonicalType(Type).isConstQualified() && 3468 !Var->hasExternalStorage()) 3469 Diag(Var->getLocation(), diag::err_const_var_requires_init) 3470 << Var->getName() 3471 << SourceRange(Var->getLocation(), Var->getLocation()); 3472#endif 3473 } 3474} 3475 3476Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 3477 DeclPtrTy *Group, 3478 unsigned NumDecls) { 3479 llvm::SmallVector<Decl*, 8> Decls; 3480 3481 if (DS.isTypeSpecOwned()) 3482 Decls.push_back((Decl*)DS.getTypeRep()); 3483 3484 for (unsigned i = 0; i != NumDecls; ++i) 3485 if (Decl *D = Group[i].getAs<Decl>()) 3486 Decls.push_back(D); 3487 3488 // Perform semantic analysis that depends on having fully processed both 3489 // the declarator and initializer. 3490 for (unsigned i = 0, e = Decls.size(); i != e; ++i) { 3491 VarDecl *IDecl = dyn_cast<VarDecl>(Decls[i]); 3492 if (!IDecl) 3493 continue; 3494 QualType T = IDecl->getType(); 3495 3496 // Block scope. C99 6.7p7: If an identifier for an object is declared with 3497 // no linkage (C99 6.2.2p6), the type for the object shall be complete... 3498 if (IDecl->isBlockVarDecl() && !IDecl->hasExternalStorage()) { 3499 if (!IDecl->isInvalidDecl() && 3500 RequireCompleteType(IDecl->getLocation(), T, 3501 diag::err_typecheck_decl_incomplete_type)) 3502 IDecl->setInvalidDecl(); 3503 } 3504 // File scope. C99 6.9.2p2: A declaration of an identifier for an 3505 // object that has file scope without an initializer, and without a 3506 // storage-class specifier or with the storage-class specifier "static", 3507 // constitutes a tentative definition. Note: A tentative definition with 3508 // external linkage is valid (C99 6.2.2p5). 3509 if (IDecl->isTentativeDefinition(Context) && !IDecl->isInvalidDecl()) { 3510 if (const IncompleteArrayType *ArrayT 3511 = Context.getAsIncompleteArrayType(T)) { 3512 if (RequireCompleteType(IDecl->getLocation(), 3513 ArrayT->getElementType(), 3514 diag::err_illegal_decl_array_incomplete_type)) 3515 IDecl->setInvalidDecl(); 3516 } else if (IDecl->getStorageClass() == VarDecl::Static) { 3517 // C99 6.9.2p3: If the declaration of an identifier for an object is 3518 // a tentative definition and has internal linkage (C99 6.2.2p3), the 3519 // declared type shall not be an incomplete type. 3520 // NOTE: code such as the following 3521 // static struct s; 3522 // struct s { int a; }; 3523 // is accepted by gcc. Hence here we issue a warning instead of 3524 // an error and we do not invalidate the static declaration. 3525 // NOTE: to avoid multiple warnings, only check the first declaration. 3526 if (IDecl->getPreviousDeclaration() == 0) 3527 RequireCompleteType(IDecl->getLocation(), T, 3528 diag::ext_typecheck_decl_incomplete_type); 3529 } 3530 } 3531 } 3532 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, 3533 Decls.data(), Decls.size())); 3534} 3535 3536 3537/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 3538/// to introduce parameters into function prototype scope. 3539Sema::DeclPtrTy 3540Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 3541 const DeclSpec &DS = D.getDeclSpec(); 3542 3543 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 3544 VarDecl::StorageClass StorageClass = VarDecl::None; 3545 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 3546 StorageClass = VarDecl::Register; 3547 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 3548 Diag(DS.getStorageClassSpecLoc(), 3549 diag::err_invalid_storage_class_in_func_decl); 3550 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3551 } 3552 3553 if (D.getDeclSpec().isThreadSpecified()) 3554 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 3555 3556 DiagnoseFunctionSpecifiers(D); 3557 3558 // Check that there are no default arguments inside the type of this 3559 // parameter (C++ only). 3560 if (getLangOptions().CPlusPlus) 3561 CheckExtraCXXDefaultArguments(D); 3562 3563 DeclaratorInfo *DInfo = 0; 3564 TagDecl *OwnedDecl = 0; 3565 QualType parmDeclType = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, 3566 &OwnedDecl); 3567 3568 if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) { 3569 // C++ [dcl.fct]p6: 3570 // Types shall not be defined in return or parameter types. 3571 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type) 3572 << Context.getTypeDeclType(OwnedDecl); 3573 } 3574 3575 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 3576 // Can this happen for params? We already checked that they don't conflict 3577 // among each other. Here they can only shadow globals, which is ok. 3578 IdentifierInfo *II = D.getIdentifier(); 3579 if (II) { 3580 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) { 3581 if (PrevDecl->isTemplateParameter()) { 3582 // Maybe we will complain about the shadowed template parameter. 3583 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 3584 // Just pretend that we didn't see the previous declaration. 3585 PrevDecl = 0; 3586 } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) { 3587 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 3588 3589 // Recover by removing the name 3590 II = 0; 3591 D.SetIdentifier(0, D.getIdentifierLoc()); 3592 } 3593 } 3594 } 3595 3596 // Parameters can not be abstract class types. 3597 // For record types, this is done by the AbstractClassUsageDiagnoser once 3598 // the class has been completely parsed. 3599 if (!CurContext->isRecord() && 3600 RequireNonAbstractType(D.getIdentifierLoc(), parmDeclType, 3601 diag::err_abstract_type_in_decl, 3602 AbstractParamType)) 3603 D.setInvalidType(true); 3604 3605 QualType T = adjustParameterType(parmDeclType); 3606 3607 ParmVarDecl *New; 3608 if (T == parmDeclType) // parameter type did not need adjustment 3609 New = ParmVarDecl::Create(Context, CurContext, 3610 D.getIdentifierLoc(), II, 3611 parmDeclType, DInfo, StorageClass, 3612 0); 3613 else // keep track of both the adjusted and unadjusted types 3614 New = OriginalParmVarDecl::Create(Context, CurContext, 3615 D.getIdentifierLoc(), II, T, DInfo, 3616 parmDeclType, StorageClass, 0); 3617 3618 if (D.isInvalidType()) 3619 New->setInvalidDecl(); 3620 3621 // Parameter declarators cannot be interface types. All ObjC objects are 3622 // passed by reference. 3623 if (T->isObjCInterfaceType()) { 3624 Diag(D.getIdentifierLoc(), 3625 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T; 3626 New->setInvalidDecl(); 3627 } 3628 3629 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 3630 if (D.getCXXScopeSpec().isSet()) { 3631 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 3632 << D.getCXXScopeSpec().getRange(); 3633 New->setInvalidDecl(); 3634 } 3635 3636 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 3637 // duration shall not be qualified by an address-space qualifier." 3638 // Since all parameters have automatic store duration, they can not have 3639 // an address space. 3640 if (T.getAddressSpace() != 0) { 3641 Diag(D.getIdentifierLoc(), 3642 diag::err_arg_with_address_space); 3643 New->setInvalidDecl(); 3644 } 3645 3646 3647 // Add the parameter declaration into this scope. 3648 S->AddDecl(DeclPtrTy::make(New)); 3649 if (II) 3650 IdResolver.AddDecl(New); 3651 3652 ProcessDeclAttributes(S, New, D); 3653 3654 if (New->hasAttr<BlocksAttr>()) { 3655 Diag(New->getLocation(), diag::err_block_on_nonlocal); 3656 } 3657 return DeclPtrTy::make(New); 3658} 3659 3660void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 3661 SourceLocation LocAfterDecls) { 3662 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 3663 "Not a function declarator!"); 3664 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 3665 3666 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 3667 // for a K&R function. 3668 if (!FTI.hasPrototype) { 3669 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 3670 --i; 3671 if (FTI.ArgInfo[i].Param == 0) { 3672 std::string Code = " int "; 3673 Code += FTI.ArgInfo[i].Ident->getName(); 3674 Code += ";\n"; 3675 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 3676 << FTI.ArgInfo[i].Ident 3677 << CodeModificationHint::CreateInsertion(LocAfterDecls, Code); 3678 3679 // Implicitly declare the argument as type 'int' for lack of a better 3680 // type. 3681 DeclSpec DS; 3682 const char* PrevSpec; // unused 3683 unsigned DiagID; // unused 3684 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 3685 PrevSpec, DiagID); 3686 Declarator ParamD(DS, Declarator::KNRTypeListContext); 3687 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 3688 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 3689 } 3690 } 3691 } 3692} 3693 3694Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, 3695 Declarator &D) { 3696 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 3697 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 3698 "Not a function declarator!"); 3699 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 3700 3701 if (FTI.hasPrototype) { 3702 // FIXME: Diagnose arguments without names in C. 3703 } 3704 3705 Scope *ParentScope = FnBodyScope->getParent(); 3706 3707 DeclPtrTy DP = HandleDeclarator(ParentScope, D, 3708 MultiTemplateParamsArg(*this), 3709 /*IsFunctionDefinition=*/true); 3710 return ActOnStartOfFunctionDef(FnBodyScope, DP); 3711} 3712 3713Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) { 3714 if (!D) 3715 return D; 3716 FunctionDecl *FD = 0; 3717 3718 if (FunctionTemplateDecl *FunTmpl 3719 = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>())) 3720 FD = FunTmpl->getTemplatedDecl(); 3721 else 3722 FD = cast<FunctionDecl>(D.getAs<Decl>()); 3723 3724 CurFunctionNeedsScopeChecking = false; 3725 3726 // See if this is a redefinition. 3727 const FunctionDecl *Definition; 3728 if (FD->getBody(Definition)) { 3729 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 3730 Diag(Definition->getLocation(), diag::note_previous_definition); 3731 } 3732 3733 // Builtin functions cannot be defined. 3734 if (unsigned BuiltinID = FD->getBuiltinID()) { 3735 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3736 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 3737 FD->setInvalidDecl(); 3738 } 3739 } 3740 3741 // The return type of a function definition must be complete 3742 // (C99 6.9.1p3, C++ [dcl.fct]p6). 3743 QualType ResultType = FD->getResultType(); 3744 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 3745 !FD->isInvalidDecl() && 3746 RequireCompleteType(FD->getLocation(), ResultType, 3747 diag::err_func_def_incomplete_result)) 3748 FD->setInvalidDecl(); 3749 3750 // GNU warning -Wmissing-prototypes: 3751 // Warn if a global function is defined without a previous 3752 // prototype declaration. This warning is issued even if the 3753 // definition itself provides a prototype. The aim is to detect 3754 // global functions that fail to be declared in header files. 3755 if (!FD->isInvalidDecl() && FD->isGlobal() && !isa<CXXMethodDecl>(FD) && 3756 !FD->isMain()) { 3757 bool MissingPrototype = true; 3758 for (const FunctionDecl *Prev = FD->getPreviousDeclaration(); 3759 Prev; Prev = Prev->getPreviousDeclaration()) { 3760 // Ignore any declarations that occur in function or method 3761 // scope, because they aren't visible from the header. 3762 if (Prev->getDeclContext()->isFunctionOrMethod()) 3763 continue; 3764 3765 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 3766 break; 3767 } 3768 3769 if (MissingPrototype) 3770 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 3771 } 3772 3773 if (FnBodyScope) 3774 PushDeclContext(FnBodyScope, FD); 3775 3776 // Check the validity of our function parameters 3777 CheckParmsForFunctionDef(FD); 3778 3779 // Introduce our parameters into the function scope 3780 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 3781 ParmVarDecl *Param = FD->getParamDecl(p); 3782 Param->setOwningFunction(FD); 3783 3784 // If this has an identifier, add it to the scope stack. 3785 if (Param->getIdentifier() && FnBodyScope) 3786 PushOnScopeChains(Param, FnBodyScope); 3787 } 3788 3789 // Checking attributes of current function definition 3790 // dllimport attribute. 3791 if (FD->getAttr<DLLImportAttr>() && 3792 (!FD->getAttr<DLLExportAttr>())) { 3793 // dllimport attribute cannot be applied to definition. 3794 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) { 3795 Diag(FD->getLocation(), 3796 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 3797 << "dllimport"; 3798 FD->setInvalidDecl(); 3799 return DeclPtrTy::make(FD); 3800 } else { 3801 // If a symbol previously declared dllimport is later defined, the 3802 // attribute is ignored in subsequent references, and a warning is 3803 // emitted. 3804 Diag(FD->getLocation(), 3805 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 3806 << FD->getNameAsCString() << "dllimport"; 3807 } 3808 } 3809 return DeclPtrTy::make(FD); 3810} 3811 3812Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) { 3813 return ActOnFinishFunctionBody(D, move(BodyArg), false); 3814} 3815 3816Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg, 3817 bool IsInstantiation) { 3818 Decl *dcl = D.getAs<Decl>(); 3819 Stmt *Body = BodyArg.takeAs<Stmt>(); 3820 3821 FunctionDecl *FD = 0; 3822 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 3823 if (FunTmpl) 3824 FD = FunTmpl->getTemplatedDecl(); 3825 else 3826 FD = dyn_cast_or_null<FunctionDecl>(dcl); 3827 3828 if (FD) { 3829 FD->setBody(Body); 3830 if (FD->isMain()) 3831 // C and C++ allow for main to automagically return 0. 3832 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3. 3833 FD->setHasImplicitReturnZero(true); 3834 else 3835 CheckFallThroughForFunctionDef(FD, Body); 3836 3837 if (!FD->isInvalidDecl()) 3838 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 3839 3840 // C++ [basic.def.odr]p2: 3841 // [...] A virtual member function is used if it is not pure. [...] 3842 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 3843 if (Method->isVirtual() && !Method->isPure()) 3844 MarkDeclarationReferenced(Method->getLocation(), Method); 3845 3846 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 3847 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 3848 assert(MD == getCurMethodDecl() && "Method parsing confused"); 3849 MD->setBody(Body); 3850 CheckFallThroughForFunctionDef(MD, Body); 3851 MD->setEndLoc(Body->getLocEnd()); 3852 3853 if (!MD->isInvalidDecl()) 3854 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 3855 } else { 3856 Body->Destroy(Context); 3857 return DeclPtrTy(); 3858 } 3859 if (!IsInstantiation) 3860 PopDeclContext(); 3861 3862 // Verify and clean out per-function state. 3863 3864 assert(&getLabelMap() == &FunctionLabelMap && "Didn't pop block right?"); 3865 3866 // Check goto/label use. 3867 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 3868 I = FunctionLabelMap.begin(), E = FunctionLabelMap.end(); I != E; ++I) { 3869 LabelStmt *L = I->second; 3870 3871 // Verify that we have no forward references left. If so, there was a goto 3872 // or address of a label taken, but no definition of it. Label fwd 3873 // definitions are indicated with a null substmt. 3874 if (L->getSubStmt() != 0) 3875 continue; 3876 3877 // Emit error. 3878 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName(); 3879 3880 // At this point, we have gotos that use the bogus label. Stitch it into 3881 // the function body so that they aren't leaked and that the AST is well 3882 // formed. 3883 if (Body == 0) { 3884 // The whole function wasn't parsed correctly, just delete this. 3885 L->Destroy(Context); 3886 continue; 3887 } 3888 3889 // Otherwise, the body is valid: we want to stitch the label decl into the 3890 // function somewhere so that it is properly owned and so that the goto 3891 // has a valid target. Do this by creating a new compound stmt with the 3892 // label in it. 3893 3894 // Give the label a sub-statement. 3895 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc())); 3896 3897 CompoundStmt *Compound = isa<CXXTryStmt>(Body) ? 3898 cast<CXXTryStmt>(Body)->getTryBlock() : 3899 cast<CompoundStmt>(Body); 3900 std::vector<Stmt*> Elements(Compound->body_begin(), Compound->body_end()); 3901 Elements.push_back(L); 3902 Compound->setStmts(Context, &Elements[0], Elements.size()); 3903 } 3904 FunctionLabelMap.clear(); 3905 3906 if (!Body) return D; 3907 3908 // Verify that that gotos and switch cases don't jump into scopes illegally. 3909 if (CurFunctionNeedsScopeChecking) 3910 DiagnoseInvalidJumps(Body); 3911 3912 // C++ constructors that have function-try-blocks can't have return 3913 // statements in the handlers of that block. (C++ [except.handle]p14) 3914 // Verify this. 3915 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 3916 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 3917 3918 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) 3919 computeBaseOrMembersToDestroy(Destructor); 3920 return D; 3921} 3922 3923/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 3924/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 3925NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 3926 IdentifierInfo &II, Scope *S) { 3927 // Before we produce a declaration for an implicitly defined 3928 // function, see whether there was a locally-scoped declaration of 3929 // this name as a function or variable. If so, use that 3930 // (non-visible) declaration, and complain about it. 3931 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 3932 = LocallyScopedExternalDecls.find(&II); 3933 if (Pos != LocallyScopedExternalDecls.end()) { 3934 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 3935 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 3936 return Pos->second; 3937 } 3938 3939 // Extension in C99. Legal in C90, but warn about it. 3940 static const unsigned int BuiltinLen = strlen("__builtin_"); 3941 if (II.getLength() > BuiltinLen && 3942 std::equal(II.getName(), II.getName() + BuiltinLen, "__builtin_")) 3943 Diag(Loc, diag::warn_builtin_unknown) << &II; 3944 else if (getLangOptions().C99) 3945 Diag(Loc, diag::ext_implicit_function_decl) << &II; 3946 else 3947 Diag(Loc, diag::warn_implicit_function_decl) << &II; 3948 3949 // Set a Declarator for the implicit definition: int foo(); 3950 const char *Dummy; 3951 DeclSpec DS; 3952 unsigned DiagID; 3953 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 3954 Error = Error; // Silence warning. 3955 assert(!Error && "Error setting up implicit decl!"); 3956 Declarator D(DS, Declarator::BlockContext); 3957 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0, 3958 0, 0, false, SourceLocation(), 3959 false, 0,0,0, Loc, Loc, D), 3960 SourceLocation()); 3961 D.SetIdentifier(&II, Loc); 3962 3963 // Insert this function into translation-unit scope. 3964 3965 DeclContext *PrevDC = CurContext; 3966 CurContext = Context.getTranslationUnitDecl(); 3967 3968 FunctionDecl *FD = 3969 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>()); 3970 FD->setImplicit(); 3971 3972 CurContext = PrevDC; 3973 3974 AddKnownFunctionAttributes(FD); 3975 3976 return FD; 3977} 3978 3979/// \brief Adds any function attributes that we know a priori based on 3980/// the declaration of this function. 3981/// 3982/// These attributes can apply both to implicitly-declared builtins 3983/// (like __builtin___printf_chk) or to library-declared functions 3984/// like NSLog or printf. 3985void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 3986 if (FD->isInvalidDecl()) 3987 return; 3988 3989 // If this is a built-in function, map its builtin attributes to 3990 // actual attributes. 3991 if (unsigned BuiltinID = FD->getBuiltinID()) { 3992 // Handle printf-formatting attributes. 3993 unsigned FormatIdx; 3994 bool HasVAListArg; 3995 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 3996 if (!FD->getAttr<FormatAttr>()) 3997 FD->addAttr(::new (Context) FormatAttr("printf", FormatIdx + 1, 3998 HasVAListArg ? 0 : FormatIdx + 2)); 3999 } 4000 4001 // Mark const if we don't care about errno and that is the only 4002 // thing preventing the function from being const. This allows 4003 // IRgen to use LLVM intrinsics for such functions. 4004 if (!getLangOptions().MathErrno && 4005 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 4006 if (!FD->getAttr<ConstAttr>()) 4007 FD->addAttr(::new (Context) ConstAttr()); 4008 } 4009 4010 if (Context.BuiltinInfo.isNoReturn(BuiltinID)) 4011 FD->addAttr(::new (Context) NoReturnAttr()); 4012 } 4013 4014 IdentifierInfo *Name = FD->getIdentifier(); 4015 if (!Name) 4016 return; 4017 if ((!getLangOptions().CPlusPlus && 4018 FD->getDeclContext()->isTranslationUnit()) || 4019 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 4020 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 4021 LinkageSpecDecl::lang_c)) { 4022 // Okay: this could be a libc/libm/Objective-C function we know 4023 // about. 4024 } else 4025 return; 4026 4027 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) { 4028 // FIXME: NSLog and NSLogv should be target specific 4029 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) { 4030 // FIXME: We known better than our headers. 4031 const_cast<FormatAttr *>(Format)->setType("printf"); 4032 } else 4033 FD->addAttr(::new (Context) FormatAttr("printf", 1, 4034 Name->isStr("NSLogv") ? 0 : 2)); 4035 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 4036 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 4037 // target-specific builtins, perhaps? 4038 if (!FD->getAttr<FormatAttr>()) 4039 FD->addAttr(::new (Context) FormatAttr("printf", 2, 4040 Name->isStr("vasprintf") ? 0 : 3)); 4041 } 4042} 4043 4044TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T) { 4045 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 4046 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 4047 4048 // Scope manipulation handled by caller. 4049 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 4050 D.getIdentifierLoc(), 4051 D.getIdentifier(), 4052 T); 4053 4054 if (const TagType *TT = T->getAs<TagType>()) { 4055 TagDecl *TD = TT->getDecl(); 4056 4057 // If the TagDecl that the TypedefDecl points to is an anonymous decl 4058 // keep track of the TypedefDecl. 4059 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl()) 4060 TD->setTypedefForAnonDecl(NewTD); 4061 } 4062 4063 if (D.isInvalidType()) 4064 NewTD->setInvalidDecl(); 4065 return NewTD; 4066} 4067 4068 4069/// \brief Determine whether a tag with a given kind is acceptable 4070/// as a redeclaration of the given tag declaration. 4071/// 4072/// \returns true if the new tag kind is acceptable, false otherwise. 4073bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 4074 TagDecl::TagKind NewTag, 4075 SourceLocation NewTagLoc, 4076 const IdentifierInfo &Name) { 4077 // C++ [dcl.type.elab]p3: 4078 // The class-key or enum keyword present in the 4079 // elaborated-type-specifier shall agree in kind with the 4080 // declaration to which the name in theelaborated-type-specifier 4081 // refers. This rule also applies to the form of 4082 // elaborated-type-specifier that declares a class-name or 4083 // friend class since it can be construed as referring to the 4084 // definition of the class. Thus, in any 4085 // elaborated-type-specifier, the enum keyword shall be used to 4086 // refer to an enumeration (7.2), the union class-keyshall be 4087 // used to refer to a union (clause 9), and either the class or 4088 // struct class-key shall be used to refer to a class (clause 9) 4089 // declared using the class or struct class-key. 4090 TagDecl::TagKind OldTag = Previous->getTagKind(); 4091 if (OldTag == NewTag) 4092 return true; 4093 4094 if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) && 4095 (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) { 4096 // Warn about the struct/class tag mismatch. 4097 bool isTemplate = false; 4098 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 4099 isTemplate = Record->getDescribedClassTemplate(); 4100 4101 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 4102 << (NewTag == TagDecl::TK_class) 4103 << isTemplate << &Name 4104 << CodeModificationHint::CreateReplacement(SourceRange(NewTagLoc), 4105 OldTag == TagDecl::TK_class? "class" : "struct"); 4106 Diag(Previous->getLocation(), diag::note_previous_use); 4107 return true; 4108 } 4109 return false; 4110} 4111 4112/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 4113/// former case, Name will be non-null. In the later case, Name will be null. 4114/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 4115/// reference/declaration/definition of a tag. 4116Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 4117 SourceLocation KWLoc, const CXXScopeSpec &SS, 4118 IdentifierInfo *Name, SourceLocation NameLoc, 4119 AttributeList *Attr, AccessSpecifier AS, 4120 MultiTemplateParamsArg TemplateParameterLists, 4121 bool &OwnedDecl, bool &IsDependent) { 4122 // If this is not a definition, it must have a name. 4123 assert((Name != 0 || TUK == TUK_Definition) && 4124 "Nameless record must be a definition!"); 4125 4126 OwnedDecl = false; 4127 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec); 4128 4129 if (TUK != TUK_Reference) { 4130 if (TemplateParameterList *TemplateParams 4131 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS, 4132 (TemplateParameterList**)TemplateParameterLists.get(), 4133 TemplateParameterLists.size())) { 4134 if (TemplateParams->size() > 0) { 4135 // This is a declaration or definition of a class template (which may 4136 // be a member of another template). 4137 OwnedDecl = false; 4138 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 4139 SS, Name, NameLoc, Attr, 4140 TemplateParams, 4141 AS); 4142 TemplateParameterLists.release(); 4143 return Result.get(); 4144 } else { 4145 // FIXME: diagnose the extraneous 'template<>', once we recover 4146 // slightly better in ParseTemplate.cpp from bogus template 4147 // parameters. 4148 } 4149 } 4150 } 4151 4152 DeclContext *SearchDC = CurContext; 4153 DeclContext *DC = CurContext; 4154 NamedDecl *PrevDecl = 0; 4155 bool isStdBadAlloc = false; 4156 bool Invalid = false; 4157 4158 if (Name && SS.isNotEmpty()) { 4159 // We have a nested-name tag ('struct foo::bar'). 4160 4161 // Check for invalid 'foo::'. 4162 if (SS.isInvalid()) { 4163 Name = 0; 4164 goto CreateNewDecl; 4165 } 4166 4167 // If this is a friend or a reference to a class in a dependent 4168 // context, don't try to make a decl for it. 4169 if (TUK == TUK_Friend || TUK == TUK_Reference) { 4170 DC = computeDeclContext(SS, false); 4171 if (!DC) { 4172 IsDependent = true; 4173 return DeclPtrTy(); 4174 } 4175 } 4176 4177 if (RequireCompleteDeclContext(SS)) 4178 return DeclPtrTy::make((Decl *)0); 4179 4180 DC = computeDeclContext(SS, true); 4181 SearchDC = DC; 4182 // Look-up name inside 'foo::'. 4183 PrevDecl 4184 = dyn_cast_or_null<TagDecl>( 4185 LookupQualifiedName(DC, Name, LookupTagName, true).getAsDecl()); 4186 4187 // A tag 'foo::bar' must already exist. 4188 if (PrevDecl == 0) { 4189 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange(); 4190 Name = 0; 4191 Invalid = true; 4192 goto CreateNewDecl; 4193 } 4194 } else if (Name) { 4195 // If this is a named struct, check to see if there was a previous forward 4196 // declaration or definition. 4197 // FIXME: We're looking into outer scopes here, even when we 4198 // shouldn't be. Doing so can result in ambiguities that we 4199 // shouldn't be diagnosing. 4200 LookupResult R = LookupName(S, Name, LookupTagName, 4201 /*RedeclarationOnly=*/(TUK != TUK_Reference)); 4202 if (R.isAmbiguous()) { 4203 DiagnoseAmbiguousLookup(R, Name, NameLoc); 4204 // FIXME: This is not best way to recover from case like: 4205 // 4206 // struct S s; 4207 // 4208 // causes needless "incomplete type" error later. 4209 Name = 0; 4210 PrevDecl = 0; 4211 Invalid = true; 4212 } else 4213 PrevDecl = R; 4214 4215 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) { 4216 // FIXME: This makes sure that we ignore the contexts associated 4217 // with C structs, unions, and enums when looking for a matching 4218 // tag declaration or definition. See the similar lookup tweak 4219 // in Sema::LookupName; is there a better way to deal with this? 4220 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 4221 SearchDC = SearchDC->getParent(); 4222 } 4223 } 4224 4225 if (PrevDecl && PrevDecl->isTemplateParameter()) { 4226 // Maybe we will complain about the shadowed template parameter. 4227 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); 4228 // Just pretend that we didn't see the previous declaration. 4229 PrevDecl = 0; 4230 } 4231 4232 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace && 4233 DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) { 4234 // This is a declaration of or a reference to "std::bad_alloc". 4235 isStdBadAlloc = true; 4236 4237 if (!PrevDecl && StdBadAlloc) { 4238 // std::bad_alloc has been implicitly declared (but made invisible to 4239 // name lookup). Fill in this implicit declaration as the previous 4240 // declaration, so that the declarations get chained appropriately. 4241 PrevDecl = StdBadAlloc; 4242 } 4243 } 4244 4245 if (PrevDecl) { 4246 // Check whether the previous declaration is usable. 4247 (void)DiagnoseUseOfDecl(PrevDecl, NameLoc); 4248 4249 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 4250 // If this is a use of a previous tag, or if the tag is already declared 4251 // in the same scope (so that the definition/declaration completes or 4252 // rementions the tag), reuse the decl. 4253 if (TUK == TUK_Reference || TUK == TUK_Friend || 4254 isDeclInScope(PrevDecl, SearchDC, S)) { 4255 // Make sure that this wasn't declared as an enum and now used as a 4256 // struct or something similar. 4257 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) { 4258 bool SafeToContinue 4259 = (PrevTagDecl->getTagKind() != TagDecl::TK_enum && 4260 Kind != TagDecl::TK_enum); 4261 if (SafeToContinue) 4262 Diag(KWLoc, diag::err_use_with_wrong_tag) 4263 << Name 4264 << CodeModificationHint::CreateReplacement(SourceRange(KWLoc), 4265 PrevTagDecl->getKindName()); 4266 else 4267 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 4268 Diag(PrevDecl->getLocation(), diag::note_previous_use); 4269 4270 if (SafeToContinue) 4271 Kind = PrevTagDecl->getTagKind(); 4272 else { 4273 // Recover by making this an anonymous redefinition. 4274 Name = 0; 4275 PrevDecl = 0; 4276 Invalid = true; 4277 } 4278 } 4279 4280 if (!Invalid) { 4281 // If this is a use, just return the declaration we found. 4282 4283 // FIXME: In the future, return a variant or some other clue 4284 // for the consumer of this Decl to know it doesn't own it. 4285 // For our current ASTs this shouldn't be a problem, but will 4286 // need to be changed with DeclGroups. 4287 if (TUK == TUK_Reference) 4288 return DeclPtrTy::make(PrevDecl); 4289 4290 // If this is a friend, make sure we create the new 4291 // declaration in the appropriate semantic context. 4292 if (TUK == TUK_Friend) 4293 SearchDC = PrevDecl->getDeclContext(); 4294 4295 // Diagnose attempts to redefine a tag. 4296 if (TUK == TUK_Definition) { 4297 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) { 4298 Diag(NameLoc, diag::err_redefinition) << Name; 4299 Diag(Def->getLocation(), diag::note_previous_definition); 4300 // If this is a redefinition, recover by making this 4301 // struct be anonymous, which will make any later 4302 // references get the previous definition. 4303 Name = 0; 4304 PrevDecl = 0; 4305 Invalid = true; 4306 } else { 4307 // If the type is currently being defined, complain 4308 // about a nested redefinition. 4309 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 4310 if (Tag->isBeingDefined()) { 4311 Diag(NameLoc, diag::err_nested_redefinition) << Name; 4312 Diag(PrevTagDecl->getLocation(), 4313 diag::note_previous_definition); 4314 Name = 0; 4315 PrevDecl = 0; 4316 Invalid = true; 4317 } 4318 } 4319 4320 // Okay, this is definition of a previously declared or referenced 4321 // tag PrevDecl. We're going to create a new Decl for it. 4322 } 4323 } 4324 // If we get here we have (another) forward declaration or we 4325 // have a definition. Just create a new decl. 4326 4327 } else { 4328 // If we get here, this is a definition of a new tag type in a nested 4329 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 4330 // new decl/type. We set PrevDecl to NULL so that the entities 4331 // have distinct types. 4332 PrevDecl = 0; 4333 } 4334 // If we get here, we're going to create a new Decl. If PrevDecl 4335 // is non-NULL, it's a definition of the tag declared by 4336 // PrevDecl. If it's NULL, we have a new definition. 4337 } else { 4338 // PrevDecl is a namespace, template, or anything else 4339 // that lives in the IDNS_Tag identifier namespace. 4340 if (isDeclInScope(PrevDecl, SearchDC, S)) { 4341 // The tag name clashes with a namespace name, issue an error and 4342 // recover by making this tag be anonymous. 4343 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 4344 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 4345 Name = 0; 4346 PrevDecl = 0; 4347 Invalid = true; 4348 } else { 4349 // The existing declaration isn't relevant to us; we're in a 4350 // new scope, so clear out the previous declaration. 4351 PrevDecl = 0; 4352 } 4353 } 4354 } else if (TUK == TUK_Reference && SS.isEmpty() && Name && 4355 (Kind != TagDecl::TK_enum || !getLangOptions().CPlusPlus)) { 4356 // C++ [basic.scope.pdecl]p5: 4357 // -- for an elaborated-type-specifier of the form 4358 // 4359 // class-key identifier 4360 // 4361 // if the elaborated-type-specifier is used in the 4362 // decl-specifier-seq or parameter-declaration-clause of a 4363 // function defined in namespace scope, the identifier is 4364 // declared as a class-name in the namespace that contains 4365 // the declaration; otherwise, except as a friend 4366 // declaration, the identifier is declared in the smallest 4367 // non-class, non-function-prototype scope that contains the 4368 // declaration. 4369 // 4370 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 4371 // C structs and unions. 4372 // 4373 // GNU C also supports this behavior as part of its incomplete 4374 // enum types extension, while GNU C++ does not. 4375 // 4376 // Find the context where we'll be declaring the tag. 4377 // FIXME: We would like to maintain the current DeclContext as the 4378 // lexical context, 4379 while (SearchDC->isRecord()) 4380 SearchDC = SearchDC->getParent(); 4381 4382 // Find the scope where we'll be declaring the tag. 4383 while (S->isClassScope() || 4384 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) || 4385 ((S->getFlags() & Scope::DeclScope) == 0) || 4386 (S->getEntity() && 4387 ((DeclContext *)S->getEntity())->isTransparentContext())) 4388 S = S->getParent(); 4389 4390 } else if (TUK == TUK_Friend && SS.isEmpty() && Name) { 4391 // C++ [namespace.memdef]p3: 4392 // If a friend declaration in a non-local class first declares a 4393 // class or function, the friend class or function is a member of 4394 // the innermost enclosing namespace. 4395 while (!SearchDC->isFileContext()) 4396 SearchDC = SearchDC->getParent(); 4397 4398 // The entity of a decl scope is a DeclContext; see PushDeclContext. 4399 while (S->getEntity() != SearchDC) 4400 S = S->getParent(); 4401 } 4402 4403CreateNewDecl: 4404 4405 // If there is an identifier, use the location of the identifier as the 4406 // location of the decl, otherwise use the location of the struct/union 4407 // keyword. 4408 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 4409 4410 // Otherwise, create a new declaration. If there is a previous 4411 // declaration of the same entity, the two will be linked via 4412 // PrevDecl. 4413 TagDecl *New; 4414 4415 if (Kind == TagDecl::TK_enum) { 4416 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 4417 // enum X { A, B, C } D; D should chain to X. 4418 New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc, 4419 cast_or_null<EnumDecl>(PrevDecl)); 4420 // If this is an undefined enum, warn. 4421 if (TUK != TUK_Definition && !Invalid) { 4422 unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum 4423 : diag::ext_forward_ref_enum; 4424 Diag(Loc, DK); 4425 } 4426 } else { 4427 // struct/union/class 4428 4429 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 4430 // struct X { int A; } D; D should chain to X. 4431 if (getLangOptions().CPlusPlus) { 4432 // FIXME: Look for a way to use RecordDecl for simple structs. 4433 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc, 4434 cast_or_null<CXXRecordDecl>(PrevDecl)); 4435 4436 if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit())) 4437 StdBadAlloc = cast<CXXRecordDecl>(New); 4438 } else 4439 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc, 4440 cast_or_null<RecordDecl>(PrevDecl)); 4441 } 4442 4443 if (Kind != TagDecl::TK_enum) { 4444 // Handle #pragma pack: if the #pragma pack stack has non-default 4445 // alignment, make up a packed attribute for this decl. These 4446 // attributes are checked when the ASTContext lays out the 4447 // structure. 4448 // 4449 // It is important for implementing the correct semantics that this 4450 // happen here (in act on tag decl). The #pragma pack stack is 4451 // maintained as a result of parser callbacks which can occur at 4452 // many points during the parsing of a struct declaration (because 4453 // the #pragma tokens are effectively skipped over during the 4454 // parsing of the struct). 4455 if (unsigned Alignment = getPragmaPackAlignment()) 4456 New->addAttr(::new (Context) PragmaPackAttr(Alignment * 8)); 4457 } 4458 4459 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) { 4460 // C++ [dcl.typedef]p3: 4461 // [...] Similarly, in a given scope, a class or enumeration 4462 // shall not be declared with the same name as a typedef-name 4463 // that is declared in that scope and refers to a type other 4464 // than the class or enumeration itself. 4465 LookupResult Lookup = LookupName(S, Name, LookupOrdinaryName, true); 4466 TypedefDecl *PrevTypedef = 0; 4467 if (Lookup.getKind() == LookupResult::Found) 4468 PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl()); 4469 4470 NamedDecl *PrevTypedefNamed = PrevTypedef; 4471 if (PrevTypedef && isDeclInScope(PrevTypedefNamed, SearchDC, S) && 4472 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) != 4473 Context.getCanonicalType(Context.getTypeDeclType(New))) { 4474 Diag(Loc, diag::err_tag_definition_of_typedef) 4475 << Context.getTypeDeclType(New) 4476 << PrevTypedef->getUnderlyingType(); 4477 Diag(PrevTypedef->getLocation(), diag::note_previous_definition); 4478 Invalid = true; 4479 } 4480 } 4481 4482 if (Invalid) 4483 New->setInvalidDecl(); 4484 4485 if (Attr) 4486 ProcessDeclAttributeList(S, New, Attr); 4487 4488 // If we're declaring or defining a tag in function prototype scope 4489 // in C, note that this type can only be used within the function. 4490 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus) 4491 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 4492 4493 // Set the lexical context. If the tag has a C++ scope specifier, the 4494 // lexical context will be different from the semantic context. 4495 New->setLexicalDeclContext(CurContext); 4496 4497 // Mark this as a friend decl if applicable. 4498 if (TUK == TUK_Friend) 4499 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ PrevDecl != NULL); 4500 4501 // Set the access specifier. 4502 if (!Invalid && TUK != TUK_Friend) 4503 SetMemberAccessSpecifier(New, PrevDecl, AS); 4504 4505 if (TUK == TUK_Definition) 4506 New->startDefinition(); 4507 4508 // If this has an identifier, add it to the scope stack. 4509 if (TUK == TUK_Friend) { 4510 // We might be replacing an existing declaration in the lookup tables; 4511 // if so, borrow its access specifier. 4512 if (PrevDecl) 4513 New->setAccess(PrevDecl->getAccess()); 4514 4515 // Friend tag decls are visible in fairly strange ways. 4516 if (!CurContext->isDependentContext()) { 4517 DeclContext *DC = New->getDeclContext()->getLookupContext(); 4518 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false); 4519 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 4520 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 4521 } 4522 } else if (Name) { 4523 S = getNonFieldDeclScope(S); 4524 PushOnScopeChains(New, S); 4525 } else { 4526 CurContext->addDecl(New); 4527 } 4528 4529 // If this is the C FILE type, notify the AST context. 4530 if (IdentifierInfo *II = New->getIdentifier()) 4531 if (!New->isInvalidDecl() && 4532 New->getDeclContext()->getLookupContext()->isTranslationUnit() && 4533 II->isStr("FILE")) 4534 Context.setFILEDecl(New); 4535 4536 OwnedDecl = true; 4537 return DeclPtrTy::make(New); 4538} 4539 4540void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) { 4541 AdjustDeclIfTemplate(TagD); 4542 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 4543 4544 // Enter the tag context. 4545 PushDeclContext(S, Tag); 4546 4547 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) { 4548 FieldCollector->StartClass(); 4549 4550 if (Record->getIdentifier()) { 4551 // C++ [class]p2: 4552 // [...] The class-name is also inserted into the scope of the 4553 // class itself; this is known as the injected-class-name. For 4554 // purposes of access checking, the injected-class-name is treated 4555 // as if it were a public member name. 4556 CXXRecordDecl *InjectedClassName 4557 = CXXRecordDecl::Create(Context, Record->getTagKind(), 4558 CurContext, Record->getLocation(), 4559 Record->getIdentifier(), 4560 Record->getTagKeywordLoc(), 4561 Record); 4562 InjectedClassName->setImplicit(); 4563 InjectedClassName->setAccess(AS_public); 4564 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 4565 InjectedClassName->setDescribedClassTemplate(Template); 4566 PushOnScopeChains(InjectedClassName, S); 4567 assert(InjectedClassName->isInjectedClassName() && 4568 "Broken injected-class-name"); 4569 } 4570 } 4571} 4572 4573void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD, 4574 SourceLocation RBraceLoc) { 4575 AdjustDeclIfTemplate(TagD); 4576 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 4577 Tag->setRBraceLoc(RBraceLoc); 4578 4579 if (isa<CXXRecordDecl>(Tag)) 4580 FieldCollector->FinishClass(); 4581 4582 // Exit this scope of this tag's definition. 4583 PopDeclContext(); 4584 4585 // Notify the consumer that we've defined a tag. 4586 Consumer.HandleTagDeclDefinition(Tag); 4587} 4588 4589// Note that FieldName may be null for anonymous bitfields. 4590bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 4591 QualType FieldTy, const Expr *BitWidth, 4592 bool *ZeroWidth) { 4593 // Default to true; that shouldn't confuse checks for emptiness 4594 if (ZeroWidth) 4595 *ZeroWidth = true; 4596 4597 // C99 6.7.2.1p4 - verify the field type. 4598 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 4599 if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) { 4600 // Handle incomplete types with specific error. 4601 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 4602 return true; 4603 if (FieldName) 4604 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 4605 << FieldName << FieldTy << BitWidth->getSourceRange(); 4606 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 4607 << FieldTy << BitWidth->getSourceRange(); 4608 } 4609 4610 // If the bit-width is type- or value-dependent, don't try to check 4611 // it now. 4612 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 4613 return false; 4614 4615 llvm::APSInt Value; 4616 if (VerifyIntegerConstantExpression(BitWidth, &Value)) 4617 return true; 4618 4619 if (Value != 0 && ZeroWidth) 4620 *ZeroWidth = false; 4621 4622 // Zero-width bitfield is ok for anonymous field. 4623 if (Value == 0 && FieldName) 4624 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 4625 4626 if (Value.isSigned() && Value.isNegative()) { 4627 if (FieldName) 4628 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 4629 << FieldName << Value.toString(10); 4630 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 4631 << Value.toString(10); 4632 } 4633 4634 if (!FieldTy->isDependentType()) { 4635 uint64_t TypeSize = Context.getTypeSize(FieldTy); 4636 if (Value.getZExtValue() > TypeSize) { 4637 if (FieldName) 4638 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 4639 << FieldName << (unsigned)TypeSize; 4640 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 4641 << (unsigned)TypeSize; 4642 } 4643 } 4644 4645 return false; 4646} 4647 4648/// ActOnField - Each field of a struct/union/class is passed into this in order 4649/// to create a FieldDecl object for it. 4650Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD, 4651 SourceLocation DeclStart, 4652 Declarator &D, ExprTy *BitfieldWidth) { 4653 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()), 4654 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 4655 AS_public); 4656 return DeclPtrTy::make(Res); 4657} 4658 4659/// HandleField - Analyze a field of a C struct or a C++ data member. 4660/// 4661FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 4662 SourceLocation DeclStart, 4663 Declarator &D, Expr *BitWidth, 4664 AccessSpecifier AS) { 4665 IdentifierInfo *II = D.getIdentifier(); 4666 SourceLocation Loc = DeclStart; 4667 if (II) Loc = D.getIdentifierLoc(); 4668 4669 DeclaratorInfo *DInfo = 0; 4670 QualType T = GetTypeForDeclarator(D, S, &DInfo); 4671 if (getLangOptions().CPlusPlus) 4672 CheckExtraCXXDefaultArguments(D); 4673 4674 DiagnoseFunctionSpecifiers(D); 4675 4676 if (D.getDeclSpec().isThreadSpecified()) 4677 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 4678 4679 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true); 4680 4681 if (PrevDecl && PrevDecl->isTemplateParameter()) { 4682 // Maybe we will complain about the shadowed template parameter. 4683 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 4684 // Just pretend that we didn't see the previous declaration. 4685 PrevDecl = 0; 4686 } 4687 4688 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 4689 PrevDecl = 0; 4690 4691 bool Mutable 4692 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 4693 SourceLocation TSSL = D.getSourceRange().getBegin(); 4694 FieldDecl *NewFD 4695 = CheckFieldDecl(II, T, DInfo, Record, Loc, Mutable, BitWidth, TSSL, 4696 AS, PrevDecl, &D); 4697 if (NewFD->isInvalidDecl() && PrevDecl) { 4698 // Don't introduce NewFD into scope; there's already something 4699 // with the same name in the same scope. 4700 } else if (II) { 4701 PushOnScopeChains(NewFD, S); 4702 } else 4703 Record->addDecl(NewFD); 4704 4705 return NewFD; 4706} 4707 4708/// \brief Build a new FieldDecl and check its well-formedness. 4709/// 4710/// This routine builds a new FieldDecl given the fields name, type, 4711/// record, etc. \p PrevDecl should refer to any previous declaration 4712/// with the same name and in the same scope as the field to be 4713/// created. 4714/// 4715/// \returns a new FieldDecl. 4716/// 4717/// \todo The Declarator argument is a hack. It will be removed once 4718FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 4719 DeclaratorInfo *DInfo, 4720 RecordDecl *Record, SourceLocation Loc, 4721 bool Mutable, Expr *BitWidth, 4722 SourceLocation TSSL, 4723 AccessSpecifier AS, NamedDecl *PrevDecl, 4724 Declarator *D) { 4725 IdentifierInfo *II = Name.getAsIdentifierInfo(); 4726 bool InvalidDecl = false; 4727 if (D) InvalidDecl = D->isInvalidType(); 4728 4729 // If we receive a broken type, recover by assuming 'int' and 4730 // marking this declaration as invalid. 4731 if (T.isNull()) { 4732 InvalidDecl = true; 4733 T = Context.IntTy; 4734 } 4735 4736 // C99 6.7.2.1p8: A member of a structure or union may have any type other 4737 // than a variably modified type. 4738 if (T->isVariablyModifiedType()) { 4739 bool SizeIsNegative; 4740 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context, 4741 SizeIsNegative); 4742 if (!FixedTy.isNull()) { 4743 Diag(Loc, diag::warn_illegal_constant_array_size); 4744 T = FixedTy; 4745 } else { 4746 if (SizeIsNegative) 4747 Diag(Loc, diag::err_typecheck_negative_array_size); 4748 else 4749 Diag(Loc, diag::err_typecheck_field_variable_size); 4750 InvalidDecl = true; 4751 } 4752 } 4753 4754 // Fields can not have abstract class types 4755 if (RequireNonAbstractType(Loc, T, diag::err_abstract_type_in_decl, 4756 AbstractFieldType)) 4757 InvalidDecl = true; 4758 4759 bool ZeroWidth = false; 4760 // If this is declared as a bit-field, check the bit-field. 4761 if (BitWidth && VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) { 4762 InvalidDecl = true; 4763 DeleteExpr(BitWidth); 4764 BitWidth = 0; 4765 ZeroWidth = false; 4766 } 4767 4768 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, DInfo, 4769 BitWidth, Mutable); 4770 if (InvalidDecl) 4771 NewFD->setInvalidDecl(); 4772 4773 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 4774 Diag(Loc, diag::err_duplicate_member) << II; 4775 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4776 NewFD->setInvalidDecl(); 4777 } 4778 4779 if (getLangOptions().CPlusPlus) { 4780 QualType EltTy = Context.getBaseElementType(T); 4781 4782 CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record); 4783 4784 if (!T->isPODType()) 4785 CXXRecord->setPOD(false); 4786 if (!ZeroWidth) 4787 CXXRecord->setEmpty(false); 4788 4789 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 4790 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 4791 4792 if (!RDecl->hasTrivialConstructor()) 4793 CXXRecord->setHasTrivialConstructor(false); 4794 if (!RDecl->hasTrivialCopyConstructor()) 4795 CXXRecord->setHasTrivialCopyConstructor(false); 4796 if (!RDecl->hasTrivialCopyAssignment()) 4797 CXXRecord->setHasTrivialCopyAssignment(false); 4798 if (!RDecl->hasTrivialDestructor()) 4799 CXXRecord->setHasTrivialDestructor(false); 4800 4801 // C++ 9.5p1: An object of a class with a non-trivial 4802 // constructor, a non-trivial copy constructor, a non-trivial 4803 // destructor, or a non-trivial copy assignment operator 4804 // cannot be a member of a union, nor can an array of such 4805 // objects. 4806 // TODO: C++0x alters this restriction significantly. 4807 if (Record->isUnion()) { 4808 // We check for copy constructors before constructors 4809 // because otherwise we'll never get complaints about 4810 // copy constructors. 4811 4812 const CXXSpecialMember invalid = (CXXSpecialMember) -1; 4813 4814 CXXSpecialMember member; 4815 if (!RDecl->hasTrivialCopyConstructor()) 4816 member = CXXCopyConstructor; 4817 else if (!RDecl->hasTrivialConstructor()) 4818 member = CXXDefaultConstructor; 4819 else if (!RDecl->hasTrivialCopyAssignment()) 4820 member = CXXCopyAssignment; 4821 else if (!RDecl->hasTrivialDestructor()) 4822 member = CXXDestructor; 4823 else 4824 member = invalid; 4825 4826 if (member != invalid) { 4827 Diag(Loc, diag::err_illegal_union_member) << Name << member; 4828 DiagnoseNontrivial(RT, member); 4829 NewFD->setInvalidDecl(); 4830 } 4831 } 4832 } 4833 } 4834 4835 // FIXME: We need to pass in the attributes given an AST 4836 // representation, not a parser representation. 4837 if (D) 4838 // FIXME: What to pass instead of TUScope? 4839 ProcessDeclAttributes(TUScope, NewFD, *D); 4840 4841 if (T.isObjCGCWeak()) 4842 Diag(Loc, diag::warn_attribute_weak_on_field); 4843 4844 NewFD->setAccess(AS); 4845 4846 // C++ [dcl.init.aggr]p1: 4847 // An aggregate is an array or a class (clause 9) with [...] no 4848 // private or protected non-static data members (clause 11). 4849 // A POD must be an aggregate. 4850 if (getLangOptions().CPlusPlus && 4851 (AS == AS_private || AS == AS_protected)) { 4852 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 4853 CXXRecord->setAggregate(false); 4854 CXXRecord->setPOD(false); 4855 } 4856 4857 return NewFD; 4858} 4859 4860/// DiagnoseNontrivial - Given that a class has a non-trivial 4861/// special member, figure out why. 4862void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) { 4863 QualType QT(T, 0U); 4864 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl()); 4865 4866 // Check whether the member was user-declared. 4867 switch (member) { 4868 case CXXDefaultConstructor: 4869 if (RD->hasUserDeclaredConstructor()) { 4870 typedef CXXRecordDecl::ctor_iterator ctor_iter; 4871 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce; ++ci) 4872 if (!ci->isImplicitlyDefined(Context)) { 4873 SourceLocation CtorLoc = ci->getLocation(); 4874 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 4875 return; 4876 } 4877 4878 assert(0 && "found no user-declared constructors"); 4879 return; 4880 } 4881 break; 4882 4883 case CXXCopyConstructor: 4884 if (RD->hasUserDeclaredCopyConstructor()) { 4885 SourceLocation CtorLoc = 4886 RD->getCopyConstructor(Context, 0)->getLocation(); 4887 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 4888 return; 4889 } 4890 break; 4891 4892 case CXXCopyAssignment: 4893 if (RD->hasUserDeclaredCopyAssignment()) { 4894 // FIXME: this should use the location of the copy 4895 // assignment, not the type. 4896 SourceLocation TyLoc = RD->getSourceRange().getBegin(); 4897 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member; 4898 return; 4899 } 4900 break; 4901 4902 case CXXDestructor: 4903 if (RD->hasUserDeclaredDestructor()) { 4904 SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation(); 4905 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member; 4906 return; 4907 } 4908 break; 4909 } 4910 4911 typedef CXXRecordDecl::base_class_iterator base_iter; 4912 4913 // Virtual bases and members inhibit trivial copying/construction, 4914 // but not trivial destruction. 4915 if (member != CXXDestructor) { 4916 // Check for virtual bases. vbases includes indirect virtual bases, 4917 // so we just iterate through the direct bases. 4918 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) 4919 if (bi->isVirtual()) { 4920 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 4921 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1; 4922 return; 4923 } 4924 4925 // Check for virtual methods. 4926 typedef CXXRecordDecl::method_iterator meth_iter; 4927 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me; 4928 ++mi) { 4929 if (mi->isVirtual()) { 4930 SourceLocation MLoc = mi->getSourceRange().getBegin(); 4931 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0; 4932 return; 4933 } 4934 } 4935 } 4936 4937 bool (CXXRecordDecl::*hasTrivial)() const; 4938 switch (member) { 4939 case CXXDefaultConstructor: 4940 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break; 4941 case CXXCopyConstructor: 4942 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break; 4943 case CXXCopyAssignment: 4944 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break; 4945 case CXXDestructor: 4946 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break; 4947 default: 4948 assert(0 && "unexpected special member"); return; 4949 } 4950 4951 // Check for nontrivial bases (and recurse). 4952 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) { 4953 const RecordType *BaseRT = bi->getType()->getAs<RecordType>(); 4954 assert(BaseRT); 4955 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl()); 4956 if (!(BaseRecTy->*hasTrivial)()) { 4957 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 4958 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member; 4959 DiagnoseNontrivial(BaseRT, member); 4960 return; 4961 } 4962 } 4963 4964 // Check for nontrivial members (and recurse). 4965 typedef RecordDecl::field_iterator field_iter; 4966 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe; 4967 ++fi) { 4968 QualType EltTy = Context.getBaseElementType((*fi)->getType()); 4969 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) { 4970 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl()); 4971 4972 if (!(EltRD->*hasTrivial)()) { 4973 SourceLocation FLoc = (*fi)->getLocation(); 4974 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member; 4975 DiagnoseNontrivial(EltRT, member); 4976 return; 4977 } 4978 } 4979 } 4980 4981 assert(0 && "found no explanation for non-trivial member"); 4982} 4983 4984/// TranslateIvarVisibility - Translate visibility from a token ID to an 4985/// AST enum value. 4986static ObjCIvarDecl::AccessControl 4987TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 4988 switch (ivarVisibility) { 4989 default: assert(0 && "Unknown visitibility kind"); 4990 case tok::objc_private: return ObjCIvarDecl::Private; 4991 case tok::objc_public: return ObjCIvarDecl::Public; 4992 case tok::objc_protected: return ObjCIvarDecl::Protected; 4993 case tok::objc_package: return ObjCIvarDecl::Package; 4994 } 4995} 4996 4997/// ActOnIvar - Each ivar field of an objective-c class is passed into this 4998/// in order to create an IvarDecl object for it. 4999Sema::DeclPtrTy Sema::ActOnIvar(Scope *S, 5000 SourceLocation DeclStart, 5001 DeclPtrTy IntfDecl, 5002 Declarator &D, ExprTy *BitfieldWidth, 5003 tok::ObjCKeywordKind Visibility) { 5004 5005 IdentifierInfo *II = D.getIdentifier(); 5006 Expr *BitWidth = (Expr*)BitfieldWidth; 5007 SourceLocation Loc = DeclStart; 5008 if (II) Loc = D.getIdentifierLoc(); 5009 5010 // FIXME: Unnamed fields can be handled in various different ways, for 5011 // example, unnamed unions inject all members into the struct namespace! 5012 5013 DeclaratorInfo *DInfo = 0; 5014 QualType T = GetTypeForDeclarator(D, S, &DInfo); 5015 5016 if (BitWidth) { 5017 // 6.7.2.1p3, 6.7.2.1p4 5018 if (VerifyBitField(Loc, II, T, BitWidth)) { 5019 D.setInvalidType(); 5020 DeleteExpr(BitWidth); 5021 BitWidth = 0; 5022 } 5023 } else { 5024 // Not a bitfield. 5025 5026 // validate II. 5027 5028 } 5029 5030 // C99 6.7.2.1p8: A member of a structure or union may have any type other 5031 // than a variably modified type. 5032 if (T->isVariablyModifiedType()) { 5033 Diag(Loc, diag::err_typecheck_ivar_variable_size); 5034 D.setInvalidType(); 5035 } 5036 5037 // Get the visibility (access control) for this ivar. 5038 ObjCIvarDecl::AccessControl ac = 5039 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 5040 : ObjCIvarDecl::None; 5041 // Must set ivar's DeclContext to its enclosing interface. 5042 Decl *EnclosingDecl = IntfDecl.getAs<Decl>(); 5043 DeclContext *EnclosingContext; 5044 if (ObjCImplementationDecl *IMPDecl = 5045 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 5046 // Case of ivar declared in an implementation. Context is that of its class. 5047 ObjCInterfaceDecl* IDecl = IMPDecl->getClassInterface(); 5048 assert(IDecl && "No class- ActOnIvar"); 5049 EnclosingContext = cast_or_null<DeclContext>(IDecl); 5050 } else 5051 EnclosingContext = dyn_cast<DeclContext>(EnclosingDecl); 5052 assert(EnclosingContext && "null DeclContext for ivar - ActOnIvar"); 5053 5054 // Construct the decl. 5055 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, 5056 EnclosingContext, Loc, II, T, 5057 DInfo, ac, (Expr *)BitfieldWidth); 5058 5059 if (II) { 5060 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true); 5061 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 5062 && !isa<TagDecl>(PrevDecl)) { 5063 Diag(Loc, diag::err_duplicate_member) << II; 5064 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 5065 NewID->setInvalidDecl(); 5066 } 5067 } 5068 5069 // Process attributes attached to the ivar. 5070 ProcessDeclAttributes(S, NewID, D); 5071 5072 if (D.isInvalidType()) 5073 NewID->setInvalidDecl(); 5074 5075 if (II) { 5076 // FIXME: When interfaces are DeclContexts, we'll need to add 5077 // these to the interface. 5078 S->AddDecl(DeclPtrTy::make(NewID)); 5079 IdResolver.AddDecl(NewID); 5080 } 5081 5082 return DeclPtrTy::make(NewID); 5083} 5084 5085void Sema::ActOnFields(Scope* S, 5086 SourceLocation RecLoc, DeclPtrTy RecDecl, 5087 DeclPtrTy *Fields, unsigned NumFields, 5088 SourceLocation LBrac, SourceLocation RBrac, 5089 AttributeList *Attr) { 5090 Decl *EnclosingDecl = RecDecl.getAs<Decl>(); 5091 assert(EnclosingDecl && "missing record or interface decl"); 5092 5093 // If the decl this is being inserted into is invalid, then it may be a 5094 // redeclaration or some other bogus case. Don't try to add fields to it. 5095 if (EnclosingDecl->isInvalidDecl()) { 5096 // FIXME: Deallocate fields? 5097 return; 5098 } 5099 5100 5101 // Verify that all the fields are okay. 5102 unsigned NumNamedMembers = 0; 5103 llvm::SmallVector<FieldDecl*, 32> RecFields; 5104 5105 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 5106 for (unsigned i = 0; i != NumFields; ++i) { 5107 FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>()); 5108 5109 // Get the type for the field. 5110 Type *FDTy = FD->getType().getTypePtr(); 5111 5112 if (!FD->isAnonymousStructOrUnion()) { 5113 // Remember all fields written by the user. 5114 RecFields.push_back(FD); 5115 } 5116 5117 // If the field is already invalid for some reason, don't emit more 5118 // diagnostics about it. 5119 if (FD->isInvalidDecl()) 5120 continue; 5121 5122 // C99 6.7.2.1p2: 5123 // A structure or union shall not contain a member with 5124 // incomplete or function type (hence, a structure shall not 5125 // contain an instance of itself, but may contain a pointer to 5126 // an instance of itself), except that the last member of a 5127 // structure with more than one named member may have incomplete 5128 // array type; such a structure (and any union containing, 5129 // possibly recursively, a member that is such a structure) 5130 // shall not be a member of a structure or an element of an 5131 // array. 5132 if (FDTy->isFunctionType()) { 5133 // Field declared as a function. 5134 Diag(FD->getLocation(), diag::err_field_declared_as_function) 5135 << FD->getDeclName(); 5136 FD->setInvalidDecl(); 5137 EnclosingDecl->setInvalidDecl(); 5138 continue; 5139 } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 && 5140 Record && Record->isStruct()) { 5141 // Flexible array member. 5142 if (NumNamedMembers < 1) { 5143 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 5144 << FD->getDeclName(); 5145 FD->setInvalidDecl(); 5146 EnclosingDecl->setInvalidDecl(); 5147 continue; 5148 } 5149 // Okay, we have a legal flexible array member at the end of the struct. 5150 if (Record) 5151 Record->setHasFlexibleArrayMember(true); 5152 } else if (!FDTy->isDependentType() && 5153 RequireCompleteType(FD->getLocation(), FD->getType(), 5154 diag::err_field_incomplete)) { 5155 // Incomplete type 5156 FD->setInvalidDecl(); 5157 EnclosingDecl->setInvalidDecl(); 5158 continue; 5159 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 5160 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 5161 // If this is a member of a union, then entire union becomes "flexible". 5162 if (Record && Record->isUnion()) { 5163 Record->setHasFlexibleArrayMember(true); 5164 } else { 5165 // If this is a struct/class and this is not the last element, reject 5166 // it. Note that GCC supports variable sized arrays in the middle of 5167 // structures. 5168 if (i != NumFields-1) 5169 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 5170 << FD->getDeclName() << FD->getType(); 5171 else { 5172 // We support flexible arrays at the end of structs in 5173 // other structs as an extension. 5174 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 5175 << FD->getDeclName(); 5176 if (Record) 5177 Record->setHasFlexibleArrayMember(true); 5178 } 5179 } 5180 } 5181 if (Record && FDTTy->getDecl()->hasObjectMember()) 5182 Record->setHasObjectMember(true); 5183 } else if (FDTy->isObjCInterfaceType()) { 5184 /// A field cannot be an Objective-c object 5185 Diag(FD->getLocation(), diag::err_statically_allocated_object); 5186 FD->setInvalidDecl(); 5187 EnclosingDecl->setInvalidDecl(); 5188 continue; 5189 } else if (getLangOptions().ObjC1 && 5190 getLangOptions().getGCMode() != LangOptions::NonGC && 5191 Record && 5192 (FD->getType()->isObjCObjectPointerType() || 5193 FD->getType().isObjCGCStrong())) 5194 Record->setHasObjectMember(true); 5195 // Keep track of the number of named members. 5196 if (FD->getIdentifier()) 5197 ++NumNamedMembers; 5198 } 5199 5200 // Okay, we successfully defined 'Record'. 5201 if (Record) { 5202 Record->completeDefinition(Context); 5203 } else { 5204 ObjCIvarDecl **ClsFields = 5205 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 5206 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 5207 ID->setIVarList(ClsFields, RecFields.size(), Context); 5208 ID->setLocEnd(RBrac); 5209 // Add ivar's to class's DeclContext. 5210 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 5211 ClsFields[i]->setLexicalDeclContext(ID); 5212 ID->addDecl(ClsFields[i]); 5213 } 5214 // Must enforce the rule that ivars in the base classes may not be 5215 // duplicates. 5216 if (ID->getSuperClass()) { 5217 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(), 5218 IVE = ID->ivar_end(); IVI != IVE; ++IVI) { 5219 ObjCIvarDecl* Ivar = (*IVI); 5220 5221 if (IdentifierInfo *II = Ivar->getIdentifier()) { 5222 ObjCIvarDecl* prevIvar = 5223 ID->getSuperClass()->lookupInstanceVariable(II); 5224 if (prevIvar) { 5225 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II; 5226 Diag(prevIvar->getLocation(), diag::note_previous_declaration); 5227 } 5228 } 5229 } 5230 } 5231 } else if (ObjCImplementationDecl *IMPDecl = 5232 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 5233 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 5234 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 5235 // Ivar declared in @implementation never belongs to the implementation. 5236 // Only it is in implementation's lexical context. 5237 ClsFields[I]->setLexicalDeclContext(IMPDecl); 5238 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 5239 } 5240 } 5241 5242 if (Attr) 5243 ProcessDeclAttributeList(S, Record, Attr); 5244} 5245 5246EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 5247 EnumConstantDecl *LastEnumConst, 5248 SourceLocation IdLoc, 5249 IdentifierInfo *Id, 5250 ExprArg val) { 5251 Expr *Val = (Expr *)val.get(); 5252 5253 llvm::APSInt EnumVal(32); 5254 QualType EltTy; 5255 if (Val && !Val->isTypeDependent()) { 5256 // Make sure to promote the operand type to int. 5257 UsualUnaryConversions(Val); 5258 if (Val != val.get()) { 5259 val.release(); 5260 val = Val; 5261 } 5262 5263 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 5264 SourceLocation ExpLoc; 5265 if (!Val->isValueDependent() && 5266 VerifyIntegerConstantExpression(Val, &EnumVal)) { 5267 Val = 0; 5268 } else { 5269 EltTy = Val->getType(); 5270 } 5271 } 5272 5273 if (!Val) { 5274 if (LastEnumConst) { 5275 // Assign the last value + 1. 5276 EnumVal = LastEnumConst->getInitVal(); 5277 ++EnumVal; 5278 5279 // Check for overflow on increment. 5280 if (EnumVal < LastEnumConst->getInitVal()) 5281 Diag(IdLoc, diag::warn_enum_value_overflow); 5282 5283 EltTy = LastEnumConst->getType(); 5284 } else { 5285 // First value, set to zero. 5286 EltTy = Context.IntTy; 5287 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy))); 5288 } 5289 } 5290 5291 val.release(); 5292 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 5293 Val, EnumVal); 5294} 5295 5296 5297Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl, 5298 DeclPtrTy lastEnumConst, 5299 SourceLocation IdLoc, 5300 IdentifierInfo *Id, 5301 SourceLocation EqualLoc, ExprTy *val) { 5302 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>()); 5303 EnumConstantDecl *LastEnumConst = 5304 cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>()); 5305 Expr *Val = static_cast<Expr*>(val); 5306 5307 // The scope passed in may not be a decl scope. Zip up the scope tree until 5308 // we find one that is. 5309 S = getNonFieldDeclScope(S); 5310 5311 // Verify that there isn't already something declared with this name in this 5312 // scope. 5313 NamedDecl *PrevDecl = LookupName(S, Id, LookupOrdinaryName); 5314 if (PrevDecl && PrevDecl->isTemplateParameter()) { 5315 // Maybe we will complain about the shadowed template parameter. 5316 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 5317 // Just pretend that we didn't see the previous declaration. 5318 PrevDecl = 0; 5319 } 5320 5321 if (PrevDecl) { 5322 // When in C++, we may get a TagDecl with the same name; in this case the 5323 // enum constant will 'hide' the tag. 5324 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 5325 "Received TagDecl when not in C++!"); 5326 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 5327 if (isa<EnumConstantDecl>(PrevDecl)) 5328 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 5329 else 5330 Diag(IdLoc, diag::err_redefinition) << Id; 5331 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5332 if (Val) Val->Destroy(Context); 5333 return DeclPtrTy(); 5334 } 5335 } 5336 5337 EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst, 5338 IdLoc, Id, Owned(Val)); 5339 5340 // Register this decl in the current scope stack. 5341 if (New) 5342 PushOnScopeChains(New, S); 5343 5344 return DeclPtrTy::make(New); 5345} 5346 5347void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 5348 SourceLocation RBraceLoc, DeclPtrTy EnumDeclX, 5349 DeclPtrTy *Elements, unsigned NumElements, 5350 Scope *S, AttributeList *Attr) { 5351 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>()); 5352 QualType EnumType = Context.getTypeDeclType(Enum); 5353 5354 if (Attr) 5355 ProcessDeclAttributeList(S, Enum, Attr); 5356 5357 // TODO: If the result value doesn't fit in an int, it must be a long or long 5358 // long value. ISO C does not support this, but GCC does as an extension, 5359 // emit a warning. 5360 unsigned IntWidth = Context.Target.getIntWidth(); 5361 unsigned CharWidth = Context.Target.getCharWidth(); 5362 unsigned ShortWidth = Context.Target.getShortWidth(); 5363 5364 // Verify that all the values are okay, compute the size of the values, and 5365 // reverse the list. 5366 unsigned NumNegativeBits = 0; 5367 unsigned NumPositiveBits = 0; 5368 5369 // Keep track of whether all elements have type int. 5370 bool AllElementsInt = true; 5371 5372 for (unsigned i = 0; i != NumElements; ++i) { 5373 EnumConstantDecl *ECD = 5374 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>()); 5375 if (!ECD) continue; // Already issued a diagnostic. 5376 5377 // If the enum value doesn't fit in an int, emit an extension warning. 5378 const llvm::APSInt &InitVal = ECD->getInitVal(); 5379 assert(InitVal.getBitWidth() >= IntWidth && 5380 "Should have promoted value to int"); 5381 if (InitVal.getBitWidth() > IntWidth) { 5382 llvm::APSInt V(InitVal); 5383 V.trunc(IntWidth); 5384 V.extend(InitVal.getBitWidth()); 5385 if (V != InitVal) 5386 Diag(ECD->getLocation(), diag::ext_enum_value_not_int) 5387 << InitVal.toString(10); 5388 } 5389 5390 // Keep track of the size of positive and negative values. 5391 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 5392 NumPositiveBits = std::max(NumPositiveBits, 5393 (unsigned)InitVal.getActiveBits()); 5394 else 5395 NumNegativeBits = std::max(NumNegativeBits, 5396 (unsigned)InitVal.getMinSignedBits()); 5397 5398 // Keep track of whether every enum element has type int (very commmon). 5399 if (AllElementsInt) 5400 AllElementsInt = ECD->getType() == Context.IntTy; 5401 } 5402 5403 // Figure out the type that should be used for this enum. 5404 // FIXME: Support -fshort-enums. 5405 QualType BestType; 5406 unsigned BestWidth; 5407 5408 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 5409 5410 if (NumNegativeBits) { 5411 // If there is a negative value, figure out the smallest integer type (of 5412 // int/long/longlong) that fits. 5413 // If it's packed, check also if it fits a char or a short. 5414 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 5415 BestType = Context.SignedCharTy; 5416 BestWidth = CharWidth; 5417 } else if (Packed && NumNegativeBits <= ShortWidth && 5418 NumPositiveBits < ShortWidth) { 5419 BestType = Context.ShortTy; 5420 BestWidth = ShortWidth; 5421 } 5422 else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 5423 BestType = Context.IntTy; 5424 BestWidth = IntWidth; 5425 } else { 5426 BestWidth = Context.Target.getLongWidth(); 5427 5428 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) 5429 BestType = Context.LongTy; 5430 else { 5431 BestWidth = Context.Target.getLongLongWidth(); 5432 5433 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 5434 Diag(Enum->getLocation(), diag::warn_enum_too_large); 5435 BestType = Context.LongLongTy; 5436 } 5437 } 5438 } else { 5439 // If there is no negative value, figure out which of uint, ulong, ulonglong 5440 // fits. 5441 // If it's packed, check also if it fits a char or a short. 5442 if (Packed && NumPositiveBits <= CharWidth) { 5443 BestType = Context.UnsignedCharTy; 5444 BestWidth = CharWidth; 5445 } else if (Packed && NumPositiveBits <= ShortWidth) { 5446 BestType = Context.UnsignedShortTy; 5447 BestWidth = ShortWidth; 5448 } 5449 else if (NumPositiveBits <= IntWidth) { 5450 BestType = Context.UnsignedIntTy; 5451 BestWidth = IntWidth; 5452 } else if (NumPositiveBits <= 5453 (BestWidth = Context.Target.getLongWidth())) { 5454 BestType = Context.UnsignedLongTy; 5455 } else { 5456 BestWidth = Context.Target.getLongLongWidth(); 5457 assert(NumPositiveBits <= BestWidth && 5458 "How could an initializer get larger than ULL?"); 5459 BestType = Context.UnsignedLongLongTy; 5460 } 5461 } 5462 5463 // Loop over all of the enumerator constants, changing their types to match 5464 // the type of the enum if needed. 5465 for (unsigned i = 0; i != NumElements; ++i) { 5466 EnumConstantDecl *ECD = 5467 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>()); 5468 if (!ECD) continue; // Already issued a diagnostic. 5469 5470 // Standard C says the enumerators have int type, but we allow, as an 5471 // extension, the enumerators to be larger than int size. If each 5472 // enumerator value fits in an int, type it as an int, otherwise type it the 5473 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 5474 // that X has type 'int', not 'unsigned'. 5475 if (ECD->getType() == Context.IntTy) { 5476 // Make sure the init value is signed. 5477 llvm::APSInt IV = ECD->getInitVal(); 5478 IV.setIsSigned(true); 5479 ECD->setInitVal(IV); 5480 5481 if (getLangOptions().CPlusPlus) 5482 // C++ [dcl.enum]p4: Following the closing brace of an 5483 // enum-specifier, each enumerator has the type of its 5484 // enumeration. 5485 ECD->setType(EnumType); 5486 continue; // Already int type. 5487 } 5488 5489 // Determine whether the value fits into an int. 5490 llvm::APSInt InitVal = ECD->getInitVal(); 5491 bool FitsInInt; 5492 if (InitVal.isUnsigned() || !InitVal.isNegative()) 5493 FitsInInt = InitVal.getActiveBits() < IntWidth; 5494 else 5495 FitsInInt = InitVal.getMinSignedBits() <= IntWidth; 5496 5497 // If it fits into an integer type, force it. Otherwise force it to match 5498 // the enum decl type. 5499 QualType NewTy; 5500 unsigned NewWidth; 5501 bool NewSign; 5502 if (FitsInInt) { 5503 NewTy = Context.IntTy; 5504 NewWidth = IntWidth; 5505 NewSign = true; 5506 } else if (ECD->getType() == BestType) { 5507 // Already the right type! 5508 if (getLangOptions().CPlusPlus) 5509 // C++ [dcl.enum]p4: Following the closing brace of an 5510 // enum-specifier, each enumerator has the type of its 5511 // enumeration. 5512 ECD->setType(EnumType); 5513 continue; 5514 } else { 5515 NewTy = BestType; 5516 NewWidth = BestWidth; 5517 NewSign = BestType->isSignedIntegerType(); 5518 } 5519 5520 // Adjust the APSInt value. 5521 InitVal.extOrTrunc(NewWidth); 5522 InitVal.setIsSigned(NewSign); 5523 ECD->setInitVal(InitVal); 5524 5525 // Adjust the Expr initializer and type. 5526 if (ECD->getInitExpr()) 5527 ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy, 5528 CastExpr::CK_Unknown, 5529 ECD->getInitExpr(), 5530 /*isLvalue=*/false)); 5531 if (getLangOptions().CPlusPlus) 5532 // C++ [dcl.enum]p4: Following the closing brace of an 5533 // enum-specifier, each enumerator has the type of its 5534 // enumeration. 5535 ECD->setType(EnumType); 5536 else 5537 ECD->setType(NewTy); 5538 } 5539 5540 Enum->completeDefinition(Context, BestType); 5541} 5542 5543Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, 5544 ExprArg expr) { 5545 StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>()); 5546 5547 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 5548 Loc, AsmString); 5549 CurContext->addDecl(New); 5550 return DeclPtrTy::make(New); 5551} 5552 5553void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 5554 SourceLocation PragmaLoc, 5555 SourceLocation NameLoc) { 5556 Decl *PrevDecl = LookupName(TUScope, Name, LookupOrdinaryName); 5557 5558 if (PrevDecl) { 5559 PrevDecl->addAttr(::new (Context) WeakAttr()); 5560 } else { 5561 (void)WeakUndeclaredIdentifiers.insert( 5562 std::pair<IdentifierInfo*,WeakInfo> 5563 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 5564 } 5565} 5566 5567void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 5568 IdentifierInfo* AliasName, 5569 SourceLocation PragmaLoc, 5570 SourceLocation NameLoc, 5571 SourceLocation AliasNameLoc) { 5572 Decl *PrevDecl = LookupName(TUScope, AliasName, LookupOrdinaryName); 5573 WeakInfo W = WeakInfo(Name, NameLoc); 5574 5575 if (PrevDecl) { 5576 if (!PrevDecl->hasAttr<AliasAttr>()) 5577 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 5578 DeclApplyPragmaWeak(TUScope, ND, W); 5579 } else { 5580 (void)WeakUndeclaredIdentifiers.insert( 5581 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 5582 } 5583} 5584