SemaDecl.cpp revision bd7eb1c3b2af5cd0a7540c79da85e2ce15a893f4
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" 28using namespace clang; 29 30Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) { 31 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false); 32 33 if (IIDecl && (isa<TypedefDecl>(IIDecl) || 34 isa<ObjCInterfaceDecl>(IIDecl) || 35 isa<TagDecl>(IIDecl))) 36 return IIDecl; 37 return 0; 38} 39 40DeclContext *Sema::getDCParent(DeclContext *DC) { 41 // If CurContext is a ObjC method, getParent() will return NULL. 42 if (isa<ObjCMethodDecl>(DC)) 43 return Context.getTranslationUnitDecl(); 44 45 // A C++ inline method is parsed *after* the topmost class it was declared in 46 // is fully parsed (it's "complete"). 47 // The parsing of a C++ inline method happens at the declaration context of 48 // the topmost (non-nested) class it is declared in. 49 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 50 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record."); 51 DC = MD->getParent(); 52 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 53 DC = RD; 54 55 // Return the declaration context of the topmost class the inline method is 56 // declared in. 57 return DC; 58 } 59 60 return DC->getParent(); 61} 62 63void Sema::PushDeclContext(DeclContext *DC) { 64 assert(getDCParent(DC) == CurContext && 65 "The next DeclContext should be directly contained in the current one."); 66 CurContext = DC; 67} 68 69void Sema::PopDeclContext() { 70 assert(CurContext && "DeclContext imbalance!"); 71 CurContext = getDCParent(CurContext); 72} 73 74/// Add this decl to the scope shadowed decl chains. 75void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) { 76 S->AddDecl(D); 77 78 // C++ [basic.scope]p4: 79 // -- exactly one declaration shall declare a class name or 80 // enumeration name that is not a typedef name and the other 81 // declarations shall all refer to the same object or 82 // enumerator, or all refer to functions and function templates; 83 // in this case the class name or enumeration name is hidden. 84 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 85 // We are pushing the name of a tag (enum or class). 86 IdentifierResolver::iterator 87 I = IdResolver.begin(TD->getIdentifier(), 88 TD->getDeclContext(), false/*LookInParentCtx*/); 89 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) { 90 // There is already a declaration with the same name in the same 91 // scope. It must be found before we find the new declaration, 92 // so swap the order on the shadowed declaration chain. 93 94 IdResolver.AddShadowedDecl(TD, *I); 95 return; 96 } 97 } 98 IdResolver.AddDecl(D); 99} 100 101void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 102 if (S->decl_empty()) return; 103 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!"); 104 105 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 106 I != E; ++I) { 107 Decl *TmpD = static_cast<Decl*>(*I); 108 assert(TmpD && "This decl didn't get pushed??"); 109 110 if (isa<CXXFieldDecl>(TmpD)) continue; 111 112 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?"); 113 ScopedDecl *D = cast<ScopedDecl>(TmpD); 114 115 IdentifierInfo *II = D->getIdentifier(); 116 if (!II) continue; 117 118 // We only want to remove the decls from the identifier decl chains for 119 // local scopes, when inside a function/method. 120 if (S->getFnParent() != 0) 121 IdResolver.RemoveDecl(D); 122 123 // Chain this decl to the containing DeclContext. 124 D->setNext(CurContext->getDeclChain()); 125 CurContext->setDeclChain(D); 126 } 127} 128 129/// getObjCInterfaceDecl - Look up a for a class declaration in the scope. 130/// return 0 if one not found. 131ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) { 132 // The third "scope" argument is 0 since we aren't enabling lazy built-in 133 // creation from this context. 134 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false); 135 136 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 137} 138 139/// LookupDecl - Look up the inner-most declaration in the specified 140/// namespace. 141Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI, 142 Scope *S, bool enableLazyBuiltinCreation) { 143 if (II == 0) return 0; 144 unsigned NS = NSI; 145 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary)) 146 NS |= Decl::IDNS_Tag; 147 148 // Scan up the scope chain looking for a decl that matches this identifier 149 // that is in the appropriate namespace. This search should not take long, as 150 // shadowing of names is uncommon, and deep shadowing is extremely uncommon. 151 for (IdentifierResolver::iterator 152 I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I) 153 if ((*I)->getIdentifierNamespace() & NS) 154 return *I; 155 156 // If we didn't find a use of this identifier, and if the identifier 157 // corresponds to a compiler builtin, create the decl object for the builtin 158 // now, injecting it into translation unit scope, and return it. 159 if (NS & Decl::IDNS_Ordinary) { 160 if (enableLazyBuiltinCreation) { 161 // If this is a builtin on this (or all) targets, create the decl. 162 if (unsigned BuiltinID = II->getBuiltinID()) 163 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S); 164 } 165 if (getLangOptions().ObjC1) { 166 // @interface and @compatibility_alias introduce typedef-like names. 167 // Unlike typedef's, they can only be introduced at file-scope (and are 168 // therefore not scoped decls). They can, however, be shadowed by 169 // other names in IDNS_Ordinary. 170 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II); 171 if (IDI != ObjCInterfaceDecls.end()) 172 return IDI->second; 173 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II); 174 if (I != ObjCAliasDecls.end()) 175 return I->second->getClassInterface(); 176 } 177 } 178 return 0; 179} 180 181void Sema::InitBuiltinVaListType() { 182 if (!Context.getBuiltinVaListType().isNull()) 183 return; 184 185 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list"); 186 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope); 187 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl); 188 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef)); 189} 190 191/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope. 192/// lazily create a decl for it. 193ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 194 Scope *S) { 195 Builtin::ID BID = (Builtin::ID)bid; 196 197 if (Context.BuiltinInfo.hasVAListUse(BID)) 198 InitBuiltinVaListType(); 199 200 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context); 201 FunctionDecl *New = FunctionDecl::Create(Context, 202 Context.getTranslationUnitDecl(), 203 SourceLocation(), II, R, 204 FunctionDecl::Extern, false, 0); 205 206 // Create Decl objects for each parameter, adding them to the 207 // FunctionDecl. 208 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) { 209 llvm::SmallVector<ParmVarDecl*, 16> Params; 210 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) 211 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0, 212 FT->getArgType(i), VarDecl::None, 0, 213 0)); 214 New->setParams(&Params[0], Params.size()); 215 } 216 217 218 219 // TUScope is the translation-unit scope to insert this function into. 220 PushOnScopeChains(New, TUScope); 221 return New; 222} 223 224/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name 225/// and scope as a previous declaration 'Old'. Figure out how to resolve this 226/// situation, merging decls or emitting diagnostics as appropriate. 227/// 228TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) { 229 // Allow multiple definitions for ObjC built-in typedefs. 230 // FIXME: Verify the underlying types are equivalent! 231 if (getLangOptions().ObjC1) { 232 const IdentifierInfo *typeIdent = New->getIdentifier(); 233 if (typeIdent == Ident_id) { 234 Context.setObjCIdType(New); 235 return New; 236 } else if (typeIdent == Ident_Class) { 237 Context.setObjCClassType(New); 238 return New; 239 } else if (typeIdent == Ident_SEL) { 240 Context.setObjCSelType(New); 241 return New; 242 } else if (typeIdent == Ident_Protocol) { 243 Context.setObjCProtoType(New->getUnderlyingType()); 244 return New; 245 } 246 // Fall through - the typedef name was not a builtin type. 247 } 248 // Verify the old decl was also a typedef. 249 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD); 250 if (!Old) { 251 Diag(New->getLocation(), diag::err_redefinition_different_kind, 252 New->getName()); 253 Diag(OldD->getLocation(), diag::err_previous_definition); 254 return New; 255 } 256 257 // If the typedef types are not identical, reject them in all languages and 258 // with any extensions enabled. 259 if (Old->getUnderlyingType() != New->getUnderlyingType() && 260 Context.getCanonicalType(Old->getUnderlyingType()) != 261 Context.getCanonicalType(New->getUnderlyingType())) { 262 Diag(New->getLocation(), diag::err_redefinition_different_typedef, 263 New->getUnderlyingType().getAsString(), 264 Old->getUnderlyingType().getAsString()); 265 Diag(Old->getLocation(), diag::err_previous_definition); 266 return Old; 267 } 268 269 if (getLangOptions().Microsoft) return New; 270 271 // Redeclaration of a type is a constraint violation (6.7.2.3p1). 272 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if 273 // *either* declaration is in a system header. The code below implements 274 // this adhoc compatibility rule. FIXME: The following code will not 275 // work properly when compiling ".i" files (containing preprocessed output). 276 if (PP.getDiagnostics().getSuppressSystemWarnings()) { 277 SourceManager &SrcMgr = Context.getSourceManager(); 278 if (SrcMgr.isInSystemHeader(Old->getLocation())) 279 return New; 280 if (SrcMgr.isInSystemHeader(New->getLocation())) 281 return New; 282 } 283 284 Diag(New->getLocation(), diag::err_redefinition, New->getName()); 285 Diag(Old->getLocation(), diag::err_previous_definition); 286 return New; 287} 288 289/// DeclhasAttr - returns true if decl Declaration already has the target 290/// attribute. 291static bool DeclHasAttr(const Decl *decl, const Attr *target) { 292 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext()) 293 if (attr->getKind() == target->getKind()) 294 return true; 295 296 return false; 297} 298 299/// MergeAttributes - append attributes from the Old decl to the New one. 300static void MergeAttributes(Decl *New, Decl *Old) { 301 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp; 302 303 while (attr) { 304 tmp = attr; 305 attr = attr->getNext(); 306 307 if (!DeclHasAttr(New, tmp)) { 308 New->addAttr(tmp); 309 } else { 310 tmp->setNext(0); 311 delete(tmp); 312 } 313 } 314 315 Old->invalidateAttrs(); 316} 317 318/// MergeFunctionDecl - We just parsed a function 'New' from 319/// declarator D which has the same name and scope as a previous 320/// declaration 'Old'. Figure out how to resolve this situation, 321/// merging decls or emitting diagnostics as appropriate. 322/// Redeclaration will be set true if thisNew is a redeclaration OldD. 323FunctionDecl * 324Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) { 325 Redeclaration = false; 326 // Verify the old decl was also a function. 327 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD); 328 if (!Old) { 329 Diag(New->getLocation(), diag::err_redefinition_different_kind, 330 New->getName()); 331 Diag(OldD->getLocation(), diag::err_previous_definition); 332 return New; 333 } 334 335 QualType OldQType = Context.getCanonicalType(Old->getType()); 336 QualType NewQType = Context.getCanonicalType(New->getType()); 337 338 // C++ [dcl.fct]p3: 339 // All declarations for a function shall agree exactly in both the 340 // return type and the parameter-type-list. 341 if (getLangOptions().CPlusPlus && OldQType == NewQType) { 342 MergeAttributes(New, Old); 343 Redeclaration = true; 344 return MergeCXXFunctionDecl(New, Old); 345 } 346 347 // C: Function types need to be compatible, not identical. This handles 348 // duplicate function decls like "void f(int); void f(enum X);" properly. 349 if (!getLangOptions().CPlusPlus && 350 Context.typesAreCompatible(OldQType, NewQType)) { 351 MergeAttributes(New, Old); 352 Redeclaration = true; 353 return New; 354 } 355 356 // A function that has already been declared has been redeclared or defined 357 // with a different type- show appropriate diagnostic 358 diag::kind PrevDiag; 359 if (Old->isThisDeclarationADefinition()) 360 PrevDiag = diag::err_previous_definition; 361 else if (Old->isImplicit()) 362 PrevDiag = diag::err_previous_implicit_declaration; 363 else 364 PrevDiag = diag::err_previous_declaration; 365 366 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 367 // TODO: This is totally simplistic. It should handle merging functions 368 // together etc, merging extern int X; int X; ... 369 Diag(New->getLocation(), diag::err_conflicting_types, New->getName()); 370 Diag(Old->getLocation(), PrevDiag); 371 return New; 372} 373 374/// Predicate for C "tentative" external object definitions (C99 6.9.2). 375static bool isTentativeDefinition(VarDecl *VD) { 376 if (VD->isFileVarDecl()) 377 return (!VD->getInit() && 378 (VD->getStorageClass() == VarDecl::None || 379 VD->getStorageClass() == VarDecl::Static)); 380 return false; 381} 382 383/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors 384/// when dealing with C "tentative" external object definitions (C99 6.9.2). 385void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) { 386 bool VDIsTentative = isTentativeDefinition(VD); 387 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType(); 388 389 for (IdentifierResolver::iterator 390 I = IdResolver.begin(VD->getIdentifier(), 391 VD->getDeclContext(), false/*LookInParentCtx*/), 392 E = IdResolver.end(); I != E; ++I) { 393 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) { 394 VarDecl *OldDecl = dyn_cast<VarDecl>(*I); 395 396 // Handle the following case: 397 // int a[10]; 398 // int a[]; - the code below makes sure we set the correct type. 399 // int a[11]; - this is an error, size isn't 10. 400 if (OldDecl && VDIsTentative && VDIsIncompleteArray && 401 OldDecl->getType()->isConstantArrayType()) 402 VD->setType(OldDecl->getType()); 403 404 // Check for "tentative" definitions. We can't accomplish this in 405 // MergeVarDecl since the initializer hasn't been attached. 406 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative) 407 continue; 408 409 // Handle __private_extern__ just like extern. 410 if (OldDecl->getStorageClass() != VarDecl::Extern && 411 OldDecl->getStorageClass() != VarDecl::PrivateExtern && 412 VD->getStorageClass() != VarDecl::Extern && 413 VD->getStorageClass() != VarDecl::PrivateExtern) { 414 Diag(VD->getLocation(), diag::err_redefinition, VD->getName()); 415 Diag(OldDecl->getLocation(), diag::err_previous_definition); 416 } 417 } 418 } 419} 420 421/// MergeVarDecl - We just parsed a variable 'New' which has the same name 422/// and scope as a previous declaration 'Old'. Figure out how to resolve this 423/// situation, merging decls or emitting diagnostics as appropriate. 424/// 425/// Tentative definition rules (C99 6.9.2p2) are checked by 426/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 427/// definitions here, since the initializer hasn't been attached. 428/// 429VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) { 430 // Verify the old decl was also a variable. 431 VarDecl *Old = dyn_cast<VarDecl>(OldD); 432 if (!Old) { 433 Diag(New->getLocation(), diag::err_redefinition_different_kind, 434 New->getName()); 435 Diag(OldD->getLocation(), diag::err_previous_definition); 436 return New; 437 } 438 439 MergeAttributes(New, Old); 440 441 // Verify the types match. 442 QualType OldCType = Context.getCanonicalType(Old->getType()); 443 QualType NewCType = Context.getCanonicalType(New->getType()); 444 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) { 445 Diag(New->getLocation(), diag::err_redefinition, New->getName()); 446 Diag(Old->getLocation(), diag::err_previous_definition); 447 return New; 448 } 449 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 450 if (New->getStorageClass() == VarDecl::Static && 451 (Old->getStorageClass() == VarDecl::None || 452 Old->getStorageClass() == VarDecl::Extern)) { 453 Diag(New->getLocation(), diag::err_static_non_static, New->getName()); 454 Diag(Old->getLocation(), diag::err_previous_definition); 455 return New; 456 } 457 // C99 6.2.2p4: Check if we have a non-static decl followed by a static. 458 if (New->getStorageClass() != VarDecl::Static && 459 Old->getStorageClass() == VarDecl::Static) { 460 Diag(New->getLocation(), diag::err_non_static_static, New->getName()); 461 Diag(Old->getLocation(), diag::err_previous_definition); 462 return New; 463 } 464 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 465 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) { 466 Diag(New->getLocation(), diag::err_redefinition, New->getName()); 467 Diag(Old->getLocation(), diag::err_previous_definition); 468 } 469 return New; 470} 471 472/// CheckParmsForFunctionDef - Check that the parameters of the given 473/// function are appropriate for the definition of a function. This 474/// takes care of any checks that cannot be performed on the 475/// declaration itself, e.g., that the types of each of the function 476/// parameters are complete. 477bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) { 478 bool HasInvalidParm = false; 479 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 480 ParmVarDecl *Param = FD->getParamDecl(p); 481 482 // C99 6.7.5.3p4: the parameters in a parameter type list in a 483 // function declarator that is part of a function definition of 484 // that function shall not have incomplete type. 485 if (Param->getType()->isIncompleteType() && 486 !Param->isInvalidDecl()) { 487 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type, 488 Param->getType().getAsString()); 489 Param->setInvalidDecl(); 490 HasInvalidParm = true; 491 } 492 } 493 494 return HasInvalidParm; 495} 496 497/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 498/// no declarator (e.g. "struct foo;") is parsed. 499Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) { 500 // TODO: emit error on 'int;' or 'const enum foo;'. 501 // TODO: emit error on 'typedef int;' 502 // if (!DS.isMissingDeclaratorOk()) Diag(...); 503 504 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep())); 505} 506 507bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) { 508 // Get the type before calling CheckSingleAssignmentConstraints(), since 509 // it can promote the expression. 510 QualType InitType = Init->getType(); 511 512 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init); 513 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType, 514 InitType, Init, "initializing"); 515} 516 517bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) { 518 const ArrayType *AT = Context.getAsArrayType(DeclT); 519 520 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 521 // C99 6.7.8p14. We have an array of character type with unknown size 522 // being initialized to a string literal. 523 llvm::APSInt ConstVal(32); 524 ConstVal = strLiteral->getByteLength() + 1; 525 // Return a new array type (C99 6.7.8p22). 526 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal, 527 ArrayType::Normal, 0); 528 } else { 529 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); 530 // C99 6.7.8p14. We have an array of character type with known size. 531 // FIXME: Avoid truncation for 64-bit length strings. 532 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue()) 533 Diag(strLiteral->getSourceRange().getBegin(), 534 diag::warn_initializer_string_for_char_array_too_long, 535 strLiteral->getSourceRange()); 536 } 537 // Set type from "char *" to "constant array of char". 538 strLiteral->setType(DeclT); 539 // For now, we always return false (meaning success). 540 return false; 541} 542 543StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) { 544 const ArrayType *AT = Context.getAsArrayType(DeclType); 545 if (AT && AT->getElementType()->isCharType()) { 546 return dyn_cast<StringLiteral>(Init); 547 } 548 return 0; 549} 550 551bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) { 552 // C99 6.7.8p3: The type of the entity to be initialized shall be an array 553 // of unknown size ("[]") or an object type that is not a variable array type. 554 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType)) 555 return Diag(VAT->getSizeExpr()->getLocStart(), 556 diag::err_variable_object_no_init, 557 VAT->getSizeExpr()->getSourceRange()); 558 559 InitListExpr *InitList = dyn_cast<InitListExpr>(Init); 560 if (!InitList) { 561 // FIXME: Handle wide strings 562 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType)) 563 return CheckStringLiteralInit(strLiteral, DeclType); 564 565 if (DeclType->isArrayType()) 566 return Diag(Init->getLocStart(), 567 diag::err_array_init_list_required, 568 Init->getSourceRange()); 569 570 return CheckSingleInitializer(Init, DeclType); 571 } 572 573 InitListChecker CheckInitList(this, InitList, DeclType); 574 return CheckInitList.HadError(); 575} 576 577Sema::DeclTy * 578Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) { 579 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl); 580 IdentifierInfo *II = D.getIdentifier(); 581 582 // All of these full declarators require an identifier. If it doesn't have 583 // one, the ParsedFreeStandingDeclSpec action should be used. 584 if (II == 0) { 585 Diag(D.getDeclSpec().getSourceRange().getBegin(), 586 diag::err_declarator_need_ident, 587 D.getDeclSpec().getSourceRange(), D.getSourceRange()); 588 return 0; 589 } 590 591 // The scope passed in may not be a decl scope. Zip up the scope tree until 592 // we find one that is. 593 while ((S->getFlags() & Scope::DeclScope) == 0) 594 S = S->getParent(); 595 596 // See if this is a redefinition of a variable in the same scope. 597 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S); 598 ScopedDecl *New; 599 bool InvalidDecl = false; 600 601 // In C++, the previous declaration we find might be a tag type 602 // (class or enum). In this case, the new declaration will hide the 603 // tag type. 604 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) 605 PrevDecl = 0; 606 607 QualType R = GetTypeForDeclarator(D, S); 608 assert(!R.isNull() && "GetTypeForDeclarator() returned null type"); 609 610 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 611 // Check that there are no default arguments (C++ only). 612 if (getLangOptions().CPlusPlus) 613 CheckExtraCXXDefaultArguments(D); 614 615 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator); 616 if (!NewTD) return 0; 617 618 // Handle attributes prior to checking for duplicates in MergeVarDecl 619 ProcessDeclAttributes(NewTD, D); 620 // Merge the decl with the existing one if appropriate. If the decl is 621 // in an outer scope, it isn't the same thing. 622 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) { 623 NewTD = MergeTypeDefDecl(NewTD, PrevDecl); 624 if (NewTD == 0) return 0; 625 } 626 New = NewTD; 627 if (S->getFnParent() == 0) { 628 // C99 6.7.7p2: If a typedef name specifies a variably modified type 629 // then it shall have block scope. 630 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) { 631 // FIXME: Diagnostic needs to be fixed. 632 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla); 633 InvalidDecl = true; 634 } 635 } 636 } else if (R.getTypePtr()->isFunctionType()) { 637 FunctionDecl::StorageClass SC = FunctionDecl::None; 638 switch (D.getDeclSpec().getStorageClassSpec()) { 639 default: assert(0 && "Unknown storage class!"); 640 case DeclSpec::SCS_auto: 641 case DeclSpec::SCS_register: 642 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func, 643 R.getAsString()); 644 InvalidDecl = true; 645 break; 646 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break; 647 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break; 648 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break; 649 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break; 650 } 651 652 bool isInline = D.getDeclSpec().isInlineSpecified(); 653 FunctionDecl *NewFD; 654 if (D.getContext() == Declarator::MemberContext) { 655 // This is a C++ method declaration. 656 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext), 657 D.getIdentifierLoc(), II, R, 658 (SC == FunctionDecl::Static), isInline, 659 LastDeclarator); 660 } else { 661 NewFD = FunctionDecl::Create(Context, CurContext, 662 D.getIdentifierLoc(), 663 II, R, SC, isInline, 664 LastDeclarator); 665 } 666 // Handle attributes. 667 ProcessDeclAttributes(NewFD, D); 668 669 // Handle GNU asm-label extension (encoded as an attribute). 670 if (Expr *E = (Expr*) D.getAsmLabel()) { 671 // The parser guarantees this is a string. 672 StringLiteral *SE = cast<StringLiteral>(E); 673 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(), 674 SE->getByteLength()))); 675 } 676 677 // Copy the parameter declarations from the declarator D to 678 // the function declaration NewFD, if they are available. 679 if (D.getNumTypeObjects() > 0) { 680 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 681 682 // Create Decl objects for each parameter, adding them to the 683 // FunctionDecl. 684 llvm::SmallVector<ParmVarDecl*, 16> Params; 685 686 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 687 // function that takes no arguments, not a function that takes a 688 // single void argument. 689 // We let through "const void" here because Sema::GetTypeForDeclarator 690 // already checks for that case. 691 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 692 FTI.ArgInfo[0].Param && 693 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 694 // empty arg list, don't push any params. 695 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param; 696 697 // In C++, the empty parameter-type-list must be spelled "void"; a 698 // typedef of void is not permitted. 699 if (getLangOptions().CPlusPlus && 700 Param->getType().getUnqualifiedType() != Context.VoidTy) { 701 Diag(Param->getLocation(), diag::ext_param_typedef_of_void); 702 } 703 704 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 705 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 706 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param); 707 } 708 709 NewFD->setParams(&Params[0], Params.size()); 710 } 711 712 // Merge the decl with the existing one if appropriate. Since C functions 713 // are in a flat namespace, make sure we consider decls in outer scopes. 714 if (PrevDecl && 715 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, CurContext, S))) { 716 bool Redeclaration = false; 717 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration); 718 if (NewFD == 0) return 0; 719 if (Redeclaration) { 720 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl)); 721 } 722 } 723 New = NewFD; 724 725 // In C++, check default arguments now that we have merged decls. 726 if (getLangOptions().CPlusPlus) 727 CheckCXXDefaultArguments(NewFD); 728 } else { 729 // Check that there are no default arguments (C++ only). 730 if (getLangOptions().CPlusPlus) 731 CheckExtraCXXDefaultArguments(D); 732 733 if (R.getTypePtr()->isObjCInterfaceType()) { 734 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object, 735 D.getIdentifier()->getName()); 736 InvalidDecl = true; 737 } 738 739 VarDecl *NewVD; 740 VarDecl::StorageClass SC; 741 switch (D.getDeclSpec().getStorageClassSpec()) { 742 default: assert(0 && "Unknown storage class!"); 743 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 744 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 745 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 746 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 747 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 748 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 749 } 750 if (D.getContext() == Declarator::MemberContext) { 751 assert(SC == VarDecl::Static && "Invalid storage class for member!"); 752 // This is a static data member for a C++ class. 753 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext), 754 D.getIdentifierLoc(), II, 755 R, LastDeclarator); 756 } else { 757 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified(); 758 if (S->getFnParent() == 0) { 759 // C99 6.9p2: The storage-class specifiers auto and register shall not 760 // appear in the declaration specifiers in an external declaration. 761 if (SC == VarDecl::Auto || SC == VarDecl::Register) { 762 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope, 763 R.getAsString()); 764 InvalidDecl = true; 765 } 766 } 767 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(), 768 II, R, SC, LastDeclarator); 769 NewVD->setThreadSpecified(ThreadSpecified); 770 } 771 // Handle attributes prior to checking for duplicates in MergeVarDecl 772 ProcessDeclAttributes(NewVD, D); 773 774 // Handle GNU asm-label extension (encoded as an attribute). 775 if (Expr *E = (Expr*) D.getAsmLabel()) { 776 // The parser guarantees this is a string. 777 StringLiteral *SE = cast<StringLiteral>(E); 778 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(), 779 SE->getByteLength()))); 780 } 781 782 // Emit an error if an address space was applied to decl with local storage. 783 // This includes arrays of objects with address space qualifiers, but not 784 // automatic variables that point to other address spaces. 785 // ISO/IEC TR 18037 S5.1.2 786 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) { 787 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl); 788 InvalidDecl = true; 789 } 790 // Merge the decl with the existing one if appropriate. If the decl is 791 // in an outer scope, it isn't the same thing. 792 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) { 793 NewVD = MergeVarDecl(NewVD, PrevDecl); 794 if (NewVD == 0) return 0; 795 } 796 New = NewVD; 797 } 798 799 // If this has an identifier, add it to the scope stack. 800 if (II) 801 PushOnScopeChains(New, S); 802 // If any semantic error occurred, mark the decl as invalid. 803 if (D.getInvalidType() || InvalidDecl) 804 New->setInvalidDecl(); 805 806 return New; 807} 808 809bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) { 810 switch (Init->getStmtClass()) { 811 default: 812 Diag(Init->getExprLoc(), 813 diag::err_init_element_not_constant, Init->getSourceRange()); 814 return true; 815 case Expr::ParenExprClass: { 816 const ParenExpr* PE = cast<ParenExpr>(Init); 817 return CheckAddressConstantExpressionLValue(PE->getSubExpr()); 818 } 819 case Expr::CompoundLiteralExprClass: 820 return cast<CompoundLiteralExpr>(Init)->isFileScope(); 821 case Expr::DeclRefExprClass: { 822 const Decl *D = cast<DeclRefExpr>(Init)->getDecl(); 823 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 824 if (VD->hasGlobalStorage()) 825 return false; 826 Diag(Init->getExprLoc(), 827 diag::err_init_element_not_constant, Init->getSourceRange()); 828 return true; 829 } 830 if (isa<FunctionDecl>(D)) 831 return false; 832 Diag(Init->getExprLoc(), 833 diag::err_init_element_not_constant, Init->getSourceRange()); 834 return true; 835 } 836 case Expr::MemberExprClass: { 837 const MemberExpr *M = cast<MemberExpr>(Init); 838 if (M->isArrow()) 839 return CheckAddressConstantExpression(M->getBase()); 840 return CheckAddressConstantExpressionLValue(M->getBase()); 841 } 842 case Expr::ArraySubscriptExprClass: { 843 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)? 844 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init); 845 return CheckAddressConstantExpression(ASE->getBase()) || 846 CheckArithmeticConstantExpression(ASE->getIdx()); 847 } 848 case Expr::StringLiteralClass: 849 case Expr::PredefinedExprClass: 850 return false; 851 case Expr::UnaryOperatorClass: { 852 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 853 854 // C99 6.6p9 855 if (Exp->getOpcode() == UnaryOperator::Deref) 856 return CheckAddressConstantExpression(Exp->getSubExpr()); 857 858 Diag(Init->getExprLoc(), 859 diag::err_init_element_not_constant, Init->getSourceRange()); 860 return true; 861 } 862 } 863} 864 865bool Sema::CheckAddressConstantExpression(const Expr* Init) { 866 switch (Init->getStmtClass()) { 867 default: 868 Diag(Init->getExprLoc(), 869 diag::err_init_element_not_constant, Init->getSourceRange()); 870 return true; 871 case Expr::ParenExprClass: { 872 const ParenExpr* PE = cast<ParenExpr>(Init); 873 return CheckAddressConstantExpression(PE->getSubExpr()); 874 } 875 case Expr::StringLiteralClass: 876 case Expr::ObjCStringLiteralClass: 877 return false; 878 case Expr::CallExprClass: { 879 const CallExpr *CE = cast<CallExpr>(Init); 880 if (CE->isBuiltinConstantExpr()) 881 return false; 882 Diag(Init->getExprLoc(), 883 diag::err_init_element_not_constant, Init->getSourceRange()); 884 return true; 885 } 886 case Expr::UnaryOperatorClass: { 887 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 888 889 // C99 6.6p9 890 if (Exp->getOpcode() == UnaryOperator::AddrOf) 891 return CheckAddressConstantExpressionLValue(Exp->getSubExpr()); 892 893 if (Exp->getOpcode() == UnaryOperator::Extension) 894 return CheckAddressConstantExpression(Exp->getSubExpr()); 895 896 Diag(Init->getExprLoc(), 897 diag::err_init_element_not_constant, Init->getSourceRange()); 898 return true; 899 } 900 case Expr::BinaryOperatorClass: { 901 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"? 902 const BinaryOperator *Exp = cast<BinaryOperator>(Init); 903 904 Expr *PExp = Exp->getLHS(); 905 Expr *IExp = Exp->getRHS(); 906 if (IExp->getType()->isPointerType()) 907 std::swap(PExp, IExp); 908 909 // FIXME: Should we pedwarn if IExp isn't an integer constant expression? 910 return CheckAddressConstantExpression(PExp) || 911 CheckArithmeticConstantExpression(IExp); 912 } 913 case Expr::ImplicitCastExprClass: 914 case Expr::ExplicitCastExprClass: { 915 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr(); 916 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) { 917 // Check for implicit promotion 918 if (SubExpr->getType()->isFunctionType() || 919 SubExpr->getType()->isArrayType()) 920 return CheckAddressConstantExpressionLValue(SubExpr); 921 } 922 923 // Check for pointer->pointer cast 924 if (SubExpr->getType()->isPointerType()) 925 return CheckAddressConstantExpression(SubExpr); 926 927 if (SubExpr->getType()->isIntegralType()) { 928 // Check for the special-case of a pointer->int->pointer cast; 929 // this isn't standard, but some code requires it. See 930 // PR2720 for an example. 931 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) { 932 if (SubCast->getSubExpr()->getType()->isPointerType()) { 933 unsigned IntWidth = Context.getIntWidth(SubCast->getType()); 934 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy); 935 if (IntWidth >= PointerWidth) { 936 return CheckAddressConstantExpression(SubCast->getSubExpr()); 937 } 938 } 939 } 940 } 941 if (SubExpr->getType()->isArithmeticType()) { 942 return CheckArithmeticConstantExpression(SubExpr); 943 } 944 945 Diag(Init->getExprLoc(), 946 diag::err_init_element_not_constant, Init->getSourceRange()); 947 return true; 948 } 949 case Expr::ConditionalOperatorClass: { 950 // FIXME: Should we pedwarn here? 951 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init); 952 if (!Exp->getCond()->getType()->isArithmeticType()) { 953 Diag(Init->getExprLoc(), 954 diag::err_init_element_not_constant, Init->getSourceRange()); 955 return true; 956 } 957 if (CheckArithmeticConstantExpression(Exp->getCond())) 958 return true; 959 if (Exp->getLHS() && 960 CheckAddressConstantExpression(Exp->getLHS())) 961 return true; 962 return CheckAddressConstantExpression(Exp->getRHS()); 963 } 964 case Expr::AddrLabelExprClass: 965 return false; 966 } 967} 968 969static const Expr* FindExpressionBaseAddress(const Expr* E); 970 971static const Expr* FindExpressionBaseAddressLValue(const Expr* E) { 972 switch (E->getStmtClass()) { 973 default: 974 return E; 975 case Expr::ParenExprClass: { 976 const ParenExpr* PE = cast<ParenExpr>(E); 977 return FindExpressionBaseAddressLValue(PE->getSubExpr()); 978 } 979 case Expr::MemberExprClass: { 980 const MemberExpr *M = cast<MemberExpr>(E); 981 if (M->isArrow()) 982 return FindExpressionBaseAddress(M->getBase()); 983 return FindExpressionBaseAddressLValue(M->getBase()); 984 } 985 case Expr::ArraySubscriptExprClass: { 986 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E); 987 return FindExpressionBaseAddress(ASE->getBase()); 988 } 989 case Expr::UnaryOperatorClass: { 990 const UnaryOperator *Exp = cast<UnaryOperator>(E); 991 992 if (Exp->getOpcode() == UnaryOperator::Deref) 993 return FindExpressionBaseAddress(Exp->getSubExpr()); 994 995 return E; 996 } 997 } 998} 999 1000static const Expr* FindExpressionBaseAddress(const Expr* E) { 1001 switch (E->getStmtClass()) { 1002 default: 1003 return E; 1004 case Expr::ParenExprClass: { 1005 const ParenExpr* PE = cast<ParenExpr>(E); 1006 return FindExpressionBaseAddress(PE->getSubExpr()); 1007 } 1008 case Expr::UnaryOperatorClass: { 1009 const UnaryOperator *Exp = cast<UnaryOperator>(E); 1010 1011 // C99 6.6p9 1012 if (Exp->getOpcode() == UnaryOperator::AddrOf) 1013 return FindExpressionBaseAddressLValue(Exp->getSubExpr()); 1014 1015 if (Exp->getOpcode() == UnaryOperator::Extension) 1016 return FindExpressionBaseAddress(Exp->getSubExpr()); 1017 1018 return E; 1019 } 1020 case Expr::BinaryOperatorClass: { 1021 const BinaryOperator *Exp = cast<BinaryOperator>(E); 1022 1023 Expr *PExp = Exp->getLHS(); 1024 Expr *IExp = Exp->getRHS(); 1025 if (IExp->getType()->isPointerType()) 1026 std::swap(PExp, IExp); 1027 1028 return FindExpressionBaseAddress(PExp); 1029 } 1030 case Expr::ImplicitCastExprClass: { 1031 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr(); 1032 1033 // Check for implicit promotion 1034 if (SubExpr->getType()->isFunctionType() || 1035 SubExpr->getType()->isArrayType()) 1036 return FindExpressionBaseAddressLValue(SubExpr); 1037 1038 // Check for pointer->pointer cast 1039 if (SubExpr->getType()->isPointerType()) 1040 return FindExpressionBaseAddress(SubExpr); 1041 1042 // We assume that we have an arithmetic expression here; 1043 // if we don't, we'll figure it out later 1044 return 0; 1045 } 1046 case Expr::ExplicitCastExprClass: { 1047 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 1048 1049 // Check for pointer->pointer cast 1050 if (SubExpr->getType()->isPointerType()) 1051 return FindExpressionBaseAddress(SubExpr); 1052 1053 // We assume that we have an arithmetic expression here; 1054 // if we don't, we'll figure it out later 1055 return 0; 1056 } 1057 } 1058} 1059 1060bool Sema::CheckArithmeticConstantExpression(const Expr* Init) { 1061 switch (Init->getStmtClass()) { 1062 default: 1063 Diag(Init->getExprLoc(), 1064 diag::err_init_element_not_constant, Init->getSourceRange()); 1065 return true; 1066 case Expr::ParenExprClass: { 1067 const ParenExpr* PE = cast<ParenExpr>(Init); 1068 return CheckArithmeticConstantExpression(PE->getSubExpr()); 1069 } 1070 case Expr::FloatingLiteralClass: 1071 case Expr::IntegerLiteralClass: 1072 case Expr::CharacterLiteralClass: 1073 case Expr::ImaginaryLiteralClass: 1074 case Expr::TypesCompatibleExprClass: 1075 case Expr::CXXBoolLiteralExprClass: 1076 return false; 1077 case Expr::CallExprClass: { 1078 const CallExpr *CE = cast<CallExpr>(Init); 1079 if (CE->isBuiltinConstantExpr()) 1080 return false; 1081 Diag(Init->getExprLoc(), 1082 diag::err_init_element_not_constant, Init->getSourceRange()); 1083 return true; 1084 } 1085 case Expr::DeclRefExprClass: { 1086 const Decl *D = cast<DeclRefExpr>(Init)->getDecl(); 1087 if (isa<EnumConstantDecl>(D)) 1088 return false; 1089 Diag(Init->getExprLoc(), 1090 diag::err_init_element_not_constant, Init->getSourceRange()); 1091 return true; 1092 } 1093 case Expr::CompoundLiteralExprClass: 1094 // Allow "(vector type){2,4}"; normal C constraints don't allow this, 1095 // but vectors are allowed to be magic. 1096 if (Init->getType()->isVectorType()) 1097 return false; 1098 Diag(Init->getExprLoc(), 1099 diag::err_init_element_not_constant, Init->getSourceRange()); 1100 return true; 1101 case Expr::UnaryOperatorClass: { 1102 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1103 1104 switch (Exp->getOpcode()) { 1105 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 1106 // See C99 6.6p3. 1107 default: 1108 Diag(Init->getExprLoc(), 1109 diag::err_init_element_not_constant, Init->getSourceRange()); 1110 return true; 1111 case UnaryOperator::SizeOf: 1112 case UnaryOperator::AlignOf: 1113 case UnaryOperator::OffsetOf: 1114 // sizeof(E) is a constantexpr if and only if E is not evaluted. 1115 // See C99 6.5.3.4p2 and 6.6p3. 1116 if (Exp->getSubExpr()->getType()->isConstantSizeType()) 1117 return false; 1118 Diag(Init->getExprLoc(), 1119 diag::err_init_element_not_constant, Init->getSourceRange()); 1120 return true; 1121 case UnaryOperator::Extension: 1122 case UnaryOperator::LNot: 1123 case UnaryOperator::Plus: 1124 case UnaryOperator::Minus: 1125 case UnaryOperator::Not: 1126 return CheckArithmeticConstantExpression(Exp->getSubExpr()); 1127 } 1128 } 1129 case Expr::SizeOfAlignOfTypeExprClass: { 1130 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init); 1131 // Special check for void types, which are allowed as an extension 1132 if (Exp->getArgumentType()->isVoidType()) 1133 return false; 1134 // alignof always evaluates to a constant. 1135 // FIXME: is sizeof(int[3.0]) a constant expression? 1136 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) { 1137 Diag(Init->getExprLoc(), 1138 diag::err_init_element_not_constant, Init->getSourceRange()); 1139 return true; 1140 } 1141 return false; 1142 } 1143 case Expr::BinaryOperatorClass: { 1144 const BinaryOperator *Exp = cast<BinaryOperator>(Init); 1145 1146 if (Exp->getLHS()->getType()->isArithmeticType() && 1147 Exp->getRHS()->getType()->isArithmeticType()) { 1148 return CheckArithmeticConstantExpression(Exp->getLHS()) || 1149 CheckArithmeticConstantExpression(Exp->getRHS()); 1150 } 1151 1152 if (Exp->getLHS()->getType()->isPointerType() && 1153 Exp->getRHS()->getType()->isPointerType()) { 1154 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS()); 1155 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS()); 1156 1157 // Only allow a null (constant integer) base; we could 1158 // allow some additional cases if necessary, but this 1159 // is sufficient to cover offsetof-like constructs. 1160 if (!LHSBase && !RHSBase) { 1161 return CheckAddressConstantExpression(Exp->getLHS()) || 1162 CheckAddressConstantExpression(Exp->getRHS()); 1163 } 1164 } 1165 1166 Diag(Init->getExprLoc(), 1167 diag::err_init_element_not_constant, Init->getSourceRange()); 1168 return true; 1169 } 1170 case Expr::ImplicitCastExprClass: 1171 case Expr::ExplicitCastExprClass: { 1172 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr(); 1173 if (SubExpr->getType()->isArithmeticType()) 1174 return CheckArithmeticConstantExpression(SubExpr); 1175 1176 if (SubExpr->getType()->isPointerType()) { 1177 const Expr* Base = FindExpressionBaseAddress(SubExpr); 1178 // If the pointer has a null base, this is an offsetof-like construct 1179 if (!Base) 1180 return CheckAddressConstantExpression(SubExpr); 1181 } 1182 1183 Diag(Init->getExprLoc(), 1184 diag::err_init_element_not_constant, Init->getSourceRange()); 1185 return true; 1186 } 1187 case Expr::ConditionalOperatorClass: { 1188 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init); 1189 if (CheckArithmeticConstantExpression(Exp->getCond())) 1190 return true; 1191 if (Exp->getLHS() && 1192 CheckArithmeticConstantExpression(Exp->getLHS())) 1193 return true; 1194 return CheckArithmeticConstantExpression(Exp->getRHS()); 1195 } 1196 } 1197} 1198 1199bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 1200 Init = Init->IgnoreParens(); 1201 1202 // Look through CXXDefaultArgExprs; they have no meaning in this context. 1203 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init)) 1204 return CheckForConstantInitializer(DAE->getExpr(), DclT); 1205 1206 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init)) 1207 return CheckForConstantInitializer(e->getInitializer(), DclT); 1208 1209 if (Init->getType()->isReferenceType()) { 1210 // FIXME: Work out how the heck reference types work 1211 return false; 1212#if 0 1213 // A reference is constant if the address of the expression 1214 // is constant 1215 // We look through initlists here to simplify 1216 // CheckAddressConstantExpressionLValue. 1217 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) { 1218 assert(Exp->getNumInits() > 0 && 1219 "Refernce initializer cannot be empty"); 1220 Init = Exp->getInit(0); 1221 } 1222 return CheckAddressConstantExpressionLValue(Init); 1223#endif 1224 } 1225 1226 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) { 1227 unsigned numInits = Exp->getNumInits(); 1228 for (unsigned i = 0; i < numInits; i++) { 1229 // FIXME: Need to get the type of the declaration for C++, 1230 // because it could be a reference? 1231 if (CheckForConstantInitializer(Exp->getInit(i), 1232 Exp->getInit(i)->getType())) 1233 return true; 1234 } 1235 return false; 1236 } 1237 1238 if (Init->isNullPointerConstant(Context)) 1239 return false; 1240 if (Init->getType()->isArithmeticType()) { 1241 QualType InitTy = Context.getCanonicalType(Init->getType()) 1242 .getUnqualifiedType(); 1243 if (InitTy == Context.BoolTy) { 1244 // Special handling for pointers implicitly cast to bool; 1245 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level. 1246 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) { 1247 Expr* SubE = ICE->getSubExpr(); 1248 if (SubE->getType()->isPointerType() || 1249 SubE->getType()->isArrayType() || 1250 SubE->getType()->isFunctionType()) { 1251 return CheckAddressConstantExpression(Init); 1252 } 1253 } 1254 } else if (InitTy->isIntegralType()) { 1255 Expr* SubE = 0; 1256 if (CastExpr* CE = dyn_cast<CastExpr>(Init)) 1257 SubE = CE->getSubExpr(); 1258 // Special check for pointer cast to int; we allow as an extension 1259 // an address constant cast to an integer if the integer 1260 // is of an appropriate width (this sort of code is apparently used 1261 // in some places). 1262 // FIXME: Add pedwarn? 1263 // FIXME: Don't allow bitfields here! Need the FieldDecl for that. 1264 if (SubE && (SubE->getType()->isPointerType() || 1265 SubE->getType()->isArrayType() || 1266 SubE->getType()->isFunctionType())) { 1267 unsigned IntWidth = Context.getTypeSize(Init->getType()); 1268 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy); 1269 if (IntWidth >= PointerWidth) 1270 return CheckAddressConstantExpression(Init); 1271 } 1272 } 1273 1274 return CheckArithmeticConstantExpression(Init); 1275 } 1276 1277 if (Init->getType()->isPointerType()) 1278 return CheckAddressConstantExpression(Init); 1279 1280 // An array type at the top level that isn't an init-list must 1281 // be a string literal 1282 if (Init->getType()->isArrayType()) 1283 return false; 1284 1285 if (Init->getType()->isFunctionType()) 1286 return false; 1287 1288 Diag(Init->getExprLoc(), diag::err_init_element_not_constant, 1289 Init->getSourceRange()); 1290 return true; 1291} 1292 1293void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) { 1294 Decl *RealDecl = static_cast<Decl *>(dcl); 1295 Expr *Init = static_cast<Expr *>(init); 1296 assert(Init && "missing initializer"); 1297 1298 // If there is no declaration, there was an error parsing it. Just ignore 1299 // the initializer. 1300 if (RealDecl == 0) { 1301 delete Init; 1302 return; 1303 } 1304 1305 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 1306 if (!VDecl) { 1307 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(), 1308 diag::err_illegal_initializer); 1309 RealDecl->setInvalidDecl(); 1310 return; 1311 } 1312 // Get the decls type and save a reference for later, since 1313 // CheckInitializerTypes may change it. 1314 QualType DclT = VDecl->getType(), SavT = DclT; 1315 if (VDecl->isBlockVarDecl()) { 1316 VarDecl::StorageClass SC = VDecl->getStorageClass(); 1317 if (SC == VarDecl::Extern) { // C99 6.7.8p5 1318 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 1319 VDecl->setInvalidDecl(); 1320 } else if (!VDecl->isInvalidDecl()) { 1321 if (CheckInitializerTypes(Init, DclT)) 1322 VDecl->setInvalidDecl(); 1323 1324 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 1325 if (!getLangOptions().CPlusPlus) { 1326 if (SC == VarDecl::Static) // C99 6.7.8p4. 1327 CheckForConstantInitializer(Init, DclT); 1328 } 1329 } 1330 } else if (VDecl->isFileVarDecl()) { 1331 if (VDecl->getStorageClass() == VarDecl::Extern) 1332 Diag(VDecl->getLocation(), diag::warn_extern_init); 1333 if (!VDecl->isInvalidDecl()) 1334 if (CheckInitializerTypes(Init, DclT)) 1335 VDecl->setInvalidDecl(); 1336 1337 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 1338 if (!getLangOptions().CPlusPlus) { 1339 // C99 6.7.8p4. All file scoped initializers need to be constant. 1340 CheckForConstantInitializer(Init, DclT); 1341 } 1342 } 1343 // If the type changed, it means we had an incomplete type that was 1344 // completed by the initializer. For example: 1345 // int ary[] = { 1, 3, 5 }; 1346 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 1347 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 1348 VDecl->setType(DclT); 1349 Init->setType(DclT); 1350 } 1351 1352 // Attach the initializer to the decl. 1353 VDecl->setInit(Init); 1354 return; 1355} 1356 1357/// The declarators are chained together backwards, reverse the list. 1358Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) { 1359 // Often we have single declarators, handle them quickly. 1360 Decl *GroupDecl = static_cast<Decl*>(group); 1361 if (GroupDecl == 0) 1362 return 0; 1363 1364 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl); 1365 ScopedDecl *NewGroup = 0; 1366 if (Group->getNextDeclarator() == 0) 1367 NewGroup = Group; 1368 else { // reverse the list. 1369 while (Group) { 1370 ScopedDecl *Next = Group->getNextDeclarator(); 1371 Group->setNextDeclarator(NewGroup); 1372 NewGroup = Group; 1373 Group = Next; 1374 } 1375 } 1376 // Perform semantic analysis that depends on having fully processed both 1377 // the declarator and initializer. 1378 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) { 1379 VarDecl *IDecl = dyn_cast<VarDecl>(ID); 1380 if (!IDecl) 1381 continue; 1382 QualType T = IDecl->getType(); 1383 1384 // C99 6.7.5.2p2: If an identifier is declared to be an object with 1385 // static storage duration, it shall not have a variable length array. 1386 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) && 1387 IDecl->getStorageClass() == VarDecl::Static) { 1388 if (T->isVariableArrayType()) { 1389 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla); 1390 IDecl->setInvalidDecl(); 1391 } 1392 } 1393 // Block scope. C99 6.7p7: If an identifier for an object is declared with 1394 // no linkage (C99 6.2.2p6), the type for the object shall be complete... 1395 if (IDecl->isBlockVarDecl() && 1396 IDecl->getStorageClass() != VarDecl::Extern) { 1397 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) { 1398 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type, 1399 T.getAsString()); 1400 IDecl->setInvalidDecl(); 1401 } 1402 } 1403 // File scope. C99 6.9.2p2: A declaration of an identifier for and 1404 // object that has file scope without an initializer, and without a 1405 // storage-class specifier or with the storage-class specifier "static", 1406 // constitutes a tentative definition. Note: A tentative definition with 1407 // external linkage is valid (C99 6.2.2p5). 1408 if (isTentativeDefinition(IDecl)) { 1409 if (T->isIncompleteArrayType()) { 1410 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete 1411 // array to be completed. Don't issue a diagnostic. 1412 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) { 1413 // C99 6.9.2p3: If the declaration of an identifier for an object is 1414 // a tentative definition and has internal linkage (C99 6.2.2p3), the 1415 // declared type shall not be an incomplete type. 1416 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type, 1417 T.getAsString()); 1418 IDecl->setInvalidDecl(); 1419 } 1420 } 1421 if (IDecl->isFileVarDecl()) 1422 CheckForFileScopedRedefinitions(S, IDecl); 1423 } 1424 return NewGroup; 1425} 1426 1427/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 1428/// to introduce parameters into function prototype scope. 1429Sema::DeclTy * 1430Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 1431 const DeclSpec &DS = D.getDeclSpec(); 1432 1433 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 1434 VarDecl::StorageClass StorageClass = VarDecl::None; 1435 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 1436 StorageClass = VarDecl::Register; 1437 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 1438 Diag(DS.getStorageClassSpecLoc(), 1439 diag::err_invalid_storage_class_in_func_decl); 1440 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1441 } 1442 if (DS.isThreadSpecified()) { 1443 Diag(DS.getThreadSpecLoc(), 1444 diag::err_invalid_storage_class_in_func_decl); 1445 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1446 } 1447 1448 // Check that there are no default arguments inside the type of this 1449 // parameter (C++ only). 1450 if (getLangOptions().CPlusPlus) 1451 CheckExtraCXXDefaultArguments(D); 1452 1453 // In this context, we *do not* check D.getInvalidType(). If the declarator 1454 // type was invalid, GetTypeForDeclarator() still returns a "valid" type, 1455 // though it will not reflect the user specified type. 1456 QualType parmDeclType = GetTypeForDeclarator(D, S); 1457 1458 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type"); 1459 1460 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 1461 // Can this happen for params? We already checked that they don't conflict 1462 // among each other. Here they can only shadow globals, which is ok. 1463 IdentifierInfo *II = D.getIdentifier(); 1464 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) { 1465 if (S->isDeclScope(PrevDecl)) { 1466 Diag(D.getIdentifierLoc(), diag::err_param_redefinition, 1467 dyn_cast<NamedDecl>(PrevDecl)->getName()); 1468 1469 // Recover by removing the name 1470 II = 0; 1471 D.SetIdentifier(0, D.getIdentifierLoc()); 1472 } 1473 } 1474 1475 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]). 1476 // Doing the promotion here has a win and a loss. The win is the type for 1477 // both Decl's and DeclRefExpr's will match (a convenient invariant for the 1478 // code generator). The loss is the orginal type isn't preserved. For example: 1479 // 1480 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *" 1481 // int blockvardecl[5]; 1482 // sizeof(parmvardecl); // size == 4 1483 // sizeof(blockvardecl); // size == 20 1484 // } 1485 // 1486 // For expressions, all implicit conversions are captured using the 1487 // ImplicitCastExpr AST node (we have no such mechanism for Decl's). 1488 // 1489 // FIXME: If a source translation tool needs to see the original type, then 1490 // we need to consider storing both types (in ParmVarDecl)... 1491 // 1492 if (parmDeclType->isArrayType()) { 1493 // int x[restrict 4] -> int *restrict 1494 parmDeclType = Context.getArrayDecayedType(parmDeclType); 1495 } else if (parmDeclType->isFunctionType()) 1496 parmDeclType = Context.getPointerType(parmDeclType); 1497 1498 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, 1499 D.getIdentifierLoc(), II, 1500 parmDeclType, StorageClass, 1501 0, 0); 1502 1503 if (D.getInvalidType()) 1504 New->setInvalidDecl(); 1505 1506 if (II) 1507 PushOnScopeChains(New, S); 1508 1509 ProcessDeclAttributes(New, D); 1510 return New; 1511 1512} 1513 1514Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 1515 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 1516 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 1517 "Not a function declarator!"); 1518 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1519 1520 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 1521 // for a K&R function. 1522 if (!FTI.hasPrototype) { 1523 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 1524 if (FTI.ArgInfo[i].Param == 0) { 1525 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared, 1526 FTI.ArgInfo[i].Ident->getName()); 1527 // Implicitly declare the argument as type 'int' for lack of a better 1528 // type. 1529 DeclSpec DS; 1530 const char* PrevSpec; // unused 1531 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 1532 PrevSpec); 1533 Declarator ParamD(DS, Declarator::KNRTypeListContext); 1534 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 1535 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD); 1536 } 1537 } 1538 } else { 1539 // FIXME: Diagnose arguments without names in C. 1540 } 1541 1542 Scope *GlobalScope = FnBodyScope->getParent(); 1543 1544 // See if this is a redefinition. 1545 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary, 1546 GlobalScope); 1547 if (PrevDcl && isDeclInScope(PrevDcl, CurContext)) { 1548 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) { 1549 const FunctionDecl *Definition; 1550 if (FD->getBody(Definition)) { 1551 Diag(D.getIdentifierLoc(), diag::err_redefinition, 1552 D.getIdentifier()->getName()); 1553 Diag(Definition->getLocation(), diag::err_previous_definition); 1554 } 1555 } 1556 } 1557 1558 return ActOnStartOfFunctionDef(FnBodyScope, 1559 ActOnDeclarator(GlobalScope, D, 0)); 1560} 1561 1562Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) { 1563 Decl *decl = static_cast<Decl*>(D); 1564 FunctionDecl *FD = cast<FunctionDecl>(decl); 1565 PushDeclContext(FD); 1566 1567 // Check the validity of our function parameters 1568 CheckParmsForFunctionDef(FD); 1569 1570 // Introduce our parameters into the function scope 1571 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 1572 ParmVarDecl *Param = FD->getParamDecl(p); 1573 // If this has an identifier, add it to the scope stack. 1574 if (Param->getIdentifier()) 1575 PushOnScopeChains(Param, FnBodyScope); 1576 } 1577 1578 return FD; 1579} 1580 1581Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) { 1582 Decl *dcl = static_cast<Decl *>(D); 1583 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) { 1584 FD->setBody((Stmt*)Body); 1585 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 1586 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 1587 MD->setBody((Stmt*)Body); 1588 } else 1589 return 0; 1590 PopDeclContext(); 1591 // Verify and clean out per-function state. 1592 1593 // Check goto/label use. 1594 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 1595 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) { 1596 // Verify that we have no forward references left. If so, there was a goto 1597 // or address of a label taken, but no definition of it. Label fwd 1598 // definitions are indicated with a null substmt. 1599 if (I->second->getSubStmt() == 0) { 1600 LabelStmt *L = I->second; 1601 // Emit error. 1602 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName()); 1603 1604 // At this point, we have gotos that use the bogus label. Stitch it into 1605 // the function body so that they aren't leaked and that the AST is well 1606 // formed. 1607 if (Body) { 1608 L->setSubStmt(new NullStmt(L->getIdentLoc())); 1609 cast<CompoundStmt>((Stmt*)Body)->push_back(L); 1610 } else { 1611 // The whole function wasn't parsed correctly, just delete this. 1612 delete L; 1613 } 1614 } 1615 } 1616 LabelMap.clear(); 1617 1618 return D; 1619} 1620 1621/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 1622/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 1623ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 1624 IdentifierInfo &II, Scope *S) { 1625 // Extension in C99. Legal in C90, but warn about it. 1626 if (getLangOptions().C99) 1627 Diag(Loc, diag::ext_implicit_function_decl, II.getName()); 1628 else 1629 Diag(Loc, diag::warn_implicit_function_decl, II.getName()); 1630 1631 // FIXME: handle stuff like: 1632 // void foo() { extern float X(); } 1633 // void bar() { X(); } <-- implicit decl for X in another scope. 1634 1635 // Set a Declarator for the implicit definition: int foo(); 1636 const char *Dummy; 1637 DeclSpec DS; 1638 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy); 1639 Error = Error; // Silence warning. 1640 assert(!Error && "Error setting up implicit decl!"); 1641 Declarator D(DS, Declarator::BlockContext); 1642 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc)); 1643 D.SetIdentifier(&II, Loc); 1644 1645 // Insert this function into translation-unit scope. 1646 1647 DeclContext *PrevDC = CurContext; 1648 CurContext = Context.getTranslationUnitDecl(); 1649 1650 FunctionDecl *FD = 1651 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0))); 1652 FD->setImplicit(); 1653 1654 CurContext = PrevDC; 1655 1656 return FD; 1657} 1658 1659 1660TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 1661 ScopedDecl *LastDeclarator) { 1662 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 1663 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 1664 1665 // Scope manipulation handled by caller. 1666 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 1667 D.getIdentifierLoc(), 1668 D.getIdentifier(), 1669 T, LastDeclarator); 1670 if (D.getInvalidType()) 1671 NewTD->setInvalidDecl(); 1672 return NewTD; 1673} 1674 1675/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 1676/// former case, Name will be non-null. In the later case, Name will be null. 1677/// TagType indicates what kind of tag this is. TK indicates whether this is a 1678/// reference/declaration/definition of a tag. 1679Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK, 1680 SourceLocation KWLoc, IdentifierInfo *Name, 1681 SourceLocation NameLoc, AttributeList *Attr) { 1682 // If this is a use of an existing tag, it must have a name. 1683 assert((Name != 0 || TK == TK_Definition) && 1684 "Nameless record must be a definition!"); 1685 1686 TagDecl::TagKind Kind; 1687 switch (TagType) { 1688 default: assert(0 && "Unknown tag type!"); 1689 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 1690 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 1691 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 1692 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break; 1693 } 1694 1695 // Two code paths: a new one for structs/unions/classes where we create 1696 // separate decls for forward declarations, and an old (eventually to 1697 // be removed) code path for enums. 1698 if (Kind != TagDecl::TK_enum) 1699 return ActOnTagStruct(S, Kind, TK, KWLoc, Name, NameLoc, Attr); 1700 1701 // If this is a named struct, check to see if there was a previous forward 1702 // declaration or definition. 1703 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up. 1704 ScopedDecl *PrevDecl = 1705 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S)); 1706 1707 if (PrevDecl) { 1708 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) && 1709 "unexpected Decl type"); 1710 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 1711 // If this is a use of a previous tag, or if the tag is already declared 1712 // in the same scope (so that the definition/declaration completes or 1713 // rementions the tag), reuse the decl. 1714 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) { 1715 // Make sure that this wasn't declared as an enum and now used as a 1716 // struct or something similar. 1717 if (PrevTagDecl->getTagKind() != Kind) { 1718 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName()); 1719 Diag(PrevDecl->getLocation(), diag::err_previous_use); 1720 // Recover by making this an anonymous redefinition. 1721 Name = 0; 1722 PrevDecl = 0; 1723 } else { 1724 // If this is a use or a forward declaration, we're good. 1725 if (TK != TK_Definition) 1726 return PrevDecl; 1727 1728 // Diagnose attempts to redefine a tag. 1729 if (PrevTagDecl->isDefinition()) { 1730 Diag(NameLoc, diag::err_redefinition, Name->getName()); 1731 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 1732 // If this is a redefinition, recover by making this struct be 1733 // anonymous, which will make any later references get the previous 1734 // definition. 1735 Name = 0; 1736 } else { 1737 // Okay, this is definition of a previously declared or referenced 1738 // tag. Move the location of the decl to be the definition site. 1739 PrevDecl->setLocation(NameLoc); 1740 return PrevDecl; 1741 } 1742 } 1743 } 1744 // If we get here, this is a definition of a new struct type in a nested 1745 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new 1746 // type. 1747 } else { 1748 // PrevDecl is a namespace. 1749 if (isDeclInScope(PrevDecl, CurContext, S)) { 1750 // The tag name clashes with a namespace name, issue an error and 1751 // recover by making this tag be anonymous. 1752 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName()); 1753 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 1754 Name = 0; 1755 } 1756 } 1757 } 1758 1759 // If there is an identifier, use the location of the identifier as the 1760 // location of the decl, otherwise use the location of the struct/union 1761 // keyword. 1762 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 1763 1764 // Otherwise, if this is the first time we've seen this tag, create the decl. 1765 TagDecl *New; 1766 if (Kind == TagDecl::TK_enum) { 1767 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 1768 // enum X { A, B, C } D; D should chain to X. 1769 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0); 1770 // If this is an undefined enum, warn. 1771 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum); 1772 } else { 1773 // struct/union/class 1774 1775 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 1776 // struct X { int A; } D; D should chain to X. 1777 if (getLangOptions().CPlusPlus) 1778 // FIXME: Look for a way to use RecordDecl for simple structs. 1779 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name); 1780 else 1781 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name); 1782 } 1783 1784 // If this has an identifier, add it to the scope stack. 1785 if (Name) { 1786 // The scope passed in may not be a decl scope. Zip up the scope tree until 1787 // we find one that is. 1788 while ((S->getFlags() & Scope::DeclScope) == 0) 1789 S = S->getParent(); 1790 1791 // Add it to the decl chain. 1792 PushOnScopeChains(New, S); 1793 } 1794 1795 if (Attr) 1796 ProcessDeclAttributeList(New, Attr); 1797 return New; 1798} 1799 1800/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike 1801/// the logic for enums, we create separate decls for forward declarations. 1802/// This is called by ActOnTag, but eventually will replace its logic. 1803Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK, 1804 SourceLocation KWLoc, IdentifierInfo *Name, 1805 SourceLocation NameLoc, AttributeList *Attr) { 1806 1807 // If this is a named struct, check to see if there was a previous forward 1808 // declaration or definition. 1809 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up. 1810 ScopedDecl *PrevDecl = 1811 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S)); 1812 1813 if (PrevDecl) { 1814 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) && 1815 "unexpected Decl type"); 1816 1817 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 1818 // If this is a use of a previous tag, or if the tag is already declared 1819 // in the same scope (so that the definition/declaration completes or 1820 // rementions the tag), reuse the decl. 1821 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) { 1822 // Make sure that this wasn't declared as an enum and now used as a 1823 // struct or something similar. 1824 if (PrevTagDecl->getTagKind() != Kind) { 1825 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName()); 1826 Diag(PrevDecl->getLocation(), diag::err_previous_use); 1827 // Recover by making this an anonymous redefinition. 1828 Name = 0; 1829 PrevDecl = 0; 1830 } else { 1831 // If this is a use, return the original decl. 1832 1833 // FIXME: In the future, return a variant or some other clue 1834 // for the consumer of this Decl to know it doesn't own it. 1835 // For our current ASTs this shouldn't be a problem, but will 1836 // need to be changed with DeclGroups. 1837 if (TK == TK_Reference) 1838 return PrevDecl; 1839 1840 // The new decl is a definition? 1841 if (TK == TK_Definition) { 1842 // Diagnose attempts to redefine a tag. 1843 if (RecordDecl* DefRecord = 1844 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) { 1845 Diag(NameLoc, diag::err_redefinition, Name->getName()); 1846 Diag(DefRecord->getLocation(), diag::err_previous_definition); 1847 // If this is a redefinition, recover by making this struct be 1848 // anonymous, which will make any later references get the previous 1849 // definition. 1850 Name = 0; 1851 PrevDecl = 0; 1852 } 1853 // Okay, this is definition of a previously declared or referenced 1854 // tag. We're going to create a new Decl. 1855 } 1856 } 1857 // If we get here we have (another) forward declaration. Just create 1858 // a new decl. 1859 } 1860 else { 1861 // If we get here, this is a definition of a new struct type in a nested 1862 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 1863 // new decl/type. We set PrevDecl to NULL so that the Records 1864 // have distinct types. 1865 PrevDecl = 0; 1866 } 1867 } else { 1868 // PrevDecl is a namespace. 1869 if (isDeclInScope(PrevDecl, CurContext, S)) { 1870 // The tag name clashes with a namespace name, issue an error and 1871 // recover by making this tag be anonymous. 1872 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName()); 1873 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 1874 Name = 0; 1875 } 1876 } 1877 } 1878 1879 // If there is an identifier, use the location of the identifier as the 1880 // location of the decl, otherwise use the location of the struct/union 1881 // keyword. 1882 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 1883 1884 // Otherwise, if this is the first time we've seen this tag, create the decl. 1885 TagDecl *New; 1886 1887 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 1888 // struct X { int A; } D; D should chain to X. 1889 if (getLangOptions().CPlusPlus) 1890 // FIXME: Look for a way to use RecordDecl for simple structs. 1891 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name, 1892 dyn_cast_or_null<CXXRecordDecl>(PrevDecl)); 1893 else 1894 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 1895 dyn_cast_or_null<RecordDecl>(PrevDecl)); 1896 1897 // If this has an identifier, add it to the scope stack. 1898 if ((TK == TK_Definition || !PrevDecl) && Name) { 1899 // The scope passed in may not be a decl scope. Zip up the scope tree until 1900 // we find one that is. 1901 while ((S->getFlags() & Scope::DeclScope) == 0) 1902 S = S->getParent(); 1903 1904 // Add it to the decl chain. 1905 PushOnScopeChains(New, S); 1906 } 1907 1908 if (Attr) 1909 ProcessDeclAttributeList(New, Attr); 1910 1911 return New; 1912} 1913 1914 1915/// Collect the instance variables declared in an Objective-C object. Used in 1916/// the creation of structures from objects using the @defs directive. 1917static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx, 1918 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) { 1919 if (Class->getSuperClass()) 1920 CollectIvars(Class->getSuperClass(), Ctx, ivars); 1921 1922 // For each ivar, create a fresh ObjCAtDefsFieldDecl. 1923 for (ObjCInterfaceDecl::ivar_iterator 1924 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) { 1925 1926 ObjCIvarDecl* ID = *I; 1927 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(), 1928 ID->getIdentifier(), 1929 ID->getType(), 1930 ID->getBitWidth())); 1931 } 1932} 1933 1934/// Called whenever @defs(ClassName) is encountered in the source. Inserts the 1935/// instance variables of ClassName into Decls. 1936void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart, 1937 IdentifierInfo *ClassName, 1938 llvm::SmallVectorImpl<DeclTy*> &Decls) { 1939 // Check that ClassName is a valid class 1940 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName); 1941 if (!Class) { 1942 Diag(DeclStart, diag::err_undef_interface, ClassName->getName()); 1943 return; 1944 } 1945 // Collect the instance variables 1946 CollectIvars(Class, Context, Decls); 1947} 1948 1949QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) { 1950 // This method tries to turn a variable array into a constant 1951 // array even when the size isn't an ICE. This is necessary 1952 // for compatibility with code that depends on gcc's buggy 1953 // constant expression folding, like struct {char x[(int)(char*)2];} 1954 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) { 1955 APValue Result; 1956 if (VLATy->getSizeExpr() && 1957 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) { 1958 llvm::APSInt &Res = Result.getInt(); 1959 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) 1960 return Context.getConstantArrayType(VLATy->getElementType(), 1961 Res, ArrayType::Normal, 0); 1962 } 1963 } 1964 return QualType(); 1965} 1966 1967/// ActOnField - Each field of a struct/union/class is passed into this in order 1968/// to create a FieldDecl object for it. 1969Sema::DeclTy *Sema::ActOnField(Scope *S, 1970 SourceLocation DeclStart, 1971 Declarator &D, ExprTy *BitfieldWidth) { 1972 IdentifierInfo *II = D.getIdentifier(); 1973 Expr *BitWidth = (Expr*)BitfieldWidth; 1974 SourceLocation Loc = DeclStart; 1975 if (II) Loc = D.getIdentifierLoc(); 1976 1977 // FIXME: Unnamed fields can be handled in various different ways, for 1978 // example, unnamed unions inject all members into the struct namespace! 1979 1980 if (BitWidth) { 1981 // TODO: Validate. 1982 //printf("WARNING: BITFIELDS IGNORED!\n"); 1983 1984 // 6.7.2.1p3 1985 // 6.7.2.1p4 1986 1987 } else { 1988 // Not a bitfield. 1989 1990 // validate II. 1991 1992 } 1993 1994 QualType T = GetTypeForDeclarator(D, S); 1995 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 1996 bool InvalidDecl = false; 1997 1998 // C99 6.7.2.1p8: A member of a structure or union may have any type other 1999 // than a variably modified type. 2000 if (T->isVariablyModifiedType()) { 2001 QualType FixedTy = TryFixInvalidVariablyModifiedType(T); 2002 if (!FixedTy.isNull()) { 2003 Diag(Loc, diag::warn_illegal_constant_array_size, Loc); 2004 T = FixedTy; 2005 } else { 2006 // FIXME: This diagnostic needs work 2007 Diag(Loc, diag::err_typecheck_illegal_vla, Loc); 2008 InvalidDecl = true; 2009 } 2010 } 2011 // FIXME: Chain fielddecls together. 2012 FieldDecl *NewFD; 2013 2014 if (getLangOptions().CPlusPlus) { 2015 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs. 2016 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext), 2017 Loc, II, T, BitWidth); 2018 if (II) 2019 PushOnScopeChains(NewFD, S); 2020 } 2021 else 2022 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth); 2023 2024 ProcessDeclAttributes(NewFD, D); 2025 2026 if (D.getInvalidType() || InvalidDecl) 2027 NewFD->setInvalidDecl(); 2028 return NewFD; 2029} 2030 2031/// TranslateIvarVisibility - Translate visibility from a token ID to an 2032/// AST enum value. 2033static ObjCIvarDecl::AccessControl 2034TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 2035 switch (ivarVisibility) { 2036 case tok::objc_private: return ObjCIvarDecl::Private; 2037 case tok::objc_public: return ObjCIvarDecl::Public; 2038 case tok::objc_protected: return ObjCIvarDecl::Protected; 2039 case tok::objc_package: return ObjCIvarDecl::Package; 2040 default: assert(false && "Unknown visitibility kind"); 2041 } 2042} 2043 2044/// ActOnIvar - Each ivar field of an objective-c class is passed into this 2045/// in order to create an IvarDecl object for it. 2046Sema::DeclTy *Sema::ActOnIvar(Scope *S, 2047 SourceLocation DeclStart, 2048 Declarator &D, ExprTy *BitfieldWidth, 2049 tok::ObjCKeywordKind Visibility) { 2050 IdentifierInfo *II = D.getIdentifier(); 2051 Expr *BitWidth = (Expr*)BitfieldWidth; 2052 SourceLocation Loc = DeclStart; 2053 if (II) Loc = D.getIdentifierLoc(); 2054 2055 // FIXME: Unnamed fields can be handled in various different ways, for 2056 // example, unnamed unions inject all members into the struct namespace! 2057 2058 2059 if (BitWidth) { 2060 // TODO: Validate. 2061 //printf("WARNING: BITFIELDS IGNORED!\n"); 2062 2063 // 6.7.2.1p3 2064 // 6.7.2.1p4 2065 2066 } else { 2067 // Not a bitfield. 2068 2069 // validate II. 2070 2071 } 2072 2073 QualType T = GetTypeForDeclarator(D, S); 2074 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 2075 bool InvalidDecl = false; 2076 2077 // C99 6.7.2.1p8: A member of a structure or union may have any type other 2078 // than a variably modified type. 2079 if (T->isVariablyModifiedType()) { 2080 // FIXME: This diagnostic needs work 2081 Diag(Loc, diag::err_typecheck_illegal_vla, Loc); 2082 InvalidDecl = true; 2083 } 2084 2085 // Get the visibility (access control) for this ivar. 2086 ObjCIvarDecl::AccessControl ac = 2087 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 2088 : ObjCIvarDecl::None; 2089 2090 // Construct the decl. 2091 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac, 2092 (Expr *)BitfieldWidth); 2093 2094 // Process attributes attached to the ivar. 2095 ProcessDeclAttributes(NewID, D); 2096 2097 if (D.getInvalidType() || InvalidDecl) 2098 NewID->setInvalidDecl(); 2099 2100 return NewID; 2101} 2102 2103void Sema::ActOnFields(Scope* S, 2104 SourceLocation RecLoc, DeclTy *RecDecl, 2105 DeclTy **Fields, unsigned NumFields, 2106 SourceLocation LBrac, SourceLocation RBrac) { 2107 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl); 2108 assert(EnclosingDecl && "missing record or interface decl"); 2109 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 2110 2111 if (Record) 2112 if (RecordDecl* DefRecord = Record->getDefinition(Context)) { 2113 // Diagnose code like: 2114 // struct S { struct S {} X; }; 2115 // We discover this when we complete the outer S. Reject and ignore the 2116 // outer S. 2117 Diag(DefRecord->getLocation(), diag::err_nested_redefinition, 2118 DefRecord->getKindName()); 2119 Diag(RecLoc, diag::err_previous_definition); 2120 Record->setInvalidDecl(); 2121 return; 2122 } 2123 2124 // Verify that all the fields are okay. 2125 unsigned NumNamedMembers = 0; 2126 llvm::SmallVector<FieldDecl*, 32> RecFields; 2127 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs; 2128 2129 for (unsigned i = 0; i != NumFields; ++i) { 2130 2131 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i])); 2132 assert(FD && "missing field decl"); 2133 2134 // Remember all fields. 2135 RecFields.push_back(FD); 2136 2137 // Get the type for the field. 2138 Type *FDTy = FD->getType().getTypePtr(); 2139 2140 // C99 6.7.2.1p2 - A field may not be a function type. 2141 if (FDTy->isFunctionType()) { 2142 Diag(FD->getLocation(), diag::err_field_declared_as_function, 2143 FD->getName()); 2144 FD->setInvalidDecl(); 2145 EnclosingDecl->setInvalidDecl(); 2146 continue; 2147 } 2148 // C99 6.7.2.1p2 - A field may not be an incomplete type except... 2149 if (FDTy->isIncompleteType()) { 2150 if (!Record) { // Incomplete ivar type is always an error. 2151 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName()); 2152 FD->setInvalidDecl(); 2153 EnclosingDecl->setInvalidDecl(); 2154 continue; 2155 } 2156 if (i != NumFields-1 || // ... that the last member ... 2157 !Record->isStruct() || // ... of a structure ... 2158 !FDTy->isArrayType()) { //... may have incomplete array type. 2159 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName()); 2160 FD->setInvalidDecl(); 2161 EnclosingDecl->setInvalidDecl(); 2162 continue; 2163 } 2164 if (NumNamedMembers < 1) { //... must have more than named member ... 2165 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct, 2166 FD->getName()); 2167 FD->setInvalidDecl(); 2168 EnclosingDecl->setInvalidDecl(); 2169 continue; 2170 } 2171 // Okay, we have a legal flexible array member at the end of the struct. 2172 if (Record) 2173 Record->setHasFlexibleArrayMember(true); 2174 } 2175 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the 2176 /// field of another structure or the element of an array. 2177 if (const RecordType *FDTTy = FDTy->getAsRecordType()) { 2178 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 2179 // If this is a member of a union, then entire union becomes "flexible". 2180 if (Record && Record->isUnion()) { 2181 Record->setHasFlexibleArrayMember(true); 2182 } else { 2183 // If this is a struct/class and this is not the last element, reject 2184 // it. Note that GCC supports variable sized arrays in the middle of 2185 // structures. 2186 if (i != NumFields-1) { 2187 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct, 2188 FD->getName()); 2189 FD->setInvalidDecl(); 2190 EnclosingDecl->setInvalidDecl(); 2191 continue; 2192 } 2193 // We support flexible arrays at the end of structs in other structs 2194 // as an extension. 2195 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct, 2196 FD->getName()); 2197 if (Record) 2198 Record->setHasFlexibleArrayMember(true); 2199 } 2200 } 2201 } 2202 /// A field cannot be an Objective-c object 2203 if (FDTy->isObjCInterfaceType()) { 2204 Diag(FD->getLocation(), diag::err_statically_allocated_object, 2205 FD->getName()); 2206 FD->setInvalidDecl(); 2207 EnclosingDecl->setInvalidDecl(); 2208 continue; 2209 } 2210 // Keep track of the number of named members. 2211 if (IdentifierInfo *II = FD->getIdentifier()) { 2212 // Detect duplicate member names. 2213 if (!FieldIDs.insert(II)) { 2214 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName()); 2215 // Find the previous decl. 2216 SourceLocation PrevLoc; 2217 for (unsigned i = 0, e = RecFields.size(); ; ++i) { 2218 assert(i != e && "Didn't find previous def!"); 2219 if (RecFields[i]->getIdentifier() == II) { 2220 PrevLoc = RecFields[i]->getLocation(); 2221 break; 2222 } 2223 } 2224 Diag(PrevLoc, diag::err_previous_definition); 2225 FD->setInvalidDecl(); 2226 EnclosingDecl->setInvalidDecl(); 2227 continue; 2228 } 2229 ++NumNamedMembers; 2230 } 2231 } 2232 2233 // Okay, we successfully defined 'Record'. 2234 if (Record) { 2235 Record->defineBody(Context, &RecFields[0], RecFields.size()); 2236 // If this is a C++ record, HandleTagDeclDefinition will be invoked in 2237 // Sema::ActOnFinishCXXClassDef. 2238 if (!isa<CXXRecordDecl>(Record)) 2239 Consumer.HandleTagDeclDefinition(Record); 2240 } else { 2241 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]); 2242 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) 2243 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac); 2244 else if (ObjCImplementationDecl *IMPDecl = 2245 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 2246 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 2247 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size()); 2248 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 2249 } 2250 } 2251} 2252 2253Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl, 2254 DeclTy *lastEnumConst, 2255 SourceLocation IdLoc, IdentifierInfo *Id, 2256 SourceLocation EqualLoc, ExprTy *val) { 2257 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl)); 2258 EnumConstantDecl *LastEnumConst = 2259 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst)); 2260 Expr *Val = static_cast<Expr*>(val); 2261 2262 // The scope passed in may not be a decl scope. Zip up the scope tree until 2263 // we find one that is. 2264 while ((S->getFlags() & Scope::DeclScope) == 0) 2265 S = S->getParent(); 2266 2267 // Verify that there isn't already something declared with this name in this 2268 // scope. 2269 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) { 2270 // When in C++, we may get a TagDecl with the same name; in this case the 2271 // enum constant will 'hide' the tag. 2272 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 2273 "Received TagDecl when not in C++!"); 2274 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 2275 if (isa<EnumConstantDecl>(PrevDecl)) 2276 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName()); 2277 else 2278 Diag(IdLoc, diag::err_redefinition, Id->getName()); 2279 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 2280 delete Val; 2281 return 0; 2282 } 2283 } 2284 2285 llvm::APSInt EnumVal(32); 2286 QualType EltTy; 2287 if (Val) { 2288 // Make sure to promote the operand type to int. 2289 UsualUnaryConversions(Val); 2290 2291 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 2292 SourceLocation ExpLoc; 2293 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) { 2294 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr, 2295 Id->getName()); 2296 delete Val; 2297 Val = 0; // Just forget about it. 2298 } else { 2299 EltTy = Val->getType(); 2300 } 2301 } 2302 2303 if (!Val) { 2304 if (LastEnumConst) { 2305 // Assign the last value + 1. 2306 EnumVal = LastEnumConst->getInitVal(); 2307 ++EnumVal; 2308 2309 // Check for overflow on increment. 2310 if (EnumVal < LastEnumConst->getInitVal()) 2311 Diag(IdLoc, diag::warn_enum_value_overflow); 2312 2313 EltTy = LastEnumConst->getType(); 2314 } else { 2315 // First value, set to zero. 2316 EltTy = Context.IntTy; 2317 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy))); 2318 } 2319 } 2320 2321 EnumConstantDecl *New = 2322 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy, 2323 Val, EnumVal, 2324 LastEnumConst); 2325 2326 // Register this decl in the current scope stack. 2327 PushOnScopeChains(New, S); 2328 return New; 2329} 2330 2331// FIXME: For consistency with ActOnFields(), we should have the parser 2332// pass in the source location for the left/right braces. 2333void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX, 2334 DeclTy **Elements, unsigned NumElements) { 2335 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX)); 2336 2337 if (Enum && Enum->isDefinition()) { 2338 // Diagnose code like: 2339 // enum e0 { 2340 // E0 = sizeof(enum e0 { E1 }) 2341 // }; 2342 Diag(Enum->getLocation(), diag::err_nested_redefinition, 2343 Enum->getName()); 2344 Diag(EnumLoc, diag::err_previous_definition); 2345 Enum->setInvalidDecl(); 2346 return; 2347 } 2348 // TODO: If the result value doesn't fit in an int, it must be a long or long 2349 // long value. ISO C does not support this, but GCC does as an extension, 2350 // emit a warning. 2351 unsigned IntWidth = Context.Target.getIntWidth(); 2352 2353 // Verify that all the values are okay, compute the size of the values, and 2354 // reverse the list. 2355 unsigned NumNegativeBits = 0; 2356 unsigned NumPositiveBits = 0; 2357 2358 // Keep track of whether all elements have type int. 2359 bool AllElementsInt = true; 2360 2361 EnumConstantDecl *EltList = 0; 2362 for (unsigned i = 0; i != NumElements; ++i) { 2363 EnumConstantDecl *ECD = 2364 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 2365 if (!ECD) continue; // Already issued a diagnostic. 2366 2367 // If the enum value doesn't fit in an int, emit an extension warning. 2368 const llvm::APSInt &InitVal = ECD->getInitVal(); 2369 assert(InitVal.getBitWidth() >= IntWidth && 2370 "Should have promoted value to int"); 2371 if (InitVal.getBitWidth() > IntWidth) { 2372 llvm::APSInt V(InitVal); 2373 V.trunc(IntWidth); 2374 V.extend(InitVal.getBitWidth()); 2375 if (V != InitVal) 2376 Diag(ECD->getLocation(), diag::ext_enum_value_not_int, 2377 InitVal.toString(10)); 2378 } 2379 2380 // Keep track of the size of positive and negative values. 2381 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 2382 NumPositiveBits = std::max(NumPositiveBits, 2383 (unsigned)InitVal.getActiveBits()); 2384 else 2385 NumNegativeBits = std::max(NumNegativeBits, 2386 (unsigned)InitVal.getMinSignedBits()); 2387 2388 // Keep track of whether every enum element has type int (very commmon). 2389 if (AllElementsInt) 2390 AllElementsInt = ECD->getType() == Context.IntTy; 2391 2392 ECD->setNextDeclarator(EltList); 2393 EltList = ECD; 2394 } 2395 2396 // Figure out the type that should be used for this enum. 2397 // FIXME: Support attribute(packed) on enums and -fshort-enums. 2398 QualType BestType; 2399 unsigned BestWidth; 2400 2401 if (NumNegativeBits) { 2402 // If there is a negative value, figure out the smallest integer type (of 2403 // int/long/longlong) that fits. 2404 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 2405 BestType = Context.IntTy; 2406 BestWidth = IntWidth; 2407 } else { 2408 BestWidth = Context.Target.getLongWidth(); 2409 2410 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) 2411 BestType = Context.LongTy; 2412 else { 2413 BestWidth = Context.Target.getLongLongWidth(); 2414 2415 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 2416 Diag(Enum->getLocation(), diag::warn_enum_too_large); 2417 BestType = Context.LongLongTy; 2418 } 2419 } 2420 } else { 2421 // If there is no negative value, figure out which of uint, ulong, ulonglong 2422 // fits. 2423 if (NumPositiveBits <= IntWidth) { 2424 BestType = Context.UnsignedIntTy; 2425 BestWidth = IntWidth; 2426 } else if (NumPositiveBits <= 2427 (BestWidth = Context.Target.getLongWidth())) { 2428 BestType = Context.UnsignedLongTy; 2429 } else { 2430 BestWidth = Context.Target.getLongLongWidth(); 2431 assert(NumPositiveBits <= BestWidth && 2432 "How could an initializer get larger than ULL?"); 2433 BestType = Context.UnsignedLongLongTy; 2434 } 2435 } 2436 2437 // Loop over all of the enumerator constants, changing their types to match 2438 // the type of the enum if needed. 2439 for (unsigned i = 0; i != NumElements; ++i) { 2440 EnumConstantDecl *ECD = 2441 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 2442 if (!ECD) continue; // Already issued a diagnostic. 2443 2444 // Standard C says the enumerators have int type, but we allow, as an 2445 // extension, the enumerators to be larger than int size. If each 2446 // enumerator value fits in an int, type it as an int, otherwise type it the 2447 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 2448 // that X has type 'int', not 'unsigned'. 2449 if (ECD->getType() == Context.IntTy) { 2450 // Make sure the init value is signed. 2451 llvm::APSInt IV = ECD->getInitVal(); 2452 IV.setIsSigned(true); 2453 ECD->setInitVal(IV); 2454 continue; // Already int type. 2455 } 2456 2457 // Determine whether the value fits into an int. 2458 llvm::APSInt InitVal = ECD->getInitVal(); 2459 bool FitsInInt; 2460 if (InitVal.isUnsigned() || !InitVal.isNegative()) 2461 FitsInInt = InitVal.getActiveBits() < IntWidth; 2462 else 2463 FitsInInt = InitVal.getMinSignedBits() <= IntWidth; 2464 2465 // If it fits into an integer type, force it. Otherwise force it to match 2466 // the enum decl type. 2467 QualType NewTy; 2468 unsigned NewWidth; 2469 bool NewSign; 2470 if (FitsInInt) { 2471 NewTy = Context.IntTy; 2472 NewWidth = IntWidth; 2473 NewSign = true; 2474 } else if (ECD->getType() == BestType) { 2475 // Already the right type! 2476 continue; 2477 } else { 2478 NewTy = BestType; 2479 NewWidth = BestWidth; 2480 NewSign = BestType->isSignedIntegerType(); 2481 } 2482 2483 // Adjust the APSInt value. 2484 InitVal.extOrTrunc(NewWidth); 2485 InitVal.setIsSigned(NewSign); 2486 ECD->setInitVal(InitVal); 2487 2488 // Adjust the Expr initializer and type. 2489 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr())); 2490 ECD->setType(NewTy); 2491 } 2492 2493 Enum->defineElements(EltList, BestType); 2494 Consumer.HandleTagDeclDefinition(Enum); 2495} 2496 2497Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, 2498 ExprTy *expr) { 2499 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr); 2500 2501 return FileScopeAsmDecl::Create(Context, Loc, AsmString); 2502} 2503 2504Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc, 2505 SourceLocation LBrace, 2506 SourceLocation RBrace, 2507 const char *Lang, 2508 unsigned StrSize, 2509 DeclTy *D) { 2510 LinkageSpecDecl::LanguageIDs Language; 2511 Decl *dcl = static_cast<Decl *>(D); 2512 if (strncmp(Lang, "\"C\"", StrSize) == 0) 2513 Language = LinkageSpecDecl::lang_c; 2514 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 2515 Language = LinkageSpecDecl::lang_cxx; 2516 else { 2517 Diag(Loc, diag::err_bad_language); 2518 return 0; 2519 } 2520 2521 // FIXME: Add all the various semantics of linkage specifications 2522 return LinkageSpecDecl::Create(Context, Loc, Language, dcl); 2523} 2524