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