Sema.cpp revision aa93a875605536d72a10359a0098396192b7d4ec
1//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===// 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 the actions class which performs semantic analysis and 11// builds an AST out of a parse stream. 12// 13//===----------------------------------------------------------------------===// 14 15#include "clang/Sema/SemaInternal.h" 16#include "clang/Sema/DelayedDiagnostic.h" 17#include "TargetAttributesSema.h" 18#include "llvm/ADT/DenseMap.h" 19#include "llvm/ADT/SmallSet.h" 20#include "llvm/ADT/APFloat.h" 21#include "clang/Sema/CXXFieldCollector.h" 22#include "clang/Sema/TemplateDeduction.h" 23#include "clang/Sema/ExternalSemaSource.h" 24#include "clang/Sema/ObjCMethodList.h" 25#include "clang/Sema/PrettyDeclStackTrace.h" 26#include "clang/Sema/Scope.h" 27#include "clang/Sema/ScopeInfo.h" 28#include "clang/Sema/SemaConsumer.h" 29#include "clang/AST/ASTContext.h" 30#include "clang/AST/ASTDiagnostic.h" 31#include "clang/AST/DeclCXX.h" 32#include "clang/AST/DeclObjC.h" 33#include "clang/AST/Expr.h" 34#include "clang/AST/ExprCXX.h" 35#include "clang/AST/StmtCXX.h" 36#include "clang/Lex/Preprocessor.h" 37#include "clang/Basic/FileManager.h" 38#include "clang/Basic/PartialDiagnostic.h" 39#include "clang/Basic/TargetInfo.h" 40using namespace clang; 41using namespace sema; 42 43FunctionScopeInfo::~FunctionScopeInfo() { } 44 45void FunctionScopeInfo::Clear() { 46 HasBranchProtectedScope = false; 47 HasBranchIntoScope = false; 48 HasIndirectGoto = false; 49 50 SwitchStack.clear(); 51 Returns.clear(); 52 ErrorTrap.reset(); 53 PossiblyUnreachableDiags.clear(); 54} 55 56BlockScopeInfo::~BlockScopeInfo() { } 57 58PrintingPolicy Sema::getPrintingPolicy() const { 59 PrintingPolicy Policy = Context.getPrintingPolicy(); 60 Policy.Bool = getLangOptions().Bool; 61 if (!Policy.Bool) { 62 if (MacroInfo *BoolMacro = PP.getMacroInfo(&Context.Idents.get("bool"))) { 63 Policy.Bool = BoolMacro->isObjectLike() && 64 BoolMacro->getNumTokens() == 1 && 65 BoolMacro->getReplacementToken(0).is(tok::kw__Bool); 66 } 67 } 68 69 return Policy; 70} 71 72void Sema::ActOnTranslationUnitScope(Scope *S) { 73 TUScope = S; 74 PushDeclContext(S, Context.getTranslationUnitDecl()); 75 76 VAListTagName = PP.getIdentifierInfo("__va_list_tag"); 77 78 if (PP.getLangOptions().ObjC1) { 79 // Synthesize "@class Protocol; 80 if (Context.getObjCProtoType().isNull()) { 81 ObjCInterfaceDecl *ProtocolDecl = 82 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(), 83 &Context.Idents.get("Protocol"), 84 SourceLocation(), true); 85 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl)); 86 PushOnScopeChains(ProtocolDecl, TUScope, false); 87 } 88 } 89} 90 91Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 92 TranslationUnitKind TUKind, 93 CodeCompleteConsumer *CodeCompleter) 94 : TheTargetAttributesSema(0), FPFeatures(pp.getLangOptions()), 95 LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer), 96 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()), 97 CollectStats(false), ExternalSource(0), CodeCompleter(CodeCompleter), 98 CurContext(0), OriginalLexicalContext(0), 99 PackContext(0), MSStructPragmaOn(false), VisContext(0), 100 ExprNeedsCleanups(0), LateTemplateParser(0), OpaqueParser(0), 101 IdResolver(pp.getLangOptions()), CXXTypeInfoDecl(0), MSVCGuidDecl(0), 102 GlobalNewDeleteDeclared(false), 103 ObjCShouldCallSuperDealloc(false), 104 ObjCShouldCallSuperFinalize(false), 105 TUKind(TUKind), 106 NumSFINAEErrors(0), SuppressAccessChecking(false), 107 AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false), 108 NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1), 109 CurrentInstantiationScope(0), TyposCorrected(0), 110 AnalysisWarnings(*this) 111{ 112 TUScope = 0; 113 LoadedExternalKnownNamespaces = false; 114 115 if (getLangOptions().CPlusPlus) 116 FieldCollector.reset(new CXXFieldCollector()); 117 118 // Tell diagnostics how to render things from the AST library. 119 PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument, 120 &Context); 121 122 ExprEvalContexts.push_back( 123 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0, false)); 124 125 FunctionScopes.push_back(new FunctionScopeInfo(Diags)); 126} 127 128void Sema::Initialize() { 129 // Tell the AST consumer about this Sema object. 130 Consumer.Initialize(Context); 131 132 // FIXME: Isn't this redundant with the initialization above? 133 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 134 SC->InitializeSema(*this); 135 136 // Tell the external Sema source about this Sema object. 137 if (ExternalSemaSource *ExternalSema 138 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 139 ExternalSema->InitializeSema(*this); 140 141 // Initialize predefined 128-bit integer types, if needed. 142 if (PP.getTargetInfo().getPointerWidth(0) >= 64) { 143 // If either of the 128-bit integer types are unavailable to name lookup, 144 // define them now. 145 DeclarationName Int128 = &Context.Idents.get("__int128_t"); 146 if (IdentifierResolver::begin(Int128) == IdentifierResolver::end()) 147 PushOnScopeChains(Context.getInt128Decl(), TUScope); 148 149 DeclarationName UInt128 = &Context.Idents.get("__uint128_t"); 150 if (IdentifierResolver::begin(UInt128) == IdentifierResolver::end()) 151 PushOnScopeChains(Context.getUInt128Decl(), TUScope); 152 } 153 154 155 // Initialize predefined Objective-C types: 156 if (PP.getLangOptions().ObjC1) { 157 // If 'SEL' does not yet refer to any declarations, make it refer to the 158 // predefined 'SEL'. 159 DeclarationName SEL = &Context.Idents.get("SEL"); 160 if (IdentifierResolver::begin(SEL) == IdentifierResolver::end()) 161 PushOnScopeChains(Context.getObjCSelDecl(), TUScope); 162 163 // If 'id' does not yet refer to any declarations, make it refer to the 164 // predefined 'id'. 165 DeclarationName Id = &Context.Idents.get("id"); 166 if (IdentifierResolver::begin(Id) == IdentifierResolver::end()) 167 PushOnScopeChains(Context.getObjCIdDecl(), TUScope); 168 169 // Create the built-in typedef for 'Class'. 170 DeclarationName Class = &Context.Idents.get("Class"); 171 if (IdentifierResolver::begin(Class) == IdentifierResolver::end()) 172 PushOnScopeChains(Context.getObjCClassDecl(), TUScope); 173 } 174} 175 176Sema::~Sema() { 177 if (PackContext) FreePackedContext(); 178 if (VisContext) FreeVisContext(); 179 delete TheTargetAttributesSema; 180 MSStructPragmaOn = false; 181 // Kill all the active scopes. 182 for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I) 183 delete FunctionScopes[I]; 184 if (FunctionScopes.size() == 1) 185 delete FunctionScopes[0]; 186 187 // Tell the SemaConsumer to forget about us; we're going out of scope. 188 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 189 SC->ForgetSema(); 190 191 // Detach from the external Sema source. 192 if (ExternalSemaSource *ExternalSema 193 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 194 ExternalSema->ForgetSema(); 195} 196 197 198/// makeUnavailableInSystemHeader - There is an error in the current 199/// context. If we're still in a system header, and we can plausibly 200/// make the relevant declaration unavailable instead of erroring, do 201/// so and return true. 202bool Sema::makeUnavailableInSystemHeader(SourceLocation loc, 203 StringRef msg) { 204 // If we're not in a function, it's an error. 205 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext); 206 if (!fn) return false; 207 208 // If we're in template instantiation, it's an error. 209 if (!ActiveTemplateInstantiations.empty()) 210 return false; 211 212 // If that function's not in a system header, it's an error. 213 if (!Context.getSourceManager().isInSystemHeader(loc)) 214 return false; 215 216 // If the function is already unavailable, it's not an error. 217 if (fn->hasAttr<UnavailableAttr>()) return true; 218 219 fn->addAttr(new (Context) UnavailableAttr(loc, Context, msg)); 220 return true; 221} 222 223ASTMutationListener *Sema::getASTMutationListener() const { 224 return getASTConsumer().GetASTMutationListener(); 225} 226 227/// \brief Print out statistics about the semantic analysis. 228void Sema::PrintStats() const { 229 llvm::errs() << "\n*** Semantic Analysis Stats:\n"; 230 llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n"; 231 232 BumpAlloc.PrintStats(); 233 AnalysisWarnings.PrintStats(); 234} 235 236/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 237/// If there is already an implicit cast, merge into the existing one. 238/// The result is of the given category. 239ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty, 240 CastKind Kind, ExprValueKind VK, 241 const CXXCastPath *BasePath, 242 CheckedConversionKind CCK) { 243 QualType ExprTy = Context.getCanonicalType(E->getType()); 244 QualType TypeTy = Context.getCanonicalType(Ty); 245 246 if (ExprTy == TypeTy) 247 return Owned(E); 248 249 if (getLangOptions().ObjCAutoRefCount) 250 CheckObjCARCConversion(SourceRange(), Ty, E, CCK); 251 252 // If this is a derived-to-base cast to a through a virtual base, we 253 // need a vtable. 254 if (Kind == CK_DerivedToBase && 255 BasePathInvolvesVirtualBase(*BasePath)) { 256 QualType T = E->getType(); 257 if (const PointerType *Pointer = T->getAs<PointerType>()) 258 T = Pointer->getPointeeType(); 259 if (const RecordType *RecordTy = T->getAs<RecordType>()) 260 MarkVTableUsed(E->getLocStart(), 261 cast<CXXRecordDecl>(RecordTy->getDecl())); 262 } 263 264 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) { 265 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) { 266 ImpCast->setType(Ty); 267 ImpCast->setValueKind(VK); 268 return Owned(E); 269 } 270 } 271 272 return Owned(ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK)); 273} 274 275/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 276/// to the conversion from scalar type ScalarTy to the Boolean type. 277CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) { 278 switch (ScalarTy->getScalarTypeKind()) { 279 case Type::STK_Bool: return CK_NoOp; 280 case Type::STK_CPointer: return CK_PointerToBoolean; 281 case Type::STK_BlockPointer: return CK_PointerToBoolean; 282 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean; 283 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean; 284 case Type::STK_Integral: return CK_IntegralToBoolean; 285 case Type::STK_Floating: return CK_FloatingToBoolean; 286 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean; 287 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean; 288 } 289 return CK_Invalid; 290} 291 292/// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector. 293static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) { 294 if (D->isUsed()) 295 return true; 296 297 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 298 // UnusedFileScopedDecls stores the first declaration. 299 // The declaration may have become definition so check again. 300 const FunctionDecl *DeclToCheck; 301 if (FD->hasBody(DeclToCheck)) 302 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 303 304 // Later redecls may add new information resulting in not having to warn, 305 // so check again. 306 DeclToCheck = FD->getMostRecentDeclaration(); 307 if (DeclToCheck != FD) 308 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 309 } 310 311 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 312 // UnusedFileScopedDecls stores the first declaration. 313 // The declaration may have become definition so check again. 314 const VarDecl *DeclToCheck = VD->getDefinition(); 315 if (DeclToCheck) 316 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 317 318 // Later redecls may add new information resulting in not having to warn, 319 // so check again. 320 DeclToCheck = VD->getMostRecentDeclaration(); 321 if (DeclToCheck != VD) 322 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 323 } 324 325 return false; 326} 327 328namespace { 329 struct UndefinedInternal { 330 NamedDecl *decl; 331 FullSourceLoc useLoc; 332 333 UndefinedInternal(NamedDecl *decl, FullSourceLoc useLoc) 334 : decl(decl), useLoc(useLoc) {} 335 }; 336 337 bool operator<(const UndefinedInternal &l, const UndefinedInternal &r) { 338 return l.useLoc.isBeforeInTranslationUnitThan(r.useLoc); 339 } 340} 341 342/// checkUndefinedInternals - Check for undefined objects with internal linkage. 343static void checkUndefinedInternals(Sema &S) { 344 if (S.UndefinedInternals.empty()) return; 345 346 // Collect all the still-undefined entities with internal linkage. 347 SmallVector<UndefinedInternal, 16> undefined; 348 for (llvm::DenseMap<NamedDecl*,SourceLocation>::iterator 349 i = S.UndefinedInternals.begin(), e = S.UndefinedInternals.end(); 350 i != e; ++i) { 351 NamedDecl *decl = i->first; 352 353 // Ignore attributes that have become invalid. 354 if (decl->isInvalidDecl()) continue; 355 356 // __attribute__((weakref)) is basically a definition. 357 if (decl->hasAttr<WeakRefAttr>()) continue; 358 359 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) { 360 if (fn->isPure() || fn->hasBody()) 361 continue; 362 } else { 363 if (cast<VarDecl>(decl)->hasDefinition() != VarDecl::DeclarationOnly) 364 continue; 365 } 366 367 // We build a FullSourceLoc so that we can sort with array_pod_sort. 368 FullSourceLoc loc(i->second, S.Context.getSourceManager()); 369 undefined.push_back(UndefinedInternal(decl, loc)); 370 } 371 372 if (undefined.empty()) return; 373 374 // Sort (in order of use site) so that we're not (as) dependent on 375 // the iteration order through an llvm::DenseMap. 376 llvm::array_pod_sort(undefined.begin(), undefined.end()); 377 378 for (SmallVectorImpl<UndefinedInternal>::iterator 379 i = undefined.begin(), e = undefined.end(); i != e; ++i) { 380 NamedDecl *decl = i->decl; 381 S.Diag(decl->getLocation(), diag::warn_undefined_internal) 382 << isa<VarDecl>(decl) << decl; 383 S.Diag(i->useLoc, diag::note_used_here); 384 } 385} 386 387void Sema::LoadExternalWeakUndeclaredIdentifiers() { 388 if (!ExternalSource) 389 return; 390 391 SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs; 392 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs); 393 for (unsigned I = 0, N = WeakIDs.size(); I != N; ++I) { 394 llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator Pos 395 = WeakUndeclaredIdentifiers.find(WeakIDs[I].first); 396 if (Pos != WeakUndeclaredIdentifiers.end()) 397 continue; 398 399 WeakUndeclaredIdentifiers.insert(WeakIDs[I]); 400 } 401} 402 403/// ActOnEndOfTranslationUnit - This is called at the very end of the 404/// translation unit when EOF is reached and all but the top-level scope is 405/// popped. 406void Sema::ActOnEndOfTranslationUnit() { 407 // Only complete translation units define vtables and perform implicit 408 // instantiations. 409 if (TUKind == TU_Complete) { 410 // If any dynamic classes have their key function defined within 411 // this translation unit, then those vtables are considered "used" and must 412 // be emitted. 413 for (DynamicClassesType::iterator I = DynamicClasses.begin(ExternalSource), 414 E = DynamicClasses.end(); 415 I != E; ++I) { 416 assert(!(*I)->isDependentType() && 417 "Should not see dependent types here!"); 418 if (const CXXMethodDecl *KeyFunction = Context.getKeyFunction(*I)) { 419 const FunctionDecl *Definition = 0; 420 if (KeyFunction->hasBody(Definition)) 421 MarkVTableUsed(Definition->getLocation(), *I, true); 422 } 423 } 424 425 // If DefinedUsedVTables ends up marking any virtual member functions it 426 // might lead to more pending template instantiations, which we then need 427 // to instantiate. 428 DefineUsedVTables(); 429 430 // C++: Perform implicit template instantiations. 431 // 432 // FIXME: When we perform these implicit instantiations, we do not 433 // carefully keep track of the point of instantiation (C++ [temp.point]). 434 // This means that name lookup that occurs within the template 435 // instantiation will always happen at the end of the translation unit, 436 // so it will find some names that should not be found. Although this is 437 // common behavior for C++ compilers, it is technically wrong. In the 438 // future, we either need to be able to filter the results of name lookup 439 // or we need to perform template instantiations earlier. 440 PerformPendingInstantiations(); 441 } 442 443 // Remove file scoped decls that turned out to be used. 444 UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(0, 445 true), 446 UnusedFileScopedDecls.end(), 447 std::bind1st(std::ptr_fun(ShouldRemoveFromUnused), 448 this)), 449 UnusedFileScopedDecls.end()); 450 451 if (TUKind == TU_Prefix) { 452 // Translation unit prefixes don't need any of the checking below. 453 TUScope = 0; 454 return; 455 } 456 457 // Check for #pragma weak identifiers that were never declared 458 // FIXME: This will cause diagnostics to be emitted in a non-determinstic 459 // order! Iterating over a densemap like this is bad. 460 LoadExternalWeakUndeclaredIdentifiers(); 461 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 462 I = WeakUndeclaredIdentifiers.begin(), 463 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) { 464 if (I->second.getUsed()) continue; 465 466 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared) 467 << I->first; 468 } 469 470 if (TUKind == TU_Module) { 471 // Modules don't need any of the checking below. 472 TUScope = 0; 473 return; 474 } 475 476 // C99 6.9.2p2: 477 // A declaration of an identifier for an object that has file 478 // scope without an initializer, and without a storage-class 479 // specifier or with the storage-class specifier static, 480 // constitutes a tentative definition. If a translation unit 481 // contains one or more tentative definitions for an identifier, 482 // and the translation unit contains no external definition for 483 // that identifier, then the behavior is exactly as if the 484 // translation unit contains a file scope declaration of that 485 // identifier, with the composite type as of the end of the 486 // translation unit, with an initializer equal to 0. 487 llvm::SmallSet<VarDecl *, 32> Seen; 488 for (TentativeDefinitionsType::iterator 489 T = TentativeDefinitions.begin(ExternalSource), 490 TEnd = TentativeDefinitions.end(); 491 T != TEnd; ++T) 492 { 493 VarDecl *VD = (*T)->getActingDefinition(); 494 495 // If the tentative definition was completed, getActingDefinition() returns 496 // null. If we've already seen this variable before, insert()'s second 497 // return value is false. 498 if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD)) 499 continue; 500 501 if (const IncompleteArrayType *ArrayT 502 = Context.getAsIncompleteArrayType(VD->getType())) { 503 if (RequireCompleteType(VD->getLocation(), 504 ArrayT->getElementType(), 505 diag::err_tentative_def_incomplete_type_arr)) { 506 VD->setInvalidDecl(); 507 continue; 508 } 509 510 // Set the length of the array to 1 (C99 6.9.2p5). 511 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 512 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 513 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), 514 One, ArrayType::Normal, 0); 515 VD->setType(T); 516 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 517 diag::err_tentative_def_incomplete_type)) 518 VD->setInvalidDecl(); 519 520 // Notify the consumer that we've completed a tentative definition. 521 if (!VD->isInvalidDecl()) 522 Consumer.CompleteTentativeDefinition(VD); 523 524 } 525 526 if (LangOpts.CPlusPlus0x && 527 Diags.getDiagnosticLevel(diag::warn_delegating_ctor_cycle, 528 SourceLocation()) 529 != DiagnosticsEngine::Ignored) 530 CheckDelegatingCtorCycles(); 531 532 // If there were errors, disable 'unused' warnings since they will mostly be 533 // noise. 534 if (!Diags.hasErrorOccurred()) { 535 // Output warning for unused file scoped decls. 536 for (UnusedFileScopedDeclsType::iterator 537 I = UnusedFileScopedDecls.begin(ExternalSource), 538 E = UnusedFileScopedDecls.end(); I != E; ++I) { 539 if (ShouldRemoveFromUnused(this, *I)) 540 continue; 541 542 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 543 const FunctionDecl *DiagD; 544 if (!FD->hasBody(DiagD)) 545 DiagD = FD; 546 if (DiagD->isDeleted()) 547 continue; // Deleted functions are supposed to be unused. 548 if (DiagD->isReferenced()) { 549 if (isa<CXXMethodDecl>(DiagD)) 550 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function) 551 << DiagD->getDeclName(); 552 else 553 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 554 << /*function*/0 << DiagD->getDeclName(); 555 } else { 556 Diag(DiagD->getLocation(), 557 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function 558 : diag::warn_unused_function) 559 << DiagD->getDeclName(); 560 } 561 } else { 562 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition(); 563 if (!DiagD) 564 DiagD = cast<VarDecl>(*I); 565 if (DiagD->isReferenced()) { 566 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 567 << /*variable*/1 << DiagD->getDeclName(); 568 } else { 569 Diag(DiagD->getLocation(), diag::warn_unused_variable) 570 << DiagD->getDeclName(); 571 } 572 } 573 } 574 575 checkUndefinedInternals(*this); 576 } 577 578 // Check we've noticed that we're no longer parsing the initializer for every 579 // variable. If we miss cases, then at best we have a performance issue and 580 // at worst a rejects-valid bug. 581 assert(ParsingInitForAutoVars.empty() && 582 "Didn't unmark var as having its initializer parsed"); 583 584 TUScope = 0; 585} 586 587 588//===----------------------------------------------------------------------===// 589// Helper functions. 590//===----------------------------------------------------------------------===// 591 592DeclContext *Sema::getFunctionLevelDeclContext() { 593 DeclContext *DC = CurContext; 594 595 while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC)) 596 DC = DC->getParent(); 597 598 return DC; 599} 600 601/// getCurFunctionDecl - If inside of a function body, this returns a pointer 602/// to the function decl for the function being parsed. If we're currently 603/// in a 'block', this returns the containing context. 604FunctionDecl *Sema::getCurFunctionDecl() { 605 DeclContext *DC = getFunctionLevelDeclContext(); 606 return dyn_cast<FunctionDecl>(DC); 607} 608 609ObjCMethodDecl *Sema::getCurMethodDecl() { 610 DeclContext *DC = getFunctionLevelDeclContext(); 611 return dyn_cast<ObjCMethodDecl>(DC); 612} 613 614NamedDecl *Sema::getCurFunctionOrMethodDecl() { 615 DeclContext *DC = getFunctionLevelDeclContext(); 616 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 617 return cast<NamedDecl>(DC); 618 return 0; 619} 620 621Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() { 622 if (!isActive()) 623 return; 624 625 if (llvm::Optional<TemplateDeductionInfo*> Info = SemaRef.isSFINAEContext()) { 626 switch (DiagnosticIDs::getDiagnosticSFINAEResponse(getDiagID())) { 627 case DiagnosticIDs::SFINAE_Report: 628 // Fall through; we'll report the diagnostic below. 629 break; 630 631 case DiagnosticIDs::SFINAE_AccessControl: 632 // Per C++ Core Issue 1170, access control is part of SFINAE. 633 // Additionally, the AccessCheckingSFINAE flag can be used to temporary 634 // make access control a part of SFINAE for the purposes of checking 635 // type traits. 636 if (!SemaRef.AccessCheckingSFINAE && 637 !SemaRef.getLangOptions().CPlusPlus0x) 638 break; 639 640 case DiagnosticIDs::SFINAE_SubstitutionFailure: 641 // Count this failure so that we know that template argument deduction 642 // has failed. 643 ++SemaRef.NumSFINAEErrors; 644 SemaRef.Diags.setLastDiagnosticIgnored(); 645 SemaRef.Diags.Clear(); 646 Clear(); 647 return; 648 649 case DiagnosticIDs::SFINAE_Suppress: 650 // Make a copy of this suppressed diagnostic and store it with the 651 // template-deduction information; 652 FlushCounts(); 653 Diagnostic DiagInfo(&SemaRef.Diags); 654 655 if (*Info) 656 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(), 657 PartialDiagnostic(DiagInfo, 658 SemaRef.Context.getDiagAllocator())); 659 660 // Suppress this diagnostic. 661 SemaRef.Diags.setLastDiagnosticIgnored(); 662 SemaRef.Diags.Clear(); 663 Clear(); 664 return; 665 } 666 } 667 668 // Set up the context's printing policy based on our current state. 669 SemaRef.Context.setPrintingPolicy(SemaRef.getPrintingPolicy()); 670 671 // Emit the diagnostic. 672 if (!this->Emit()) 673 return; 674 675 // If this is not a note, and we're in a template instantiation 676 // that is different from the last template instantiation where 677 // we emitted an error, print a template instantiation 678 // backtrace. 679 if (!DiagnosticIDs::isBuiltinNote(DiagID) && 680 !SemaRef.ActiveTemplateInstantiations.empty() && 681 SemaRef.ActiveTemplateInstantiations.back() 682 != SemaRef.LastTemplateInstantiationErrorContext) { 683 SemaRef.PrintInstantiationStack(); 684 SemaRef.LastTemplateInstantiationErrorContext 685 = SemaRef.ActiveTemplateInstantiations.back(); 686 } 687} 688 689Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) { 690 DiagnosticBuilder DB = Diags.Report(Loc, DiagID); 691 return SemaDiagnosticBuilder(DB, *this, DiagID); 692} 693 694Sema::SemaDiagnosticBuilder 695Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) { 696 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID())); 697 PD.Emit(Builder); 698 699 return Builder; 700} 701 702/// \brief Looks through the macro-expansion chain for the given 703/// location, looking for a macro expansion with the given name. 704/// If one is found, returns true and sets the location to that 705/// expansion loc. 706bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) { 707 SourceLocation loc = locref; 708 if (!loc.isMacroID()) return false; 709 710 // There's no good way right now to look at the intermediate 711 // expansions, so just jump to the expansion location. 712 loc = getSourceManager().getExpansionLoc(loc); 713 714 // If that's written with the name, stop here. 715 SmallVector<char, 16> buffer; 716 if (getPreprocessor().getSpelling(loc, buffer) == name) { 717 locref = loc; 718 return true; 719 } 720 return false; 721} 722 723/// \brief Determines the active Scope associated with the given declaration 724/// context. 725/// 726/// This routine maps a declaration context to the active Scope object that 727/// represents that declaration context in the parser. It is typically used 728/// from "scope-less" code (e.g., template instantiation, lazy creation of 729/// declarations) that injects a name for name-lookup purposes and, therefore, 730/// must update the Scope. 731/// 732/// \returns The scope corresponding to the given declaraion context, or NULL 733/// if no such scope is open. 734Scope *Sema::getScopeForContext(DeclContext *Ctx) { 735 736 if (!Ctx) 737 return 0; 738 739 Ctx = Ctx->getPrimaryContext(); 740 for (Scope *S = getCurScope(); S; S = S->getParent()) { 741 // Ignore scopes that cannot have declarations. This is important for 742 // out-of-line definitions of static class members. 743 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) 744 if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity())) 745 if (Ctx == Entity->getPrimaryContext()) 746 return S; 747 } 748 749 return 0; 750} 751 752/// \brief Enter a new function scope 753void Sema::PushFunctionScope() { 754 if (FunctionScopes.size() == 1) { 755 // Use the "top" function scope rather than having to allocate 756 // memory for a new scope. 757 FunctionScopes.back()->Clear(); 758 FunctionScopes.push_back(FunctionScopes.back()); 759 return; 760 } 761 762 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics())); 763} 764 765void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) { 766 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(), 767 BlockScope, Block)); 768} 769 770void Sema::PopFunctionOrBlockScope(const AnalysisBasedWarnings::Policy *WP, 771 const Decl *D, const BlockExpr *blkExpr) { 772 FunctionScopeInfo *Scope = FunctionScopes.pop_back_val(); 773 assert(!FunctionScopes.empty() && "mismatched push/pop!"); 774 775 // Issue any analysis-based warnings. 776 if (WP && D) 777 AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr); 778 else { 779 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator 780 i = Scope->PossiblyUnreachableDiags.begin(), 781 e = Scope->PossiblyUnreachableDiags.end(); 782 i != e; ++i) { 783 const sema::PossiblyUnreachableDiag &D = *i; 784 Diag(D.Loc, D.PD); 785 } 786 } 787 788 if (FunctionScopes.back() != Scope) { 789 delete Scope; 790 } 791} 792 793/// \brief Determine whether any errors occurred within this function/method/ 794/// block. 795bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const { 796 return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred(); 797} 798 799BlockScopeInfo *Sema::getCurBlock() { 800 if (FunctionScopes.empty()) 801 return 0; 802 803 return dyn_cast<BlockScopeInfo>(FunctionScopes.back()); 804} 805 806// Pin this vtable to this file. 807ExternalSemaSource::~ExternalSemaSource() {} 808 809std::pair<ObjCMethodList, ObjCMethodList> 810ExternalSemaSource::ReadMethodPool(Selector Sel) { 811 return std::pair<ObjCMethodList, ObjCMethodList>(); 812} 813 814void ExternalSemaSource::ReadKnownNamespaces( 815 SmallVectorImpl<NamespaceDecl *> &Namespaces) { 816} 817 818void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const { 819 SourceLocation Loc = this->Loc; 820 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation(); 821 if (Loc.isValid()) { 822 Loc.print(OS, S.getSourceManager()); 823 OS << ": "; 824 } 825 OS << Message; 826 827 if (TheDecl && isa<NamedDecl>(TheDecl)) { 828 std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString(); 829 if (!Name.empty()) 830 OS << " '" << Name << '\''; 831 } 832 833 OS << '\n'; 834} 835 836/// \brief Figure out if an expression could be turned into a call. 837/// 838/// Use this when trying to recover from an error where the programmer may have 839/// written just the name of a function instead of actually calling it. 840/// 841/// \param E - The expression to examine. 842/// \param ZeroArgCallReturnTy - If the expression can be turned into a call 843/// with no arguments, this parameter is set to the type returned by such a 844/// call; otherwise, it is set to an empty QualType. 845/// \param OverloadSet - If the expression is an overloaded function 846/// name, this parameter is populated with the decls of the various overloads. 847bool Sema::isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy, 848 UnresolvedSetImpl &OverloadSet) { 849 ZeroArgCallReturnTy = QualType(); 850 OverloadSet.clear(); 851 852 if (E.getType() == Context.OverloadTy) { 853 OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E)); 854 const OverloadExpr *Overloads = FR.Expression; 855 856 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(), 857 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) { 858 OverloadSet.addDecl(*it); 859 860 // Check whether the function is a non-template which takes no 861 // arguments. 862 if (const FunctionDecl *OverloadDecl 863 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) { 864 if (OverloadDecl->getMinRequiredArguments() == 0) 865 ZeroArgCallReturnTy = OverloadDecl->getResultType(); 866 } 867 } 868 869 // Ignore overloads that are pointer-to-member constants. 870 if (FR.HasFormOfMemberPointer) 871 return false; 872 873 return true; 874 } 875 876 if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) { 877 if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) { 878 if (Fun->getMinRequiredArguments() == 0) 879 ZeroArgCallReturnTy = Fun->getResultType(); 880 return true; 881 } 882 } 883 884 // We don't have an expression that's convenient to get a FunctionDecl from, 885 // but we can at least check if the type is "function of 0 arguments". 886 QualType ExprTy = E.getType(); 887 const FunctionType *FunTy = NULL; 888 QualType PointeeTy = ExprTy->getPointeeType(); 889 if (!PointeeTy.isNull()) 890 FunTy = PointeeTy->getAs<FunctionType>(); 891 if (!FunTy) 892 FunTy = ExprTy->getAs<FunctionType>(); 893 if (!FunTy && ExprTy == Context.BoundMemberTy) { 894 // Look for the bound-member type. If it's still overloaded, give up, 895 // although we probably should have fallen into the OverloadExpr case above 896 // if we actually have an overloaded bound member. 897 QualType BoundMemberTy = Expr::findBoundMemberType(&E); 898 if (!BoundMemberTy.isNull()) 899 FunTy = BoundMemberTy->castAs<FunctionType>(); 900 } 901 902 if (const FunctionProtoType *FPT = 903 dyn_cast_or_null<FunctionProtoType>(FunTy)) { 904 if (FPT->getNumArgs() == 0) 905 ZeroArgCallReturnTy = FunTy->getResultType(); 906 return true; 907 } 908 return false; 909} 910 911/// \brief Give notes for a set of overloads. 912/// 913/// A companion to isExprCallable. In cases when the name that the programmer 914/// wrote was an overloaded function, we may be able to make some guesses about 915/// plausible overloads based on their return types; such guesses can be handed 916/// off to this method to be emitted as notes. 917/// 918/// \param Overloads - The overloads to note. 919/// \param FinalNoteLoc - If we've suppressed printing some overloads due to 920/// -fshow-overloads=best, this is the location to attach to the note about too 921/// many candidates. Typically this will be the location of the original 922/// ill-formed expression. 923static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, 924 const SourceLocation FinalNoteLoc) { 925 int ShownOverloads = 0; 926 int SuppressedOverloads = 0; 927 for (UnresolvedSetImpl::iterator It = Overloads.begin(), 928 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { 929 // FIXME: Magic number for max shown overloads stolen from 930 // OverloadCandidateSet::NoteCandidates. 931 if (ShownOverloads >= 4 && 932 S.Diags.getShowOverloads() == DiagnosticsEngine::Ovl_Best) { 933 ++SuppressedOverloads; 934 continue; 935 } 936 937 NamedDecl *Fn = (*It)->getUnderlyingDecl(); 938 S.Diag(Fn->getLocStart(), diag::note_possible_target_of_call); 939 ++ShownOverloads; 940 } 941 942 if (SuppressedOverloads) 943 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates) 944 << SuppressedOverloads; 945} 946 947static void notePlausibleOverloads(Sema &S, SourceLocation Loc, 948 const UnresolvedSetImpl &Overloads, 949 bool (*IsPlausibleResult)(QualType)) { 950 if (!IsPlausibleResult) 951 return noteOverloads(S, Overloads, Loc); 952 953 UnresolvedSet<2> PlausibleOverloads; 954 for (OverloadExpr::decls_iterator It = Overloads.begin(), 955 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { 956 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It); 957 QualType OverloadResultTy = OverloadDecl->getResultType(); 958 if (IsPlausibleResult(OverloadResultTy)) 959 PlausibleOverloads.addDecl(It.getDecl()); 960 } 961 noteOverloads(S, PlausibleOverloads, Loc); 962} 963 964/// Determine whether the given expression can be called by just 965/// putting parentheses after it. Notably, expressions with unary 966/// operators can't be because the unary operator will start parsing 967/// outside the call. 968static bool IsCallableWithAppend(Expr *E) { 969 E = E->IgnoreImplicit(); 970 return (!isa<CStyleCastExpr>(E) && 971 !isa<UnaryOperator>(E) && 972 !isa<BinaryOperator>(E) && 973 !isa<CXXOperatorCallExpr>(E)); 974} 975 976bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 977 bool ForceComplain, 978 bool (*IsPlausibleResult)(QualType)) { 979 SourceLocation Loc = E.get()->getExprLoc(); 980 SourceRange Range = E.get()->getSourceRange(); 981 982 QualType ZeroArgCallTy; 983 UnresolvedSet<4> Overloads; 984 if (isExprCallable(*E.get(), ZeroArgCallTy, Overloads) && 985 !ZeroArgCallTy.isNull() && 986 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) { 987 // At this point, we know E is potentially callable with 0 988 // arguments and that it returns something of a reasonable type, 989 // so we can emit a fixit and carry on pretending that E was 990 // actually a CallExpr. 991 SourceLocation ParenInsertionLoc = 992 PP.getLocForEndOfToken(Range.getEnd()); 993 Diag(Loc, PD) 994 << /*zero-arg*/ 1 << Range 995 << (IsCallableWithAppend(E.get()) 996 ? FixItHint::CreateInsertion(ParenInsertionLoc, "()") 997 : FixItHint()); 998 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult); 999 1000 // FIXME: Try this before emitting the fixit, and suppress diagnostics 1001 // while doing so. 1002 E = ActOnCallExpr(0, E.take(), ParenInsertionLoc, 1003 MultiExprArg(*this, 0, 0), 1004 ParenInsertionLoc.getLocWithOffset(1)); 1005 return true; 1006 } 1007 1008 if (!ForceComplain) return false; 1009 1010 Diag(Loc, PD) << /*not zero-arg*/ 0 << Range; 1011 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult); 1012 E = ExprError(); 1013 return true; 1014} 1015