SemaDecl.cpp revision cb8e803696224e723e294d7e3ef79e5e393493eb
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 913Sema::DeclTy * 914Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) { 915 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl); 916 DeclarationName Name = GetNameForDeclarator(D); 917 918 // All of these full declarators require an identifier. If it doesn't have 919 // one, the ParsedFreeStandingDeclSpec action should be used. 920 if (!Name) { 921 if (!D.getInvalidType()) // Reject this if we think it is valid. 922 Diag(D.getDeclSpec().getSourceRange().getBegin(), 923 diag::err_declarator_need_ident) 924 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 925 return 0; 926 } 927 928 // The scope passed in may not be a decl scope. Zip up the scope tree until 929 // we find one that is. 930 while ((S->getFlags() & Scope::DeclScope) == 0 || 931 (S->getFlags() & Scope::TemplateParamScope) != 0) 932 S = S->getParent(); 933 934 DeclContext *DC; 935 Decl *PrevDecl; 936 ScopedDecl *New; 937 bool InvalidDecl = false; 938 939 // See if this is a redefinition of a variable in the same scope. 940 if (!D.getCXXScopeSpec().isSet()) { 941 DC = CurContext; 942 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S); 943 } else { // Something like "int foo::x;" 944 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep()); 945 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC); 946 947 // C++ 7.3.1.2p2: 948 // Members (including explicit specializations of templates) of a named 949 // namespace can also be defined outside that namespace by explicit 950 // qualification of the name being defined, provided that the entity being 951 // defined was already declared in the namespace and the definition appears 952 // after the point of declaration in a namespace that encloses the 953 // declarations namespace. 954 // 955 // FIXME: We need to perform this check later, once we know that 956 // we've actually found a redeclaration. Otherwise, just the fact 957 // that there is some entity with the same name will suppress this 958 // diagnostic, e.g., we fail to diagnose: 959 // class X { 960 // void f(); 961 // }; 962 // 963 // void X::f(int) { } // ill-formed, but we don't complain. 964 if (PrevDecl == 0) { 965 // No previous declaration in the qualifying scope. 966 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member) 967 << Name << D.getCXXScopeSpec().getRange(); 968 InvalidDecl = true; 969 } else if (!CurContext->Encloses(DC)) { 970 // The qualifying scope doesn't enclose the original declaration. 971 // Emit diagnostic based on current scope. 972 SourceLocation L = D.getIdentifierLoc(); 973 SourceRange R = D.getCXXScopeSpec().getRange(); 974 if (isa<FunctionDecl>(CurContext)) { 975 Diag(L, diag::err_invalid_declarator_in_function) << Name << R; 976 } else { 977 Diag(L, diag::err_invalid_declarator_scope) 978 << Name << cast<NamedDecl>(DC)->getDeclName() << R; 979 } 980 InvalidDecl = true; 981 } 982 } 983 984 if (PrevDecl && PrevDecl->isTemplateParameter()) { 985 // Maybe we will complain about the shadowed template parameter. 986 InvalidDecl = InvalidDecl 987 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 988 // Just pretend that we didn't see the previous declaration. 989 PrevDecl = 0; 990 } 991 992 // In C++, the previous declaration we find might be a tag type 993 // (class or enum). In this case, the new declaration will hide the 994 // tag type. 995 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) 996 PrevDecl = 0; 997 998 QualType R = GetTypeForDeclarator(D, S); 999 assert(!R.isNull() && "GetTypeForDeclarator() returned null type"); 1000 1001 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 1002 // Check that there are no default arguments (C++ only). 1003 if (getLangOptions().CPlusPlus) 1004 CheckExtraCXXDefaultArguments(D); 1005 1006 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator); 1007 if (!NewTD) return 0; 1008 1009 // Handle attributes prior to checking for duplicates in MergeVarDecl 1010 ProcessDeclAttributes(NewTD, D); 1011 // Merge the decl with the existing one if appropriate. If the decl is 1012 // in an outer scope, it isn't the same thing. 1013 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) { 1014 NewTD = MergeTypeDefDecl(NewTD, PrevDecl); 1015 if (NewTD == 0) return 0; 1016 } 1017 New = NewTD; 1018 if (S->getFnParent() == 0) { 1019 // C99 6.7.7p2: If a typedef name specifies a variably modified type 1020 // then it shall have block scope. 1021 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) { 1022 if (NewTD->getUnderlyingType()->isVariableArrayType()) 1023 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope); 1024 else 1025 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope); 1026 1027 InvalidDecl = true; 1028 } 1029 } 1030 } else if (R.getTypePtr()->isFunctionType()) { 1031 FunctionDecl::StorageClass SC = FunctionDecl::None; 1032 switch (D.getDeclSpec().getStorageClassSpec()) { 1033 default: assert(0 && "Unknown storage class!"); 1034 case DeclSpec::SCS_auto: 1035 case DeclSpec::SCS_register: 1036 case DeclSpec::SCS_mutable: 1037 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func); 1038 InvalidDecl = true; 1039 break; 1040 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break; 1041 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break; 1042 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break; 1043 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break; 1044 } 1045 1046 bool isInline = D.getDeclSpec().isInlineSpecified(); 1047 // bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 1048 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 1049 1050 FunctionDecl *NewFD; 1051 if (D.getKind() == Declarator::DK_Constructor) { 1052 // This is a C++ constructor declaration. 1053 assert(DC->isCXXRecord() && 1054 "Constructors can only be declared in a member context"); 1055 1056 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC); 1057 1058 // Create the new declaration 1059 NewFD = CXXConstructorDecl::Create(Context, 1060 cast<CXXRecordDecl>(DC), 1061 D.getIdentifierLoc(), Name, R, 1062 isExplicit, isInline, 1063 /*isImplicitlyDeclared=*/false); 1064 1065 if (isInvalidDecl) 1066 NewFD->setInvalidDecl(); 1067 } else if (D.getKind() == Declarator::DK_Destructor) { 1068 // This is a C++ destructor declaration. 1069 if (DC->isCXXRecord()) { 1070 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC); 1071 1072 NewFD = CXXDestructorDecl::Create(Context, 1073 cast<CXXRecordDecl>(DC), 1074 D.getIdentifierLoc(), Name, R, 1075 isInline, 1076 /*isImplicitlyDeclared=*/false); 1077 1078 if (isInvalidDecl) 1079 NewFD->setInvalidDecl(); 1080 } else { 1081 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 1082 // Create a FunctionDecl to satisfy the function definition parsing 1083 // code path. 1084 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(), 1085 Name, R, SC, isInline, LastDeclarator, 1086 // FIXME: Move to DeclGroup... 1087 D.getDeclSpec().getSourceRange().getBegin()); 1088 NewFD->setInvalidDecl(); 1089 } 1090 } else if (D.getKind() == Declarator::DK_Conversion) { 1091 if (!DC->isCXXRecord()) { 1092 Diag(D.getIdentifierLoc(), 1093 diag::err_conv_function_not_member); 1094 return 0; 1095 } else { 1096 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC); 1097 1098 NewFD = CXXConversionDecl::Create(Context, 1099 cast<CXXRecordDecl>(DC), 1100 D.getIdentifierLoc(), Name, R, 1101 isInline, isExplicit); 1102 1103 if (isInvalidDecl) 1104 NewFD->setInvalidDecl(); 1105 } 1106 } else if (DC->isCXXRecord()) { 1107 // This is a C++ method declaration. 1108 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC), 1109 D.getIdentifierLoc(), Name, R, 1110 (SC == FunctionDecl::Static), isInline, 1111 LastDeclarator); 1112 } else { 1113 NewFD = FunctionDecl::Create(Context, DC, 1114 D.getIdentifierLoc(), 1115 Name, R, SC, isInline, LastDeclarator, 1116 // FIXME: Move to DeclGroup... 1117 D.getDeclSpec().getSourceRange().getBegin()); 1118 } 1119 // Handle attributes. 1120 ProcessDeclAttributes(NewFD, D); 1121 1122 // Set the lexical context. If the declarator has a C++ 1123 // scope specifier, the lexical context will be different 1124 // from the semantic context. 1125 NewFD->setLexicalDeclContext(CurContext); 1126 1127 // Handle GNU asm-label extension (encoded as an attribute). 1128 if (Expr *E = (Expr*) D.getAsmLabel()) { 1129 // The parser guarantees this is a string. 1130 StringLiteral *SE = cast<StringLiteral>(E); 1131 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(), 1132 SE->getByteLength()))); 1133 } 1134 1135 // Copy the parameter declarations from the declarator D to 1136 // the function declaration NewFD, if they are available. 1137 if (D.getNumTypeObjects() > 0) { 1138 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1139 1140 // Create Decl objects for each parameter, adding them to the 1141 // FunctionDecl. 1142 llvm::SmallVector<ParmVarDecl*, 16> Params; 1143 1144 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 1145 // function that takes no arguments, not a function that takes a 1146 // single void argument. 1147 // We let through "const void" here because Sema::GetTypeForDeclarator 1148 // already checks for that case. 1149 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 1150 FTI.ArgInfo[0].Param && 1151 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 1152 // empty arg list, don't push any params. 1153 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param; 1154 1155 // In C++, the empty parameter-type-list must be spelled "void"; a 1156 // typedef of void is not permitted. 1157 if (getLangOptions().CPlusPlus && 1158 Param->getType().getUnqualifiedType() != Context.VoidTy) { 1159 Diag(Param->getLocation(), diag::ext_param_typedef_of_void); 1160 } 1161 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 1162 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 1163 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param); 1164 } 1165 1166 NewFD->setParams(&Params[0], Params.size()); 1167 } else if (R->getAsTypedefType()) { 1168 // When we're declaring a function with a typedef, as in the 1169 // following example, we'll need to synthesize (unnamed) 1170 // parameters for use in the declaration. 1171 // 1172 // @code 1173 // typedef void fn(int); 1174 // fn f; 1175 // @endcode 1176 const FunctionTypeProto *FT = R->getAsFunctionTypeProto(); 1177 if (!FT) { 1178 // This is a typedef of a function with no prototype, so we 1179 // don't need to do anything. 1180 } else if ((FT->getNumArgs() == 0) || 1181 (FT->getNumArgs() == 1 && !FT->isVariadic() && 1182 FT->getArgType(0)->isVoidType())) { 1183 // This is a zero-argument function. We don't need to do anything. 1184 } else { 1185 // Synthesize a parameter for each argument type. 1186 llvm::SmallVector<ParmVarDecl*, 16> Params; 1187 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin(); 1188 ArgType != FT->arg_type_end(); ++ArgType) { 1189 Params.push_back(ParmVarDecl::Create(Context, DC, 1190 SourceLocation(), 0, 1191 *ArgType, VarDecl::None, 1192 0, 0)); 1193 } 1194 1195 NewFD->setParams(&Params[0], Params.size()); 1196 } 1197 } 1198 1199 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 1200 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DC); 1201 1202 // C++ [class.copy]p3: 1203 // A declaration of a constructor for a class X is ill-formed if 1204 // its first parameter is of type (optionally cv-qualified) X and 1205 // either there are no other parameters or else all other 1206 // parameters have default arguments. 1207 if ((Constructor->getNumParams() == 1) || 1208 (Constructor->getNumParams() > 1 && 1209 Constructor->getParamDecl(1)->getDefaultArg() != 0)) { 1210 QualType ParamType = Constructor->getParamDecl(0)->getType(); 1211 QualType ClassTy = Context.getTagDeclType(ClassDecl); 1212 if (Context.getCanonicalType(ParamType).getUnqualifiedType() 1213 == ClassTy) { 1214 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg) 1215 << SourceRange(Constructor->getParamDecl(0)->getLocation()); 1216 Constructor->setInvalidDecl(); 1217 } 1218 } 1219 1220 // Notify the class that we've added a constructor. 1221 ClassDecl->addedConstructor(Context, Constructor); 1222 } 1223 else if (isa<CXXDestructorDecl>(NewFD)) 1224 cast<CXXRecordDecl>(NewFD->getParent())->setUserDeclaredDestructor(true); 1225 else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 1226 ActOnConversionDeclarator(Conversion); 1227 1228 // Extra checking for C++ overloaded operators (C++ [over.oper]). 1229 if (NewFD->isOverloadedOperator() && 1230 CheckOverloadedOperatorDeclaration(NewFD)) 1231 NewFD->setInvalidDecl(); 1232 1233 // Merge the decl with the existing one if appropriate. Since C functions 1234 // are in a flat namespace, make sure we consider decls in outer scopes. 1235 if (PrevDecl && 1236 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) { 1237 bool Redeclaration = false; 1238 1239 // If C++, determine whether NewFD is an overload of PrevDecl or 1240 // a declaration that requires merging. If it's an overload, 1241 // there's no more work to do here; we'll just add the new 1242 // function to the scope. 1243 OverloadedFunctionDecl::function_iterator MatchedDecl; 1244 if (!getLangOptions().CPlusPlus || 1245 !IsOverload(NewFD, PrevDecl, MatchedDecl)) { 1246 Decl *OldDecl = PrevDecl; 1247 1248 // If PrevDecl was an overloaded function, extract the 1249 // FunctionDecl that matched. 1250 if (isa<OverloadedFunctionDecl>(PrevDecl)) 1251 OldDecl = *MatchedDecl; 1252 1253 // NewFD and PrevDecl represent declarations that need to be 1254 // merged. 1255 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration); 1256 1257 if (NewFD == 0) return 0; 1258 if (Redeclaration) { 1259 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 1260 1261 if (OldDecl == PrevDecl) { 1262 // Remove the name binding for the previous 1263 // declaration. 1264 if (S->isDeclScope(PrevDecl)) { 1265 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl)); 1266 S->RemoveDecl(PrevDecl); 1267 } 1268 1269 // Introduce the new binding for this declaration. 1270 IdResolver.AddDecl(NewFD); 1271 if (getLangOptions().CPlusPlus && NewFD->getParent()) 1272 NewFD->getParent()->insert(Context, NewFD); 1273 1274 // Add the redeclaration to the current scope, since we'll 1275 // be skipping PushOnScopeChains. 1276 S->AddDecl(NewFD); 1277 } else { 1278 // We need to update the OverloadedFunctionDecl with the 1279 // latest declaration of this function, so that name 1280 // lookup will always refer to the latest declaration of 1281 // this function. 1282 *MatchedDecl = NewFD; 1283 } 1284 1285 if (getLangOptions().CPlusPlus) { 1286 // Add this declaration to the current context. 1287 CurContext->addDecl(Context, NewFD, false); 1288 1289 // Check default arguments now that we have merged decls. 1290 CheckCXXDefaultArguments(NewFD); 1291 } 1292 1293 return NewFD; 1294 } 1295 } 1296 } 1297 New = NewFD; 1298 1299 // In C++, check default arguments now that we have merged decls. 1300 if (getLangOptions().CPlusPlus) 1301 CheckCXXDefaultArguments(NewFD); 1302 } else { 1303 // Check that there are no default arguments (C++ only). 1304 if (getLangOptions().CPlusPlus) 1305 CheckExtraCXXDefaultArguments(D); 1306 1307 if (R.getTypePtr()->isObjCInterfaceType()) { 1308 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object) 1309 << D.getIdentifier(); 1310 InvalidDecl = true; 1311 } 1312 1313 VarDecl *NewVD; 1314 VarDecl::StorageClass SC; 1315 switch (D.getDeclSpec().getStorageClassSpec()) { 1316 default: assert(0 && "Unknown storage class!"); 1317 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 1318 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 1319 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 1320 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 1321 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 1322 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 1323 case DeclSpec::SCS_mutable: 1324 // mutable can only appear on non-static class members, so it's always 1325 // an error here 1326 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 1327 InvalidDecl = true; 1328 SC = VarDecl::None; 1329 break; 1330 } 1331 1332 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1333 if (!II) { 1334 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 1335 << Name.getAsString(); 1336 return 0; 1337 } 1338 1339 if (DC->isCXXRecord()) { 1340 assert(SC == VarDecl::Static && "Invalid storage class for member!"); 1341 // This is a static data member for a C++ class. 1342 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC), 1343 D.getIdentifierLoc(), II, 1344 R, LastDeclarator); 1345 } else { 1346 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified(); 1347 if (S->getFnParent() == 0) { 1348 // C99 6.9p2: The storage-class specifiers auto and register shall not 1349 // appear in the declaration specifiers in an external declaration. 1350 if (SC == VarDecl::Auto || SC == VarDecl::Register) { 1351 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 1352 InvalidDecl = true; 1353 } 1354 } 1355 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(), 1356 II, R, SC, LastDeclarator, 1357 // FIXME: Move to DeclGroup... 1358 D.getDeclSpec().getSourceRange().getBegin()); 1359 NewVD->setThreadSpecified(ThreadSpecified); 1360 } 1361 // Handle attributes prior to checking for duplicates in MergeVarDecl 1362 ProcessDeclAttributes(NewVD, D); 1363 1364 // Handle GNU asm-label extension (encoded as an attribute). 1365 if (Expr *E = (Expr*) D.getAsmLabel()) { 1366 // The parser guarantees this is a string. 1367 StringLiteral *SE = cast<StringLiteral>(E); 1368 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(), 1369 SE->getByteLength()))); 1370 } 1371 1372 // Emit an error if an address space was applied to decl with local storage. 1373 // This includes arrays of objects with address space qualifiers, but not 1374 // automatic variables that point to other address spaces. 1375 // ISO/IEC TR 18037 S5.1.2 1376 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) { 1377 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl); 1378 InvalidDecl = true; 1379 } 1380 // Merge the decl with the existing one if appropriate. If the decl is 1381 // in an outer scope, it isn't the same thing. 1382 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) { 1383 NewVD = MergeVarDecl(NewVD, PrevDecl); 1384 if (NewVD == 0) return 0; 1385 } 1386 New = NewVD; 1387 } 1388 1389 // Set the lexical context. If the declarator has a C++ scope specifier, the 1390 // lexical context will be different from the semantic context. 1391 New->setLexicalDeclContext(CurContext); 1392 1393 // If this has an identifier, add it to the scope stack. 1394 if (Name) 1395 PushOnScopeChains(New, S); 1396 // If any semantic error occurred, mark the decl as invalid. 1397 if (D.getInvalidType() || InvalidDecl) 1398 New->setInvalidDecl(); 1399 1400 return New; 1401} 1402 1403void Sema::InitializerElementNotConstant(const Expr *Init) { 1404 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 1405 << Init->getSourceRange(); 1406} 1407 1408bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) { 1409 switch (Init->getStmtClass()) { 1410 default: 1411 InitializerElementNotConstant(Init); 1412 return true; 1413 case Expr::ParenExprClass: { 1414 const ParenExpr* PE = cast<ParenExpr>(Init); 1415 return CheckAddressConstantExpressionLValue(PE->getSubExpr()); 1416 } 1417 case Expr::CompoundLiteralExprClass: 1418 return cast<CompoundLiteralExpr>(Init)->isFileScope(); 1419 case Expr::DeclRefExprClass: { 1420 const Decl *D = cast<DeclRefExpr>(Init)->getDecl(); 1421 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1422 if (VD->hasGlobalStorage()) 1423 return false; 1424 InitializerElementNotConstant(Init); 1425 return true; 1426 } 1427 if (isa<FunctionDecl>(D)) 1428 return false; 1429 InitializerElementNotConstant(Init); 1430 return true; 1431 } 1432 case Expr::MemberExprClass: { 1433 const MemberExpr *M = cast<MemberExpr>(Init); 1434 if (M->isArrow()) 1435 return CheckAddressConstantExpression(M->getBase()); 1436 return CheckAddressConstantExpressionLValue(M->getBase()); 1437 } 1438 case Expr::ArraySubscriptExprClass: { 1439 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)? 1440 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init); 1441 return CheckAddressConstantExpression(ASE->getBase()) || 1442 CheckArithmeticConstantExpression(ASE->getIdx()); 1443 } 1444 case Expr::StringLiteralClass: 1445 case Expr::PredefinedExprClass: 1446 return false; 1447 case Expr::UnaryOperatorClass: { 1448 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1449 1450 // C99 6.6p9 1451 if (Exp->getOpcode() == UnaryOperator::Deref) 1452 return CheckAddressConstantExpression(Exp->getSubExpr()); 1453 1454 InitializerElementNotConstant(Init); 1455 return true; 1456 } 1457 } 1458} 1459 1460bool Sema::CheckAddressConstantExpression(const Expr* Init) { 1461 switch (Init->getStmtClass()) { 1462 default: 1463 InitializerElementNotConstant(Init); 1464 return true; 1465 case Expr::ParenExprClass: 1466 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr()); 1467 case Expr::StringLiteralClass: 1468 case Expr::ObjCStringLiteralClass: 1469 return false; 1470 case Expr::CallExprClass: 1471 case Expr::CXXOperatorCallExprClass: 1472 // __builtin___CFStringMakeConstantString is a valid constant l-value. 1473 if (cast<CallExpr>(Init)->isBuiltinCall() == 1474 Builtin::BI__builtin___CFStringMakeConstantString) 1475 return false; 1476 1477 InitializerElementNotConstant(Init); 1478 return true; 1479 1480 case Expr::UnaryOperatorClass: { 1481 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1482 1483 // C99 6.6p9 1484 if (Exp->getOpcode() == UnaryOperator::AddrOf) 1485 return CheckAddressConstantExpressionLValue(Exp->getSubExpr()); 1486 1487 if (Exp->getOpcode() == UnaryOperator::Extension) 1488 return CheckAddressConstantExpression(Exp->getSubExpr()); 1489 1490 InitializerElementNotConstant(Init); 1491 return true; 1492 } 1493 case Expr::BinaryOperatorClass: { 1494 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"? 1495 const BinaryOperator *Exp = cast<BinaryOperator>(Init); 1496 1497 Expr *PExp = Exp->getLHS(); 1498 Expr *IExp = Exp->getRHS(); 1499 if (IExp->getType()->isPointerType()) 1500 std::swap(PExp, IExp); 1501 1502 // FIXME: Should we pedwarn if IExp isn't an integer constant expression? 1503 return CheckAddressConstantExpression(PExp) || 1504 CheckArithmeticConstantExpression(IExp); 1505 } 1506 case Expr::ImplicitCastExprClass: 1507 case Expr::CStyleCastExprClass: { 1508 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr(); 1509 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) { 1510 // Check for implicit promotion 1511 if (SubExpr->getType()->isFunctionType() || 1512 SubExpr->getType()->isArrayType()) 1513 return CheckAddressConstantExpressionLValue(SubExpr); 1514 } 1515 1516 // Check for pointer->pointer cast 1517 if (SubExpr->getType()->isPointerType()) 1518 return CheckAddressConstantExpression(SubExpr); 1519 1520 if (SubExpr->getType()->isIntegralType()) { 1521 // Check for the special-case of a pointer->int->pointer cast; 1522 // this isn't standard, but some code requires it. See 1523 // PR2720 for an example. 1524 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) { 1525 if (SubCast->getSubExpr()->getType()->isPointerType()) { 1526 unsigned IntWidth = Context.getIntWidth(SubCast->getType()); 1527 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy); 1528 if (IntWidth >= PointerWidth) { 1529 return CheckAddressConstantExpression(SubCast->getSubExpr()); 1530 } 1531 } 1532 } 1533 } 1534 if (SubExpr->getType()->isArithmeticType()) { 1535 return CheckArithmeticConstantExpression(SubExpr); 1536 } 1537 1538 InitializerElementNotConstant(Init); 1539 return true; 1540 } 1541 case Expr::ConditionalOperatorClass: { 1542 // FIXME: Should we pedwarn here? 1543 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init); 1544 if (!Exp->getCond()->getType()->isArithmeticType()) { 1545 InitializerElementNotConstant(Init); 1546 return true; 1547 } 1548 if (CheckArithmeticConstantExpression(Exp->getCond())) 1549 return true; 1550 if (Exp->getLHS() && 1551 CheckAddressConstantExpression(Exp->getLHS())) 1552 return true; 1553 return CheckAddressConstantExpression(Exp->getRHS()); 1554 } 1555 case Expr::AddrLabelExprClass: 1556 return false; 1557 } 1558} 1559 1560static const Expr* FindExpressionBaseAddress(const Expr* E); 1561 1562static const Expr* FindExpressionBaseAddressLValue(const Expr* E) { 1563 switch (E->getStmtClass()) { 1564 default: 1565 return E; 1566 case Expr::ParenExprClass: { 1567 const ParenExpr* PE = cast<ParenExpr>(E); 1568 return FindExpressionBaseAddressLValue(PE->getSubExpr()); 1569 } 1570 case Expr::MemberExprClass: { 1571 const MemberExpr *M = cast<MemberExpr>(E); 1572 if (M->isArrow()) 1573 return FindExpressionBaseAddress(M->getBase()); 1574 return FindExpressionBaseAddressLValue(M->getBase()); 1575 } 1576 case Expr::ArraySubscriptExprClass: { 1577 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E); 1578 return FindExpressionBaseAddress(ASE->getBase()); 1579 } 1580 case Expr::UnaryOperatorClass: { 1581 const UnaryOperator *Exp = cast<UnaryOperator>(E); 1582 1583 if (Exp->getOpcode() == UnaryOperator::Deref) 1584 return FindExpressionBaseAddress(Exp->getSubExpr()); 1585 1586 return E; 1587 } 1588 } 1589} 1590 1591static const Expr* FindExpressionBaseAddress(const Expr* E) { 1592 switch (E->getStmtClass()) { 1593 default: 1594 return E; 1595 case Expr::ParenExprClass: { 1596 const ParenExpr* PE = cast<ParenExpr>(E); 1597 return FindExpressionBaseAddress(PE->getSubExpr()); 1598 } 1599 case Expr::UnaryOperatorClass: { 1600 const UnaryOperator *Exp = cast<UnaryOperator>(E); 1601 1602 // C99 6.6p9 1603 if (Exp->getOpcode() == UnaryOperator::AddrOf) 1604 return FindExpressionBaseAddressLValue(Exp->getSubExpr()); 1605 1606 if (Exp->getOpcode() == UnaryOperator::Extension) 1607 return FindExpressionBaseAddress(Exp->getSubExpr()); 1608 1609 return E; 1610 } 1611 case Expr::BinaryOperatorClass: { 1612 const BinaryOperator *Exp = cast<BinaryOperator>(E); 1613 1614 Expr *PExp = Exp->getLHS(); 1615 Expr *IExp = Exp->getRHS(); 1616 if (IExp->getType()->isPointerType()) 1617 std::swap(PExp, IExp); 1618 1619 return FindExpressionBaseAddress(PExp); 1620 } 1621 case Expr::ImplicitCastExprClass: { 1622 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr(); 1623 1624 // Check for implicit promotion 1625 if (SubExpr->getType()->isFunctionType() || 1626 SubExpr->getType()->isArrayType()) 1627 return FindExpressionBaseAddressLValue(SubExpr); 1628 1629 // Check for pointer->pointer cast 1630 if (SubExpr->getType()->isPointerType()) 1631 return FindExpressionBaseAddress(SubExpr); 1632 1633 // We assume that we have an arithmetic expression here; 1634 // if we don't, we'll figure it out later 1635 return 0; 1636 } 1637 case Expr::CStyleCastExprClass: { 1638 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 1639 1640 // Check for pointer->pointer cast 1641 if (SubExpr->getType()->isPointerType()) 1642 return FindExpressionBaseAddress(SubExpr); 1643 1644 // We assume that we have an arithmetic expression here; 1645 // if we don't, we'll figure it out later 1646 return 0; 1647 } 1648 } 1649} 1650 1651bool Sema::CheckArithmeticConstantExpression(const Expr* Init) { 1652 switch (Init->getStmtClass()) { 1653 default: 1654 InitializerElementNotConstant(Init); 1655 return true; 1656 case Expr::ParenExprClass: { 1657 const ParenExpr* PE = cast<ParenExpr>(Init); 1658 return CheckArithmeticConstantExpression(PE->getSubExpr()); 1659 } 1660 case Expr::FloatingLiteralClass: 1661 case Expr::IntegerLiteralClass: 1662 case Expr::CharacterLiteralClass: 1663 case Expr::ImaginaryLiteralClass: 1664 case Expr::TypesCompatibleExprClass: 1665 case Expr::CXXBoolLiteralExprClass: 1666 return false; 1667 case Expr::CallExprClass: 1668 case Expr::CXXOperatorCallExprClass: { 1669 const CallExpr *CE = cast<CallExpr>(Init); 1670 1671 // Allow any constant foldable calls to builtins. 1672 if (CE->isBuiltinCall() && CE->isEvaluatable(Context)) 1673 return false; 1674 1675 InitializerElementNotConstant(Init); 1676 return true; 1677 } 1678 case Expr::DeclRefExprClass: { 1679 const Decl *D = cast<DeclRefExpr>(Init)->getDecl(); 1680 if (isa<EnumConstantDecl>(D)) 1681 return false; 1682 InitializerElementNotConstant(Init); 1683 return true; 1684 } 1685 case Expr::CompoundLiteralExprClass: 1686 // Allow "(vector type){2,4}"; normal C constraints don't allow this, 1687 // but vectors are allowed to be magic. 1688 if (Init->getType()->isVectorType()) 1689 return false; 1690 InitializerElementNotConstant(Init); 1691 return true; 1692 case Expr::UnaryOperatorClass: { 1693 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1694 1695 switch (Exp->getOpcode()) { 1696 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 1697 // See C99 6.6p3. 1698 default: 1699 InitializerElementNotConstant(Init); 1700 return true; 1701 case UnaryOperator::OffsetOf: 1702 if (Exp->getSubExpr()->getType()->isConstantSizeType()) 1703 return false; 1704 InitializerElementNotConstant(Init); 1705 return true; 1706 case UnaryOperator::Extension: 1707 case UnaryOperator::LNot: 1708 case UnaryOperator::Plus: 1709 case UnaryOperator::Minus: 1710 case UnaryOperator::Not: 1711 return CheckArithmeticConstantExpression(Exp->getSubExpr()); 1712 } 1713 } 1714 case Expr::SizeOfAlignOfExprClass: { 1715 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init); 1716 // Special check for void types, which are allowed as an extension 1717 if (Exp->getTypeOfArgument()->isVoidType()) 1718 return false; 1719 // alignof always evaluates to a constant. 1720 // FIXME: is sizeof(int[3.0]) a constant expression? 1721 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) { 1722 InitializerElementNotConstant(Init); 1723 return true; 1724 } 1725 return false; 1726 } 1727 case Expr::BinaryOperatorClass: { 1728 const BinaryOperator *Exp = cast<BinaryOperator>(Init); 1729 1730 if (Exp->getLHS()->getType()->isArithmeticType() && 1731 Exp->getRHS()->getType()->isArithmeticType()) { 1732 return CheckArithmeticConstantExpression(Exp->getLHS()) || 1733 CheckArithmeticConstantExpression(Exp->getRHS()); 1734 } 1735 1736 if (Exp->getLHS()->getType()->isPointerType() && 1737 Exp->getRHS()->getType()->isPointerType()) { 1738 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS()); 1739 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS()); 1740 1741 // Only allow a null (constant integer) base; we could 1742 // allow some additional cases if necessary, but this 1743 // is sufficient to cover offsetof-like constructs. 1744 if (!LHSBase && !RHSBase) { 1745 return CheckAddressConstantExpression(Exp->getLHS()) || 1746 CheckAddressConstantExpression(Exp->getRHS()); 1747 } 1748 } 1749 1750 InitializerElementNotConstant(Init); 1751 return true; 1752 } 1753 case Expr::ImplicitCastExprClass: 1754 case Expr::CStyleCastExprClass: { 1755 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr(); 1756 if (SubExpr->getType()->isArithmeticType()) 1757 return CheckArithmeticConstantExpression(SubExpr); 1758 1759 if (SubExpr->getType()->isPointerType()) { 1760 const Expr* Base = FindExpressionBaseAddress(SubExpr); 1761 // If the pointer has a null base, this is an offsetof-like construct 1762 if (!Base) 1763 return CheckAddressConstantExpression(SubExpr); 1764 } 1765 1766 InitializerElementNotConstant(Init); 1767 return true; 1768 } 1769 case Expr::ConditionalOperatorClass: { 1770 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init); 1771 1772 // If GNU extensions are disabled, we require all operands to be arithmetic 1773 // constant expressions. 1774 if (getLangOptions().NoExtensions) { 1775 return CheckArithmeticConstantExpression(Exp->getCond()) || 1776 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) || 1777 CheckArithmeticConstantExpression(Exp->getRHS()); 1778 } 1779 1780 // Otherwise, we have to emulate some of the behavior of fold here. 1781 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant 1782 // because it can constant fold things away. To retain compatibility with 1783 // GCC code, we see if we can fold the condition to a constant (which we 1784 // should always be able to do in theory). If so, we only require the 1785 // specified arm of the conditional to be a constant. This is a horrible 1786 // hack, but is require by real world code that uses __builtin_constant_p. 1787 APValue Val; 1788 if (!Exp->getCond()->Evaluate(Val, Context)) { 1789 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression 1790 // won't be able to either. Use it to emit the diagnostic though. 1791 bool Res = CheckArithmeticConstantExpression(Exp->getCond()); 1792 assert(Res && "Evaluate couldn't evaluate this constant?"); 1793 return Res; 1794 } 1795 1796 // Verify that the side following the condition is also a constant. 1797 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS(); 1798 if (Val.getInt() == 0) 1799 std::swap(TrueSide, FalseSide); 1800 1801 if (TrueSide && CheckArithmeticConstantExpression(TrueSide)) 1802 return true; 1803 1804 // Okay, the evaluated side evaluates to a constant, so we accept this. 1805 // Check to see if the other side is obviously not a constant. If so, 1806 // emit a warning that this is a GNU extension. 1807 if (FalseSide && !FalseSide->isEvaluatable(Context)) 1808 Diag(Init->getExprLoc(), 1809 diag::ext_typecheck_expression_not_constant_but_accepted) 1810 << FalseSide->getSourceRange(); 1811 return false; 1812 } 1813 } 1814} 1815 1816bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 1817 Expr::EvalResult Result; 1818 1819 Init = Init->IgnoreParens(); 1820 1821 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects) 1822 return false; 1823 1824 // Look through CXXDefaultArgExprs; they have no meaning in this context. 1825 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init)) 1826 return CheckForConstantInitializer(DAE->getExpr(), DclT); 1827 1828 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init)) 1829 return CheckForConstantInitializer(e->getInitializer(), DclT); 1830 1831 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) { 1832 unsigned numInits = Exp->getNumInits(); 1833 for (unsigned i = 0; i < numInits; i++) { 1834 // FIXME: Need to get the type of the declaration for C++, 1835 // because it could be a reference? 1836 if (CheckForConstantInitializer(Exp->getInit(i), 1837 Exp->getInit(i)->getType())) 1838 return true; 1839 } 1840 return false; 1841 } 1842 1843 // FIXME: We can probably remove some of this code below, now that 1844 // Expr::Evaluate is doing the heavy lifting for scalars. 1845 1846 if (Init->isNullPointerConstant(Context)) 1847 return false; 1848 if (Init->getType()->isArithmeticType()) { 1849 QualType InitTy = Context.getCanonicalType(Init->getType()) 1850 .getUnqualifiedType(); 1851 if (InitTy == Context.BoolTy) { 1852 // Special handling for pointers implicitly cast to bool; 1853 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level. 1854 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) { 1855 Expr* SubE = ICE->getSubExpr(); 1856 if (SubE->getType()->isPointerType() || 1857 SubE->getType()->isArrayType() || 1858 SubE->getType()->isFunctionType()) { 1859 return CheckAddressConstantExpression(Init); 1860 } 1861 } 1862 } else if (InitTy->isIntegralType()) { 1863 Expr* SubE = 0; 1864 if (CastExpr* CE = dyn_cast<CastExpr>(Init)) 1865 SubE = CE->getSubExpr(); 1866 // Special check for pointer cast to int; we allow as an extension 1867 // an address constant cast to an integer if the integer 1868 // is of an appropriate width (this sort of code is apparently used 1869 // in some places). 1870 // FIXME: Add pedwarn? 1871 // FIXME: Don't allow bitfields here! Need the FieldDecl for that. 1872 if (SubE && (SubE->getType()->isPointerType() || 1873 SubE->getType()->isArrayType() || 1874 SubE->getType()->isFunctionType())) { 1875 unsigned IntWidth = Context.getTypeSize(Init->getType()); 1876 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy); 1877 if (IntWidth >= PointerWidth) 1878 return CheckAddressConstantExpression(Init); 1879 } 1880 } 1881 1882 return CheckArithmeticConstantExpression(Init); 1883 } 1884 1885 if (Init->getType()->isPointerType()) 1886 return CheckAddressConstantExpression(Init); 1887 1888 // An array type at the top level that isn't an init-list must 1889 // be a string literal 1890 if (Init->getType()->isArrayType()) 1891 return false; 1892 1893 if (Init->getType()->isFunctionType()) 1894 return false; 1895 1896 // Allow block exprs at top level. 1897 if (Init->getType()->isBlockPointerType()) 1898 return false; 1899 1900 InitializerElementNotConstant(Init); 1901 return true; 1902} 1903 1904void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) { 1905 Decl *RealDecl = static_cast<Decl *>(dcl); 1906 Expr *Init = static_cast<Expr *>(init.release()); 1907 assert(Init && "missing initializer"); 1908 1909 // If there is no declaration, there was an error parsing it. Just ignore 1910 // the initializer. 1911 if (RealDecl == 0) { 1912 delete Init; 1913 return; 1914 } 1915 1916 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 1917 if (!VDecl) { 1918 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(), 1919 diag::err_illegal_initializer); 1920 RealDecl->setInvalidDecl(); 1921 return; 1922 } 1923 // Get the decls type and save a reference for later, since 1924 // CheckInitializerTypes may change it. 1925 QualType DclT = VDecl->getType(), SavT = DclT; 1926 if (VDecl->isBlockVarDecl()) { 1927 VarDecl::StorageClass SC = VDecl->getStorageClass(); 1928 if (SC == VarDecl::Extern) { // C99 6.7.8p5 1929 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 1930 VDecl->setInvalidDecl(); 1931 } else if (!VDecl->isInvalidDecl()) { 1932 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(), 1933 VDecl->getDeclName())) 1934 VDecl->setInvalidDecl(); 1935 1936 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 1937 if (!getLangOptions().CPlusPlus) { 1938 if (SC == VarDecl::Static) // C99 6.7.8p4. 1939 CheckForConstantInitializer(Init, DclT); 1940 } 1941 } 1942 } else if (VDecl->isFileVarDecl()) { 1943 if (VDecl->getStorageClass() == VarDecl::Extern) 1944 Diag(VDecl->getLocation(), diag::warn_extern_init); 1945 if (!VDecl->isInvalidDecl()) 1946 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(), 1947 VDecl->getDeclName())) 1948 VDecl->setInvalidDecl(); 1949 1950 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 1951 if (!getLangOptions().CPlusPlus) { 1952 // C99 6.7.8p4. All file scoped initializers need to be constant. 1953 CheckForConstantInitializer(Init, DclT); 1954 } 1955 } 1956 // If the type changed, it means we had an incomplete type that was 1957 // completed by the initializer. For example: 1958 // int ary[] = { 1, 3, 5 }; 1959 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 1960 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 1961 VDecl->setType(DclT); 1962 Init->setType(DclT); 1963 } 1964 1965 // Attach the initializer to the decl. 1966 VDecl->setInit(Init); 1967 return; 1968} 1969 1970void Sema::ActOnUninitializedDecl(DeclTy *dcl) { 1971 Decl *RealDecl = static_cast<Decl *>(dcl); 1972 1973 // If there is no declaration, there was an error parsing it. Just ignore it. 1974 if (RealDecl == 0) 1975 return; 1976 1977 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 1978 QualType Type = Var->getType(); 1979 // C++ [dcl.init.ref]p3: 1980 // The initializer can be omitted for a reference only in a 1981 // parameter declaration (8.3.5), in the declaration of a 1982 // function return type, in the declaration of a class member 1983 // within its class declaration (9.2), and where the extern 1984 // specifier is explicitly used. 1985 if (Type->isReferenceType() && 1986 Var->getStorageClass() != VarDecl::Extern && 1987 Var->getStorageClass() != VarDecl::PrivateExtern) { 1988 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 1989 << Var->getDeclName() 1990 << SourceRange(Var->getLocation(), Var->getLocation()); 1991 Var->setInvalidDecl(); 1992 return; 1993 } 1994 1995 // C++ [dcl.init]p9: 1996 // 1997 // If no initializer is specified for an object, and the object 1998 // is of (possibly cv-qualified) non-POD class type (or array 1999 // thereof), the object shall be default-initialized; if the 2000 // object is of const-qualified type, the underlying class type 2001 // shall have a user-declared default constructor. 2002 if (getLangOptions().CPlusPlus) { 2003 QualType InitType = Type; 2004 if (const ArrayType *Array = Context.getAsArrayType(Type)) 2005 InitType = Array->getElementType(); 2006 if (Var->getStorageClass() != VarDecl::Extern && 2007 Var->getStorageClass() != VarDecl::PrivateExtern && 2008 InitType->isRecordType()) { 2009 const CXXConstructorDecl *Constructor 2010 = PerformInitializationByConstructor(InitType, 0, 0, 2011 Var->getLocation(), 2012 SourceRange(Var->getLocation(), 2013 Var->getLocation()), 2014 Var->getDeclName(), 2015 IK_Default); 2016 if (!Constructor) 2017 Var->setInvalidDecl(); 2018 } 2019 } 2020 2021#if 0 2022 // FIXME: Temporarily disabled because we are not properly parsing 2023 // linkage specifications on declarations, e.g., 2024 // 2025 // extern "C" const CGPoint CGPointerZero; 2026 // 2027 // C++ [dcl.init]p9: 2028 // 2029 // If no initializer is specified for an object, and the 2030 // object is of (possibly cv-qualified) non-POD class type (or 2031 // array thereof), the object shall be default-initialized; if 2032 // the object is of const-qualified type, the underlying class 2033 // type shall have a user-declared default 2034 // constructor. Otherwise, if no initializer is specified for 2035 // an object, the object and its subobjects, if any, have an 2036 // indeterminate initial value; if the object or any of its 2037 // subobjects are of const-qualified type, the program is 2038 // ill-formed. 2039 // 2040 // This isn't technically an error in C, so we don't diagnose it. 2041 // 2042 // FIXME: Actually perform the POD/user-defined default 2043 // constructor check. 2044 if (getLangOptions().CPlusPlus && 2045 Context.getCanonicalType(Type).isConstQualified() && 2046 Var->getStorageClass() != VarDecl::Extern) 2047 Diag(Var->getLocation(), diag::err_const_var_requires_init) 2048 << Var->getName() 2049 << SourceRange(Var->getLocation(), Var->getLocation()); 2050#endif 2051 } 2052} 2053 2054/// The declarators are chained together backwards, reverse the list. 2055Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) { 2056 // Often we have single declarators, handle them quickly. 2057 Decl *GroupDecl = static_cast<Decl*>(group); 2058 if (GroupDecl == 0) 2059 return 0; 2060 2061 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl); 2062 ScopedDecl *NewGroup = 0; 2063 if (Group->getNextDeclarator() == 0) 2064 NewGroup = Group; 2065 else { // reverse the list. 2066 while (Group) { 2067 ScopedDecl *Next = Group->getNextDeclarator(); 2068 Group->setNextDeclarator(NewGroup); 2069 NewGroup = Group; 2070 Group = Next; 2071 } 2072 } 2073 // Perform semantic analysis that depends on having fully processed both 2074 // the declarator and initializer. 2075 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) { 2076 VarDecl *IDecl = dyn_cast<VarDecl>(ID); 2077 if (!IDecl) 2078 continue; 2079 QualType T = IDecl->getType(); 2080 2081 if (T->isVariableArrayType()) { 2082 const VariableArrayType *VAT = 2083 cast<VariableArrayType>(T.getUnqualifiedType()); 2084 2085 // FIXME: This won't give the correct result for 2086 // int a[10][n]; 2087 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 2088 if (IDecl->isFileVarDecl()) { 2089 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) << 2090 SizeRange; 2091 2092 IDecl->setInvalidDecl(); 2093 } else { 2094 // C99 6.7.5.2p2: If an identifier is declared to be an object with 2095 // static storage duration, it shall not have a variable length array. 2096 if (IDecl->getStorageClass() == VarDecl::Static) { 2097 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage) 2098 << SizeRange; 2099 IDecl->setInvalidDecl(); 2100 } else if (IDecl->getStorageClass() == VarDecl::Extern) { 2101 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage) 2102 << SizeRange; 2103 IDecl->setInvalidDecl(); 2104 } 2105 } 2106 } else if (T->isVariablyModifiedType()) { 2107 if (IDecl->isFileVarDecl()) { 2108 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope); 2109 IDecl->setInvalidDecl(); 2110 } else { 2111 if (IDecl->getStorageClass() == VarDecl::Extern) { 2112 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage); 2113 IDecl->setInvalidDecl(); 2114 } 2115 } 2116 } 2117 2118 // Block scope. C99 6.7p7: If an identifier for an object is declared with 2119 // no linkage (C99 6.2.2p6), the type for the object shall be complete... 2120 if (IDecl->isBlockVarDecl() && 2121 IDecl->getStorageClass() != VarDecl::Extern) { 2122 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) { 2123 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T; 2124 IDecl->setInvalidDecl(); 2125 } 2126 } 2127 // File scope. C99 6.9.2p2: A declaration of an identifier for and 2128 // object that has file scope without an initializer, and without a 2129 // storage-class specifier or with the storage-class specifier "static", 2130 // constitutes a tentative definition. Note: A tentative definition with 2131 // external linkage is valid (C99 6.2.2p5). 2132 if (isTentativeDefinition(IDecl)) { 2133 if (T->isIncompleteArrayType()) { 2134 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete 2135 // array to be completed. Don't issue a diagnostic. 2136 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) { 2137 // C99 6.9.2p3: If the declaration of an identifier for an object is 2138 // a tentative definition and has internal linkage (C99 6.2.2p3), the 2139 // declared type shall not be an incomplete type. 2140 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T; 2141 IDecl->setInvalidDecl(); 2142 } 2143 } 2144 if (IDecl->isFileVarDecl()) 2145 CheckForFileScopedRedefinitions(S, IDecl); 2146 } 2147 return NewGroup; 2148} 2149 2150/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 2151/// to introduce parameters into function prototype scope. 2152Sema::DeclTy * 2153Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 2154 // FIXME: disallow CXXScopeSpec for param declarators. 2155 const DeclSpec &DS = D.getDeclSpec(); 2156 2157 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 2158 VarDecl::StorageClass StorageClass = VarDecl::None; 2159 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 2160 StorageClass = VarDecl::Register; 2161 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 2162 Diag(DS.getStorageClassSpecLoc(), 2163 diag::err_invalid_storage_class_in_func_decl); 2164 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2165 } 2166 if (DS.isThreadSpecified()) { 2167 Diag(DS.getThreadSpecLoc(), 2168 diag::err_invalid_storage_class_in_func_decl); 2169 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2170 } 2171 2172 // Check that there are no default arguments inside the type of this 2173 // parameter (C++ only). 2174 if (getLangOptions().CPlusPlus) 2175 CheckExtraCXXDefaultArguments(D); 2176 2177 // In this context, we *do not* check D.getInvalidType(). If the declarator 2178 // type was invalid, GetTypeForDeclarator() still returns a "valid" type, 2179 // though it will not reflect the user specified type. 2180 QualType parmDeclType = GetTypeForDeclarator(D, S); 2181 2182 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type"); 2183 2184 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 2185 // Can this happen for params? We already checked that they don't conflict 2186 // among each other. Here they can only shadow globals, which is ok. 2187 IdentifierInfo *II = D.getIdentifier(); 2188 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) { 2189 if (PrevDecl->isTemplateParameter()) { 2190 // Maybe we will complain about the shadowed template parameter. 2191 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 2192 // Just pretend that we didn't see the previous declaration. 2193 PrevDecl = 0; 2194 } else if (S->isDeclScope(PrevDecl)) { 2195 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 2196 2197 // Recover by removing the name 2198 II = 0; 2199 D.SetIdentifier(0, D.getIdentifierLoc()); 2200 } 2201 } 2202 2203 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]). 2204 // Doing the promotion here has a win and a loss. The win is the type for 2205 // both Decl's and DeclRefExpr's will match (a convenient invariant for the 2206 // code generator). The loss is the orginal type isn't preserved. For example: 2207 // 2208 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *" 2209 // int blockvardecl[5]; 2210 // sizeof(parmvardecl); // size == 4 2211 // sizeof(blockvardecl); // size == 20 2212 // } 2213 // 2214 // For expressions, all implicit conversions are captured using the 2215 // ImplicitCastExpr AST node (we have no such mechanism for Decl's). 2216 // 2217 // FIXME: If a source translation tool needs to see the original type, then 2218 // we need to consider storing both types (in ParmVarDecl)... 2219 // 2220 if (parmDeclType->isArrayType()) { 2221 // int x[restrict 4] -> int *restrict 2222 parmDeclType = Context.getArrayDecayedType(parmDeclType); 2223 } else if (parmDeclType->isFunctionType()) 2224 parmDeclType = Context.getPointerType(parmDeclType); 2225 2226 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, 2227 D.getIdentifierLoc(), II, 2228 parmDeclType, StorageClass, 2229 0, 0); 2230 2231 if (D.getInvalidType()) 2232 New->setInvalidDecl(); 2233 2234 // Add the parameter declaration into this scope. 2235 S->AddDecl(New); 2236 if (II) 2237 IdResolver.AddDecl(New); 2238 2239 ProcessDeclAttributes(New, D); 2240 return New; 2241 2242} 2243 2244Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 2245 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 2246 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 2247 "Not a function declarator!"); 2248 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2249 2250 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 2251 // for a K&R function. 2252 if (!FTI.hasPrototype) { 2253 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 2254 if (FTI.ArgInfo[i].Param == 0) { 2255 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 2256 << FTI.ArgInfo[i].Ident; 2257 // Implicitly declare the argument as type 'int' for lack of a better 2258 // type. 2259 DeclSpec DS; 2260 const char* PrevSpec; // unused 2261 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 2262 PrevSpec); 2263 Declarator ParamD(DS, Declarator::KNRTypeListContext); 2264 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 2265 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD); 2266 } 2267 } 2268 } else { 2269 // FIXME: Diagnose arguments without names in C. 2270 } 2271 2272 Scope *GlobalScope = FnBodyScope->getParent(); 2273 2274 return ActOnStartOfFunctionDef(FnBodyScope, 2275 ActOnDeclarator(GlobalScope, D, 0)); 2276} 2277 2278Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) { 2279 Decl *decl = static_cast<Decl*>(D); 2280 FunctionDecl *FD = cast<FunctionDecl>(decl); 2281 2282 // See if this is a redefinition. 2283 const FunctionDecl *Definition; 2284 if (FD->getBody(Definition)) { 2285 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 2286 Diag(Definition->getLocation(), diag::note_previous_definition); 2287 } 2288 2289 PushDeclContext(FnBodyScope, FD); 2290 2291 // Check the validity of our function parameters 2292 CheckParmsForFunctionDef(FD); 2293 2294 // Introduce our parameters into the function scope 2295 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 2296 ParmVarDecl *Param = FD->getParamDecl(p); 2297 // If this has an identifier, add it to the scope stack. 2298 if (Param->getIdentifier()) 2299 PushOnScopeChains(Param, FnBodyScope); 2300 } 2301 2302 return FD; 2303} 2304 2305Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) { 2306 Decl *dcl = static_cast<Decl *>(D); 2307 Stmt *Body = static_cast<Stmt*>(BodyArg.release()); 2308 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) { 2309 FD->setBody(Body); 2310 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 2311 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 2312 MD->setBody((Stmt*)Body); 2313 } else 2314 return 0; 2315 PopDeclContext(); 2316 // Verify and clean out per-function state. 2317 2318 // Check goto/label use. 2319 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 2320 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) { 2321 // Verify that we have no forward references left. If so, there was a goto 2322 // or address of a label taken, but no definition of it. Label fwd 2323 // definitions are indicated with a null substmt. 2324 if (I->second->getSubStmt() == 0) { 2325 LabelStmt *L = I->second; 2326 // Emit error. 2327 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName(); 2328 2329 // At this point, we have gotos that use the bogus label. Stitch it into 2330 // the function body so that they aren't leaked and that the AST is well 2331 // formed. 2332 if (Body) { 2333 L->setSubStmt(new NullStmt(L->getIdentLoc())); 2334 cast<CompoundStmt>(Body)->push_back(L); 2335 } else { 2336 // The whole function wasn't parsed correctly, just delete this. 2337 delete L; 2338 } 2339 } 2340 } 2341 LabelMap.clear(); 2342 2343 return D; 2344} 2345 2346/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 2347/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 2348ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 2349 IdentifierInfo &II, Scope *S) { 2350 // Extension in C99. Legal in C90, but warn about it. 2351 if (getLangOptions().C99) 2352 Diag(Loc, diag::ext_implicit_function_decl) << &II; 2353 else 2354 Diag(Loc, diag::warn_implicit_function_decl) << &II; 2355 2356 // FIXME: handle stuff like: 2357 // void foo() { extern float X(); } 2358 // void bar() { X(); } <-- implicit decl for X in another scope. 2359 2360 // Set a Declarator for the implicit definition: int foo(); 2361 const char *Dummy; 2362 DeclSpec DS; 2363 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy); 2364 Error = Error; // Silence warning. 2365 assert(!Error && "Error setting up implicit decl!"); 2366 Declarator D(DS, Declarator::BlockContext); 2367 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc)); 2368 D.SetIdentifier(&II, Loc); 2369 2370 // Insert this function into translation-unit scope. 2371 2372 DeclContext *PrevDC = CurContext; 2373 CurContext = Context.getTranslationUnitDecl(); 2374 2375 FunctionDecl *FD = 2376 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0))); 2377 FD->setImplicit(); 2378 2379 CurContext = PrevDC; 2380 2381 return FD; 2382} 2383 2384 2385TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 2386 ScopedDecl *LastDeclarator) { 2387 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 2388 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 2389 2390 // Scope manipulation handled by caller. 2391 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 2392 D.getIdentifierLoc(), 2393 D.getIdentifier(), 2394 T, LastDeclarator); 2395 if (D.getInvalidType()) 2396 NewTD->setInvalidDecl(); 2397 return NewTD; 2398} 2399 2400/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 2401/// former case, Name will be non-null. In the later case, Name will be null. 2402/// TagType indicates what kind of tag this is. TK indicates whether this is a 2403/// reference/declaration/definition of a tag. 2404Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK, 2405 SourceLocation KWLoc, const CXXScopeSpec &SS, 2406 IdentifierInfo *Name, SourceLocation NameLoc, 2407 AttributeList *Attr) { 2408 // If this is not a definition, it must have a name. 2409 assert((Name != 0 || TK == TK_Definition) && 2410 "Nameless record must be a definition!"); 2411 2412 TagDecl::TagKind Kind; 2413 switch (TagType) { 2414 default: assert(0 && "Unknown tag type!"); 2415 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 2416 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 2417 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 2418 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break; 2419 } 2420 2421 DeclContext *DC = CurContext; 2422 ScopedDecl *PrevDecl = 0; 2423 2424 if (Name && SS.isNotEmpty()) { 2425 // We have a nested-name tag ('struct foo::bar'). 2426 2427 // Check for invalid 'foo::'. 2428 if (SS.isInvalid()) { 2429 Name = 0; 2430 goto CreateNewDecl; 2431 } 2432 2433 DC = static_cast<DeclContext*>(SS.getScopeRep()); 2434 // Look-up name inside 'foo::'. 2435 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC)); 2436 2437 // A tag 'foo::bar' must already exist. 2438 if (PrevDecl == 0) { 2439 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange(); 2440 Name = 0; 2441 goto CreateNewDecl; 2442 } 2443 } else { 2444 // If this is a named struct, check to see if there was a previous forward 2445 // declaration or definition. 2446 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up. 2447 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S)); 2448 } 2449 2450 if (PrevDecl && PrevDecl->isTemplateParameter()) { 2451 // Maybe we will complain about the shadowed template parameter. 2452 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); 2453 // Just pretend that we didn't see the previous declaration. 2454 PrevDecl = 0; 2455 } 2456 2457 if (PrevDecl) { 2458 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) && 2459 "unexpected Decl type"); 2460 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 2461 // If this is a use of a previous tag, or if the tag is already declared 2462 // in the same scope (so that the definition/declaration completes or 2463 // rementions the tag), reuse the decl. 2464 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) { 2465 // Make sure that this wasn't declared as an enum and now used as a 2466 // struct or something similar. 2467 if (PrevTagDecl->getTagKind() != Kind) { 2468 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 2469 Diag(PrevDecl->getLocation(), diag::note_previous_use); 2470 // Recover by making this an anonymous redefinition. 2471 Name = 0; 2472 PrevDecl = 0; 2473 } else { 2474 // If this is a use, just return the declaration we found. 2475 2476 // FIXME: In the future, return a variant or some other clue 2477 // for the consumer of this Decl to know it doesn't own it. 2478 // For our current ASTs this shouldn't be a problem, but will 2479 // need to be changed with DeclGroups. 2480 if (TK == TK_Reference) 2481 return PrevDecl; 2482 2483 // Diagnose attempts to redefine a tag. 2484 if (TK == TK_Definition) { 2485 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) { 2486 Diag(NameLoc, diag::err_redefinition) << Name; 2487 Diag(Def->getLocation(), diag::note_previous_definition); 2488 // If this is a redefinition, recover by making this struct be 2489 // anonymous, which will make any later references get the previous 2490 // definition. 2491 Name = 0; 2492 PrevDecl = 0; 2493 } 2494 // Okay, this is definition of a previously declared or referenced 2495 // tag PrevDecl. We're going to create a new Decl for it. 2496 } 2497 } 2498 // If we get here we have (another) forward declaration or we 2499 // have a definition. Just create a new decl. 2500 } else { 2501 // If we get here, this is a definition of a new tag type in a nested 2502 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 2503 // new decl/type. We set PrevDecl to NULL so that the entities 2504 // have distinct types. 2505 PrevDecl = 0; 2506 } 2507 // If we get here, we're going to create a new Decl. If PrevDecl 2508 // is non-NULL, it's a definition of the tag declared by 2509 // PrevDecl. If it's NULL, we have a new definition. 2510 } else { 2511 // PrevDecl is a namespace. 2512 if (isDeclInScope(PrevDecl, DC, S)) { 2513 // The tag name clashes with a namespace name, issue an error and 2514 // recover by making this tag be anonymous. 2515 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 2516 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2517 Name = 0; 2518 PrevDecl = 0; 2519 } else { 2520 // The existing declaration isn't relevant to us; we're in a 2521 // new scope, so clear out the previous declaration. 2522 PrevDecl = 0; 2523 } 2524 } 2525 } 2526 2527 CreateNewDecl: 2528 2529 // If there is an identifier, use the location of the identifier as the 2530 // location of the decl, otherwise use the location of the struct/union 2531 // keyword. 2532 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 2533 2534 // Otherwise, create a new declaration. If there is a previous 2535 // declaration of the same entity, the two will be linked via 2536 // PrevDecl. 2537 TagDecl *New; 2538 if (Kind == TagDecl::TK_enum) { 2539 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 2540 // enum X { A, B, C } D; D should chain to X. 2541 New = EnumDecl::Create(Context, DC, Loc, Name, 2542 cast_or_null<EnumDecl>(PrevDecl)); 2543 // If this is an undefined enum, warn. 2544 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum); 2545 } else { 2546 // struct/union/class 2547 2548 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 2549 // struct X { int A; } D; D should chain to X. 2550 if (getLangOptions().CPlusPlus) 2551 // FIXME: Look for a way to use RecordDecl for simple structs. 2552 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name, 2553 cast_or_null<CXXRecordDecl>(PrevDecl)); 2554 else 2555 New = RecordDecl::Create(Context, Kind, DC, Loc, Name, 2556 cast_or_null<RecordDecl>(PrevDecl)); 2557 } 2558 2559 if (Kind != TagDecl::TK_enum) { 2560 // Handle #pragma pack: if the #pragma pack stack has non-default 2561 // alignment, make up a packed attribute for this decl. These 2562 // attributes are checked when the ASTContext lays out the 2563 // structure. 2564 // 2565 // It is important for implementing the correct semantics that this 2566 // happen here (in act on tag decl). The #pragma pack stack is 2567 // maintained as a result of parser callbacks which can occur at 2568 // many points during the parsing of a struct declaration (because 2569 // the #pragma tokens are effectively skipped over during the 2570 // parsing of the struct). 2571 if (unsigned Alignment = PackContext.getAlignment()) 2572 New->addAttr(new PackedAttr(Alignment * 8)); 2573 } 2574 2575 if (Attr) 2576 ProcessDeclAttributeList(New, Attr); 2577 2578 // Set the lexical context. If the tag has a C++ scope specifier, the 2579 // lexical context will be different from the semantic context. 2580 New->setLexicalDeclContext(CurContext); 2581 2582 // If this has an identifier, add it to the scope stack. 2583 if (Name) { 2584 // The scope passed in may not be a decl scope. Zip up the scope tree until 2585 // we find one that is. 2586 while ((S->getFlags() & Scope::DeclScope) == 0) 2587 S = S->getParent(); 2588 2589 // Add it to the decl chain. 2590 PushOnScopeChains(New, S); 2591 } 2592 2593 return New; 2594} 2595 2596/// Collect the instance variables declared in an Objective-C object. Used in 2597/// the creation of structures from objects using the @defs directive. 2598/// FIXME: This should be consolidated with CollectObjCIvars as it is also 2599/// part of the AST generation logic of @defs. 2600static void CollectIvars(ObjCInterfaceDecl *Class, RecordDecl *Record, 2601 ASTContext& Ctx, 2602 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) { 2603 if (Class->getSuperClass()) 2604 CollectIvars(Class->getSuperClass(), Record, Ctx, ivars); 2605 2606 // For each ivar, create a fresh ObjCAtDefsFieldDecl. 2607 for (ObjCInterfaceDecl::ivar_iterator 2608 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) { 2609 2610 ObjCIvarDecl* ID = *I; 2611 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, Record, 2612 ID->getLocation(), 2613 ID->getIdentifier(), 2614 ID->getType(), 2615 ID->getBitWidth())); 2616 } 2617} 2618 2619/// Called whenever @defs(ClassName) is encountered in the source. Inserts the 2620/// instance variables of ClassName into Decls. 2621void Sema::ActOnDefs(Scope *S, DeclTy *TagD, SourceLocation DeclStart, 2622 IdentifierInfo *ClassName, 2623 llvm::SmallVectorImpl<DeclTy*> &Decls) { 2624 // Check that ClassName is a valid class 2625 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName); 2626 if (!Class) { 2627 Diag(DeclStart, diag::err_undef_interface) << ClassName; 2628 return; 2629 } 2630 // Collect the instance variables 2631 CollectIvars(Class, dyn_cast<RecordDecl>((Decl*)TagD), Context, Decls); 2632 2633 // Introduce all of these fields into the appropriate scope. 2634 for (llvm::SmallVectorImpl<DeclTy*>::iterator D = Decls.begin(); 2635 D != Decls.end(); ++D) { 2636 FieldDecl *FD = cast<FieldDecl>((Decl*)*D); 2637 if (getLangOptions().CPlusPlus) 2638 PushOnScopeChains(cast<FieldDecl>(FD), S); 2639 else if (RecordDecl *Record = dyn_cast<RecordDecl>((Decl*)TagD)) 2640 Record->addDecl(Context, FD); 2641 } 2642} 2643 2644/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array 2645/// types into constant array types in certain situations which would otherwise 2646/// be errors (for GCC compatibility). 2647static QualType TryToFixInvalidVariablyModifiedType(QualType T, 2648 ASTContext &Context) { 2649 // This method tries to turn a variable array into a constant 2650 // array even when the size isn't an ICE. This is necessary 2651 // for compatibility with code that depends on gcc's buggy 2652 // constant expression folding, like struct {char x[(int)(char*)2];} 2653 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 2654 if (!VLATy) return QualType(); 2655 2656 APValue Result; 2657 if (!VLATy->getSizeExpr() || 2658 !VLATy->getSizeExpr()->Evaluate(Result, Context)) 2659 return QualType(); 2660 2661 assert(Result.isInt() && "Size expressions must be integers!"); 2662 llvm::APSInt &Res = Result.getInt(); 2663 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) 2664 return Context.getConstantArrayType(VLATy->getElementType(), 2665 Res, ArrayType::Normal, 0); 2666 return QualType(); 2667} 2668 2669bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 2670 QualType FieldTy, const Expr *BitWidth) { 2671 // FIXME: 6.7.2.1p4 - verify the field type. 2672 2673 llvm::APSInt Value; 2674 if (VerifyIntegerConstantExpression(BitWidth, &Value)) 2675 return true; 2676 2677 // Zero-width bitfield is ok for anonymous field. 2678 if (Value == 0 && FieldName) 2679 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 2680 2681 if (Value.isNegative()) 2682 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName; 2683 2684 uint64_t TypeSize = Context.getTypeSize(FieldTy); 2685 // FIXME: We won't need the 0 size once we check that the field type is valid. 2686 if (TypeSize && Value.getZExtValue() > TypeSize) 2687 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 2688 << FieldName << (unsigned)TypeSize; 2689 2690 return false; 2691} 2692 2693/// ActOnField - Each field of a struct/union/class is passed into this in order 2694/// to create a FieldDecl object for it. 2695Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD, 2696 SourceLocation DeclStart, 2697 Declarator &D, ExprTy *BitfieldWidth) { 2698 IdentifierInfo *II = D.getIdentifier(); 2699 Expr *BitWidth = (Expr*)BitfieldWidth; 2700 SourceLocation Loc = DeclStart; 2701 RecordDecl *Record = (RecordDecl *)TagD; 2702 if (II) Loc = D.getIdentifierLoc(); 2703 2704 // FIXME: Unnamed fields can be handled in various different ways, for 2705 // example, unnamed unions inject all members into the struct namespace! 2706 2707 QualType T = GetTypeForDeclarator(D, S); 2708 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 2709 bool InvalidDecl = false; 2710 2711 // C99 6.7.2.1p8: A member of a structure or union may have any type other 2712 // than a variably modified type. 2713 if (T->isVariablyModifiedType()) { 2714 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context); 2715 if (!FixedTy.isNull()) { 2716 Diag(Loc, diag::warn_illegal_constant_array_size); 2717 T = FixedTy; 2718 } else { 2719 Diag(Loc, diag::err_typecheck_field_variable_size); 2720 T = Context.IntTy; 2721 InvalidDecl = true; 2722 } 2723 } 2724 2725 if (BitWidth) { 2726 if (VerifyBitField(Loc, II, T, BitWidth)) 2727 InvalidDecl = true; 2728 } else { 2729 // Not a bitfield. 2730 2731 // validate II. 2732 2733 } 2734 2735 // FIXME: Chain fielddecls together. 2736 FieldDecl *NewFD; 2737 2738 // FIXME: We don't want CurContext for C, do we? No, we'll need some 2739 // other way to determine the current RecordDecl. 2740 NewFD = FieldDecl::Create(Context, Record, 2741 Loc, II, T, BitWidth, 2742 D.getDeclSpec().getStorageClassSpec() == 2743 DeclSpec::SCS_mutable, 2744 /*PrevDecl=*/0); 2745 2746 ProcessDeclAttributes(NewFD, D); 2747 2748 if (D.getInvalidType() || InvalidDecl) 2749 NewFD->setInvalidDecl(); 2750 2751 if (II && getLangOptions().CPlusPlus) 2752 PushOnScopeChains(NewFD, S); 2753 else 2754 Record->addDecl(Context, NewFD); 2755 2756 return NewFD; 2757} 2758 2759/// TranslateIvarVisibility - Translate visibility from a token ID to an 2760/// AST enum value. 2761static ObjCIvarDecl::AccessControl 2762TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 2763 switch (ivarVisibility) { 2764 default: assert(0 && "Unknown visitibility kind"); 2765 case tok::objc_private: return ObjCIvarDecl::Private; 2766 case tok::objc_public: return ObjCIvarDecl::Public; 2767 case tok::objc_protected: return ObjCIvarDecl::Protected; 2768 case tok::objc_package: return ObjCIvarDecl::Package; 2769 } 2770} 2771 2772/// ActOnIvar - Each ivar field of an objective-c class is passed into this 2773/// in order to create an IvarDecl object for it. 2774Sema::DeclTy *Sema::ActOnIvar(Scope *S, 2775 SourceLocation DeclStart, 2776 Declarator &D, ExprTy *BitfieldWidth, 2777 tok::ObjCKeywordKind Visibility) { 2778 IdentifierInfo *II = D.getIdentifier(); 2779 Expr *BitWidth = (Expr*)BitfieldWidth; 2780 SourceLocation Loc = DeclStart; 2781 if (II) Loc = D.getIdentifierLoc(); 2782 2783 // FIXME: Unnamed fields can be handled in various different ways, for 2784 // example, unnamed unions inject all members into the struct namespace! 2785 2786 QualType T = GetTypeForDeclarator(D, S); 2787 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 2788 bool InvalidDecl = false; 2789 2790 if (BitWidth) { 2791 // TODO: Validate. 2792 //printf("WARNING: BITFIELDS IGNORED!\n"); 2793 2794 // 6.7.2.1p3 2795 // 6.7.2.1p4 2796 2797 } else { 2798 // Not a bitfield. 2799 2800 // validate II. 2801 2802 } 2803 2804 // C99 6.7.2.1p8: A member of a structure or union may have any type other 2805 // than a variably modified type. 2806 if (T->isVariablyModifiedType()) { 2807 Diag(Loc, diag::err_typecheck_ivar_variable_size); 2808 InvalidDecl = true; 2809 } 2810 2811 // Get the visibility (access control) for this ivar. 2812 ObjCIvarDecl::AccessControl ac = 2813 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 2814 : ObjCIvarDecl::None; 2815 2816 // Construct the decl. 2817 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac, 2818 (Expr *)BitfieldWidth); 2819 2820 // Process attributes attached to the ivar. 2821 ProcessDeclAttributes(NewID, D); 2822 2823 if (D.getInvalidType() || InvalidDecl) 2824 NewID->setInvalidDecl(); 2825 2826 return NewID; 2827} 2828 2829void Sema::ActOnFields(Scope* S, 2830 SourceLocation RecLoc, DeclTy *RecDecl, 2831 DeclTy **Fields, unsigned NumFields, 2832 SourceLocation LBrac, SourceLocation RBrac, 2833 AttributeList *Attr) { 2834 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl); 2835 assert(EnclosingDecl && "missing record or interface decl"); 2836 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 2837 2838 if (Record) 2839 if (RecordDecl* DefRecord = Record->getDefinition(Context)) { 2840 // Diagnose code like: 2841 // struct S { struct S {} X; }; 2842 // We discover this when we complete the outer S. Reject and ignore the 2843 // outer S. 2844 Diag(DefRecord->getLocation(), diag::err_nested_redefinition) 2845 << DefRecord->getDeclName(); 2846 Diag(RecLoc, diag::note_previous_definition); 2847 Record->setInvalidDecl(); 2848 return; 2849 } 2850 2851 // Verify that all the fields are okay. 2852 unsigned NumNamedMembers = 0; 2853 llvm::SmallVector<FieldDecl*, 32> RecFields; 2854 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs; 2855 2856 for (unsigned i = 0; i != NumFields; ++i) { 2857 2858 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i])); 2859 assert(FD && "missing field decl"); 2860 2861 // Remember all fields. 2862 RecFields.push_back(FD); 2863 2864 // Get the type for the field. 2865 Type *FDTy = FD->getType().getTypePtr(); 2866 2867 // C99 6.7.2.1p2 - A field may not be a function type. 2868 if (FDTy->isFunctionType()) { 2869 Diag(FD->getLocation(), diag::err_field_declared_as_function) 2870 << FD->getDeclName(); 2871 FD->setInvalidDecl(); 2872 EnclosingDecl->setInvalidDecl(); 2873 continue; 2874 } 2875 // C99 6.7.2.1p2 - A field may not be an incomplete type except... 2876 if (FDTy->isIncompleteType()) { 2877 if (!Record) { // Incomplete ivar type is always an error. 2878 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName(); 2879 FD->setInvalidDecl(); 2880 EnclosingDecl->setInvalidDecl(); 2881 continue; 2882 } 2883 if (i != NumFields-1 || // ... that the last member ... 2884 !Record->isStruct() || // ... of a structure ... 2885 !FDTy->isArrayType()) { //... may have incomplete array type. 2886 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName(); 2887 FD->setInvalidDecl(); 2888 EnclosingDecl->setInvalidDecl(); 2889 continue; 2890 } 2891 if (NumNamedMembers < 1) { //... must have more than named member ... 2892 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 2893 << FD->getDeclName(); 2894 FD->setInvalidDecl(); 2895 EnclosingDecl->setInvalidDecl(); 2896 continue; 2897 } 2898 // Okay, we have a legal flexible array member at the end of the struct. 2899 if (Record) 2900 Record->setHasFlexibleArrayMember(true); 2901 } 2902 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the 2903 /// field of another structure or the element of an array. 2904 if (const RecordType *FDTTy = FDTy->getAsRecordType()) { 2905 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 2906 // If this is a member of a union, then entire union becomes "flexible". 2907 if (Record && Record->isUnion()) { 2908 Record->setHasFlexibleArrayMember(true); 2909 } else { 2910 // If this is a struct/class and this is not the last element, reject 2911 // it. Note that GCC supports variable sized arrays in the middle of 2912 // structures. 2913 if (i != NumFields-1) { 2914 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct) 2915 << FD->getDeclName(); 2916 FD->setInvalidDecl(); 2917 EnclosingDecl->setInvalidDecl(); 2918 continue; 2919 } 2920 // We support flexible arrays at the end of structs in other structs 2921 // as an extension. 2922 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 2923 << FD->getDeclName(); 2924 if (Record) 2925 Record->setHasFlexibleArrayMember(true); 2926 } 2927 } 2928 } 2929 /// A field cannot be an Objective-c object 2930 if (FDTy->isObjCInterfaceType()) { 2931 Diag(FD->getLocation(), diag::err_statically_allocated_object) 2932 << FD->getDeclName(); 2933 FD->setInvalidDecl(); 2934 EnclosingDecl->setInvalidDecl(); 2935 continue; 2936 } 2937 // Keep track of the number of named members. 2938 if (IdentifierInfo *II = FD->getIdentifier()) { 2939 // Detect duplicate member names. 2940 if (!FieldIDs.insert(II)) { 2941 Diag(FD->getLocation(), diag::err_duplicate_member) << II; 2942 // Find the previous decl. 2943 SourceLocation PrevLoc; 2944 for (unsigned i = 0; ; ++i) { 2945 assert(i != RecFields.size() && "Didn't find previous def!"); 2946 if (RecFields[i]->getIdentifier() == II) { 2947 PrevLoc = RecFields[i]->getLocation(); 2948 break; 2949 } 2950 } 2951 Diag(PrevLoc, diag::note_previous_definition); 2952 FD->setInvalidDecl(); 2953 EnclosingDecl->setInvalidDecl(); 2954 continue; 2955 } 2956 ++NumNamedMembers; 2957 } 2958 } 2959 2960 // Okay, we successfully defined 'Record'. 2961 if (Record) { 2962 Record->completeDefinition(Context); 2963 // If this is a C++ record, HandleTagDeclDefinition will be invoked in 2964 // Sema::ActOnFinishCXXClassDef. 2965 if (!isa<CXXRecordDecl>(Record)) 2966 Consumer.HandleTagDeclDefinition(Record); 2967 } else { 2968 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]); 2969 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 2970 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac); 2971 ID->addRecordToClass(Context); 2972 } 2973 else if (ObjCImplementationDecl *IMPDecl = 2974 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 2975 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 2976 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size()); 2977 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 2978 } 2979 } 2980 2981 if (Attr) 2982 ProcessDeclAttributeList(Record, Attr); 2983} 2984 2985Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl, 2986 DeclTy *lastEnumConst, 2987 SourceLocation IdLoc, IdentifierInfo *Id, 2988 SourceLocation EqualLoc, ExprTy *val) { 2989 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl)); 2990 EnumConstantDecl *LastEnumConst = 2991 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst)); 2992 Expr *Val = static_cast<Expr*>(val); 2993 2994 // The scope passed in may not be a decl scope. Zip up the scope tree until 2995 // we find one that is. 2996 while ((S->getFlags() & Scope::DeclScope) == 0) 2997 S = S->getParent(); 2998 2999 // Verify that there isn't already something declared with this name in this 3000 // scope. 3001 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S); 3002 if (PrevDecl && PrevDecl->isTemplateParameter()) { 3003 // Maybe we will complain about the shadowed template parameter. 3004 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 3005 // Just pretend that we didn't see the previous declaration. 3006 PrevDecl = 0; 3007 } 3008 3009 if (PrevDecl) { 3010 // When in C++, we may get a TagDecl with the same name; in this case the 3011 // enum constant will 'hide' the tag. 3012 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 3013 "Received TagDecl when not in C++!"); 3014 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 3015 if (isa<EnumConstantDecl>(PrevDecl)) 3016 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 3017 else 3018 Diag(IdLoc, diag::err_redefinition) << Id; 3019 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3020 delete Val; 3021 return 0; 3022 } 3023 } 3024 3025 llvm::APSInt EnumVal(32); 3026 QualType EltTy; 3027 if (Val) { 3028 // Make sure to promote the operand type to int. 3029 UsualUnaryConversions(Val); 3030 3031 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 3032 SourceLocation ExpLoc; 3033 if (VerifyIntegerConstantExpression(Val, &EnumVal)) { 3034 delete Val; 3035 Val = 0; // Just forget about it. 3036 } else { 3037 EltTy = Val->getType(); 3038 } 3039 } 3040 3041 if (!Val) { 3042 if (LastEnumConst) { 3043 // Assign the last value + 1. 3044 EnumVal = LastEnumConst->getInitVal(); 3045 ++EnumVal; 3046 3047 // Check for overflow on increment. 3048 if (EnumVal < LastEnumConst->getInitVal()) 3049 Diag(IdLoc, diag::warn_enum_value_overflow); 3050 3051 EltTy = LastEnumConst->getType(); 3052 } else { 3053 // First value, set to zero. 3054 EltTy = Context.IntTy; 3055 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy))); 3056 } 3057 } 3058 3059 EnumConstantDecl *New = 3060 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy, 3061 Val, EnumVal, 3062 LastEnumConst); 3063 3064 // Register this decl in the current scope stack. 3065 PushOnScopeChains(New, S); 3066 return New; 3067} 3068 3069// FIXME: For consistency with ActOnFields(), we should have the parser 3070// pass in the source location for the left/right braces. 3071void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX, 3072 DeclTy **Elements, unsigned NumElements) { 3073 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX)); 3074 3075 if (Enum) { 3076 if (EnumDecl *Def = cast_or_null<EnumDecl>(Enum->getDefinition(Context))) { 3077 // Diagnose code like: 3078 // enum e0 { 3079 // E0 = sizeof(enum e0 { E1 }) 3080 // }; 3081 Diag(Def->getLocation(), diag::err_nested_redefinition) 3082 << Enum->getDeclName(); 3083 Diag(Enum->getLocation(), diag::note_previous_definition); 3084 Enum->setInvalidDecl(); 3085 return; 3086 } 3087 } 3088 // TODO: If the result value doesn't fit in an int, it must be a long or long 3089 // long value. ISO C does not support this, but GCC does as an extension, 3090 // emit a warning. 3091 unsigned IntWidth = Context.Target.getIntWidth(); 3092 3093 // Verify that all the values are okay, compute the size of the values, and 3094 // reverse the list. 3095 unsigned NumNegativeBits = 0; 3096 unsigned NumPositiveBits = 0; 3097 3098 // Keep track of whether all elements have type int. 3099 bool AllElementsInt = true; 3100 3101 QualType EnumType = Context.getTypeDeclType(Enum); 3102 EnumConstantDecl *EltList = 0; 3103 for (unsigned i = 0; i != NumElements; ++i) { 3104 EnumConstantDecl *ECD = 3105 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 3106 if (!ECD) continue; // Already issued a diagnostic. 3107 3108 // If the enum value doesn't fit in an int, emit an extension warning. 3109 const llvm::APSInt &InitVal = ECD->getInitVal(); 3110 assert(InitVal.getBitWidth() >= IntWidth && 3111 "Should have promoted value to int"); 3112 if (InitVal.getBitWidth() > IntWidth) { 3113 llvm::APSInt V(InitVal); 3114 V.trunc(IntWidth); 3115 V.extend(InitVal.getBitWidth()); 3116 if (V != InitVal) 3117 Diag(ECD->getLocation(), diag::ext_enum_value_not_int) 3118 << InitVal.toString(10); 3119 } 3120 3121 // Keep track of the size of positive and negative values. 3122 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 3123 NumPositiveBits = std::max(NumPositiveBits, 3124 (unsigned)InitVal.getActiveBits()); 3125 else 3126 NumNegativeBits = std::max(NumNegativeBits, 3127 (unsigned)InitVal.getMinSignedBits()); 3128 3129 // Keep track of whether every enum element has type int (very commmon). 3130 if (AllElementsInt) 3131 AllElementsInt = ECD->getType() == Context.IntTy; 3132 3133 ECD->setNextDeclarator(EltList); 3134 EltList = ECD; 3135 } 3136 3137 // Figure out the type that should be used for this enum. 3138 // FIXME: Support attribute(packed) on enums and -fshort-enums. 3139 QualType BestType; 3140 unsigned BestWidth; 3141 3142 if (NumNegativeBits) { 3143 // If there is a negative value, figure out the smallest integer type (of 3144 // int/long/longlong) that fits. 3145 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 3146 BestType = Context.IntTy; 3147 BestWidth = IntWidth; 3148 } else { 3149 BestWidth = Context.Target.getLongWidth(); 3150 3151 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) 3152 BestType = Context.LongTy; 3153 else { 3154 BestWidth = Context.Target.getLongLongWidth(); 3155 3156 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 3157 Diag(Enum->getLocation(), diag::warn_enum_too_large); 3158 BestType = Context.LongLongTy; 3159 } 3160 } 3161 } else { 3162 // If there is no negative value, figure out which of uint, ulong, ulonglong 3163 // fits. 3164 if (NumPositiveBits <= IntWidth) { 3165 BestType = Context.UnsignedIntTy; 3166 BestWidth = IntWidth; 3167 } else if (NumPositiveBits <= 3168 (BestWidth = Context.Target.getLongWidth())) { 3169 BestType = Context.UnsignedLongTy; 3170 } else { 3171 BestWidth = Context.Target.getLongLongWidth(); 3172 assert(NumPositiveBits <= BestWidth && 3173 "How could an initializer get larger than ULL?"); 3174 BestType = Context.UnsignedLongLongTy; 3175 } 3176 } 3177 3178 // Loop over all of the enumerator constants, changing their types to match 3179 // the type of the enum if needed. 3180 for (unsigned i = 0; i != NumElements; ++i) { 3181 EnumConstantDecl *ECD = 3182 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 3183 if (!ECD) continue; // Already issued a diagnostic. 3184 3185 // Standard C says the enumerators have int type, but we allow, as an 3186 // extension, the enumerators to be larger than int size. If each 3187 // enumerator value fits in an int, type it as an int, otherwise type it the 3188 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 3189 // that X has type 'int', not 'unsigned'. 3190 if (ECD->getType() == Context.IntTy) { 3191 // Make sure the init value is signed. 3192 llvm::APSInt IV = ECD->getInitVal(); 3193 IV.setIsSigned(true); 3194 ECD->setInitVal(IV); 3195 3196 if (getLangOptions().CPlusPlus) 3197 // C++ [dcl.enum]p4: Following the closing brace of an 3198 // enum-specifier, each enumerator has the type of its 3199 // enumeration. 3200 ECD->setType(EnumType); 3201 continue; // Already int type. 3202 } 3203 3204 // Determine whether the value fits into an int. 3205 llvm::APSInt InitVal = ECD->getInitVal(); 3206 bool FitsInInt; 3207 if (InitVal.isUnsigned() || !InitVal.isNegative()) 3208 FitsInInt = InitVal.getActiveBits() < IntWidth; 3209 else 3210 FitsInInt = InitVal.getMinSignedBits() <= IntWidth; 3211 3212 // If it fits into an integer type, force it. Otherwise force it to match 3213 // the enum decl type. 3214 QualType NewTy; 3215 unsigned NewWidth; 3216 bool NewSign; 3217 if (FitsInInt) { 3218 NewTy = Context.IntTy; 3219 NewWidth = IntWidth; 3220 NewSign = true; 3221 } else if (ECD->getType() == BestType) { 3222 // Already the right type! 3223 if (getLangOptions().CPlusPlus) 3224 // C++ [dcl.enum]p4: Following the closing brace of an 3225 // enum-specifier, each enumerator has the type of its 3226 // enumeration. 3227 ECD->setType(EnumType); 3228 continue; 3229 } else { 3230 NewTy = BestType; 3231 NewWidth = BestWidth; 3232 NewSign = BestType->isSignedIntegerType(); 3233 } 3234 3235 // Adjust the APSInt value. 3236 InitVal.extOrTrunc(NewWidth); 3237 InitVal.setIsSigned(NewSign); 3238 ECD->setInitVal(InitVal); 3239 3240 // Adjust the Expr initializer and type. 3241 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(), 3242 /*isLvalue=*/false)); 3243 if (getLangOptions().CPlusPlus) 3244 // C++ [dcl.enum]p4: Following the closing brace of an 3245 // enum-specifier, each enumerator has the type of its 3246 // enumeration. 3247 ECD->setType(EnumType); 3248 else 3249 ECD->setType(NewTy); 3250 } 3251 3252 Enum->completeDefinition(Context, BestType); 3253 Consumer.HandleTagDeclDefinition(Enum); 3254} 3255 3256Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, 3257 ExprArg expr) { 3258 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release()); 3259 3260 return FileScopeAsmDecl::Create(Context, Loc, AsmString); 3261} 3262 3263Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc, 3264 SourceLocation LBrace, 3265 SourceLocation RBrace, 3266 const char *Lang, 3267 unsigned StrSize, 3268 DeclTy *D) { 3269 LinkageSpecDecl::LanguageIDs Language; 3270 Decl *dcl = static_cast<Decl *>(D); 3271 if (strncmp(Lang, "\"C\"", StrSize) == 0) 3272 Language = LinkageSpecDecl::lang_c; 3273 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 3274 Language = LinkageSpecDecl::lang_cxx; 3275 else { 3276 Diag(Loc, diag::err_bad_language); 3277 return 0; 3278 } 3279 3280 // FIXME: Add all the various semantics of linkage specifications 3281 return LinkageSpecDecl::Create(Context, Loc, Language, dcl); 3282} 3283 3284void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name, 3285 ExprTy *alignment, SourceLocation PragmaLoc, 3286 SourceLocation LParenLoc, SourceLocation RParenLoc) { 3287 Expr *Alignment = static_cast<Expr *>(alignment); 3288 3289 // If specified then alignment must be a "small" power of two. 3290 unsigned AlignmentVal = 0; 3291 if (Alignment) { 3292 llvm::APSInt Val; 3293 if (!Alignment->isIntegerConstantExpr(Val, Context) || 3294 !Val.isPowerOf2() || 3295 Val.getZExtValue() > 16) { 3296 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment); 3297 delete Alignment; 3298 return; // Ignore 3299 } 3300 3301 AlignmentVal = (unsigned) Val.getZExtValue(); 3302 } 3303 3304 switch (Kind) { 3305 case Action::PPK_Default: // pack([n]) 3306 PackContext.setAlignment(AlignmentVal); 3307 break; 3308 3309 case Action::PPK_Show: // pack(show) 3310 // Show the current alignment, making sure to show the right value 3311 // for the default. 3312 AlignmentVal = PackContext.getAlignment(); 3313 // FIXME: This should come from the target. 3314 if (AlignmentVal == 0) 3315 AlignmentVal = 8; 3316 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal; 3317 break; 3318 3319 case Action::PPK_Push: // pack(push [, id] [, [n]) 3320 PackContext.push(Name); 3321 // Set the new alignment if specified. 3322 if (Alignment) 3323 PackContext.setAlignment(AlignmentVal); 3324 break; 3325 3326 case Action::PPK_Pop: // pack(pop [, id] [, n]) 3327 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack: 3328 // "#pragma pack(pop, identifier, n) is undefined" 3329 if (Alignment && Name) 3330 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment); 3331 3332 // Do the pop. 3333 if (!PackContext.pop(Name)) { 3334 // If a name was specified then failure indicates the name 3335 // wasn't found. Otherwise failure indicates the stack was 3336 // empty. 3337 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed) 3338 << (Name ? "no record matching name" : "stack empty"); 3339 3340 // FIXME: Warn about popping named records as MSVC does. 3341 } else { 3342 // Pop succeeded, set the new alignment if specified. 3343 if (Alignment) 3344 PackContext.setAlignment(AlignmentVal); 3345 } 3346 break; 3347 3348 default: 3349 assert(0 && "Invalid #pragma pack kind."); 3350 } 3351} 3352 3353bool PragmaPackStack::pop(IdentifierInfo *Name) { 3354 if (Stack.empty()) 3355 return false; 3356 3357 // If name is empty just pop top. 3358 if (!Name) { 3359 Alignment = Stack.back().first; 3360 Stack.pop_back(); 3361 return true; 3362 } 3363 3364 // Otherwise, find the named record. 3365 for (unsigned i = Stack.size(); i != 0; ) { 3366 --i; 3367 if (Stack[i].second == Name) { 3368 // Found it, pop up to and including this record. 3369 Alignment = Stack[i].first; 3370 Stack.erase(Stack.begin() + i, Stack.end()); 3371 return true; 3372 } 3373 } 3374 3375 return false; 3376} 3377