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