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/AST/ASTContext.h" 16 #include "clang/AST/ASTDiagnostic.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclFriend.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/StmtCXX.h" 23 #include "clang/Basic/DiagnosticOptions.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Lex/HeaderSearch.h" 27 #include "clang/Lex/Preprocessor.h" 28 #include "clang/Sema/CXXFieldCollector.h" 29 #include "clang/Sema/DelayedDiagnostic.h" 30 #include "clang/Sema/ExternalSemaSource.h" 31 #include "clang/Sema/Initialization.h" 32 #include "clang/Sema/MultiplexExternalSemaSource.h" 33 #include "clang/Sema/ObjCMethodList.h" 34 #include "clang/Sema/PrettyDeclStackTrace.h" 35 #include "clang/Sema/Scope.h" 36 #include "clang/Sema/ScopeInfo.h" 37 #include "clang/Sema/SemaConsumer.h" 38 #include "clang/Sema/SemaInternal.h" 39 #include "clang/Sema/TemplateDeduction.h" 40 #include "llvm/ADT/DenseMap.h" 41 #include "llvm/ADT/SmallSet.h" 42 using namespace clang; 43 using namespace sema; 44 45 SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) { 46 return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts); 47 } 48 49 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); } 50 51 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context, 52 const Preprocessor &PP) { 53 PrintingPolicy Policy = Context.getPrintingPolicy(); 54 // Our printing policy is copied over the ASTContext printing policy whenever 55 // a diagnostic is emitted, so recompute it. 56 Policy.Bool = Context.getLangOpts().Bool; 57 if (!Policy.Bool) { 58 if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) { 59 Policy.Bool = BoolMacro->isObjectLike() && 60 BoolMacro->getNumTokens() == 1 && 61 BoolMacro->getReplacementToken(0).is(tok::kw__Bool); 62 } 63 } 64 65 return Policy; 66 } 67 68 void Sema::ActOnTranslationUnitScope(Scope *S) { 69 TUScope = S; 70 PushDeclContext(S, Context.getTranslationUnitDecl()); 71 } 72 73 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 74 TranslationUnitKind TUKind, 75 CodeCompleteConsumer *CodeCompleter) 76 : ExternalSource(nullptr), 77 isMultiplexExternalSource(false), FPFeatures(pp.getLangOpts()), 78 LangOpts(pp.getLangOpts()), PP(pp), Context(ctxt), Consumer(consumer), 79 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()), 80 CollectStats(false), CodeCompleter(CodeCompleter), 81 CurContext(nullptr), OriginalLexicalContext(nullptr), 82 MSStructPragmaOn(false), 83 MSPointerToMemberRepresentationMethod( 84 LangOpts.getMSPointerToMemberRepresentationMethod()), 85 VtorDispStack(MSVtorDispAttr::Mode(LangOpts.VtorDispMode)), 86 PackStack(0), DataSegStack(nullptr), BSSSegStack(nullptr), 87 ConstSegStack(nullptr), CodeSegStack(nullptr), CurInitSeg(nullptr), 88 VisContext(nullptr), 89 IsBuildingRecoveryCallExpr(false), 90 Cleanup{}, LateTemplateParser(nullptr), 91 LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp), 92 StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr), 93 CXXTypeInfoDecl(nullptr), MSVCGuidDecl(nullptr), 94 NSNumberDecl(nullptr), NSValueDecl(nullptr), 95 NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr), 96 ValueWithBytesObjCTypeMethod(nullptr), 97 NSArrayDecl(nullptr), ArrayWithObjectsMethod(nullptr), 98 NSDictionaryDecl(nullptr), DictionaryWithObjectsMethod(nullptr), 99 MSAsmLabelNameCounter(0), 100 GlobalNewDeleteDeclared(false), 101 TUKind(TUKind), 102 NumSFINAEErrors(0), 103 CachedFakeTopLevelModule(nullptr), 104 AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false), 105 NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1), 106 CurrentInstantiationScope(nullptr), DisableTypoCorrection(false), 107 TyposCorrected(0), AnalysisWarnings(*this), ThreadSafetyDeclCache(nullptr), 108 VarDataSharingAttributesStack(nullptr), CurScope(nullptr), 109 Ident_super(nullptr), Ident___float128(nullptr) 110 { 111 TUScope = nullptr; 112 113 LoadedExternalKnownNamespaces = false; 114 for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I) 115 NSNumberLiteralMethods[I] = nullptr; 116 117 if (getLangOpts().ObjC1) 118 NSAPIObj.reset(new NSAPI(Context)); 119 120 if (getLangOpts().CPlusPlus) 121 FieldCollector.reset(new CXXFieldCollector()); 122 123 // Tell diagnostics how to render things from the AST library. 124 Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context); 125 126 ExprEvalContexts.emplace_back(PotentiallyEvaluated, 0, CleanupInfo{}, nullptr, 127 false); 128 129 FunctionScopes.push_back(new FunctionScopeInfo(Diags)); 130 131 // Initilization of data sharing attributes stack for OpenMP 132 InitDataSharingAttributesStack(); 133 } 134 135 void Sema::addImplicitTypedef(StringRef Name, QualType T) { 136 DeclarationName DN = &Context.Idents.get(Name); 137 if (IdResolver.begin(DN) == IdResolver.end()) 138 PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope); 139 } 140 141 void Sema::Initialize() { 142 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 143 SC->InitializeSema(*this); 144 145 // Tell the external Sema source about this Sema object. 146 if (ExternalSemaSource *ExternalSema 147 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 148 ExternalSema->InitializeSema(*this); 149 150 // This needs to happen after ExternalSemaSource::InitializeSema(this) or we 151 // will not be able to merge any duplicate __va_list_tag decls correctly. 152 VAListTagName = PP.getIdentifierInfo("__va_list_tag"); 153 154 if (!TUScope) 155 return; 156 157 // Initialize predefined 128-bit integer types, if needed. 158 if (Context.getTargetInfo().hasInt128Type()) { 159 // If either of the 128-bit integer types are unavailable to name lookup, 160 // define them now. 161 DeclarationName Int128 = &Context.Idents.get("__int128_t"); 162 if (IdResolver.begin(Int128) == IdResolver.end()) 163 PushOnScopeChains(Context.getInt128Decl(), TUScope); 164 165 DeclarationName UInt128 = &Context.Idents.get("__uint128_t"); 166 if (IdResolver.begin(UInt128) == IdResolver.end()) 167 PushOnScopeChains(Context.getUInt128Decl(), TUScope); 168 } 169 170 171 // Initialize predefined Objective-C types: 172 if (getLangOpts().ObjC1) { 173 // If 'SEL' does not yet refer to any declarations, make it refer to the 174 // predefined 'SEL'. 175 DeclarationName SEL = &Context.Idents.get("SEL"); 176 if (IdResolver.begin(SEL) == IdResolver.end()) 177 PushOnScopeChains(Context.getObjCSelDecl(), TUScope); 178 179 // If 'id' does not yet refer to any declarations, make it refer to the 180 // predefined 'id'. 181 DeclarationName Id = &Context.Idents.get("id"); 182 if (IdResolver.begin(Id) == IdResolver.end()) 183 PushOnScopeChains(Context.getObjCIdDecl(), TUScope); 184 185 // Create the built-in typedef for 'Class'. 186 DeclarationName Class = &Context.Idents.get("Class"); 187 if (IdResolver.begin(Class) == IdResolver.end()) 188 PushOnScopeChains(Context.getObjCClassDecl(), TUScope); 189 190 // Create the built-in forward declaratino for 'Protocol'. 191 DeclarationName Protocol = &Context.Idents.get("Protocol"); 192 if (IdResolver.begin(Protocol) == IdResolver.end()) 193 PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope); 194 } 195 196 // Create the internal type for the *StringMakeConstantString builtins. 197 DeclarationName ConstantString = &Context.Idents.get("__NSConstantString"); 198 if (IdResolver.begin(ConstantString) == IdResolver.end()) 199 PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope); 200 201 // Initialize Microsoft "predefined C++ types". 202 if (getLangOpts().MSVCCompat) { 203 if (getLangOpts().CPlusPlus && 204 IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end()) 205 PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class), 206 TUScope); 207 208 addImplicitTypedef("size_t", Context.getSizeType()); 209 } 210 211 // Initialize predefined OpenCL types and supported optional core features. 212 if (getLangOpts().OpenCL) { 213 #define OPENCLEXT(Ext) \ 214 if (Context.getTargetInfo().getSupportedOpenCLOpts().is_##Ext##_supported_core( \ 215 getLangOpts().OpenCLVersion)) \ 216 getOpenCLOptions().Ext = 1; 217 #include "clang/Basic/OpenCLExtensions.def" 218 219 addImplicitTypedef("sampler_t", Context.OCLSamplerTy); 220 addImplicitTypedef("event_t", Context.OCLEventTy); 221 if (getLangOpts().OpenCLVersion >= 200) { 222 addImplicitTypedef("clk_event_t", Context.OCLClkEventTy); 223 addImplicitTypedef("queue_t", Context.OCLQueueTy); 224 addImplicitTypedef("ndrange_t", Context.OCLNDRangeTy); 225 addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy); 226 addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy)); 227 addImplicitTypedef("atomic_uint", 228 Context.getAtomicType(Context.UnsignedIntTy)); 229 addImplicitTypedef("atomic_long", Context.getAtomicType(Context.LongTy)); 230 addImplicitTypedef("atomic_ulong", 231 Context.getAtomicType(Context.UnsignedLongTy)); 232 addImplicitTypedef("atomic_float", 233 Context.getAtomicType(Context.FloatTy)); 234 addImplicitTypedef("atomic_double", 235 Context.getAtomicType(Context.DoubleTy)); 236 // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as 237 // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide. 238 addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy)); 239 addImplicitTypedef("atomic_intptr_t", 240 Context.getAtomicType(Context.getIntPtrType())); 241 addImplicitTypedef("atomic_uintptr_t", 242 Context.getAtomicType(Context.getUIntPtrType())); 243 addImplicitTypedef("atomic_size_t", 244 Context.getAtomicType(Context.getSizeType())); 245 addImplicitTypedef("atomic_ptrdiff_t", 246 Context.getAtomicType(Context.getPointerDiffType())); 247 } 248 } 249 250 if (Context.getTargetInfo().hasBuiltinMSVaList()) { 251 DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list"); 252 if (IdResolver.begin(MSVaList) == IdResolver.end()) 253 PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope); 254 } 255 256 DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list"); 257 if (IdResolver.begin(BuiltinVaList) == IdResolver.end()) 258 PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope); 259 } 260 261 Sema::~Sema() { 262 if (VisContext) FreeVisContext(); 263 // Kill all the active scopes. 264 for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I) 265 delete FunctionScopes[I]; 266 if (FunctionScopes.size() == 1) 267 delete FunctionScopes[0]; 268 269 // Tell the SemaConsumer to forget about us; we're going out of scope. 270 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 271 SC->ForgetSema(); 272 273 // Detach from the external Sema source. 274 if (ExternalSemaSource *ExternalSema 275 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 276 ExternalSema->ForgetSema(); 277 278 // If Sema's ExternalSource is the multiplexer - we own it. 279 if (isMultiplexExternalSource) 280 delete ExternalSource; 281 282 threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache); 283 284 // Destroys data sharing attributes stack for OpenMP 285 DestroyDataSharingAttributesStack(); 286 287 assert(DelayedTypos.empty() && "Uncorrected typos!"); 288 } 289 290 /// makeUnavailableInSystemHeader - There is an error in the current 291 /// context. If we're still in a system header, and we can plausibly 292 /// make the relevant declaration unavailable instead of erroring, do 293 /// so and return true. 294 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc, 295 UnavailableAttr::ImplicitReason reason) { 296 // If we're not in a function, it's an error. 297 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext); 298 if (!fn) return false; 299 300 // If we're in template instantiation, it's an error. 301 if (!ActiveTemplateInstantiations.empty()) 302 return false; 303 304 // If that function's not in a system header, it's an error. 305 if (!Context.getSourceManager().isInSystemHeader(loc)) 306 return false; 307 308 // If the function is already unavailable, it's not an error. 309 if (fn->hasAttr<UnavailableAttr>()) return true; 310 311 fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc)); 312 return true; 313 } 314 315 ASTMutationListener *Sema::getASTMutationListener() const { 316 return getASTConsumer().GetASTMutationListener(); 317 } 318 319 ///\brief Registers an external source. If an external source already exists, 320 /// creates a multiplex external source and appends to it. 321 /// 322 ///\param[in] E - A non-null external sema source. 323 /// 324 void Sema::addExternalSource(ExternalSemaSource *E) { 325 assert(E && "Cannot use with NULL ptr"); 326 327 if (!ExternalSource) { 328 ExternalSource = E; 329 return; 330 } 331 332 if (isMultiplexExternalSource) 333 static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E); 334 else { 335 ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E); 336 isMultiplexExternalSource = true; 337 } 338 } 339 340 /// \brief Print out statistics about the semantic analysis. 341 void Sema::PrintStats() const { 342 llvm::errs() << "\n*** Semantic Analysis Stats:\n"; 343 llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n"; 344 345 BumpAlloc.PrintStats(); 346 AnalysisWarnings.PrintStats(); 347 } 348 349 void Sema::diagnoseNullableToNonnullConversion(QualType DstType, 350 QualType SrcType, 351 SourceLocation Loc) { 352 Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context); 353 if (!ExprNullability || *ExprNullability != NullabilityKind::Nullable) 354 return; 355 356 Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context); 357 if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull) 358 return; 359 360 Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType; 361 } 362 363 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 364 /// If there is already an implicit cast, merge into the existing one. 365 /// The result is of the given category. 366 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty, 367 CastKind Kind, ExprValueKind VK, 368 const CXXCastPath *BasePath, 369 CheckedConversionKind CCK) { 370 #ifndef NDEBUG 371 if (VK == VK_RValue && !E->isRValue()) { 372 switch (Kind) { 373 default: 374 llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast " 375 "kind"); 376 case CK_LValueToRValue: 377 case CK_ArrayToPointerDecay: 378 case CK_FunctionToPointerDecay: 379 case CK_ToVoid: 380 break; 381 } 382 } 383 assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue"); 384 #endif 385 386 diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getLocStart()); 387 388 QualType ExprTy = Context.getCanonicalType(E->getType()); 389 QualType TypeTy = Context.getCanonicalType(Ty); 390 391 if (ExprTy == TypeTy) 392 return E; 393 394 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) { 395 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) { 396 ImpCast->setType(Ty); 397 ImpCast->setValueKind(VK); 398 return E; 399 } 400 } 401 402 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK); 403 } 404 405 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 406 /// to the conversion from scalar type ScalarTy to the Boolean type. 407 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) { 408 switch (ScalarTy->getScalarTypeKind()) { 409 case Type::STK_Bool: return CK_NoOp; 410 case Type::STK_CPointer: return CK_PointerToBoolean; 411 case Type::STK_BlockPointer: return CK_PointerToBoolean; 412 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean; 413 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean; 414 case Type::STK_Integral: return CK_IntegralToBoolean; 415 case Type::STK_Floating: return CK_FloatingToBoolean; 416 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean; 417 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean; 418 } 419 return CK_Invalid; 420 } 421 422 /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector. 423 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) { 424 if (D->getMostRecentDecl()->isUsed()) 425 return true; 426 427 if (D->isExternallyVisible()) 428 return true; 429 430 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 431 // UnusedFileScopedDecls stores the first declaration. 432 // The declaration may have become definition so check again. 433 const FunctionDecl *DeclToCheck; 434 if (FD->hasBody(DeclToCheck)) 435 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 436 437 // Later redecls may add new information resulting in not having to warn, 438 // so check again. 439 DeclToCheck = FD->getMostRecentDecl(); 440 if (DeclToCheck != FD) 441 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 442 } 443 444 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 445 // If a variable usable in constant expressions is referenced, 446 // don't warn if it isn't used: if the value of a variable is required 447 // for the computation of a constant expression, it doesn't make sense to 448 // warn even if the variable isn't odr-used. (isReferenced doesn't 449 // precisely reflect that, but it's a decent approximation.) 450 if (VD->isReferenced() && 451 VD->isUsableInConstantExpressions(SemaRef->Context)) 452 return true; 453 454 // UnusedFileScopedDecls stores the first declaration. 455 // The declaration may have become definition so check again. 456 const VarDecl *DeclToCheck = VD->getDefinition(); 457 if (DeclToCheck) 458 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 459 460 // Later redecls may add new information resulting in not having to warn, 461 // so check again. 462 DeclToCheck = VD->getMostRecentDecl(); 463 if (DeclToCheck != VD) 464 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 465 } 466 467 return false; 468 } 469 470 /// Obtains a sorted list of functions and variables that are undefined but 471 /// ODR-used. 472 void Sema::getUndefinedButUsed( 473 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) { 474 for (const auto &UndefinedUse : UndefinedButUsed) { 475 NamedDecl *ND = UndefinedUse.first; 476 477 // Ignore attributes that have become invalid. 478 if (ND->isInvalidDecl()) continue; 479 480 // __attribute__((weakref)) is basically a definition. 481 if (ND->hasAttr<WeakRefAttr>()) continue; 482 483 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 484 if (FD->isDefined()) 485 continue; 486 if (FD->isExternallyVisible() && 487 !FD->getMostRecentDecl()->isInlined()) 488 continue; 489 } else { 490 auto *VD = cast<VarDecl>(ND); 491 if (VD->hasDefinition() != VarDecl::DeclarationOnly) 492 continue; 493 if (VD->isExternallyVisible() && !VD->getMostRecentDecl()->isInline()) 494 continue; 495 } 496 497 Undefined.push_back(std::make_pair(ND, UndefinedUse.second)); 498 } 499 } 500 501 /// checkUndefinedButUsed - Check for undefined objects with internal linkage 502 /// or that are inline. 503 static void checkUndefinedButUsed(Sema &S) { 504 if (S.UndefinedButUsed.empty()) return; 505 506 // Collect all the still-undefined entities with internal linkage. 507 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined; 508 S.getUndefinedButUsed(Undefined); 509 if (Undefined.empty()) return; 510 511 for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator 512 I = Undefined.begin(), E = Undefined.end(); I != E; ++I) { 513 NamedDecl *ND = I->first; 514 515 if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) { 516 // An exported function will always be emitted when defined, so even if 517 // the function is inline, it doesn't have to be emitted in this TU. An 518 // imported function implies that it has been exported somewhere else. 519 continue; 520 } 521 522 if (!ND->isExternallyVisible()) { 523 S.Diag(ND->getLocation(), diag::warn_undefined_internal) 524 << isa<VarDecl>(ND) << ND; 525 } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) { 526 (void)FD; 527 assert(FD->getMostRecentDecl()->isInlined() && 528 "used object requires definition but isn't inline or internal?"); 529 // FIXME: This is ill-formed; we should reject. 530 S.Diag(ND->getLocation(), diag::warn_undefined_inline) << ND; 531 } else { 532 assert(cast<VarDecl>(ND)->getMostRecentDecl()->isInline() && 533 "used var requires definition but isn't inline or internal?"); 534 S.Diag(ND->getLocation(), diag::err_undefined_inline_var) << ND; 535 } 536 if (I->second.isValid()) 537 S.Diag(I->second, diag::note_used_here); 538 } 539 540 S.UndefinedButUsed.clear(); 541 } 542 543 void Sema::LoadExternalWeakUndeclaredIdentifiers() { 544 if (!ExternalSource) 545 return; 546 547 SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs; 548 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs); 549 for (auto &WeakID : WeakIDs) 550 WeakUndeclaredIdentifiers.insert(WeakID); 551 } 552 553 554 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap; 555 556 /// \brief Returns true, if all methods and nested classes of the given 557 /// CXXRecordDecl are defined in this translation unit. 558 /// 559 /// Should only be called from ActOnEndOfTranslationUnit so that all 560 /// definitions are actually read. 561 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD, 562 RecordCompleteMap &MNCComplete) { 563 RecordCompleteMap::iterator Cache = MNCComplete.find(RD); 564 if (Cache != MNCComplete.end()) 565 return Cache->second; 566 if (!RD->isCompleteDefinition()) 567 return false; 568 bool Complete = true; 569 for (DeclContext::decl_iterator I = RD->decls_begin(), 570 E = RD->decls_end(); 571 I != E && Complete; ++I) { 572 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I)) 573 Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M)); 574 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I)) 575 // If the template function is marked as late template parsed at this 576 // point, it has not been instantiated and therefore we have not 577 // performed semantic analysis on it yet, so we cannot know if the type 578 // can be considered complete. 579 Complete = !F->getTemplatedDecl()->isLateTemplateParsed() && 580 F->getTemplatedDecl()->isDefined(); 581 else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) { 582 if (R->isInjectedClassName()) 583 continue; 584 if (R->hasDefinition()) 585 Complete = MethodsAndNestedClassesComplete(R->getDefinition(), 586 MNCComplete); 587 else 588 Complete = false; 589 } 590 } 591 MNCComplete[RD] = Complete; 592 return Complete; 593 } 594 595 /// \brief Returns true, if the given CXXRecordDecl is fully defined in this 596 /// translation unit, i.e. all methods are defined or pure virtual and all 597 /// friends, friend functions and nested classes are fully defined in this 598 /// translation unit. 599 /// 600 /// Should only be called from ActOnEndOfTranslationUnit so that all 601 /// definitions are actually read. 602 static bool IsRecordFullyDefined(const CXXRecordDecl *RD, 603 RecordCompleteMap &RecordsComplete, 604 RecordCompleteMap &MNCComplete) { 605 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD); 606 if (Cache != RecordsComplete.end()) 607 return Cache->second; 608 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete); 609 for (CXXRecordDecl::friend_iterator I = RD->friend_begin(), 610 E = RD->friend_end(); 611 I != E && Complete; ++I) { 612 // Check if friend classes and methods are complete. 613 if (TypeSourceInfo *TSI = (*I)->getFriendType()) { 614 // Friend classes are available as the TypeSourceInfo of the FriendDecl. 615 if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl()) 616 Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete); 617 else 618 Complete = false; 619 } else { 620 // Friend functions are available through the NamedDecl of FriendDecl. 621 if (const FunctionDecl *FD = 622 dyn_cast<FunctionDecl>((*I)->getFriendDecl())) 623 Complete = FD->isDefined(); 624 else 625 // This is a template friend, give up. 626 Complete = false; 627 } 628 } 629 RecordsComplete[RD] = Complete; 630 return Complete; 631 } 632 633 void Sema::emitAndClearUnusedLocalTypedefWarnings() { 634 if (ExternalSource) 635 ExternalSource->ReadUnusedLocalTypedefNameCandidates( 636 UnusedLocalTypedefNameCandidates); 637 for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) { 638 if (TD->isReferenced()) 639 continue; 640 Diag(TD->getLocation(), diag::warn_unused_local_typedef) 641 << isa<TypeAliasDecl>(TD) << TD->getDeclName(); 642 } 643 UnusedLocalTypedefNameCandidates.clear(); 644 } 645 646 /// ActOnEndOfTranslationUnit - This is called at the very end of the 647 /// translation unit when EOF is reached and all but the top-level scope is 648 /// popped. 649 void Sema::ActOnEndOfTranslationUnit() { 650 assert(DelayedDiagnostics.getCurrentPool() == nullptr 651 && "reached end of translation unit with a pool attached?"); 652 653 // If code completion is enabled, don't perform any end-of-translation-unit 654 // work. 655 if (PP.isCodeCompletionEnabled()) 656 return; 657 658 // Complete translation units and modules define vtables and perform implicit 659 // instantiations. PCH files do not. 660 if (TUKind != TU_Prefix) { 661 DiagnoseUseOfUnimplementedSelectors(); 662 663 // If DefinedUsedVTables ends up marking any virtual member functions it 664 // might lead to more pending template instantiations, which we then need 665 // to instantiate. 666 DefineUsedVTables(); 667 668 // C++: Perform implicit template instantiations. 669 // 670 // FIXME: When we perform these implicit instantiations, we do not 671 // carefully keep track of the point of instantiation (C++ [temp.point]). 672 // This means that name lookup that occurs within the template 673 // instantiation will always happen at the end of the translation unit, 674 // so it will find some names that are not required to be found. This is 675 // valid, but we could do better by diagnosing if an instantiation uses a 676 // name that was not visible at its first point of instantiation. 677 if (ExternalSource) { 678 // Load pending instantiations from the external source. 679 SmallVector<PendingImplicitInstantiation, 4> Pending; 680 ExternalSource->ReadPendingInstantiations(Pending); 681 PendingInstantiations.insert(PendingInstantiations.begin(), 682 Pending.begin(), Pending.end()); 683 } 684 PerformPendingInstantiations(); 685 686 if (LateTemplateParserCleanup) 687 LateTemplateParserCleanup(OpaqueParser); 688 689 CheckDelayedMemberExceptionSpecs(); 690 } 691 692 // All delayed member exception specs should be checked or we end up accepting 693 // incompatible declarations. 694 // FIXME: This is wrong for TUKind == TU_Prefix. In that case, we need to 695 // write out the lists to the AST file (if any). 696 assert(DelayedDefaultedMemberExceptionSpecs.empty()); 697 assert(DelayedExceptionSpecChecks.empty()); 698 699 // All dllexport classes should have been processed already. 700 assert(DelayedDllExportClasses.empty()); 701 702 // Remove file scoped decls that turned out to be used. 703 UnusedFileScopedDecls.erase( 704 std::remove_if(UnusedFileScopedDecls.begin(nullptr, true), 705 UnusedFileScopedDecls.end(), 706 std::bind1st(std::ptr_fun(ShouldRemoveFromUnused), this)), 707 UnusedFileScopedDecls.end()); 708 709 if (TUKind == TU_Prefix) { 710 // Translation unit prefixes don't need any of the checking below. 711 TUScope = nullptr; 712 return; 713 } 714 715 // Check for #pragma weak identifiers that were never declared 716 LoadExternalWeakUndeclaredIdentifiers(); 717 for (auto WeakID : WeakUndeclaredIdentifiers) { 718 if (WeakID.second.getUsed()) 719 continue; 720 721 Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(), 722 LookupOrdinaryName); 723 if (PrevDecl != nullptr && 724 !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) 725 Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type) 726 << "'weak'" << ExpectedVariableOrFunction; 727 else 728 Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared) 729 << WeakID.first; 730 } 731 732 if (LangOpts.CPlusPlus11 && 733 !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation())) 734 CheckDelegatingCtorCycles(); 735 736 if (!Diags.hasErrorOccurred()) { 737 if (ExternalSource) 738 ExternalSource->ReadUndefinedButUsed(UndefinedButUsed); 739 checkUndefinedButUsed(*this); 740 } 741 742 if (TUKind == TU_Module) { 743 // If we are building a module, resolve all of the exported declarations 744 // now. 745 if (Module *CurrentModule = PP.getCurrentModule()) { 746 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap(); 747 748 SmallVector<Module *, 2> Stack; 749 Stack.push_back(CurrentModule); 750 while (!Stack.empty()) { 751 Module *Mod = Stack.pop_back_val(); 752 753 // Resolve the exported declarations and conflicts. 754 // FIXME: Actually complain, once we figure out how to teach the 755 // diagnostic client to deal with complaints in the module map at this 756 // point. 757 ModMap.resolveExports(Mod, /*Complain=*/false); 758 ModMap.resolveUses(Mod, /*Complain=*/false); 759 ModMap.resolveConflicts(Mod, /*Complain=*/false); 760 761 // Queue the submodules, so their exports will also be resolved. 762 Stack.append(Mod->submodule_begin(), Mod->submodule_end()); 763 } 764 } 765 766 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for 767 // modules when they are built, not every time they are used. 768 emitAndClearUnusedLocalTypedefWarnings(); 769 770 // Modules don't need any of the checking below. 771 TUScope = nullptr; 772 return; 773 } 774 775 // C99 6.9.2p2: 776 // A declaration of an identifier for an object that has file 777 // scope without an initializer, and without a storage-class 778 // specifier or with the storage-class specifier static, 779 // constitutes a tentative definition. If a translation unit 780 // contains one or more tentative definitions for an identifier, 781 // and the translation unit contains no external definition for 782 // that identifier, then the behavior is exactly as if the 783 // translation unit contains a file scope declaration of that 784 // identifier, with the composite type as of the end of the 785 // translation unit, with an initializer equal to 0. 786 llvm::SmallSet<VarDecl *, 32> Seen; 787 for (TentativeDefinitionsType::iterator 788 T = TentativeDefinitions.begin(ExternalSource), 789 TEnd = TentativeDefinitions.end(); 790 T != TEnd; ++T) 791 { 792 VarDecl *VD = (*T)->getActingDefinition(); 793 794 // If the tentative definition was completed, getActingDefinition() returns 795 // null. If we've already seen this variable before, insert()'s second 796 // return value is false. 797 if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second) 798 continue; 799 800 if (const IncompleteArrayType *ArrayT 801 = Context.getAsIncompleteArrayType(VD->getType())) { 802 // Set the length of the array to 1 (C99 6.9.2p5). 803 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 804 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 805 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), 806 One, ArrayType::Normal, 0); 807 VD->setType(T); 808 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 809 diag::err_tentative_def_incomplete_type)) 810 VD->setInvalidDecl(); 811 812 // No initialization is performed for a tentative definition. 813 CheckCompleteVariableDeclaration(VD); 814 815 // Notify the consumer that we've completed a tentative definition. 816 if (!VD->isInvalidDecl()) 817 Consumer.CompleteTentativeDefinition(VD); 818 819 } 820 821 // If there were errors, disable 'unused' warnings since they will mostly be 822 // noise. 823 if (!Diags.hasErrorOccurred()) { 824 // Output warning for unused file scoped decls. 825 for (UnusedFileScopedDeclsType::iterator 826 I = UnusedFileScopedDecls.begin(ExternalSource), 827 E = UnusedFileScopedDecls.end(); I != E; ++I) { 828 if (ShouldRemoveFromUnused(this, *I)) 829 continue; 830 831 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 832 const FunctionDecl *DiagD; 833 if (!FD->hasBody(DiagD)) 834 DiagD = FD; 835 if (DiagD->isDeleted()) 836 continue; // Deleted functions are supposed to be unused. 837 if (DiagD->isReferenced()) { 838 if (isa<CXXMethodDecl>(DiagD)) 839 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function) 840 << DiagD->getDeclName(); 841 else { 842 if (FD->getStorageClass() == SC_Static && 843 !FD->isInlineSpecified() && 844 !SourceMgr.isInMainFile( 845 SourceMgr.getExpansionLoc(FD->getLocation()))) 846 Diag(DiagD->getLocation(), 847 diag::warn_unneeded_static_internal_decl) 848 << DiagD->getDeclName(); 849 else 850 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 851 << /*function*/0 << DiagD->getDeclName(); 852 } 853 } else { 854 Diag(DiagD->getLocation(), 855 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function 856 : diag::warn_unused_function) 857 << DiagD->getDeclName(); 858 } 859 } else { 860 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition(); 861 if (!DiagD) 862 DiagD = cast<VarDecl>(*I); 863 if (DiagD->isReferenced()) { 864 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 865 << /*variable*/1 << DiagD->getDeclName(); 866 } else if (DiagD->getType().isConstQualified()) { 867 Diag(DiagD->getLocation(), diag::warn_unused_const_variable) 868 << DiagD->getDeclName(); 869 } else { 870 Diag(DiagD->getLocation(), diag::warn_unused_variable) 871 << DiagD->getDeclName(); 872 } 873 } 874 } 875 876 emitAndClearUnusedLocalTypedefWarnings(); 877 } 878 879 if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) { 880 RecordCompleteMap RecordsComplete; 881 RecordCompleteMap MNCComplete; 882 for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(), 883 E = UnusedPrivateFields.end(); I != E; ++I) { 884 const NamedDecl *D = *I; 885 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()); 886 if (RD && !RD->isUnion() && 887 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) { 888 Diag(D->getLocation(), diag::warn_unused_private_field) 889 << D->getDeclName(); 890 } 891 } 892 } 893 894 if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) { 895 if (ExternalSource) 896 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs); 897 for (const auto &DeletedFieldInfo : DeleteExprs) { 898 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) { 899 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first, 900 DeleteExprLoc.second); 901 } 902 } 903 } 904 905 // Check we've noticed that we're no longer parsing the initializer for every 906 // variable. If we miss cases, then at best we have a performance issue and 907 // at worst a rejects-valid bug. 908 assert(ParsingInitForAutoVars.empty() && 909 "Didn't unmark var as having its initializer parsed"); 910 911 TUScope = nullptr; 912 } 913 914 915 //===----------------------------------------------------------------------===// 916 // Helper functions. 917 //===----------------------------------------------------------------------===// 918 919 DeclContext *Sema::getFunctionLevelDeclContext() { 920 DeclContext *DC = CurContext; 921 922 while (true) { 923 if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) { 924 DC = DC->getParent(); 925 } else if (isa<CXXMethodDecl>(DC) && 926 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 927 cast<CXXRecordDecl>(DC->getParent())->isLambda()) { 928 DC = DC->getParent()->getParent(); 929 } 930 else break; 931 } 932 933 return DC; 934 } 935 936 /// getCurFunctionDecl - If inside of a function body, this returns a pointer 937 /// to the function decl for the function being parsed. If we're currently 938 /// in a 'block', this returns the containing context. 939 FunctionDecl *Sema::getCurFunctionDecl() { 940 DeclContext *DC = getFunctionLevelDeclContext(); 941 return dyn_cast<FunctionDecl>(DC); 942 } 943 944 ObjCMethodDecl *Sema::getCurMethodDecl() { 945 DeclContext *DC = getFunctionLevelDeclContext(); 946 while (isa<RecordDecl>(DC)) 947 DC = DC->getParent(); 948 return dyn_cast<ObjCMethodDecl>(DC); 949 } 950 951 NamedDecl *Sema::getCurFunctionOrMethodDecl() { 952 DeclContext *DC = getFunctionLevelDeclContext(); 953 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 954 return cast<NamedDecl>(DC); 955 return nullptr; 956 } 957 958 void Sema::EmitCurrentDiagnostic(unsigned DiagID) { 959 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here 960 // and yet we also use the current diag ID on the DiagnosticsEngine. This has 961 // been made more painfully obvious by the refactor that introduced this 962 // function, but it is possible that the incoming argument can be 963 // eliminnated. If it truly cannot be (for example, there is some reentrancy 964 // issue I am not seeing yet), then there should at least be a clarifying 965 // comment somewhere. 966 if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) { 967 switch (DiagnosticIDs::getDiagnosticSFINAEResponse( 968 Diags.getCurrentDiagID())) { 969 case DiagnosticIDs::SFINAE_Report: 970 // We'll report the diagnostic below. 971 break; 972 973 case DiagnosticIDs::SFINAE_SubstitutionFailure: 974 // Count this failure so that we know that template argument deduction 975 // has failed. 976 ++NumSFINAEErrors; 977 978 // Make a copy of this suppressed diagnostic and store it with the 979 // template-deduction information. 980 if (*Info && !(*Info)->hasSFINAEDiagnostic()) { 981 Diagnostic DiagInfo(&Diags); 982 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(), 983 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 984 } 985 986 Diags.setLastDiagnosticIgnored(); 987 Diags.Clear(); 988 return; 989 990 case DiagnosticIDs::SFINAE_AccessControl: { 991 // Per C++ Core Issue 1170, access control is part of SFINAE. 992 // Additionally, the AccessCheckingSFINAE flag can be used to temporarily 993 // make access control a part of SFINAE for the purposes of checking 994 // type traits. 995 if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11) 996 break; 997 998 SourceLocation Loc = Diags.getCurrentDiagLoc(); 999 1000 // Suppress this diagnostic. 1001 ++NumSFINAEErrors; 1002 1003 // Make a copy of this suppressed diagnostic and store it with the 1004 // template-deduction information. 1005 if (*Info && !(*Info)->hasSFINAEDiagnostic()) { 1006 Diagnostic DiagInfo(&Diags); 1007 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(), 1008 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 1009 } 1010 1011 Diags.setLastDiagnosticIgnored(); 1012 Diags.Clear(); 1013 1014 // Now the diagnostic state is clear, produce a C++98 compatibility 1015 // warning. 1016 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control); 1017 1018 // The last diagnostic which Sema produced was ignored. Suppress any 1019 // notes attached to it. 1020 Diags.setLastDiagnosticIgnored(); 1021 return; 1022 } 1023 1024 case DiagnosticIDs::SFINAE_Suppress: 1025 // Make a copy of this suppressed diagnostic and store it with the 1026 // template-deduction information; 1027 if (*Info) { 1028 Diagnostic DiagInfo(&Diags); 1029 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(), 1030 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 1031 } 1032 1033 // Suppress this diagnostic. 1034 Diags.setLastDiagnosticIgnored(); 1035 Diags.Clear(); 1036 return; 1037 } 1038 } 1039 1040 // Set up the context's printing policy based on our current state. 1041 Context.setPrintingPolicy(getPrintingPolicy()); 1042 1043 // Emit the diagnostic. 1044 if (!Diags.EmitCurrentDiagnostic()) 1045 return; 1046 1047 // If this is not a note, and we're in a template instantiation 1048 // that is different from the last template instantiation where 1049 // we emitted an error, print a template instantiation 1050 // backtrace. 1051 if (!DiagnosticIDs::isBuiltinNote(DiagID) && 1052 !ActiveTemplateInstantiations.empty() && 1053 ActiveTemplateInstantiations.back() 1054 != LastTemplateInstantiationErrorContext) { 1055 PrintInstantiationStack(); 1056 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiations.back(); 1057 } 1058 } 1059 1060 Sema::SemaDiagnosticBuilder 1061 Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) { 1062 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID())); 1063 PD.Emit(Builder); 1064 1065 return Builder; 1066 } 1067 1068 /// \brief Looks through the macro-expansion chain for the given 1069 /// location, looking for a macro expansion with the given name. 1070 /// If one is found, returns true and sets the location to that 1071 /// expansion loc. 1072 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) { 1073 SourceLocation loc = locref; 1074 if (!loc.isMacroID()) return false; 1075 1076 // There's no good way right now to look at the intermediate 1077 // expansions, so just jump to the expansion location. 1078 loc = getSourceManager().getExpansionLoc(loc); 1079 1080 // If that's written with the name, stop here. 1081 SmallVector<char, 16> buffer; 1082 if (getPreprocessor().getSpelling(loc, buffer) == name) { 1083 locref = loc; 1084 return true; 1085 } 1086 return false; 1087 } 1088 1089 /// \brief Determines the active Scope associated with the given declaration 1090 /// context. 1091 /// 1092 /// This routine maps a declaration context to the active Scope object that 1093 /// represents that declaration context in the parser. It is typically used 1094 /// from "scope-less" code (e.g., template instantiation, lazy creation of 1095 /// declarations) that injects a name for name-lookup purposes and, therefore, 1096 /// must update the Scope. 1097 /// 1098 /// \returns The scope corresponding to the given declaraion context, or NULL 1099 /// if no such scope is open. 1100 Scope *Sema::getScopeForContext(DeclContext *Ctx) { 1101 1102 if (!Ctx) 1103 return nullptr; 1104 1105 Ctx = Ctx->getPrimaryContext(); 1106 for (Scope *S = getCurScope(); S; S = S->getParent()) { 1107 // Ignore scopes that cannot have declarations. This is important for 1108 // out-of-line definitions of static class members. 1109 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) 1110 if (DeclContext *Entity = S->getEntity()) 1111 if (Ctx == Entity->getPrimaryContext()) 1112 return S; 1113 } 1114 1115 return nullptr; 1116 } 1117 1118 /// \brief Enter a new function scope 1119 void Sema::PushFunctionScope() { 1120 if (FunctionScopes.size() == 1) { 1121 // Use the "top" function scope rather than having to allocate 1122 // memory for a new scope. 1123 FunctionScopes.back()->Clear(); 1124 FunctionScopes.push_back(FunctionScopes.back()); 1125 return; 1126 } 1127 1128 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics())); 1129 } 1130 1131 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) { 1132 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(), 1133 BlockScope, Block)); 1134 } 1135 1136 LambdaScopeInfo *Sema::PushLambdaScope() { 1137 LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics()); 1138 FunctionScopes.push_back(LSI); 1139 return LSI; 1140 } 1141 1142 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) { 1143 if (LambdaScopeInfo *const LSI = getCurLambda()) { 1144 LSI->AutoTemplateParameterDepth = Depth; 1145 return; 1146 } 1147 llvm_unreachable( 1148 "Remove assertion if intentionally called in a non-lambda context."); 1149 } 1150 1151 void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP, 1152 const Decl *D, const BlockExpr *blkExpr) { 1153 FunctionScopeInfo *Scope = FunctionScopes.pop_back_val(); 1154 assert(!FunctionScopes.empty() && "mismatched push/pop!"); 1155 1156 // Issue any analysis-based warnings. 1157 if (WP && D) 1158 AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr); 1159 else 1160 for (const auto &PUD : Scope->PossiblyUnreachableDiags) 1161 Diag(PUD.Loc, PUD.PD); 1162 1163 if (FunctionScopes.back() != Scope) 1164 delete Scope; 1165 } 1166 1167 void Sema::PushCompoundScope() { 1168 getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo()); 1169 } 1170 1171 void Sema::PopCompoundScope() { 1172 FunctionScopeInfo *CurFunction = getCurFunction(); 1173 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop"); 1174 1175 CurFunction->CompoundScopes.pop_back(); 1176 } 1177 1178 /// \brief Determine whether any errors occurred within this function/method/ 1179 /// block. 1180 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const { 1181 return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred(); 1182 } 1183 1184 BlockScopeInfo *Sema::getCurBlock() { 1185 if (FunctionScopes.empty()) 1186 return nullptr; 1187 1188 auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back()); 1189 if (CurBSI && CurBSI->TheDecl && 1190 !CurBSI->TheDecl->Encloses(CurContext)) { 1191 // We have switched contexts due to template instantiation. 1192 assert(!ActiveTemplateInstantiations.empty()); 1193 return nullptr; 1194 } 1195 1196 return CurBSI; 1197 } 1198 1199 LambdaScopeInfo *Sema::getCurLambda() { 1200 if (FunctionScopes.empty()) 1201 return nullptr; 1202 1203 auto CurLSI = dyn_cast<LambdaScopeInfo>(FunctionScopes.back()); 1204 if (CurLSI && CurLSI->Lambda && 1205 !CurLSI->Lambda->Encloses(CurContext)) { 1206 // We have switched contexts due to template instantiation. 1207 assert(!ActiveTemplateInstantiations.empty()); 1208 return nullptr; 1209 } 1210 1211 return CurLSI; 1212 } 1213 // We have a generic lambda if we parsed auto parameters, or we have 1214 // an associated template parameter list. 1215 LambdaScopeInfo *Sema::getCurGenericLambda() { 1216 if (LambdaScopeInfo *LSI = getCurLambda()) { 1217 return (LSI->AutoTemplateParams.size() || 1218 LSI->GLTemplateParameterList) ? LSI : nullptr; 1219 } 1220 return nullptr; 1221 } 1222 1223 1224 void Sema::ActOnComment(SourceRange Comment) { 1225 if (!LangOpts.RetainCommentsFromSystemHeaders && 1226 SourceMgr.isInSystemHeader(Comment.getBegin())) 1227 return; 1228 RawComment RC(SourceMgr, Comment, false, 1229 LangOpts.CommentOpts.ParseAllComments); 1230 if (RC.isAlmostTrailingComment()) { 1231 SourceRange MagicMarkerRange(Comment.getBegin(), 1232 Comment.getBegin().getLocWithOffset(3)); 1233 StringRef MagicMarkerText; 1234 switch (RC.getKind()) { 1235 case RawComment::RCK_OrdinaryBCPL: 1236 MagicMarkerText = "///<"; 1237 break; 1238 case RawComment::RCK_OrdinaryC: 1239 MagicMarkerText = "/**<"; 1240 break; 1241 default: 1242 llvm_unreachable("if this is an almost Doxygen comment, " 1243 "it should be ordinary"); 1244 } 1245 Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) << 1246 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText); 1247 } 1248 Context.addComment(RC); 1249 } 1250 1251 // Pin this vtable to this file. 1252 ExternalSemaSource::~ExternalSemaSource() {} 1253 1254 void ExternalSemaSource::ReadMethodPool(Selector Sel) { } 1255 void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { } 1256 1257 void ExternalSemaSource::ReadKnownNamespaces( 1258 SmallVectorImpl<NamespaceDecl *> &Namespaces) { 1259 } 1260 1261 void ExternalSemaSource::ReadUndefinedButUsed( 1262 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {} 1263 1264 void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector< 1265 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {} 1266 1267 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const { 1268 SourceLocation Loc = this->Loc; 1269 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation(); 1270 if (Loc.isValid()) { 1271 Loc.print(OS, S.getSourceManager()); 1272 OS << ": "; 1273 } 1274 OS << Message; 1275 1276 if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) { 1277 OS << " '"; 1278 ND->getNameForDiagnostic(OS, ND->getASTContext().getPrintingPolicy(), true); 1279 OS << "'"; 1280 } 1281 1282 OS << '\n'; 1283 } 1284 1285 /// \brief Figure out if an expression could be turned into a call. 1286 /// 1287 /// Use this when trying to recover from an error where the programmer may have 1288 /// written just the name of a function instead of actually calling it. 1289 /// 1290 /// \param E - The expression to examine. 1291 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call 1292 /// with no arguments, this parameter is set to the type returned by such a 1293 /// call; otherwise, it is set to an empty QualType. 1294 /// \param OverloadSet - If the expression is an overloaded function 1295 /// name, this parameter is populated with the decls of the various overloads. 1296 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, 1297 UnresolvedSetImpl &OverloadSet) { 1298 ZeroArgCallReturnTy = QualType(); 1299 OverloadSet.clear(); 1300 1301 const OverloadExpr *Overloads = nullptr; 1302 bool IsMemExpr = false; 1303 if (E.getType() == Context.OverloadTy) { 1304 OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E)); 1305 1306 // Ignore overloads that are pointer-to-member constants. 1307 if (FR.HasFormOfMemberPointer) 1308 return false; 1309 1310 Overloads = FR.Expression; 1311 } else if (E.getType() == Context.BoundMemberTy) { 1312 Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens()); 1313 IsMemExpr = true; 1314 } 1315 1316 bool Ambiguous = false; 1317 1318 if (Overloads) { 1319 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(), 1320 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) { 1321 OverloadSet.addDecl(*it); 1322 1323 // Check whether the function is a non-template, non-member which takes no 1324 // arguments. 1325 if (IsMemExpr) 1326 continue; 1327 if (const FunctionDecl *OverloadDecl 1328 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) { 1329 if (OverloadDecl->getMinRequiredArguments() == 0) { 1330 if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) { 1331 ZeroArgCallReturnTy = QualType(); 1332 Ambiguous = true; 1333 } else 1334 ZeroArgCallReturnTy = OverloadDecl->getReturnType(); 1335 } 1336 } 1337 } 1338 1339 // If it's not a member, use better machinery to try to resolve the call 1340 if (!IsMemExpr) 1341 return !ZeroArgCallReturnTy.isNull(); 1342 } 1343 1344 // Attempt to call the member with no arguments - this will correctly handle 1345 // member templates with defaults/deduction of template arguments, overloads 1346 // with default arguments, etc. 1347 if (IsMemExpr && !E.isTypeDependent()) { 1348 bool Suppress = getDiagnostics().getSuppressAllDiagnostics(); 1349 getDiagnostics().setSuppressAllDiagnostics(true); 1350 ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(), 1351 None, SourceLocation()); 1352 getDiagnostics().setSuppressAllDiagnostics(Suppress); 1353 if (R.isUsable()) { 1354 ZeroArgCallReturnTy = R.get()->getType(); 1355 return true; 1356 } 1357 return false; 1358 } 1359 1360 if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) { 1361 if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) { 1362 if (Fun->getMinRequiredArguments() == 0) 1363 ZeroArgCallReturnTy = Fun->getReturnType(); 1364 return true; 1365 } 1366 } 1367 1368 // We don't have an expression that's convenient to get a FunctionDecl from, 1369 // but we can at least check if the type is "function of 0 arguments". 1370 QualType ExprTy = E.getType(); 1371 const FunctionType *FunTy = nullptr; 1372 QualType PointeeTy = ExprTy->getPointeeType(); 1373 if (!PointeeTy.isNull()) 1374 FunTy = PointeeTy->getAs<FunctionType>(); 1375 if (!FunTy) 1376 FunTy = ExprTy->getAs<FunctionType>(); 1377 1378 if (const FunctionProtoType *FPT = 1379 dyn_cast_or_null<FunctionProtoType>(FunTy)) { 1380 if (FPT->getNumParams() == 0) 1381 ZeroArgCallReturnTy = FunTy->getReturnType(); 1382 return true; 1383 } 1384 return false; 1385 } 1386 1387 /// \brief Give notes for a set of overloads. 1388 /// 1389 /// A companion to tryExprAsCall. In cases when the name that the programmer 1390 /// wrote was an overloaded function, we may be able to make some guesses about 1391 /// plausible overloads based on their return types; such guesses can be handed 1392 /// off to this method to be emitted as notes. 1393 /// 1394 /// \param Overloads - The overloads to note. 1395 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to 1396 /// -fshow-overloads=best, this is the location to attach to the note about too 1397 /// many candidates. Typically this will be the location of the original 1398 /// ill-formed expression. 1399 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, 1400 const SourceLocation FinalNoteLoc) { 1401 int ShownOverloads = 0; 1402 int SuppressedOverloads = 0; 1403 for (UnresolvedSetImpl::iterator It = Overloads.begin(), 1404 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { 1405 // FIXME: Magic number for max shown overloads stolen from 1406 // OverloadCandidateSet::NoteCandidates. 1407 if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) { 1408 ++SuppressedOverloads; 1409 continue; 1410 } 1411 1412 NamedDecl *Fn = (*It)->getUnderlyingDecl(); 1413 S.Diag(Fn->getLocation(), diag::note_possible_target_of_call); 1414 ++ShownOverloads; 1415 } 1416 1417 if (SuppressedOverloads) 1418 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates) 1419 << SuppressedOverloads; 1420 } 1421 1422 static void notePlausibleOverloads(Sema &S, SourceLocation Loc, 1423 const UnresolvedSetImpl &Overloads, 1424 bool (*IsPlausibleResult)(QualType)) { 1425 if (!IsPlausibleResult) 1426 return noteOverloads(S, Overloads, Loc); 1427 1428 UnresolvedSet<2> PlausibleOverloads; 1429 for (OverloadExpr::decls_iterator It = Overloads.begin(), 1430 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { 1431 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It); 1432 QualType OverloadResultTy = OverloadDecl->getReturnType(); 1433 if (IsPlausibleResult(OverloadResultTy)) 1434 PlausibleOverloads.addDecl(It.getDecl()); 1435 } 1436 noteOverloads(S, PlausibleOverloads, Loc); 1437 } 1438 1439 /// Determine whether the given expression can be called by just 1440 /// putting parentheses after it. Notably, expressions with unary 1441 /// operators can't be because the unary operator will start parsing 1442 /// outside the call. 1443 static bool IsCallableWithAppend(Expr *E) { 1444 E = E->IgnoreImplicit(); 1445 return (!isa<CStyleCastExpr>(E) && 1446 !isa<UnaryOperator>(E) && 1447 !isa<BinaryOperator>(E) && 1448 !isa<CXXOperatorCallExpr>(E)); 1449 } 1450 1451 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 1452 bool ForceComplain, 1453 bool (*IsPlausibleResult)(QualType)) { 1454 SourceLocation Loc = E.get()->getExprLoc(); 1455 SourceRange Range = E.get()->getSourceRange(); 1456 1457 QualType ZeroArgCallTy; 1458 UnresolvedSet<4> Overloads; 1459 if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) && 1460 !ZeroArgCallTy.isNull() && 1461 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) { 1462 // At this point, we know E is potentially callable with 0 1463 // arguments and that it returns something of a reasonable type, 1464 // so we can emit a fixit and carry on pretending that E was 1465 // actually a CallExpr. 1466 SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd()); 1467 Diag(Loc, PD) 1468 << /*zero-arg*/ 1 << Range 1469 << (IsCallableWithAppend(E.get()) 1470 ? FixItHint::CreateInsertion(ParenInsertionLoc, "()") 1471 : FixItHint()); 1472 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult); 1473 1474 // FIXME: Try this before emitting the fixit, and suppress diagnostics 1475 // while doing so. 1476 E = ActOnCallExpr(nullptr, E.get(), Range.getEnd(), None, 1477 Range.getEnd().getLocWithOffset(1)); 1478 return true; 1479 } 1480 1481 if (!ForceComplain) return false; 1482 1483 Diag(Loc, PD) << /*not zero-arg*/ 0 << Range; 1484 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult); 1485 E = ExprError(); 1486 return true; 1487 } 1488 1489 IdentifierInfo *Sema::getSuperIdentifier() const { 1490 if (!Ident_super) 1491 Ident_super = &Context.Idents.get("super"); 1492 return Ident_super; 1493 } 1494 1495 IdentifierInfo *Sema::getFloat128Identifier() const { 1496 if (!Ident___float128) 1497 Ident___float128 = &Context.Idents.get("__float128"); 1498 return Ident___float128; 1499 } 1500 1501 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD, 1502 CapturedRegionKind K) { 1503 CapturingScopeInfo *CSI = new CapturedRegionScopeInfo( 1504 getDiagnostics(), S, CD, RD, CD->getContextParam(), K, 1505 (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0); 1506 CSI->ReturnType = Context.VoidTy; 1507 FunctionScopes.push_back(CSI); 1508 } 1509 1510 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() { 1511 if (FunctionScopes.empty()) 1512 return nullptr; 1513 1514 return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back()); 1515 } 1516 1517 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> & 1518 Sema::getMismatchingDeleteExpressions() const { 1519 return DeleteExprs; 1520 } 1521