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