1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the actions class which performs semantic analysis and 10 // builds an AST out of a parse stream. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "UsedDeclVisitor.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTDiagnostic.h" 17 #include "clang/AST/Decl.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/PrettyDeclStackTrace.h" 24 #include "clang/AST/StmtCXX.h" 25 #include "clang/Basic/DarwinSDKInfo.h" 26 #include "clang/Basic/DiagnosticOptions.h" 27 #include "clang/Basic/PartialDiagnostic.h" 28 #include "clang/Basic/SourceManager.h" 29 #include "clang/Basic/Stack.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" 32 #include "clang/Lex/HeaderSearchOptions.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/CXXFieldCollector.h" 35 #include "clang/Sema/DelayedDiagnostic.h" 36 #include "clang/Sema/ExternalSemaSource.h" 37 #include "clang/Sema/Initialization.h" 38 #include "clang/Sema/MultiplexExternalSemaSource.h" 39 #include "clang/Sema/ObjCMethodList.h" 40 #include "clang/Sema/Scope.h" 41 #include "clang/Sema/ScopeInfo.h" 42 #include "clang/Sema/SemaConsumer.h" 43 #include "clang/Sema/SemaInternal.h" 44 #include "clang/Sema/TemplateDeduction.h" 45 #include "clang/Sema/TemplateInstCallback.h" 46 #include "clang/Sema/TypoCorrection.h" 47 #include "llvm/ADT/DenseMap.h" 48 #include "llvm/ADT/SmallPtrSet.h" 49 #include "llvm/Support/TimeProfiler.h" 50 51 using namespace clang; 52 using namespace sema; 53 54 SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) { 55 return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts); 56 } 57 58 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); } 59 60 DarwinSDKInfo * 61 Sema::getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc, 62 StringRef Platform) { 63 auto *SDKInfo = getDarwinSDKInfoForAvailabilityChecking(); 64 if (!SDKInfo && !WarnedDarwinSDKInfoMissing) { 65 Diag(Loc, diag::warn_missing_sdksettings_for_availability_checking) 66 << Platform; 67 WarnedDarwinSDKInfoMissing = true; 68 } 69 return SDKInfo; 70 } 71 72 DarwinSDKInfo *Sema::getDarwinSDKInfoForAvailabilityChecking() { 73 if (CachedDarwinSDKInfo) 74 return CachedDarwinSDKInfo->get(); 75 auto SDKInfo = parseDarwinSDKInfo( 76 PP.getFileManager().getVirtualFileSystem(), 77 PP.getHeaderSearchInfo().getHeaderSearchOpts().Sysroot); 78 if (SDKInfo && *SDKInfo) { 79 CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(std::move(**SDKInfo)); 80 return CachedDarwinSDKInfo->get(); 81 } 82 if (!SDKInfo) 83 llvm::consumeError(SDKInfo.takeError()); 84 CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>(); 85 return nullptr; 86 } 87 88 IdentifierInfo * 89 Sema::InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName, 90 unsigned int Index) { 91 std::string InventedName; 92 llvm::raw_string_ostream OS(InventedName); 93 94 if (!ParamName) 95 OS << "auto:" << Index + 1; 96 else 97 OS << ParamName->getName() << ":auto"; 98 99 OS.flush(); 100 return &Context.Idents.get(OS.str()); 101 } 102 103 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context, 104 const Preprocessor &PP) { 105 PrintingPolicy Policy = Context.getPrintingPolicy(); 106 // In diagnostics, we print _Bool as bool if the latter is defined as the 107 // former. 108 Policy.Bool = Context.getLangOpts().Bool; 109 if (!Policy.Bool) { 110 if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) { 111 Policy.Bool = BoolMacro->isObjectLike() && 112 BoolMacro->getNumTokens() == 1 && 113 BoolMacro->getReplacementToken(0).is(tok::kw__Bool); 114 } 115 } 116 117 return Policy; 118 } 119 120 void Sema::ActOnTranslationUnitScope(Scope *S) { 121 TUScope = S; 122 PushDeclContext(S, Context.getTranslationUnitDecl()); 123 } 124 125 namespace clang { 126 namespace sema { 127 128 class SemaPPCallbacks : public PPCallbacks { 129 Sema *S = nullptr; 130 llvm::SmallVector<SourceLocation, 8> IncludeStack; 131 132 public: 133 void set(Sema &S) { this->S = &S; } 134 135 void reset() { S = nullptr; } 136 137 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason, 138 SrcMgr::CharacteristicKind FileType, 139 FileID PrevFID) override { 140 if (!S) 141 return; 142 switch (Reason) { 143 case EnterFile: { 144 SourceManager &SM = S->getSourceManager(); 145 SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc)); 146 if (IncludeLoc.isValid()) { 147 if (llvm::timeTraceProfilerEnabled()) { 148 const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc)); 149 llvm::timeTraceProfilerBegin( 150 "Source", FE != nullptr ? FE->getName() : StringRef("<unknown>")); 151 } 152 153 IncludeStack.push_back(IncludeLoc); 154 S->DiagnoseNonDefaultPragmaAlignPack( 155 Sema::PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude, 156 IncludeLoc); 157 } 158 break; 159 } 160 case ExitFile: 161 if (!IncludeStack.empty()) { 162 if (llvm::timeTraceProfilerEnabled()) 163 llvm::timeTraceProfilerEnd(); 164 165 S->DiagnoseNonDefaultPragmaAlignPack( 166 Sema::PragmaAlignPackDiagnoseKind::ChangedStateAtExit, 167 IncludeStack.pop_back_val()); 168 } 169 break; 170 default: 171 break; 172 } 173 } 174 }; 175 176 } // end namespace sema 177 } // end namespace clang 178 179 const unsigned Sema::MaxAlignmentExponent; 180 const uint64_t Sema::MaximumAlignment; 181 182 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 183 TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter) 184 : ExternalSource(nullptr), isMultiplexExternalSource(false), 185 CurFPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp), 186 Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()), 187 SourceMgr(PP.getSourceManager()), CollectStats(false), 188 CodeCompleter(CodeCompleter), CurContext(nullptr), 189 OriginalLexicalContext(nullptr), MSStructPragmaOn(false), 190 MSPointerToMemberRepresentationMethod( 191 LangOpts.getMSPointerToMemberRepresentationMethod()), 192 VtorDispStack(LangOpts.getVtorDispMode()), 193 AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack)), 194 DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr), 195 CodeSegStack(nullptr), FpPragmaStack(FPOptionsOverride()), 196 CurInitSeg(nullptr), VisContext(nullptr), 197 PragmaAttributeCurrentTargetDecl(nullptr), 198 IsBuildingRecoveryCallExpr(false), LateTemplateParser(nullptr), 199 LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp), 200 StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr), 201 StdCoroutineTraitsCache(nullptr), CXXTypeInfoDecl(nullptr), 202 MSVCGuidDecl(nullptr), NSNumberDecl(nullptr), NSValueDecl(nullptr), 203 NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr), 204 ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr), 205 ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr), 206 DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false), 207 TUKind(TUKind), NumSFINAEErrors(0), 208 FullyCheckedComparisonCategories( 209 static_cast<unsigned>(ComparisonCategoryType::Last) + 1), 210 SatisfactionCache(Context), AccessCheckingSFINAE(false), 211 InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0), 212 ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr), 213 DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this), 214 ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr), 215 CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) { 216 assert(pp.TUKind == TUKind); 217 TUScope = nullptr; 218 isConstantEvaluatedOverride = false; 219 220 LoadedExternalKnownNamespaces = false; 221 for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I) 222 NSNumberLiteralMethods[I] = nullptr; 223 224 if (getLangOpts().ObjC) 225 NSAPIObj.reset(new NSAPI(Context)); 226 227 if (getLangOpts().CPlusPlus) 228 FieldCollector.reset(new CXXFieldCollector()); 229 230 // Tell diagnostics how to render things from the AST library. 231 Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context); 232 233 ExprEvalContexts.emplace_back( 234 ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{}, 235 nullptr, ExpressionEvaluationContextRecord::EK_Other); 236 237 // Initialization of data sharing attributes stack for OpenMP 238 InitDataSharingAttributesStack(); 239 240 std::unique_ptr<sema::SemaPPCallbacks> Callbacks = 241 std::make_unique<sema::SemaPPCallbacks>(); 242 SemaPPCallbackHandler = Callbacks.get(); 243 PP.addPPCallbacks(std::move(Callbacks)); 244 SemaPPCallbackHandler->set(*this); 245 if (getLangOpts().getFPEvalMethod() == LangOptions::FEM_UnsetOnCommandLine) 246 // Use setting from TargetInfo. 247 PP.setCurrentFPEvalMethod(SourceLocation(), 248 ctxt.getTargetInfo().getFPEvalMethod()); 249 else 250 // Set initial value of __FLT_EVAL_METHOD__ from the command line. 251 PP.setCurrentFPEvalMethod(SourceLocation(), 252 getLangOpts().getFPEvalMethod()); 253 CurFPFeatures.setFPEvalMethod(PP.getCurrentFPEvalMethod()); 254 } 255 256 // Anchor Sema's type info to this TU. 257 void Sema::anchor() {} 258 259 void Sema::addImplicitTypedef(StringRef Name, QualType T) { 260 DeclarationName DN = &Context.Idents.get(Name); 261 if (IdResolver.begin(DN) == IdResolver.end()) 262 PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope); 263 } 264 265 void Sema::Initialize() { 266 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 267 SC->InitializeSema(*this); 268 269 // Tell the external Sema source about this Sema object. 270 if (ExternalSemaSource *ExternalSema 271 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 272 ExternalSema->InitializeSema(*this); 273 274 // This needs to happen after ExternalSemaSource::InitializeSema(this) or we 275 // will not be able to merge any duplicate __va_list_tag decls correctly. 276 VAListTagName = PP.getIdentifierInfo("__va_list_tag"); 277 278 if (!TUScope) 279 return; 280 281 // Initialize predefined 128-bit integer types, if needed. 282 if (Context.getTargetInfo().hasInt128Type() || 283 (Context.getAuxTargetInfo() && 284 Context.getAuxTargetInfo()->hasInt128Type())) { 285 // If either of the 128-bit integer types are unavailable to name lookup, 286 // define them now. 287 DeclarationName Int128 = &Context.Idents.get("__int128_t"); 288 if (IdResolver.begin(Int128) == IdResolver.end()) 289 PushOnScopeChains(Context.getInt128Decl(), TUScope); 290 291 DeclarationName UInt128 = &Context.Idents.get("__uint128_t"); 292 if (IdResolver.begin(UInt128) == IdResolver.end()) 293 PushOnScopeChains(Context.getUInt128Decl(), TUScope); 294 } 295 296 297 // Initialize predefined Objective-C types: 298 if (getLangOpts().ObjC) { 299 // If 'SEL' does not yet refer to any declarations, make it refer to the 300 // predefined 'SEL'. 301 DeclarationName SEL = &Context.Idents.get("SEL"); 302 if (IdResolver.begin(SEL) == IdResolver.end()) 303 PushOnScopeChains(Context.getObjCSelDecl(), TUScope); 304 305 // If 'id' does not yet refer to any declarations, make it refer to the 306 // predefined 'id'. 307 DeclarationName Id = &Context.Idents.get("id"); 308 if (IdResolver.begin(Id) == IdResolver.end()) 309 PushOnScopeChains(Context.getObjCIdDecl(), TUScope); 310 311 // Create the built-in typedef for 'Class'. 312 DeclarationName Class = &Context.Idents.get("Class"); 313 if (IdResolver.begin(Class) == IdResolver.end()) 314 PushOnScopeChains(Context.getObjCClassDecl(), TUScope); 315 316 // Create the built-in forward declaratino for 'Protocol'. 317 DeclarationName Protocol = &Context.Idents.get("Protocol"); 318 if (IdResolver.begin(Protocol) == IdResolver.end()) 319 PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope); 320 } 321 322 // Create the internal type for the *StringMakeConstantString builtins. 323 DeclarationName ConstantString = &Context.Idents.get("__NSConstantString"); 324 if (IdResolver.begin(ConstantString) == IdResolver.end()) 325 PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope); 326 327 // Initialize Microsoft "predefined C++ types". 328 if (getLangOpts().MSVCCompat) { 329 if (getLangOpts().CPlusPlus && 330 IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end()) 331 PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class), 332 TUScope); 333 334 addImplicitTypedef("size_t", Context.getSizeType()); 335 } 336 337 // Initialize predefined OpenCL types and supported extensions and (optional) 338 // core features. 339 if (getLangOpts().OpenCL) { 340 getOpenCLOptions().addSupport( 341 Context.getTargetInfo().getSupportedOpenCLOpts(), getLangOpts()); 342 addImplicitTypedef("sampler_t", Context.OCLSamplerTy); 343 addImplicitTypedef("event_t", Context.OCLEventTy); 344 auto OCLCompatibleVersion = getLangOpts().getOpenCLCompatibleVersion(); 345 if (OCLCompatibleVersion >= 200) { 346 if (getLangOpts().OpenCLCPlusPlus || getLangOpts().Blocks) { 347 addImplicitTypedef("clk_event_t", Context.OCLClkEventTy); 348 addImplicitTypedef("queue_t", Context.OCLQueueTy); 349 } 350 if (getLangOpts().OpenCLPipes) 351 addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy); 352 addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy)); 353 addImplicitTypedef("atomic_uint", 354 Context.getAtomicType(Context.UnsignedIntTy)); 355 addImplicitTypedef("atomic_float", 356 Context.getAtomicType(Context.FloatTy)); 357 // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as 358 // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide. 359 addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy)); 360 361 362 // OpenCL v2.0 s6.13.11.6: 363 // - The atomic_long and atomic_ulong types are supported if the 364 // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics 365 // extensions are supported. 366 // - The atomic_double type is only supported if double precision 367 // is supported and the cl_khr_int64_base_atomics and 368 // cl_khr_int64_extended_atomics extensions are supported. 369 // - If the device address space is 64-bits, the data types 370 // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and 371 // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and 372 // cl_khr_int64_extended_atomics extensions are supported. 373 374 auto AddPointerSizeDependentTypes = [&]() { 375 auto AtomicSizeT = Context.getAtomicType(Context.getSizeType()); 376 auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType()); 377 auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType()); 378 auto AtomicPtrDiffT = 379 Context.getAtomicType(Context.getPointerDiffType()); 380 addImplicitTypedef("atomic_size_t", AtomicSizeT); 381 addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT); 382 addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT); 383 addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT); 384 }; 385 386 if (Context.getTypeSize(Context.getSizeType()) == 32) { 387 AddPointerSizeDependentTypes(); 388 } 389 390 if (getOpenCLOptions().isSupported("cl_khr_fp16", getLangOpts())) { 391 auto AtomicHalfT = Context.getAtomicType(Context.HalfTy); 392 addImplicitTypedef("atomic_half", AtomicHalfT); 393 } 394 395 std::vector<QualType> Atomic64BitTypes; 396 if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics", 397 getLangOpts()) && 398 getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics", 399 getLangOpts())) { 400 if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) { 401 auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy); 402 addImplicitTypedef("atomic_double", AtomicDoubleT); 403 Atomic64BitTypes.push_back(AtomicDoubleT); 404 } 405 auto AtomicLongT = Context.getAtomicType(Context.LongTy); 406 auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy); 407 addImplicitTypedef("atomic_long", AtomicLongT); 408 addImplicitTypedef("atomic_ulong", AtomicULongT); 409 410 411 if (Context.getTypeSize(Context.getSizeType()) == 64) { 412 AddPointerSizeDependentTypes(); 413 } 414 } 415 } 416 417 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 418 if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) { \ 419 addImplicitTypedef(#ExtType, Context.Id##Ty); \ 420 } 421 #include "clang/Basic/OpenCLExtensionTypes.def" 422 } 423 424 if (Context.getTargetInfo().hasAArch64SVETypes()) { 425 #define SVE_TYPE(Name, Id, SingletonId) \ 426 addImplicitTypedef(Name, Context.SingletonId); 427 #include "clang/Basic/AArch64SVEACLETypes.def" 428 } 429 430 if (Context.getTargetInfo().getTriple().isPPC64()) { 431 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \ 432 addImplicitTypedef(#Name, Context.Id##Ty); 433 #include "clang/Basic/PPCTypes.def" 434 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \ 435 addImplicitTypedef(#Name, Context.Id##Ty); 436 #include "clang/Basic/PPCTypes.def" 437 } 438 439 if (Context.getTargetInfo().hasRISCVVTypes()) { 440 #define RVV_TYPE(Name, Id, SingletonId) \ 441 addImplicitTypedef(Name, Context.SingletonId); 442 #include "clang/Basic/RISCVVTypes.def" 443 } 444 445 if (Context.getTargetInfo().hasBuiltinMSVaList()) { 446 DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list"); 447 if (IdResolver.begin(MSVaList) == IdResolver.end()) 448 PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope); 449 } 450 451 DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list"); 452 if (IdResolver.begin(BuiltinVaList) == IdResolver.end()) 453 PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope); 454 } 455 456 Sema::~Sema() { 457 assert(InstantiatingSpecializations.empty() && 458 "failed to clean up an InstantiatingTemplate?"); 459 460 if (VisContext) FreeVisContext(); 461 462 // Kill all the active scopes. 463 for (sema::FunctionScopeInfo *FSI : FunctionScopes) 464 delete FSI; 465 466 // Tell the SemaConsumer to forget about us; we're going out of scope. 467 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 468 SC->ForgetSema(); 469 470 // Detach from the external Sema source. 471 if (ExternalSemaSource *ExternalSema 472 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 473 ExternalSema->ForgetSema(); 474 475 // If Sema's ExternalSource is the multiplexer - we own it. 476 if (isMultiplexExternalSource) 477 delete ExternalSource; 478 479 // Delete cached satisfactions. 480 std::vector<ConstraintSatisfaction *> Satisfactions; 481 Satisfactions.reserve(Satisfactions.size()); 482 for (auto &Node : SatisfactionCache) 483 Satisfactions.push_back(&Node); 484 for (auto *Node : Satisfactions) 485 delete Node; 486 487 threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache); 488 489 // Destroys data sharing attributes stack for OpenMP 490 DestroyDataSharingAttributesStack(); 491 492 // Detach from the PP callback handler which outlives Sema since it's owned 493 // by the preprocessor. 494 SemaPPCallbackHandler->reset(); 495 } 496 497 void Sema::warnStackExhausted(SourceLocation Loc) { 498 // Only warn about this once. 499 if (!WarnedStackExhausted) { 500 Diag(Loc, diag::warn_stack_exhausted); 501 WarnedStackExhausted = true; 502 } 503 } 504 505 void Sema::runWithSufficientStackSpace(SourceLocation Loc, 506 llvm::function_ref<void()> Fn) { 507 clang::runWithSufficientStackSpace([&] { warnStackExhausted(Loc); }, Fn); 508 } 509 510 /// makeUnavailableInSystemHeader - There is an error in the current 511 /// context. If we're still in a system header, and we can plausibly 512 /// make the relevant declaration unavailable instead of erroring, do 513 /// so and return true. 514 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc, 515 UnavailableAttr::ImplicitReason reason) { 516 // If we're not in a function, it's an error. 517 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext); 518 if (!fn) return false; 519 520 // If we're in template instantiation, it's an error. 521 if (inTemplateInstantiation()) 522 return false; 523 524 // If that function's not in a system header, it's an error. 525 if (!Context.getSourceManager().isInSystemHeader(loc)) 526 return false; 527 528 // If the function is already unavailable, it's not an error. 529 if (fn->hasAttr<UnavailableAttr>()) return true; 530 531 fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc)); 532 return true; 533 } 534 535 ASTMutationListener *Sema::getASTMutationListener() const { 536 return getASTConsumer().GetASTMutationListener(); 537 } 538 539 ///Registers an external source. If an external source already exists, 540 /// creates a multiplex external source and appends to it. 541 /// 542 ///\param[in] E - A non-null external sema source. 543 /// 544 void Sema::addExternalSource(ExternalSemaSource *E) { 545 assert(E && "Cannot use with NULL ptr"); 546 547 if (!ExternalSource) { 548 ExternalSource = E; 549 return; 550 } 551 552 if (isMultiplexExternalSource) 553 static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E); 554 else { 555 ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E); 556 isMultiplexExternalSource = true; 557 } 558 } 559 560 /// Print out statistics about the semantic analysis. 561 void Sema::PrintStats() const { 562 llvm::errs() << "\n*** Semantic Analysis Stats:\n"; 563 llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n"; 564 565 BumpAlloc.PrintStats(); 566 AnalysisWarnings.PrintStats(); 567 } 568 569 void Sema::diagnoseNullableToNonnullConversion(QualType DstType, 570 QualType SrcType, 571 SourceLocation Loc) { 572 Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context); 573 if (!ExprNullability || (*ExprNullability != NullabilityKind::Nullable && 574 *ExprNullability != NullabilityKind::NullableResult)) 575 return; 576 577 Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context); 578 if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull) 579 return; 580 581 Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType; 582 } 583 584 void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr* E) { 585 if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant, 586 E->getBeginLoc())) 587 return; 588 // nullptr only exists from C++11 on, so don't warn on its absence earlier. 589 if (!getLangOpts().CPlusPlus11) 590 return; 591 592 if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer) 593 return; 594 if (E->IgnoreParenImpCasts()->getType()->isNullPtrType()) 595 return; 596 597 // Don't diagnose the conversion from a 0 literal to a null pointer argument 598 // in a synthesized call to operator<=>. 599 if (!CodeSynthesisContexts.empty() && 600 CodeSynthesisContexts.back().Kind == 601 CodeSynthesisContext::RewritingOperatorAsSpaceship) 602 return; 603 604 // If it is a macro from system header, and if the macro name is not "NULL", 605 // do not warn. 606 SourceLocation MaybeMacroLoc = E->getBeginLoc(); 607 if (Diags.getSuppressSystemWarnings() && 608 SourceMgr.isInSystemMacro(MaybeMacroLoc) && 609 !findMacroSpelling(MaybeMacroLoc, "NULL")) 610 return; 611 612 Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant) 613 << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr"); 614 } 615 616 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 617 /// If there is already an implicit cast, merge into the existing one. 618 /// The result is of the given category. 619 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty, 620 CastKind Kind, ExprValueKind VK, 621 const CXXCastPath *BasePath, 622 CheckedConversionKind CCK) { 623 #ifndef NDEBUG 624 if (VK == VK_PRValue && !E->isPRValue()) { 625 switch (Kind) { 626 default: 627 llvm_unreachable( 628 ("can't implicitly cast glvalue to prvalue with this cast " 629 "kind: " + 630 std::string(CastExpr::getCastKindName(Kind))) 631 .c_str()); 632 case CK_Dependent: 633 case CK_LValueToRValue: 634 case CK_ArrayToPointerDecay: 635 case CK_FunctionToPointerDecay: 636 case CK_ToVoid: 637 case CK_NonAtomicToAtomic: 638 break; 639 } 640 } 641 assert((VK == VK_PRValue || Kind == CK_Dependent || !E->isPRValue()) && 642 "can't cast prvalue to glvalue"); 643 #endif 644 645 diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc()); 646 diagnoseZeroToNullptrConversion(Kind, E); 647 648 QualType ExprTy = Context.getCanonicalType(E->getType()); 649 QualType TypeTy = Context.getCanonicalType(Ty); 650 651 if (ExprTy == TypeTy) 652 return E; 653 654 if (Kind == CK_ArrayToPointerDecay) { 655 // C++1z [conv.array]: The temporary materialization conversion is applied. 656 // We also use this to fuel C++ DR1213, which applies to C++11 onwards. 657 if (getLangOpts().CPlusPlus && E->isPRValue()) { 658 // The temporary is an lvalue in C++98 and an xvalue otherwise. 659 ExprResult Materialized = CreateMaterializeTemporaryExpr( 660 E->getType(), E, !getLangOpts().CPlusPlus11); 661 if (Materialized.isInvalid()) 662 return ExprError(); 663 E = Materialized.get(); 664 } 665 // C17 6.7.1p6 footnote 124: The implementation can treat any register 666 // declaration simply as an auto declaration. However, whether or not 667 // addressable storage is actually used, the address of any part of an 668 // object declared with storage-class specifier register cannot be 669 // computed, either explicitly(by use of the unary & operator as discussed 670 // in 6.5.3.2) or implicitly(by converting an array name to a pointer as 671 // discussed in 6.3.2.1).Thus, the only operator that can be applied to an 672 // array declared with storage-class specifier register is sizeof. 673 if (VK == VK_PRValue && !getLangOpts().CPlusPlus && !E->isPRValue()) { 674 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) { 675 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 676 if (VD->getStorageClass() == SC_Register) { 677 Diag(E->getExprLoc(), diag::err_typecheck_address_of) 678 << /*register variable*/ 3 << E->getSourceRange(); 679 return ExprError(); 680 } 681 } 682 } 683 } 684 } 685 686 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) { 687 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) { 688 ImpCast->setType(Ty); 689 ImpCast->setValueKind(VK); 690 return E; 691 } 692 } 693 694 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK, 695 CurFPFeatureOverrides()); 696 } 697 698 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 699 /// to the conversion from scalar type ScalarTy to the Boolean type. 700 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) { 701 switch (ScalarTy->getScalarTypeKind()) { 702 case Type::STK_Bool: return CK_NoOp; 703 case Type::STK_CPointer: return CK_PointerToBoolean; 704 case Type::STK_BlockPointer: return CK_PointerToBoolean; 705 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean; 706 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean; 707 case Type::STK_Integral: return CK_IntegralToBoolean; 708 case Type::STK_Floating: return CK_FloatingToBoolean; 709 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean; 710 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean; 711 case Type::STK_FixedPoint: return CK_FixedPointToBoolean; 712 } 713 llvm_unreachable("unknown scalar type kind"); 714 } 715 716 /// Used to prune the decls of Sema's UnusedFileScopedDecls vector. 717 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) { 718 if (D->getMostRecentDecl()->isUsed()) 719 return true; 720 721 if (D->isExternallyVisible()) 722 return true; 723 724 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 725 // If this is a function template and none of its specializations is used, 726 // we should warn. 727 if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate()) 728 for (const auto *Spec : Template->specializations()) 729 if (ShouldRemoveFromUnused(SemaRef, Spec)) 730 return true; 731 732 // UnusedFileScopedDecls stores the first declaration. 733 // The declaration may have become definition so check again. 734 const FunctionDecl *DeclToCheck; 735 if (FD->hasBody(DeclToCheck)) 736 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 737 738 // Later redecls may add new information resulting in not having to warn, 739 // so check again. 740 DeclToCheck = FD->getMostRecentDecl(); 741 if (DeclToCheck != FD) 742 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 743 } 744 745 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 746 // If a variable usable in constant expressions is referenced, 747 // don't warn if it isn't used: if the value of a variable is required 748 // for the computation of a constant expression, it doesn't make sense to 749 // warn even if the variable isn't odr-used. (isReferenced doesn't 750 // precisely reflect that, but it's a decent approximation.) 751 if (VD->isReferenced() && 752 VD->mightBeUsableInConstantExpressions(SemaRef->Context)) 753 return true; 754 755 if (VarTemplateDecl *Template = VD->getDescribedVarTemplate()) 756 // If this is a variable template and none of its specializations is used, 757 // we should warn. 758 for (const auto *Spec : Template->specializations()) 759 if (ShouldRemoveFromUnused(SemaRef, Spec)) 760 return true; 761 762 // UnusedFileScopedDecls stores the first declaration. 763 // The declaration may have become definition so check again. 764 const VarDecl *DeclToCheck = VD->getDefinition(); 765 if (DeclToCheck) 766 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 767 768 // Later redecls may add new information resulting in not having to warn, 769 // so check again. 770 DeclToCheck = VD->getMostRecentDecl(); 771 if (DeclToCheck != VD) 772 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 773 } 774 775 return false; 776 } 777 778 static bool isFunctionOrVarDeclExternC(NamedDecl *ND) { 779 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 780 return FD->isExternC(); 781 return cast<VarDecl>(ND)->isExternC(); 782 } 783 784 /// Determine whether ND is an external-linkage function or variable whose 785 /// type has no linkage. 786 bool Sema::isExternalWithNoLinkageType(ValueDecl *VD) { 787 // Note: it's not quite enough to check whether VD has UniqueExternalLinkage, 788 // because we also want to catch the case where its type has VisibleNoLinkage, 789 // which does not affect the linkage of VD. 790 return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() && 791 !isExternalFormalLinkage(VD->getType()->getLinkage()) && 792 !isFunctionOrVarDeclExternC(VD); 793 } 794 795 /// Obtains a sorted list of functions and variables that are undefined but 796 /// ODR-used. 797 void Sema::getUndefinedButUsed( 798 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) { 799 for (const auto &UndefinedUse : UndefinedButUsed) { 800 NamedDecl *ND = UndefinedUse.first; 801 802 // Ignore attributes that have become invalid. 803 if (ND->isInvalidDecl()) continue; 804 805 // __attribute__((weakref)) is basically a definition. 806 if (ND->hasAttr<WeakRefAttr>()) continue; 807 808 if (isa<CXXDeductionGuideDecl>(ND)) 809 continue; 810 811 if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) { 812 // An exported function will always be emitted when defined, so even if 813 // the function is inline, it doesn't have to be emitted in this TU. An 814 // imported function implies that it has been exported somewhere else. 815 continue; 816 } 817 818 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 819 if (FD->isDefined()) 820 continue; 821 if (FD->isExternallyVisible() && 822 !isExternalWithNoLinkageType(FD) && 823 !FD->getMostRecentDecl()->isInlined() && 824 !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>()) 825 continue; 826 if (FD->getBuiltinID()) 827 continue; 828 } else { 829 auto *VD = cast<VarDecl>(ND); 830 if (VD->hasDefinition() != VarDecl::DeclarationOnly) 831 continue; 832 if (VD->isExternallyVisible() && 833 !isExternalWithNoLinkageType(VD) && 834 !VD->getMostRecentDecl()->isInline() && 835 !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>()) 836 continue; 837 838 // Skip VarDecls that lack formal definitions but which we know are in 839 // fact defined somewhere. 840 if (VD->isKnownToBeDefined()) 841 continue; 842 } 843 844 Undefined.push_back(std::make_pair(ND, UndefinedUse.second)); 845 } 846 } 847 848 /// checkUndefinedButUsed - Check for undefined objects with internal linkage 849 /// or that are inline. 850 static void checkUndefinedButUsed(Sema &S) { 851 if (S.UndefinedButUsed.empty()) return; 852 853 // Collect all the still-undefined entities with internal linkage. 854 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined; 855 S.getUndefinedButUsed(Undefined); 856 if (Undefined.empty()) return; 857 858 for (auto Undef : Undefined) { 859 ValueDecl *VD = cast<ValueDecl>(Undef.first); 860 SourceLocation UseLoc = Undef.second; 861 862 if (S.isExternalWithNoLinkageType(VD)) { 863 // C++ [basic.link]p8: 864 // A type without linkage shall not be used as the type of a variable 865 // or function with external linkage unless 866 // -- the entity has C language linkage 867 // -- the entity is not odr-used or is defined in the same TU 868 // 869 // As an extension, accept this in cases where the type is externally 870 // visible, since the function or variable actually can be defined in 871 // another translation unit in that case. 872 S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage()) 873 ? diag::ext_undefined_internal_type 874 : diag::err_undefined_internal_type) 875 << isa<VarDecl>(VD) << VD; 876 } else if (!VD->isExternallyVisible()) { 877 // FIXME: We can promote this to an error. The function or variable can't 878 // be defined anywhere else, so the program must necessarily violate the 879 // one definition rule. 880 bool IsImplicitBase = false; 881 if (const auto *BaseD = dyn_cast<FunctionDecl>(VD)) { 882 auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>(); 883 if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive( 884 llvm::omp::TraitProperty:: 885 implementation_extension_disable_implicit_base)) { 886 const auto *Func = cast<FunctionDecl>( 887 cast<DeclRefExpr>(DVAttr->getVariantFuncRef())->getDecl()); 888 IsImplicitBase = BaseD->isImplicit() && 889 Func->getIdentifier()->isMangledOpenMPVariantName(); 890 } 891 } 892 if (!S.getLangOpts().OpenMP || !IsImplicitBase) 893 S.Diag(VD->getLocation(), diag::warn_undefined_internal) 894 << isa<VarDecl>(VD) << VD; 895 } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) { 896 (void)FD; 897 assert(FD->getMostRecentDecl()->isInlined() && 898 "used object requires definition but isn't inline or internal?"); 899 // FIXME: This is ill-formed; we should reject. 900 S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD; 901 } else { 902 assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() && 903 "used var requires definition but isn't inline or internal?"); 904 S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD; 905 } 906 if (UseLoc.isValid()) 907 S.Diag(UseLoc, diag::note_used_here); 908 } 909 910 S.UndefinedButUsed.clear(); 911 } 912 913 void Sema::LoadExternalWeakUndeclaredIdentifiers() { 914 if (!ExternalSource) 915 return; 916 917 SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs; 918 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs); 919 for (auto &WeakID : WeakIDs) 920 WeakUndeclaredIdentifiers.insert(WeakID); 921 } 922 923 924 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap; 925 926 /// Returns true, if all methods and nested classes of the given 927 /// CXXRecordDecl are defined in this translation unit. 928 /// 929 /// Should only be called from ActOnEndOfTranslationUnit so that all 930 /// definitions are actually read. 931 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD, 932 RecordCompleteMap &MNCComplete) { 933 RecordCompleteMap::iterator Cache = MNCComplete.find(RD); 934 if (Cache != MNCComplete.end()) 935 return Cache->second; 936 if (!RD->isCompleteDefinition()) 937 return false; 938 bool Complete = true; 939 for (DeclContext::decl_iterator I = RD->decls_begin(), 940 E = RD->decls_end(); 941 I != E && Complete; ++I) { 942 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I)) 943 Complete = M->isDefined() || M->isDefaulted() || 944 (M->isPure() && !isa<CXXDestructorDecl>(M)); 945 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I)) 946 // If the template function is marked as late template parsed at this 947 // point, it has not been instantiated and therefore we have not 948 // performed semantic analysis on it yet, so we cannot know if the type 949 // can be considered complete. 950 Complete = !F->getTemplatedDecl()->isLateTemplateParsed() && 951 F->getTemplatedDecl()->isDefined(); 952 else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) { 953 if (R->isInjectedClassName()) 954 continue; 955 if (R->hasDefinition()) 956 Complete = MethodsAndNestedClassesComplete(R->getDefinition(), 957 MNCComplete); 958 else 959 Complete = false; 960 } 961 } 962 MNCComplete[RD] = Complete; 963 return Complete; 964 } 965 966 /// Returns true, if the given CXXRecordDecl is fully defined in this 967 /// translation unit, i.e. all methods are defined or pure virtual and all 968 /// friends, friend functions and nested classes are fully defined in this 969 /// translation unit. 970 /// 971 /// Should only be called from ActOnEndOfTranslationUnit so that all 972 /// definitions are actually read. 973 static bool IsRecordFullyDefined(const CXXRecordDecl *RD, 974 RecordCompleteMap &RecordsComplete, 975 RecordCompleteMap &MNCComplete) { 976 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD); 977 if (Cache != RecordsComplete.end()) 978 return Cache->second; 979 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete); 980 for (CXXRecordDecl::friend_iterator I = RD->friend_begin(), 981 E = RD->friend_end(); 982 I != E && Complete; ++I) { 983 // Check if friend classes and methods are complete. 984 if (TypeSourceInfo *TSI = (*I)->getFriendType()) { 985 // Friend classes are available as the TypeSourceInfo of the FriendDecl. 986 if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl()) 987 Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete); 988 else 989 Complete = false; 990 } else { 991 // Friend functions are available through the NamedDecl of FriendDecl. 992 if (const FunctionDecl *FD = 993 dyn_cast<FunctionDecl>((*I)->getFriendDecl())) 994 Complete = FD->isDefined(); 995 else 996 // This is a template friend, give up. 997 Complete = false; 998 } 999 } 1000 RecordsComplete[RD] = Complete; 1001 return Complete; 1002 } 1003 1004 void Sema::emitAndClearUnusedLocalTypedefWarnings() { 1005 if (ExternalSource) 1006 ExternalSource->ReadUnusedLocalTypedefNameCandidates( 1007 UnusedLocalTypedefNameCandidates); 1008 for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) { 1009 if (TD->isReferenced()) 1010 continue; 1011 Diag(TD->getLocation(), diag::warn_unused_local_typedef) 1012 << isa<TypeAliasDecl>(TD) << TD->getDeclName(); 1013 } 1014 UnusedLocalTypedefNameCandidates.clear(); 1015 } 1016 1017 /// This is called before the very first declaration in the translation unit 1018 /// is parsed. Note that the ASTContext may have already injected some 1019 /// declarations. 1020 void Sema::ActOnStartOfTranslationUnit() { 1021 if (getLangOpts().ModulesTS && 1022 (getLangOpts().getCompilingModule() == LangOptions::CMK_ModuleInterface || 1023 getLangOpts().getCompilingModule() == LangOptions::CMK_None)) { 1024 // We start in an implied global module fragment. 1025 SourceLocation StartOfTU = 1026 SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); 1027 ActOnGlobalModuleFragmentDecl(StartOfTU); 1028 ModuleScopes.back().ImplicitGlobalModuleFragment = true; 1029 } 1030 } 1031 1032 void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) { 1033 // No explicit actions are required at the end of the global module fragment. 1034 if (Kind == TUFragmentKind::Global) 1035 return; 1036 1037 // Transfer late parsed template instantiations over to the pending template 1038 // instantiation list. During normal compilation, the late template parser 1039 // will be installed and instantiating these templates will succeed. 1040 // 1041 // If we are building a TU prefix for serialization, it is also safe to 1042 // transfer these over, even though they are not parsed. The end of the TU 1043 // should be outside of any eager template instantiation scope, so when this 1044 // AST is deserialized, these templates will not be parsed until the end of 1045 // the combined TU. 1046 PendingInstantiations.insert(PendingInstantiations.end(), 1047 LateParsedInstantiations.begin(), 1048 LateParsedInstantiations.end()); 1049 LateParsedInstantiations.clear(); 1050 1051 // If DefinedUsedVTables ends up marking any virtual member functions it 1052 // might lead to more pending template instantiations, which we then need 1053 // to instantiate. 1054 DefineUsedVTables(); 1055 1056 // C++: Perform implicit template instantiations. 1057 // 1058 // FIXME: When we perform these implicit instantiations, we do not 1059 // carefully keep track of the point of instantiation (C++ [temp.point]). 1060 // This means that name lookup that occurs within the template 1061 // instantiation will always happen at the end of the translation unit, 1062 // so it will find some names that are not required to be found. This is 1063 // valid, but we could do better by diagnosing if an instantiation uses a 1064 // name that was not visible at its first point of instantiation. 1065 if (ExternalSource) { 1066 // Load pending instantiations from the external source. 1067 SmallVector<PendingImplicitInstantiation, 4> Pending; 1068 ExternalSource->ReadPendingInstantiations(Pending); 1069 for (auto PII : Pending) 1070 if (auto Func = dyn_cast<FunctionDecl>(PII.first)) 1071 Func->setInstantiationIsPending(true); 1072 PendingInstantiations.insert(PendingInstantiations.begin(), 1073 Pending.begin(), Pending.end()); 1074 } 1075 1076 { 1077 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations"); 1078 PerformPendingInstantiations(); 1079 } 1080 1081 emitDeferredDiags(); 1082 1083 assert(LateParsedInstantiations.empty() && 1084 "end of TU template instantiation should not create more " 1085 "late-parsed templates"); 1086 1087 // Report diagnostics for uncorrected delayed typos. Ideally all of them 1088 // should have been corrected by that time, but it is very hard to cover all 1089 // cases in practice. 1090 for (const auto &Typo : DelayedTypos) { 1091 // We pass an empty TypoCorrection to indicate no correction was performed. 1092 Typo.second.DiagHandler(TypoCorrection()); 1093 } 1094 DelayedTypos.clear(); 1095 } 1096 1097 /// ActOnEndOfTranslationUnit - This is called at the very end of the 1098 /// translation unit when EOF is reached and all but the top-level scope is 1099 /// popped. 1100 void Sema::ActOnEndOfTranslationUnit() { 1101 assert(DelayedDiagnostics.getCurrentPool() == nullptr 1102 && "reached end of translation unit with a pool attached?"); 1103 1104 // If code completion is enabled, don't perform any end-of-translation-unit 1105 // work. 1106 if (PP.isCodeCompletionEnabled()) 1107 return; 1108 1109 // Complete translation units and modules define vtables and perform implicit 1110 // instantiations. PCH files do not. 1111 if (TUKind != TU_Prefix) { 1112 DiagnoseUseOfUnimplementedSelectors(); 1113 1114 ActOnEndOfTranslationUnitFragment( 1115 !ModuleScopes.empty() && ModuleScopes.back().Module->Kind == 1116 Module::PrivateModuleFragment 1117 ? TUFragmentKind::Private 1118 : TUFragmentKind::Normal); 1119 1120 if (LateTemplateParserCleanup) 1121 LateTemplateParserCleanup(OpaqueParser); 1122 1123 CheckDelayedMemberExceptionSpecs(); 1124 } else { 1125 // If we are building a TU prefix for serialization, it is safe to transfer 1126 // these over, even though they are not parsed. The end of the TU should be 1127 // outside of any eager template instantiation scope, so when this AST is 1128 // deserialized, these templates will not be parsed until the end of the 1129 // combined TU. 1130 PendingInstantiations.insert(PendingInstantiations.end(), 1131 LateParsedInstantiations.begin(), 1132 LateParsedInstantiations.end()); 1133 LateParsedInstantiations.clear(); 1134 1135 if (LangOpts.PCHInstantiateTemplates) { 1136 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations"); 1137 PerformPendingInstantiations(); 1138 } 1139 } 1140 1141 DiagnoseUnterminatedPragmaAlignPack(); 1142 DiagnoseUnterminatedPragmaAttribute(); 1143 1144 // All delayed member exception specs should be checked or we end up accepting 1145 // incompatible declarations. 1146 assert(DelayedOverridingExceptionSpecChecks.empty()); 1147 assert(DelayedEquivalentExceptionSpecChecks.empty()); 1148 1149 // All dllexport classes should have been processed already. 1150 assert(DelayedDllExportClasses.empty()); 1151 assert(DelayedDllExportMemberFunctions.empty()); 1152 1153 // Remove file scoped decls that turned out to be used. 1154 UnusedFileScopedDecls.erase( 1155 std::remove_if(UnusedFileScopedDecls.begin(nullptr, true), 1156 UnusedFileScopedDecls.end(), 1157 [this](const DeclaratorDecl *DD) { 1158 return ShouldRemoveFromUnused(this, DD); 1159 }), 1160 UnusedFileScopedDecls.end()); 1161 1162 if (TUKind == TU_Prefix) { 1163 // Translation unit prefixes don't need any of the checking below. 1164 if (!PP.isIncrementalProcessingEnabled()) 1165 TUScope = nullptr; 1166 return; 1167 } 1168 1169 // Check for #pragma weak identifiers that were never declared 1170 LoadExternalWeakUndeclaredIdentifiers(); 1171 for (auto WeakID : WeakUndeclaredIdentifiers) { 1172 if (WeakID.second.getUsed()) 1173 continue; 1174 1175 Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(), 1176 LookupOrdinaryName); 1177 if (PrevDecl != nullptr && 1178 !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) 1179 Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type) 1180 << "'weak'" << ExpectedVariableOrFunction; 1181 else 1182 Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared) 1183 << WeakID.first; 1184 } 1185 1186 if (LangOpts.CPlusPlus11 && 1187 !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation())) 1188 CheckDelegatingCtorCycles(); 1189 1190 if (!Diags.hasErrorOccurred()) { 1191 if (ExternalSource) 1192 ExternalSource->ReadUndefinedButUsed(UndefinedButUsed); 1193 checkUndefinedButUsed(*this); 1194 } 1195 1196 // A global-module-fragment is only permitted within a module unit. 1197 bool DiagnosedMissingModuleDeclaration = false; 1198 if (!ModuleScopes.empty() && 1199 ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment && 1200 !ModuleScopes.back().ImplicitGlobalModuleFragment) { 1201 Diag(ModuleScopes.back().BeginLoc, 1202 diag::err_module_declaration_missing_after_global_module_introducer); 1203 DiagnosedMissingModuleDeclaration = true; 1204 } 1205 1206 if (TUKind == TU_Module) { 1207 // If we are building a module interface unit, we need to have seen the 1208 // module declaration by now. 1209 if (getLangOpts().getCompilingModule() == 1210 LangOptions::CMK_ModuleInterface && 1211 (ModuleScopes.empty() || 1212 !ModuleScopes.back().Module->isModulePurview()) && 1213 !DiagnosedMissingModuleDeclaration) { 1214 // FIXME: Make a better guess as to where to put the module declaration. 1215 Diag(getSourceManager().getLocForStartOfFile( 1216 getSourceManager().getMainFileID()), 1217 diag::err_module_declaration_missing); 1218 } 1219 1220 // If we are building a module, resolve all of the exported declarations 1221 // now. 1222 if (Module *CurrentModule = PP.getCurrentModule()) { 1223 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap(); 1224 1225 SmallVector<Module *, 2> Stack; 1226 Stack.push_back(CurrentModule); 1227 while (!Stack.empty()) { 1228 Module *Mod = Stack.pop_back_val(); 1229 1230 // Resolve the exported declarations and conflicts. 1231 // FIXME: Actually complain, once we figure out how to teach the 1232 // diagnostic client to deal with complaints in the module map at this 1233 // point. 1234 ModMap.resolveExports(Mod, /*Complain=*/false); 1235 ModMap.resolveUses(Mod, /*Complain=*/false); 1236 ModMap.resolveConflicts(Mod, /*Complain=*/false); 1237 1238 // Queue the submodules, so their exports will also be resolved. 1239 Stack.append(Mod->submodule_begin(), Mod->submodule_end()); 1240 } 1241 } 1242 1243 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for 1244 // modules when they are built, not every time they are used. 1245 emitAndClearUnusedLocalTypedefWarnings(); 1246 } 1247 1248 // C99 6.9.2p2: 1249 // A declaration of an identifier for an object that has file 1250 // scope without an initializer, and without a storage-class 1251 // specifier or with the storage-class specifier static, 1252 // constitutes a tentative definition. If a translation unit 1253 // contains one or more tentative definitions for an identifier, 1254 // and the translation unit contains no external definition for 1255 // that identifier, then the behavior is exactly as if the 1256 // translation unit contains a file scope declaration of that 1257 // identifier, with the composite type as of the end of the 1258 // translation unit, with an initializer equal to 0. 1259 llvm::SmallSet<VarDecl *, 32> Seen; 1260 for (TentativeDefinitionsType::iterator 1261 T = TentativeDefinitions.begin(ExternalSource), 1262 TEnd = TentativeDefinitions.end(); 1263 T != TEnd; ++T) { 1264 VarDecl *VD = (*T)->getActingDefinition(); 1265 1266 // If the tentative definition was completed, getActingDefinition() returns 1267 // null. If we've already seen this variable before, insert()'s second 1268 // return value is false. 1269 if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second) 1270 continue; 1271 1272 if (const IncompleteArrayType *ArrayT 1273 = Context.getAsIncompleteArrayType(VD->getType())) { 1274 // Set the length of the array to 1 (C99 6.9.2p5). 1275 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 1276 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 1277 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), One, 1278 nullptr, ArrayType::Normal, 0); 1279 VD->setType(T); 1280 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 1281 diag::err_tentative_def_incomplete_type)) 1282 VD->setInvalidDecl(); 1283 1284 // No initialization is performed for a tentative definition. 1285 CheckCompleteVariableDeclaration(VD); 1286 1287 // Notify the consumer that we've completed a tentative definition. 1288 if (!VD->isInvalidDecl()) 1289 Consumer.CompleteTentativeDefinition(VD); 1290 } 1291 1292 for (auto D : ExternalDeclarations) { 1293 if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed()) 1294 continue; 1295 1296 Consumer.CompleteExternalDeclaration(D); 1297 } 1298 1299 // If there were errors, disable 'unused' warnings since they will mostly be 1300 // noise. Don't warn for a use from a module: either we should warn on all 1301 // file-scope declarations in modules or not at all, but whether the 1302 // declaration is used is immaterial. 1303 if (!Diags.hasErrorOccurred() && TUKind != TU_Module) { 1304 // Output warning for unused file scoped decls. 1305 for (UnusedFileScopedDeclsType::iterator 1306 I = UnusedFileScopedDecls.begin(ExternalSource), 1307 E = UnusedFileScopedDecls.end(); I != E; ++I) { 1308 if (ShouldRemoveFromUnused(this, *I)) 1309 continue; 1310 1311 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 1312 const FunctionDecl *DiagD; 1313 if (!FD->hasBody(DiagD)) 1314 DiagD = FD; 1315 if (DiagD->isDeleted()) 1316 continue; // Deleted functions are supposed to be unused. 1317 if (DiagD->isReferenced()) { 1318 if (isa<CXXMethodDecl>(DiagD)) 1319 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function) 1320 << DiagD; 1321 else { 1322 if (FD->getStorageClass() == SC_Static && 1323 !FD->isInlineSpecified() && 1324 !SourceMgr.isInMainFile( 1325 SourceMgr.getExpansionLoc(FD->getLocation()))) 1326 Diag(DiagD->getLocation(), 1327 diag::warn_unneeded_static_internal_decl) 1328 << DiagD; 1329 else 1330 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 1331 << /*function*/ 0 << DiagD; 1332 } 1333 } else { 1334 if (FD->getDescribedFunctionTemplate()) 1335 Diag(DiagD->getLocation(), diag::warn_unused_template) 1336 << /*function*/ 0 << DiagD; 1337 else 1338 Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD) 1339 ? diag::warn_unused_member_function 1340 : diag::warn_unused_function) 1341 << DiagD; 1342 } 1343 } else { 1344 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition(); 1345 if (!DiagD) 1346 DiagD = cast<VarDecl>(*I); 1347 if (DiagD->isReferenced()) { 1348 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 1349 << /*variable*/ 1 << DiagD; 1350 } else if (DiagD->getType().isConstQualified()) { 1351 const SourceManager &SM = SourceMgr; 1352 if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) || 1353 !PP.getLangOpts().IsHeaderFile) 1354 Diag(DiagD->getLocation(), diag::warn_unused_const_variable) 1355 << DiagD; 1356 } else { 1357 if (DiagD->getDescribedVarTemplate()) 1358 Diag(DiagD->getLocation(), diag::warn_unused_template) 1359 << /*variable*/ 1 << DiagD; 1360 else 1361 Diag(DiagD->getLocation(), diag::warn_unused_variable) << DiagD; 1362 } 1363 } 1364 } 1365 1366 emitAndClearUnusedLocalTypedefWarnings(); 1367 } 1368 1369 if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) { 1370 // FIXME: Load additional unused private field candidates from the external 1371 // source. 1372 RecordCompleteMap RecordsComplete; 1373 RecordCompleteMap MNCComplete; 1374 for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(), 1375 E = UnusedPrivateFields.end(); I != E; ++I) { 1376 const NamedDecl *D = *I; 1377 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()); 1378 if (RD && !RD->isUnion() && 1379 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) { 1380 Diag(D->getLocation(), diag::warn_unused_private_field) 1381 << D->getDeclName(); 1382 } 1383 } 1384 } 1385 1386 if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) { 1387 if (ExternalSource) 1388 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs); 1389 for (const auto &DeletedFieldInfo : DeleteExprs) { 1390 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) { 1391 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first, 1392 DeleteExprLoc.second); 1393 } 1394 } 1395 } 1396 1397 // Check we've noticed that we're no longer parsing the initializer for every 1398 // variable. If we miss cases, then at best we have a performance issue and 1399 // at worst a rejects-valid bug. 1400 assert(ParsingInitForAutoVars.empty() && 1401 "Didn't unmark var as having its initializer parsed"); 1402 1403 if (!PP.isIncrementalProcessingEnabled()) 1404 TUScope = nullptr; 1405 } 1406 1407 1408 //===----------------------------------------------------------------------===// 1409 // Helper functions. 1410 //===----------------------------------------------------------------------===// 1411 1412 DeclContext *Sema::getFunctionLevelDeclContext() { 1413 DeclContext *DC = CurContext; 1414 1415 while (true) { 1416 if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC) || 1417 isa<RequiresExprBodyDecl>(DC)) { 1418 DC = DC->getParent(); 1419 } else if (isa<CXXMethodDecl>(DC) && 1420 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 1421 cast<CXXRecordDecl>(DC->getParent())->isLambda()) { 1422 DC = DC->getParent()->getParent(); 1423 } 1424 else break; 1425 } 1426 1427 return DC; 1428 } 1429 1430 /// getCurFunctionDecl - If inside of a function body, this returns a pointer 1431 /// to the function decl for the function being parsed. If we're currently 1432 /// in a 'block', this returns the containing context. 1433 FunctionDecl *Sema::getCurFunctionDecl() { 1434 DeclContext *DC = getFunctionLevelDeclContext(); 1435 return dyn_cast<FunctionDecl>(DC); 1436 } 1437 1438 ObjCMethodDecl *Sema::getCurMethodDecl() { 1439 DeclContext *DC = getFunctionLevelDeclContext(); 1440 while (isa<RecordDecl>(DC)) 1441 DC = DC->getParent(); 1442 return dyn_cast<ObjCMethodDecl>(DC); 1443 } 1444 1445 NamedDecl *Sema::getCurFunctionOrMethodDecl() { 1446 DeclContext *DC = getFunctionLevelDeclContext(); 1447 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 1448 return cast<NamedDecl>(DC); 1449 return nullptr; 1450 } 1451 1452 LangAS Sema::getDefaultCXXMethodAddrSpace() const { 1453 if (getLangOpts().OpenCL) 1454 return getASTContext().getDefaultOpenCLPointeeAddrSpace(); 1455 return LangAS::Default; 1456 } 1457 1458 void Sema::EmitCurrentDiagnostic(unsigned DiagID) { 1459 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here 1460 // and yet we also use the current diag ID on the DiagnosticsEngine. This has 1461 // been made more painfully obvious by the refactor that introduced this 1462 // function, but it is possible that the incoming argument can be 1463 // eliminated. If it truly cannot be (for example, there is some reentrancy 1464 // issue I am not seeing yet), then there should at least be a clarifying 1465 // comment somewhere. 1466 if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) { 1467 switch (DiagnosticIDs::getDiagnosticSFINAEResponse( 1468 Diags.getCurrentDiagID())) { 1469 case DiagnosticIDs::SFINAE_Report: 1470 // We'll report the diagnostic below. 1471 break; 1472 1473 case DiagnosticIDs::SFINAE_SubstitutionFailure: 1474 // Count this failure so that we know that template argument deduction 1475 // has failed. 1476 ++NumSFINAEErrors; 1477 1478 // Make a copy of this suppressed diagnostic and store it with the 1479 // template-deduction information. 1480 if (*Info && !(*Info)->hasSFINAEDiagnostic()) { 1481 Diagnostic DiagInfo(&Diags); 1482 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(), 1483 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 1484 } 1485 1486 Diags.setLastDiagnosticIgnored(true); 1487 Diags.Clear(); 1488 return; 1489 1490 case DiagnosticIDs::SFINAE_AccessControl: { 1491 // Per C++ Core Issue 1170, access control is part of SFINAE. 1492 // Additionally, the AccessCheckingSFINAE flag can be used to temporarily 1493 // make access control a part of SFINAE for the purposes of checking 1494 // type traits. 1495 if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11) 1496 break; 1497 1498 SourceLocation Loc = Diags.getCurrentDiagLoc(); 1499 1500 // Suppress this diagnostic. 1501 ++NumSFINAEErrors; 1502 1503 // Make a copy of this suppressed diagnostic and store it with the 1504 // template-deduction information. 1505 if (*Info && !(*Info)->hasSFINAEDiagnostic()) { 1506 Diagnostic DiagInfo(&Diags); 1507 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(), 1508 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 1509 } 1510 1511 Diags.setLastDiagnosticIgnored(true); 1512 Diags.Clear(); 1513 1514 // Now the diagnostic state is clear, produce a C++98 compatibility 1515 // warning. 1516 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control); 1517 1518 // The last diagnostic which Sema produced was ignored. Suppress any 1519 // notes attached to it. 1520 Diags.setLastDiagnosticIgnored(true); 1521 return; 1522 } 1523 1524 case DiagnosticIDs::SFINAE_Suppress: 1525 // Make a copy of this suppressed diagnostic and store it with the 1526 // template-deduction information; 1527 if (*Info) { 1528 Diagnostic DiagInfo(&Diags); 1529 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(), 1530 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 1531 } 1532 1533 // Suppress this diagnostic. 1534 Diags.setLastDiagnosticIgnored(true); 1535 Diags.Clear(); 1536 return; 1537 } 1538 } 1539 1540 // Copy the diagnostic printing policy over the ASTContext printing policy. 1541 // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292 1542 Context.setPrintingPolicy(getPrintingPolicy()); 1543 1544 // Emit the diagnostic. 1545 if (!Diags.EmitCurrentDiagnostic()) 1546 return; 1547 1548 // If this is not a note, and we're in a template instantiation 1549 // that is different from the last template instantiation where 1550 // we emitted an error, print a template instantiation 1551 // backtrace. 1552 if (!DiagnosticIDs::isBuiltinNote(DiagID)) 1553 PrintContextStack(); 1554 } 1555 1556 Sema::SemaDiagnosticBuilder 1557 Sema::Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint) { 1558 return Diag(Loc, PD.getDiagID(), DeferHint) << PD; 1559 } 1560 1561 bool Sema::hasUncompilableErrorOccurred() const { 1562 if (getDiagnostics().hasUncompilableErrorOccurred()) 1563 return true; 1564 auto *FD = dyn_cast<FunctionDecl>(CurContext); 1565 if (!FD) 1566 return false; 1567 auto Loc = DeviceDeferredDiags.find(FD); 1568 if (Loc == DeviceDeferredDiags.end()) 1569 return false; 1570 for (auto PDAt : Loc->second) { 1571 if (DiagnosticIDs::isDefaultMappingAsError(PDAt.second.getDiagID())) 1572 return true; 1573 } 1574 return false; 1575 } 1576 1577 // Print notes showing how we can reach FD starting from an a priori 1578 // known-callable function. 1579 static void emitCallStackNotes(Sema &S, FunctionDecl *FD) { 1580 auto FnIt = S.DeviceKnownEmittedFns.find(FD); 1581 while (FnIt != S.DeviceKnownEmittedFns.end()) { 1582 // Respect error limit. 1583 if (S.Diags.hasFatalErrorOccurred()) 1584 return; 1585 DiagnosticBuilder Builder( 1586 S.Diags.Report(FnIt->second.Loc, diag::note_called_by)); 1587 Builder << FnIt->second.FD; 1588 FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD); 1589 } 1590 } 1591 1592 namespace { 1593 1594 /// Helper class that emits deferred diagnostic messages if an entity directly 1595 /// or indirectly using the function that causes the deferred diagnostic 1596 /// messages is known to be emitted. 1597 /// 1598 /// During parsing of AST, certain diagnostic messages are recorded as deferred 1599 /// diagnostics since it is unknown whether the functions containing such 1600 /// diagnostics will be emitted. A list of potentially emitted functions and 1601 /// variables that may potentially trigger emission of functions are also 1602 /// recorded. DeferredDiagnosticsEmitter recursively visits used functions 1603 /// by each function to emit deferred diagnostics. 1604 /// 1605 /// During the visit, certain OpenMP directives or initializer of variables 1606 /// with certain OpenMP attributes will cause subsequent visiting of any 1607 /// functions enter a state which is called OpenMP device context in this 1608 /// implementation. The state is exited when the directive or initializer is 1609 /// exited. This state can change the emission states of subsequent uses 1610 /// of functions. 1611 /// 1612 /// Conceptually the functions or variables to be visited form a use graph 1613 /// where the parent node uses the child node. At any point of the visit, 1614 /// the tree nodes traversed from the tree root to the current node form a use 1615 /// stack. The emission state of the current node depends on two factors: 1616 /// 1. the emission state of the root node 1617 /// 2. whether the current node is in OpenMP device context 1618 /// If the function is decided to be emitted, its contained deferred diagnostics 1619 /// are emitted, together with the information about the use stack. 1620 /// 1621 class DeferredDiagnosticsEmitter 1622 : public UsedDeclVisitor<DeferredDiagnosticsEmitter> { 1623 public: 1624 typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited; 1625 1626 // Whether the function is already in the current use-path. 1627 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> InUsePath; 1628 1629 // The current use-path. 1630 llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath; 1631 1632 // Whether the visiting of the function has been done. Done[0] is for the 1633 // case not in OpenMP device context. Done[1] is for the case in OpenMP 1634 // device context. We need two sets because diagnostics emission may be 1635 // different depending on whether it is in OpenMP device context. 1636 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2]; 1637 1638 // Emission state of the root node of the current use graph. 1639 bool ShouldEmitRootNode; 1640 1641 // Current OpenMP device context level. It is initialized to 0 and each 1642 // entering of device context increases it by 1 and each exit decreases 1643 // it by 1. Non-zero value indicates it is currently in device context. 1644 unsigned InOMPDeviceContext; 1645 1646 DeferredDiagnosticsEmitter(Sema &S) 1647 : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {} 1648 1649 bool shouldVisitDiscardedStmt() const { return false; } 1650 1651 void VisitOMPTargetDirective(OMPTargetDirective *Node) { 1652 ++InOMPDeviceContext; 1653 Inherited::VisitOMPTargetDirective(Node); 1654 --InOMPDeviceContext; 1655 } 1656 1657 void visitUsedDecl(SourceLocation Loc, Decl *D) { 1658 if (isa<VarDecl>(D)) 1659 return; 1660 if (auto *FD = dyn_cast<FunctionDecl>(D)) 1661 checkFunc(Loc, FD); 1662 else 1663 Inherited::visitUsedDecl(Loc, D); 1664 } 1665 1666 void checkVar(VarDecl *VD) { 1667 assert(VD->isFileVarDecl() && 1668 "Should only check file-scope variables"); 1669 if (auto *Init = VD->getInit()) { 1670 auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD); 1671 bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || 1672 *DevTy == OMPDeclareTargetDeclAttr::DT_Any); 1673 if (IsDev) 1674 ++InOMPDeviceContext; 1675 this->Visit(Init); 1676 if (IsDev) 1677 --InOMPDeviceContext; 1678 } 1679 } 1680 1681 void checkFunc(SourceLocation Loc, FunctionDecl *FD) { 1682 auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0]; 1683 FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back(); 1684 if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) || 1685 S.shouldIgnoreInHostDeviceCheck(FD) || InUsePath.count(FD)) 1686 return; 1687 // Finalize analysis of OpenMP-specific constructs. 1688 if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 && 1689 (ShouldEmitRootNode || InOMPDeviceContext)) 1690 S.finalizeOpenMPDelayedAnalysis(Caller, FD, Loc); 1691 if (Caller) 1692 S.DeviceKnownEmittedFns[FD] = {Caller, Loc}; 1693 // Always emit deferred diagnostics for the direct users. This does not 1694 // lead to explosion of diagnostics since each user is visited at most 1695 // twice. 1696 if (ShouldEmitRootNode || InOMPDeviceContext) 1697 emitDeferredDiags(FD, Caller); 1698 // Do not revisit a function if the function body has been completely 1699 // visited before. 1700 if (!Done.insert(FD).second) 1701 return; 1702 InUsePath.insert(FD); 1703 UsePath.push_back(FD); 1704 if (auto *S = FD->getBody()) { 1705 this->Visit(S); 1706 } 1707 UsePath.pop_back(); 1708 InUsePath.erase(FD); 1709 } 1710 1711 void checkRecordedDecl(Decl *D) { 1712 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 1713 ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) == 1714 Sema::FunctionEmissionStatus::Emitted; 1715 checkFunc(SourceLocation(), FD); 1716 } else 1717 checkVar(cast<VarDecl>(D)); 1718 } 1719 1720 // Emit any deferred diagnostics for FD 1721 void emitDeferredDiags(FunctionDecl *FD, bool ShowCallStack) { 1722 auto It = S.DeviceDeferredDiags.find(FD); 1723 if (It == S.DeviceDeferredDiags.end()) 1724 return; 1725 bool HasWarningOrError = false; 1726 bool FirstDiag = true; 1727 for (PartialDiagnosticAt &PDAt : It->second) { 1728 // Respect error limit. 1729 if (S.Diags.hasFatalErrorOccurred()) 1730 return; 1731 const SourceLocation &Loc = PDAt.first; 1732 const PartialDiagnostic &PD = PDAt.second; 1733 HasWarningOrError |= 1734 S.getDiagnostics().getDiagnosticLevel(PD.getDiagID(), Loc) >= 1735 DiagnosticsEngine::Warning; 1736 { 1737 DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID())); 1738 PD.Emit(Builder); 1739 } 1740 // Emit the note on the first diagnostic in case too many diagnostics 1741 // cause the note not emitted. 1742 if (FirstDiag && HasWarningOrError && ShowCallStack) { 1743 emitCallStackNotes(S, FD); 1744 FirstDiag = false; 1745 } 1746 } 1747 } 1748 }; 1749 } // namespace 1750 1751 void Sema::emitDeferredDiags() { 1752 if (ExternalSource) 1753 ExternalSource->ReadDeclsToCheckForDeferredDiags( 1754 DeclsToCheckForDeferredDiags); 1755 1756 if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) || 1757 DeclsToCheckForDeferredDiags.empty()) 1758 return; 1759 1760 DeferredDiagnosticsEmitter DDE(*this); 1761 for (auto D : DeclsToCheckForDeferredDiags) 1762 DDE.checkRecordedDecl(D); 1763 } 1764 1765 // In CUDA, there are some constructs which may appear in semantically-valid 1766 // code, but trigger errors if we ever generate code for the function in which 1767 // they appear. Essentially every construct you're not allowed to use on the 1768 // device falls into this category, because you are allowed to use these 1769 // constructs in a __host__ __device__ function, but only if that function is 1770 // never codegen'ed on the device. 1771 // 1772 // To handle semantic checking for these constructs, we keep track of the set of 1773 // functions we know will be emitted, either because we could tell a priori that 1774 // they would be emitted, or because they were transitively called by a 1775 // known-emitted function. 1776 // 1777 // We also keep a partial call graph of which not-known-emitted functions call 1778 // which other not-known-emitted functions. 1779 // 1780 // When we see something which is illegal if the current function is emitted 1781 // (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or 1782 // CheckCUDACall), we first check if the current function is known-emitted. If 1783 // so, we immediately output the diagnostic. 1784 // 1785 // Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags 1786 // until we discover that the function is known-emitted, at which point we take 1787 // it out of this map and emit the diagnostic. 1788 1789 Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K, SourceLocation Loc, 1790 unsigned DiagID, 1791 FunctionDecl *Fn, Sema &S) 1792 : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn), 1793 ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) { 1794 switch (K) { 1795 case K_Nop: 1796 break; 1797 case K_Immediate: 1798 case K_ImmediateWithCallStack: 1799 ImmediateDiag.emplace( 1800 ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID)); 1801 break; 1802 case K_Deferred: 1803 assert(Fn && "Must have a function to attach the deferred diag to."); 1804 auto &Diags = S.DeviceDeferredDiags[Fn]; 1805 PartialDiagId.emplace(Diags.size()); 1806 Diags.emplace_back(Loc, S.PDiag(DiagID)); 1807 break; 1808 } 1809 } 1810 1811 Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D) 1812 : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn), 1813 ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag), 1814 PartialDiagId(D.PartialDiagId) { 1815 // Clean the previous diagnostics. 1816 D.ShowCallStack = false; 1817 D.ImmediateDiag.reset(); 1818 D.PartialDiagId.reset(); 1819 } 1820 1821 Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() { 1822 if (ImmediateDiag) { 1823 // Emit our diagnostic and, if it was a warning or error, output a callstack 1824 // if Fn isn't a priori known-emitted. 1825 bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel( 1826 DiagID, Loc) >= DiagnosticsEngine::Warning; 1827 ImmediateDiag.reset(); // Emit the immediate diag. 1828 if (IsWarningOrError && ShowCallStack) 1829 emitCallStackNotes(S, Fn); 1830 } else { 1831 assert((!PartialDiagId || ShowCallStack) && 1832 "Must always show call stack for deferred diags."); 1833 } 1834 } 1835 1836 Sema::SemaDiagnosticBuilder 1837 Sema::targetDiag(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD) { 1838 FD = FD ? FD : getCurFunctionDecl(); 1839 if (LangOpts.OpenMP) 1840 return LangOpts.OpenMPIsDevice ? diagIfOpenMPDeviceCode(Loc, DiagID, FD) 1841 : diagIfOpenMPHostCode(Loc, DiagID, FD); 1842 if (getLangOpts().CUDA) 1843 return getLangOpts().CUDAIsDevice ? CUDADiagIfDeviceCode(Loc, DiagID) 1844 : CUDADiagIfHostCode(Loc, DiagID); 1845 1846 if (getLangOpts().SYCLIsDevice) 1847 return SYCLDiagIfDeviceCode(Loc, DiagID); 1848 1849 return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc, DiagID, 1850 FD, *this); 1851 } 1852 1853 Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID, 1854 bool DeferHint) { 1855 bool IsError = Diags.getDiagnosticIDs()->isDefaultMappingAsError(DiagID); 1856 bool ShouldDefer = getLangOpts().CUDA && LangOpts.GPUDeferDiag && 1857 DiagnosticIDs::isDeferrable(DiagID) && 1858 (DeferHint || DeferDiags || !IsError); 1859 auto SetIsLastErrorImmediate = [&](bool Flag) { 1860 if (IsError) 1861 IsLastErrorImmediate = Flag; 1862 }; 1863 if (!ShouldDefer) { 1864 SetIsLastErrorImmediate(true); 1865 return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc, 1866 DiagID, getCurFunctionDecl(), *this); 1867 } 1868 1869 SemaDiagnosticBuilder DB = getLangOpts().CUDAIsDevice 1870 ? CUDADiagIfDeviceCode(Loc, DiagID) 1871 : CUDADiagIfHostCode(Loc, DiagID); 1872 SetIsLastErrorImmediate(DB.isImmediate()); 1873 return DB; 1874 } 1875 1876 void Sema::checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D) { 1877 if (isUnevaluatedContext() || Ty.isNull()) 1878 return; 1879 1880 // The original idea behind checkTypeSupport function is that unused 1881 // declarations can be replaced with an array of bytes of the same size during 1882 // codegen, such replacement doesn't seem to be possible for types without 1883 // constant byte size like zero length arrays. So, do a deep check for SYCL. 1884 if (D && LangOpts.SYCLIsDevice) { 1885 llvm::DenseSet<QualType> Visited; 1886 deepTypeCheckForSYCLDevice(Loc, Visited, D); 1887 } 1888 1889 Decl *C = cast<Decl>(getCurLexicalContext()); 1890 1891 // Memcpy operations for structs containing a member with unsupported type 1892 // are ok, though. 1893 if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) { 1894 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) && 1895 MD->isTrivial()) 1896 return; 1897 1898 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD)) 1899 if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial()) 1900 return; 1901 } 1902 1903 // Try to associate errors with the lexical context, if that is a function, or 1904 // the value declaration otherwise. 1905 FunctionDecl *FD = isa<FunctionDecl>(C) ? cast<FunctionDecl>(C) 1906 : dyn_cast_or_null<FunctionDecl>(D); 1907 1908 auto CheckDeviceType = [&](QualType Ty) { 1909 if (Ty->isDependentType()) 1910 return; 1911 1912 if (Ty->isBitIntType()) { 1913 if (!Context.getTargetInfo().hasBitIntType()) { 1914 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type); 1915 if (D) 1916 PD << D; 1917 else 1918 PD << "expression"; 1919 targetDiag(Loc, PD, FD) 1920 << false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/ 1921 << Ty << Context.getTargetInfo().getTriple().str(); 1922 } 1923 return; 1924 } 1925 1926 // Check if we are dealing with two 'long double' but with different 1927 // semantics. 1928 bool LongDoubleMismatched = false; 1929 if (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128) { 1930 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(Ty); 1931 if ((&Sem != &llvm::APFloat::PPCDoubleDouble() && 1932 !Context.getTargetInfo().hasFloat128Type()) || 1933 (&Sem == &llvm::APFloat::PPCDoubleDouble() && 1934 !Context.getTargetInfo().hasIbm128Type())) 1935 LongDoubleMismatched = true; 1936 } 1937 1938 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) || 1939 (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) || 1940 (Ty->isIbm128Type() && !Context.getTargetInfo().hasIbm128Type()) || 1941 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 && 1942 !Context.getTargetInfo().hasInt128Type()) || 1943 LongDoubleMismatched) { 1944 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type); 1945 if (D) 1946 PD << D; 1947 else 1948 PD << "expression"; 1949 1950 if (targetDiag(Loc, PD, FD) 1951 << true /*show bit size*/ 1952 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty 1953 << false /*return*/ << Context.getTargetInfo().getTriple().str()) { 1954 if (D) 1955 D->setInvalidDecl(); 1956 } 1957 if (D) 1958 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D; 1959 } 1960 }; 1961 1962 auto CheckType = [&](QualType Ty, bool IsRetTy = false) { 1963 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice) || 1964 LangOpts.CUDAIsDevice) 1965 CheckDeviceType(Ty); 1966 1967 QualType UnqualTy = Ty.getCanonicalType().getUnqualifiedType(); 1968 const TargetInfo &TI = Context.getTargetInfo(); 1969 if (!TI.hasLongDoubleType() && UnqualTy == Context.LongDoubleTy) { 1970 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type); 1971 if (D) 1972 PD << D; 1973 else 1974 PD << "expression"; 1975 1976 if (Diag(Loc, PD, FD) 1977 << false /*show bit size*/ << 0 << Ty << false /*return*/ 1978 << Context.getTargetInfo().getTriple().str()) { 1979 if (D) 1980 D->setInvalidDecl(); 1981 } 1982 if (D) 1983 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D; 1984 } 1985 1986 bool IsDouble = UnqualTy == Context.DoubleTy; 1987 bool IsFloat = UnqualTy == Context.FloatTy; 1988 if (IsRetTy && !TI.hasFPReturn() && (IsDouble || IsFloat)) { 1989 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type); 1990 if (D) 1991 PD << D; 1992 else 1993 PD << "expression"; 1994 1995 if (Diag(Loc, PD, FD) 1996 << false /*show bit size*/ << 0 << Ty << true /*return*/ 1997 << Context.getTargetInfo().getTriple().str()) { 1998 if (D) 1999 D->setInvalidDecl(); 2000 } 2001 if (D) 2002 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D; 2003 } 2004 }; 2005 2006 CheckType(Ty); 2007 if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) { 2008 for (const auto &ParamTy : FPTy->param_types()) 2009 CheckType(ParamTy); 2010 CheckType(FPTy->getReturnType(), /*IsRetTy=*/true); 2011 } 2012 if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Ty)) 2013 CheckType(FNPTy->getReturnType(), /*IsRetTy=*/true); 2014 } 2015 2016 /// Looks through the macro-expansion chain for the given 2017 /// location, looking for a macro expansion with the given name. 2018 /// If one is found, returns true and sets the location to that 2019 /// expansion loc. 2020 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) { 2021 SourceLocation loc = locref; 2022 if (!loc.isMacroID()) return false; 2023 2024 // There's no good way right now to look at the intermediate 2025 // expansions, so just jump to the expansion location. 2026 loc = getSourceManager().getExpansionLoc(loc); 2027 2028 // If that's written with the name, stop here. 2029 SmallString<16> buffer; 2030 if (getPreprocessor().getSpelling(loc, buffer) == name) { 2031 locref = loc; 2032 return true; 2033 } 2034 return false; 2035 } 2036 2037 /// Determines the active Scope associated with the given declaration 2038 /// context. 2039 /// 2040 /// This routine maps a declaration context to the active Scope object that 2041 /// represents that declaration context in the parser. It is typically used 2042 /// from "scope-less" code (e.g., template instantiation, lazy creation of 2043 /// declarations) that injects a name for name-lookup purposes and, therefore, 2044 /// must update the Scope. 2045 /// 2046 /// \returns The scope corresponding to the given declaraion context, or NULL 2047 /// if no such scope is open. 2048 Scope *Sema::getScopeForContext(DeclContext *Ctx) { 2049 2050 if (!Ctx) 2051 return nullptr; 2052 2053 Ctx = Ctx->getPrimaryContext(); 2054 for (Scope *S = getCurScope(); S; S = S->getParent()) { 2055 // Ignore scopes that cannot have declarations. This is important for 2056 // out-of-line definitions of static class members. 2057 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) 2058 if (DeclContext *Entity = S->getEntity()) 2059 if (Ctx == Entity->getPrimaryContext()) 2060 return S; 2061 } 2062 2063 return nullptr; 2064 } 2065 2066 /// Enter a new function scope 2067 void Sema::PushFunctionScope() { 2068 if (FunctionScopes.empty() && CachedFunctionScope) { 2069 // Use CachedFunctionScope to avoid allocating memory when possible. 2070 CachedFunctionScope->Clear(); 2071 FunctionScopes.push_back(CachedFunctionScope.release()); 2072 } else { 2073 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics())); 2074 } 2075 if (LangOpts.OpenMP) 2076 pushOpenMPFunctionRegion(); 2077 } 2078 2079 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) { 2080 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(), 2081 BlockScope, Block)); 2082 } 2083 2084 LambdaScopeInfo *Sema::PushLambdaScope() { 2085 LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics()); 2086 FunctionScopes.push_back(LSI); 2087 return LSI; 2088 } 2089 2090 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) { 2091 if (LambdaScopeInfo *const LSI = getCurLambda()) { 2092 LSI->AutoTemplateParameterDepth = Depth; 2093 return; 2094 } 2095 llvm_unreachable( 2096 "Remove assertion if intentionally called in a non-lambda context."); 2097 } 2098 2099 // Check that the type of the VarDecl has an accessible copy constructor and 2100 // resolve its destructor's exception specification. 2101 // This also performs initialization of block variables when they are moved 2102 // to the heap. It uses the same rules as applicable for implicit moves 2103 // according to the C++ standard in effect ([class.copy.elision]p3). 2104 static void checkEscapingByref(VarDecl *VD, Sema &S) { 2105 QualType T = VD->getType(); 2106 EnterExpressionEvaluationContext scope( 2107 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 2108 SourceLocation Loc = VD->getLocation(); 2109 Expr *VarRef = 2110 new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc); 2111 ExprResult Result; 2112 auto IE = InitializedEntity::InitializeBlock(Loc, T); 2113 if (S.getLangOpts().CPlusPlus2b) { 2114 auto *E = ImplicitCastExpr::Create(S.Context, T, CK_NoOp, VarRef, nullptr, 2115 VK_XValue, FPOptionsOverride()); 2116 Result = S.PerformCopyInitialization(IE, SourceLocation(), E); 2117 } else { 2118 Result = S.PerformMoveOrCopyInitialization( 2119 IE, Sema::NamedReturnInfo{VD, Sema::NamedReturnInfo::MoveEligible}, 2120 VarRef); 2121 } 2122 2123 if (!Result.isInvalid()) { 2124 Result = S.MaybeCreateExprWithCleanups(Result); 2125 Expr *Init = Result.getAs<Expr>(); 2126 S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init)); 2127 } 2128 2129 // The destructor's exception specification is needed when IRGen generates 2130 // block copy/destroy functions. Resolve it here. 2131 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2132 if (CXXDestructorDecl *DD = RD->getDestructor()) { 2133 auto *FPT = DD->getType()->getAs<FunctionProtoType>(); 2134 S.ResolveExceptionSpec(Loc, FPT); 2135 } 2136 } 2137 2138 static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) { 2139 // Set the EscapingByref flag of __block variables captured by 2140 // escaping blocks. 2141 for (const BlockDecl *BD : FSI.Blocks) { 2142 for (const BlockDecl::Capture &BC : BD->captures()) { 2143 VarDecl *VD = BC.getVariable(); 2144 if (VD->hasAttr<BlocksAttr>()) { 2145 // Nothing to do if this is a __block variable captured by a 2146 // non-escaping block. 2147 if (BD->doesNotEscape()) 2148 continue; 2149 VD->setEscapingByref(); 2150 } 2151 // Check whether the captured variable is or contains an object of 2152 // non-trivial C union type. 2153 QualType CapType = BC.getVariable()->getType(); 2154 if (CapType.hasNonTrivialToPrimitiveDestructCUnion() || 2155 CapType.hasNonTrivialToPrimitiveCopyCUnion()) 2156 S.checkNonTrivialCUnion(BC.getVariable()->getType(), 2157 BD->getCaretLocation(), 2158 Sema::NTCUC_BlockCapture, 2159 Sema::NTCUK_Destruct|Sema::NTCUK_Copy); 2160 } 2161 } 2162 2163 for (VarDecl *VD : FSI.ByrefBlockVars) { 2164 // __block variables might require us to capture a copy-initializer. 2165 if (!VD->isEscapingByref()) 2166 continue; 2167 // It's currently invalid to ever have a __block variable with an 2168 // array type; should we diagnose that here? 2169 // Regardless, we don't want to ignore array nesting when 2170 // constructing this copy. 2171 if (VD->getType()->isStructureOrClassType()) 2172 checkEscapingByref(VD, S); 2173 } 2174 } 2175 2176 /// Pop a function (or block or lambda or captured region) scope from the stack. 2177 /// 2178 /// \param WP The warning policy to use for CFG-based warnings, or null if such 2179 /// warnings should not be produced. 2180 /// \param D The declaration corresponding to this function scope, if producing 2181 /// CFG-based warnings. 2182 /// \param BlockType The type of the block expression, if D is a BlockDecl. 2183 Sema::PoppedFunctionScopePtr 2184 Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP, 2185 const Decl *D, QualType BlockType) { 2186 assert(!FunctionScopes.empty() && "mismatched push/pop!"); 2187 2188 markEscapingByrefs(*FunctionScopes.back(), *this); 2189 2190 PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(), 2191 PoppedFunctionScopeDeleter(this)); 2192 2193 if (LangOpts.OpenMP) 2194 popOpenMPFunctionRegion(Scope.get()); 2195 2196 // Issue any analysis-based warnings. 2197 if (WP && D) 2198 AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType); 2199 else 2200 for (const auto &PUD : Scope->PossiblyUnreachableDiags) 2201 Diag(PUD.Loc, PUD.PD); 2202 2203 return Scope; 2204 } 2205 2206 void Sema::PoppedFunctionScopeDeleter:: 2207 operator()(sema::FunctionScopeInfo *Scope) const { 2208 // Stash the function scope for later reuse if it's for a normal function. 2209 if (Scope->isPlainFunction() && !Self->CachedFunctionScope) 2210 Self->CachedFunctionScope.reset(Scope); 2211 else 2212 delete Scope; 2213 } 2214 2215 void Sema::PushCompoundScope(bool IsStmtExpr) { 2216 getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo(IsStmtExpr)); 2217 } 2218 2219 void Sema::PopCompoundScope() { 2220 FunctionScopeInfo *CurFunction = getCurFunction(); 2221 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop"); 2222 2223 CurFunction->CompoundScopes.pop_back(); 2224 } 2225 2226 /// Determine whether any errors occurred within this function/method/ 2227 /// block. 2228 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const { 2229 return getCurFunction()->hasUnrecoverableErrorOccurred(); 2230 } 2231 2232 void Sema::setFunctionHasBranchIntoScope() { 2233 if (!FunctionScopes.empty()) 2234 FunctionScopes.back()->setHasBranchIntoScope(); 2235 } 2236 2237 void Sema::setFunctionHasBranchProtectedScope() { 2238 if (!FunctionScopes.empty()) 2239 FunctionScopes.back()->setHasBranchProtectedScope(); 2240 } 2241 2242 void Sema::setFunctionHasIndirectGoto() { 2243 if (!FunctionScopes.empty()) 2244 FunctionScopes.back()->setHasIndirectGoto(); 2245 } 2246 2247 void Sema::setFunctionHasMustTail() { 2248 if (!FunctionScopes.empty()) 2249 FunctionScopes.back()->setHasMustTail(); 2250 } 2251 2252 BlockScopeInfo *Sema::getCurBlock() { 2253 if (FunctionScopes.empty()) 2254 return nullptr; 2255 2256 auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back()); 2257 if (CurBSI && CurBSI->TheDecl && 2258 !CurBSI->TheDecl->Encloses(CurContext)) { 2259 // We have switched contexts due to template instantiation. 2260 assert(!CodeSynthesisContexts.empty()); 2261 return nullptr; 2262 } 2263 2264 return CurBSI; 2265 } 2266 2267 FunctionScopeInfo *Sema::getEnclosingFunction() const { 2268 if (FunctionScopes.empty()) 2269 return nullptr; 2270 2271 for (int e = FunctionScopes.size() - 1; e >= 0; --e) { 2272 if (isa<sema::BlockScopeInfo>(FunctionScopes[e])) 2273 continue; 2274 return FunctionScopes[e]; 2275 } 2276 return nullptr; 2277 } 2278 2279 LambdaScopeInfo *Sema::getEnclosingLambda() const { 2280 for (auto *Scope : llvm::reverse(FunctionScopes)) { 2281 if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope)) { 2282 if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext)) { 2283 // We have switched contexts due to template instantiation. 2284 // FIXME: We should swap out the FunctionScopes during code synthesis 2285 // so that we don't need to check for this. 2286 assert(!CodeSynthesisContexts.empty()); 2287 return nullptr; 2288 } 2289 return LSI; 2290 } 2291 } 2292 return nullptr; 2293 } 2294 2295 LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) { 2296 if (FunctionScopes.empty()) 2297 return nullptr; 2298 2299 auto I = FunctionScopes.rbegin(); 2300 if (IgnoreNonLambdaCapturingScope) { 2301 auto E = FunctionScopes.rend(); 2302 while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I)) 2303 ++I; 2304 if (I == E) 2305 return nullptr; 2306 } 2307 auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I); 2308 if (CurLSI && CurLSI->Lambda && 2309 !CurLSI->Lambda->Encloses(CurContext)) { 2310 // We have switched contexts due to template instantiation. 2311 assert(!CodeSynthesisContexts.empty()); 2312 return nullptr; 2313 } 2314 2315 return CurLSI; 2316 } 2317 2318 // We have a generic lambda if we parsed auto parameters, or we have 2319 // an associated template parameter list. 2320 LambdaScopeInfo *Sema::getCurGenericLambda() { 2321 if (LambdaScopeInfo *LSI = getCurLambda()) { 2322 return (LSI->TemplateParams.size() || 2323 LSI->GLTemplateParameterList) ? LSI : nullptr; 2324 } 2325 return nullptr; 2326 } 2327 2328 2329 void Sema::ActOnComment(SourceRange Comment) { 2330 if (!LangOpts.RetainCommentsFromSystemHeaders && 2331 SourceMgr.isInSystemHeader(Comment.getBegin())) 2332 return; 2333 RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false); 2334 if (RC.isAlmostTrailingComment()) { 2335 SourceRange MagicMarkerRange(Comment.getBegin(), 2336 Comment.getBegin().getLocWithOffset(3)); 2337 StringRef MagicMarkerText; 2338 switch (RC.getKind()) { 2339 case RawComment::RCK_OrdinaryBCPL: 2340 MagicMarkerText = "///<"; 2341 break; 2342 case RawComment::RCK_OrdinaryC: 2343 MagicMarkerText = "/**<"; 2344 break; 2345 default: 2346 llvm_unreachable("if this is an almost Doxygen comment, " 2347 "it should be ordinary"); 2348 } 2349 Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) << 2350 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText); 2351 } 2352 Context.addComment(RC); 2353 } 2354 2355 // Pin this vtable to this file. 2356 ExternalSemaSource::~ExternalSemaSource() {} 2357 char ExternalSemaSource::ID; 2358 2359 void ExternalSemaSource::ReadMethodPool(Selector Sel) { } 2360 void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { } 2361 2362 void ExternalSemaSource::ReadKnownNamespaces( 2363 SmallVectorImpl<NamespaceDecl *> &Namespaces) { 2364 } 2365 2366 void ExternalSemaSource::ReadUndefinedButUsed( 2367 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {} 2368 2369 void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector< 2370 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {} 2371 2372 /// Figure out if an expression could be turned into a call. 2373 /// 2374 /// Use this when trying to recover from an error where the programmer may have 2375 /// written just the name of a function instead of actually calling it. 2376 /// 2377 /// \param E - The expression to examine. 2378 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call 2379 /// with no arguments, this parameter is set to the type returned by such a 2380 /// call; otherwise, it is set to an empty QualType. 2381 /// \param OverloadSet - If the expression is an overloaded function 2382 /// name, this parameter is populated with the decls of the various overloads. 2383 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, 2384 UnresolvedSetImpl &OverloadSet) { 2385 ZeroArgCallReturnTy = QualType(); 2386 OverloadSet.clear(); 2387 2388 const OverloadExpr *Overloads = nullptr; 2389 bool IsMemExpr = false; 2390 if (E.getType() == Context.OverloadTy) { 2391 OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E)); 2392 2393 // Ignore overloads that are pointer-to-member constants. 2394 if (FR.HasFormOfMemberPointer) 2395 return false; 2396 2397 Overloads = FR.Expression; 2398 } else if (E.getType() == Context.BoundMemberTy) { 2399 Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens()); 2400 IsMemExpr = true; 2401 } 2402 2403 bool Ambiguous = false; 2404 bool IsMV = false; 2405 2406 if (Overloads) { 2407 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(), 2408 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) { 2409 OverloadSet.addDecl(*it); 2410 2411 // Check whether the function is a non-template, non-member which takes no 2412 // arguments. 2413 if (IsMemExpr) 2414 continue; 2415 if (const FunctionDecl *OverloadDecl 2416 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) { 2417 if (OverloadDecl->getMinRequiredArguments() == 0) { 2418 if (!ZeroArgCallReturnTy.isNull() && !Ambiguous && 2419 (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() || 2420 OverloadDecl->isCPUSpecificMultiVersion()))) { 2421 ZeroArgCallReturnTy = QualType(); 2422 Ambiguous = true; 2423 } else { 2424 ZeroArgCallReturnTy = OverloadDecl->getReturnType(); 2425 IsMV = OverloadDecl->isCPUDispatchMultiVersion() || 2426 OverloadDecl->isCPUSpecificMultiVersion(); 2427 } 2428 } 2429 } 2430 } 2431 2432 // If it's not a member, use better machinery to try to resolve the call 2433 if (!IsMemExpr) 2434 return !ZeroArgCallReturnTy.isNull(); 2435 } 2436 2437 // Attempt to call the member with no arguments - this will correctly handle 2438 // member templates with defaults/deduction of template arguments, overloads 2439 // with default arguments, etc. 2440 if (IsMemExpr && !E.isTypeDependent()) { 2441 Sema::TentativeAnalysisScope Trap(*this); 2442 ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(), 2443 None, SourceLocation()); 2444 if (R.isUsable()) { 2445 ZeroArgCallReturnTy = R.get()->getType(); 2446 return true; 2447 } 2448 return false; 2449 } 2450 2451 if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) { 2452 if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) { 2453 if (Fun->getMinRequiredArguments() == 0) 2454 ZeroArgCallReturnTy = Fun->getReturnType(); 2455 return true; 2456 } 2457 } 2458 2459 // We don't have an expression that's convenient to get a FunctionDecl from, 2460 // but we can at least check if the type is "function of 0 arguments". 2461 QualType ExprTy = E.getType(); 2462 const FunctionType *FunTy = nullptr; 2463 QualType PointeeTy = ExprTy->getPointeeType(); 2464 if (!PointeeTy.isNull()) 2465 FunTy = PointeeTy->getAs<FunctionType>(); 2466 if (!FunTy) 2467 FunTy = ExprTy->getAs<FunctionType>(); 2468 2469 if (const FunctionProtoType *FPT = 2470 dyn_cast_or_null<FunctionProtoType>(FunTy)) { 2471 if (FPT->getNumParams() == 0) 2472 ZeroArgCallReturnTy = FunTy->getReturnType(); 2473 return true; 2474 } 2475 return false; 2476 } 2477 2478 /// Give notes for a set of overloads. 2479 /// 2480 /// A companion to tryExprAsCall. In cases when the name that the programmer 2481 /// wrote was an overloaded function, we may be able to make some guesses about 2482 /// plausible overloads based on their return types; such guesses can be handed 2483 /// off to this method to be emitted as notes. 2484 /// 2485 /// \param Overloads - The overloads to note. 2486 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to 2487 /// -fshow-overloads=best, this is the location to attach to the note about too 2488 /// many candidates. Typically this will be the location of the original 2489 /// ill-formed expression. 2490 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, 2491 const SourceLocation FinalNoteLoc) { 2492 unsigned ShownOverloads = 0; 2493 unsigned SuppressedOverloads = 0; 2494 for (UnresolvedSetImpl::iterator It = Overloads.begin(), 2495 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { 2496 if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) { 2497 ++SuppressedOverloads; 2498 continue; 2499 } 2500 2501 NamedDecl *Fn = (*It)->getUnderlyingDecl(); 2502 // Don't print overloads for non-default multiversioned functions. 2503 if (const auto *FD = Fn->getAsFunction()) { 2504 if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() && 2505 !FD->getAttr<TargetAttr>()->isDefaultVersion()) 2506 continue; 2507 } 2508 S.Diag(Fn->getLocation(), diag::note_possible_target_of_call); 2509 ++ShownOverloads; 2510 } 2511 2512 S.Diags.overloadCandidatesShown(ShownOverloads); 2513 2514 if (SuppressedOverloads) 2515 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates) 2516 << SuppressedOverloads; 2517 } 2518 2519 static void notePlausibleOverloads(Sema &S, SourceLocation Loc, 2520 const UnresolvedSetImpl &Overloads, 2521 bool (*IsPlausibleResult)(QualType)) { 2522 if (!IsPlausibleResult) 2523 return noteOverloads(S, Overloads, Loc); 2524 2525 UnresolvedSet<2> PlausibleOverloads; 2526 for (OverloadExpr::decls_iterator It = Overloads.begin(), 2527 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { 2528 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It); 2529 QualType OverloadResultTy = OverloadDecl->getReturnType(); 2530 if (IsPlausibleResult(OverloadResultTy)) 2531 PlausibleOverloads.addDecl(It.getDecl()); 2532 } 2533 noteOverloads(S, PlausibleOverloads, Loc); 2534 } 2535 2536 /// Determine whether the given expression can be called by just 2537 /// putting parentheses after it. Notably, expressions with unary 2538 /// operators can't be because the unary operator will start parsing 2539 /// outside the call. 2540 static bool IsCallableWithAppend(Expr *E) { 2541 E = E->IgnoreImplicit(); 2542 return (!isa<CStyleCastExpr>(E) && 2543 !isa<UnaryOperator>(E) && 2544 !isa<BinaryOperator>(E) && 2545 !isa<CXXOperatorCallExpr>(E)); 2546 } 2547 2548 static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) { 2549 if (const auto *UO = dyn_cast<UnaryOperator>(E)) 2550 E = UO->getSubExpr(); 2551 2552 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 2553 if (ULE->getNumDecls() == 0) 2554 return false; 2555 2556 const NamedDecl *ND = *ULE->decls_begin(); 2557 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 2558 return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion(); 2559 } 2560 return false; 2561 } 2562 2563 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 2564 bool ForceComplain, 2565 bool (*IsPlausibleResult)(QualType)) { 2566 SourceLocation Loc = E.get()->getExprLoc(); 2567 SourceRange Range = E.get()->getSourceRange(); 2568 UnresolvedSet<4> Overloads; 2569 2570 // If this is a SFINAE context, don't try anything that might trigger ADL 2571 // prematurely. 2572 if (!isSFINAEContext()) { 2573 QualType ZeroArgCallTy; 2574 if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) && 2575 !ZeroArgCallTy.isNull() && 2576 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) { 2577 // At this point, we know E is potentially callable with 0 2578 // arguments and that it returns something of a reasonable type, 2579 // so we can emit a fixit and carry on pretending that E was 2580 // actually a CallExpr. 2581 SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd()); 2582 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get()); 2583 Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range 2584 << (IsCallableWithAppend(E.get()) 2585 ? FixItHint::CreateInsertion(ParenInsertionLoc, 2586 "()") 2587 : FixItHint()); 2588 if (!IsMV) 2589 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult); 2590 2591 // FIXME: Try this before emitting the fixit, and suppress diagnostics 2592 // while doing so. 2593 E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), None, 2594 Range.getEnd().getLocWithOffset(1)); 2595 return true; 2596 } 2597 } 2598 if (!ForceComplain) return false; 2599 2600 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get()); 2601 Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range; 2602 if (!IsMV) 2603 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult); 2604 E = ExprError(); 2605 return true; 2606 } 2607 2608 IdentifierInfo *Sema::getSuperIdentifier() const { 2609 if (!Ident_super) 2610 Ident_super = &Context.Idents.get("super"); 2611 return Ident_super; 2612 } 2613 2614 IdentifierInfo *Sema::getFloat128Identifier() const { 2615 if (!Ident___float128) 2616 Ident___float128 = &Context.Idents.get("__float128"); 2617 return Ident___float128; 2618 } 2619 2620 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD, 2621 CapturedRegionKind K, 2622 unsigned OpenMPCaptureLevel) { 2623 auto *CSI = new CapturedRegionScopeInfo( 2624 getDiagnostics(), S, CD, RD, CD->getContextParam(), K, 2625 (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0, 2626 OpenMPCaptureLevel); 2627 CSI->ReturnType = Context.VoidTy; 2628 FunctionScopes.push_back(CSI); 2629 } 2630 2631 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() { 2632 if (FunctionScopes.empty()) 2633 return nullptr; 2634 2635 return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back()); 2636 } 2637 2638 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> & 2639 Sema::getMismatchingDeleteExpressions() const { 2640 return DeleteExprs; 2641 } 2642 2643 Sema::FPFeaturesStateRAII::FPFeaturesStateRAII(Sema &S) 2644 : S(S), OldFPFeaturesState(S.CurFPFeatures), 2645 OldOverrides(S.FpPragmaStack.CurrentValue), 2646 OldEvalMethod(S.PP.getCurrentFPEvalMethod()), 2647 OldFPPragmaLocation(S.PP.getLastFPEvalPragmaLocation()) {} 2648 2649 Sema::FPFeaturesStateRAII::~FPFeaturesStateRAII() { 2650 S.CurFPFeatures = OldFPFeaturesState; 2651 S.FpPragmaStack.CurrentValue = OldOverrides; 2652 S.PP.setCurrentFPEvalMethod(OldFPPragmaLocation, OldEvalMethod); 2653 } 2654