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