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