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