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