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