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