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