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