1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the actions class which performs semantic analysis and 11 // builds an AST out of a parse stream. 12 // 13 //===----------------------------------------------------------------------===// 14 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/StmtCXX.h" 23 #include "clang/Basic/DiagnosticOptions.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Lex/HeaderSearch.h" 27 #include "clang/Lex/Preprocessor.h" 28 #include "clang/Sema/CXXFieldCollector.h" 29 #include "clang/Sema/DelayedDiagnostic.h" 30 #include "clang/Sema/ExternalSemaSource.h" 31 #include "clang/Sema/Initialization.h" 32 #include "clang/Sema/MultiplexExternalSemaSource.h" 33 #include "clang/Sema/ObjCMethodList.h" 34 #include "clang/Sema/PrettyDeclStackTrace.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 "llvm/ADT/DenseMap.h" 41 #include "llvm/ADT/SmallSet.h" 42 using namespace clang; 43 using namespace sema; 44 45 SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) { 46 return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts); 47 } 48 49 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); } 50 51 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context, 52 const Preprocessor &PP) { 53 PrintingPolicy Policy = Context.getPrintingPolicy(); 54 // Our printing policy is copied over the ASTContext printing policy whenever 55 // a diagnostic is emitted, so recompute it. 56 Policy.Bool = Context.getLangOpts().Bool; 57 if (!Policy.Bool) { 58 if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) { 59 Policy.Bool = BoolMacro->isObjectLike() && 60 BoolMacro->getNumTokens() == 1 && 61 BoolMacro->getReplacementToken(0).is(tok::kw__Bool); 62 } 63 } 64 65 return Policy; 66 } 67 68 void Sema::ActOnTranslationUnitScope(Scope *S) { 69 TUScope = S; 70 PushDeclContext(S, Context.getTranslationUnitDecl()); 71 } 72 73 namespace clang { 74 namespace sema { 75 76 class SemaPPCallbacks : public PPCallbacks { 77 Sema *S = nullptr; 78 llvm::SmallVector<SourceLocation, 8> IncludeStack; 79 80 public: 81 void set(Sema &S) { this->S = &S; } 82 83 void reset() { S = nullptr; } 84 85 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason, 86 SrcMgr::CharacteristicKind FileType, 87 FileID PrevFID) override { 88 if (!S) 89 return; 90 switch (Reason) { 91 case EnterFile: { 92 SourceManager &SM = S->getSourceManager(); 93 SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc)); 94 if (IncludeLoc.isValid()) { 95 IncludeStack.push_back(IncludeLoc); 96 S->DiagnoseNonDefaultPragmaPack( 97 Sema::PragmaPackDiagnoseKind::NonDefaultStateAtInclude, IncludeLoc); 98 } 99 break; 100 } 101 case ExitFile: 102 if (!IncludeStack.empty()) 103 S->DiagnoseNonDefaultPragmaPack( 104 Sema::PragmaPackDiagnoseKind::ChangedStateAtExit, 105 IncludeStack.pop_back_val()); 106 break; 107 default: 108 break; 109 } 110 } 111 }; 112 113 } // end namespace sema 114 } // end namespace clang 115 116 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 117 TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter) 118 : ExternalSource(nullptr), isMultiplexExternalSource(false), 119 FPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp), 120 Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()), 121 SourceMgr(PP.getSourceManager()), CollectStats(false), 122 CodeCompleter(CodeCompleter), CurContext(nullptr), 123 OriginalLexicalContext(nullptr), MSStructPragmaOn(false), 124 MSPointerToMemberRepresentationMethod( 125 LangOpts.getMSPointerToMemberRepresentationMethod()), 126 VtorDispStack(MSVtorDispAttr::Mode(LangOpts.VtorDispMode)), PackStack(0), 127 DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr), 128 CodeSegStack(nullptr), CurInitSeg(nullptr), VisContext(nullptr), 129 PragmaAttributeCurrentTargetDecl(nullptr), 130 IsBuildingRecoveryCallExpr(false), Cleanup{}, LateTemplateParser(nullptr), 131 LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp), 132 StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr), 133 CXXTypeInfoDecl(nullptr), MSVCGuidDecl(nullptr), NSNumberDecl(nullptr), 134 NSValueDecl(nullptr), NSStringDecl(nullptr), 135 StringWithUTF8StringMethod(nullptr), 136 ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr), 137 ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr), 138 DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false), 139 TUKind(TUKind), NumSFINAEErrors(0), AccessCheckingSFINAE(false), 140 InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0), 141 ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr), 142 DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this), 143 ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr), 144 CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) { 145 TUScope = nullptr; 146 147 LoadedExternalKnownNamespaces = false; 148 for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I) 149 NSNumberLiteralMethods[I] = nullptr; 150 151 if (getLangOpts().ObjC1) 152 NSAPIObj.reset(new NSAPI(Context)); 153 154 if (getLangOpts().CPlusPlus) 155 FieldCollector.reset(new CXXFieldCollector()); 156 157 // Tell diagnostics how to render things from the AST library. 158 Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context); 159 160 ExprEvalContexts.emplace_back( 161 ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{}, 162 nullptr, false); 163 164 FunctionScopes.push_back(new FunctionScopeInfo(Diags)); 165 166 // Initilization of data sharing attributes stack for OpenMP 167 InitDataSharingAttributesStack(); 168 169 std::unique_ptr<sema::SemaPPCallbacks> Callbacks = 170 llvm::make_unique<sema::SemaPPCallbacks>(); 171 SemaPPCallbackHandler = Callbacks.get(); 172 PP.addPPCallbacks(std::move(Callbacks)); 173 SemaPPCallbackHandler->set(*this); 174 } 175 176 void Sema::addImplicitTypedef(StringRef Name, QualType T) { 177 DeclarationName DN = &Context.Idents.get(Name); 178 if (IdResolver.begin(DN) == IdResolver.end()) 179 PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope); 180 } 181 182 void Sema::Initialize() { 183 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 184 SC->InitializeSema(*this); 185 186 // Tell the external Sema source about this Sema object. 187 if (ExternalSemaSource *ExternalSema 188 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 189 ExternalSema->InitializeSema(*this); 190 191 // This needs to happen after ExternalSemaSource::InitializeSema(this) or we 192 // will not be able to merge any duplicate __va_list_tag decls correctly. 193 VAListTagName = PP.getIdentifierInfo("__va_list_tag"); 194 195 if (!TUScope) 196 return; 197 198 // Initialize predefined 128-bit integer types, if needed. 199 if (Context.getTargetInfo().hasInt128Type()) { 200 // If either of the 128-bit integer types are unavailable to name lookup, 201 // define them now. 202 DeclarationName Int128 = &Context.Idents.get("__int128_t"); 203 if (IdResolver.begin(Int128) == IdResolver.end()) 204 PushOnScopeChains(Context.getInt128Decl(), TUScope); 205 206 DeclarationName UInt128 = &Context.Idents.get("__uint128_t"); 207 if (IdResolver.begin(UInt128) == IdResolver.end()) 208 PushOnScopeChains(Context.getUInt128Decl(), TUScope); 209 } 210 211 212 // Initialize predefined Objective-C types: 213 if (getLangOpts().ObjC1) { 214 // If 'SEL' does not yet refer to any declarations, make it refer to the 215 // predefined 'SEL'. 216 DeclarationName SEL = &Context.Idents.get("SEL"); 217 if (IdResolver.begin(SEL) == IdResolver.end()) 218 PushOnScopeChains(Context.getObjCSelDecl(), TUScope); 219 220 // If 'id' does not yet refer to any declarations, make it refer to the 221 // predefined 'id'. 222 DeclarationName Id = &Context.Idents.get("id"); 223 if (IdResolver.begin(Id) == IdResolver.end()) 224 PushOnScopeChains(Context.getObjCIdDecl(), TUScope); 225 226 // Create the built-in typedef for 'Class'. 227 DeclarationName Class = &Context.Idents.get("Class"); 228 if (IdResolver.begin(Class) == IdResolver.end()) 229 PushOnScopeChains(Context.getObjCClassDecl(), TUScope); 230 231 // Create the built-in forward declaratino for 'Protocol'. 232 DeclarationName Protocol = &Context.Idents.get("Protocol"); 233 if (IdResolver.begin(Protocol) == IdResolver.end()) 234 PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope); 235 } 236 237 // Create the internal type for the *StringMakeConstantString builtins. 238 DeclarationName ConstantString = &Context.Idents.get("__NSConstantString"); 239 if (IdResolver.begin(ConstantString) == IdResolver.end()) 240 PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope); 241 242 // Initialize Microsoft "predefined C++ types". 243 if (getLangOpts().MSVCCompat) { 244 if (getLangOpts().CPlusPlus && 245 IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end()) 246 PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class), 247 TUScope); 248 249 addImplicitTypedef("size_t", Context.getSizeType()); 250 } 251 252 // Initialize predefined OpenCL types and supported extensions and (optional) 253 // core features. 254 if (getLangOpts().OpenCL) { 255 getOpenCLOptions().addSupport(Context.getTargetInfo().getSupportedOpenCLOpts()); 256 getOpenCLOptions().enableSupportedCore(getLangOpts().OpenCLVersion); 257 addImplicitTypedef("sampler_t", Context.OCLSamplerTy); 258 addImplicitTypedef("event_t", Context.OCLEventTy); 259 if (getLangOpts().OpenCLVersion >= 200) { 260 addImplicitTypedef("clk_event_t", Context.OCLClkEventTy); 261 addImplicitTypedef("queue_t", Context.OCLQueueTy); 262 addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy); 263 addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy)); 264 addImplicitTypedef("atomic_uint", 265 Context.getAtomicType(Context.UnsignedIntTy)); 266 auto AtomicLongT = Context.getAtomicType(Context.LongTy); 267 addImplicitTypedef("atomic_long", AtomicLongT); 268 auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy); 269 addImplicitTypedef("atomic_ulong", AtomicULongT); 270 addImplicitTypedef("atomic_float", 271 Context.getAtomicType(Context.FloatTy)); 272 auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy); 273 addImplicitTypedef("atomic_double", AtomicDoubleT); 274 // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as 275 // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide. 276 addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy)); 277 auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType()); 278 addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT); 279 auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType()); 280 addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT); 281 auto AtomicSizeT = Context.getAtomicType(Context.getSizeType()); 282 addImplicitTypedef("atomic_size_t", AtomicSizeT); 283 auto AtomicPtrDiffT = Context.getAtomicType(Context.getPointerDiffType()); 284 addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT); 285 286 // OpenCL v2.0 s6.13.11.6: 287 // - The atomic_long and atomic_ulong types are supported if the 288 // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics 289 // extensions are supported. 290 // - The atomic_double type is only supported if double precision 291 // is supported and the cl_khr_int64_base_atomics and 292 // cl_khr_int64_extended_atomics extensions are supported. 293 // - If the device address space is 64-bits, the data types 294 // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and 295 // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and 296 // cl_khr_int64_extended_atomics extensions are supported. 297 std::vector<QualType> Atomic64BitTypes; 298 Atomic64BitTypes.push_back(AtomicLongT); 299 Atomic64BitTypes.push_back(AtomicULongT); 300 Atomic64BitTypes.push_back(AtomicDoubleT); 301 if (Context.getTypeSize(AtomicSizeT) == 64) { 302 Atomic64BitTypes.push_back(AtomicSizeT); 303 Atomic64BitTypes.push_back(AtomicIntPtrT); 304 Atomic64BitTypes.push_back(AtomicUIntPtrT); 305 Atomic64BitTypes.push_back(AtomicPtrDiffT); 306 } 307 for (auto &I : Atomic64BitTypes) 308 setOpenCLExtensionForType(I, 309 "cl_khr_int64_base_atomics cl_khr_int64_extended_atomics"); 310 311 setOpenCLExtensionForType(AtomicDoubleT, "cl_khr_fp64"); 312 } 313 314 setOpenCLExtensionForType(Context.DoubleTy, "cl_khr_fp64"); 315 316 #define GENERIC_IMAGE_TYPE_EXT(Type, Id, Ext) \ 317 setOpenCLExtensionForType(Context.Id, Ext); 318 #include "clang/Basic/OpenCLImageTypes.def" 319 }; 320 321 if (Context.getTargetInfo().hasBuiltinMSVaList()) { 322 DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list"); 323 if (IdResolver.begin(MSVaList) == IdResolver.end()) 324 PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope); 325 } 326 327 DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list"); 328 if (IdResolver.begin(BuiltinVaList) == IdResolver.end()) 329 PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope); 330 } 331 332 Sema::~Sema() { 333 if (VisContext) FreeVisContext(); 334 // Kill all the active scopes. 335 for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I) 336 delete FunctionScopes[I]; 337 if (FunctionScopes.size() == 1) 338 delete FunctionScopes[0]; 339 340 // Tell the SemaConsumer to forget about us; we're going out of scope. 341 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 342 SC->ForgetSema(); 343 344 // Detach from the external Sema source. 345 if (ExternalSemaSource *ExternalSema 346 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 347 ExternalSema->ForgetSema(); 348 349 // If Sema's ExternalSource is the multiplexer - we own it. 350 if (isMultiplexExternalSource) 351 delete ExternalSource; 352 353 threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache); 354 355 // Destroys data sharing attributes stack for OpenMP 356 DestroyDataSharingAttributesStack(); 357 358 // Detach from the PP callback handler which outlives Sema since it's owned 359 // by the preprocessor. 360 SemaPPCallbackHandler->reset(); 361 362 assert(DelayedTypos.empty() && "Uncorrected typos!"); 363 } 364 365 /// makeUnavailableInSystemHeader - There is an error in the current 366 /// context. If we're still in a system header, and we can plausibly 367 /// make the relevant declaration unavailable instead of erroring, do 368 /// so and return true. 369 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc, 370 UnavailableAttr::ImplicitReason reason) { 371 // If we're not in a function, it's an error. 372 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext); 373 if (!fn) return false; 374 375 // If we're in template instantiation, it's an error. 376 if (inTemplateInstantiation()) 377 return false; 378 379 // If that function's not in a system header, it's an error. 380 if (!Context.getSourceManager().isInSystemHeader(loc)) 381 return false; 382 383 // If the function is already unavailable, it's not an error. 384 if (fn->hasAttr<UnavailableAttr>()) return true; 385 386 fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc)); 387 return true; 388 } 389 390 ASTMutationListener *Sema::getASTMutationListener() const { 391 return getASTConsumer().GetASTMutationListener(); 392 } 393 394 ///\brief Registers an external source. If an external source already exists, 395 /// creates a multiplex external source and appends to it. 396 /// 397 ///\param[in] E - A non-null external sema source. 398 /// 399 void Sema::addExternalSource(ExternalSemaSource *E) { 400 assert(E && "Cannot use with NULL ptr"); 401 402 if (!ExternalSource) { 403 ExternalSource = E; 404 return; 405 } 406 407 if (isMultiplexExternalSource) 408 static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E); 409 else { 410 ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E); 411 isMultiplexExternalSource = true; 412 } 413 } 414 415 /// \brief Print out statistics about the semantic analysis. 416 void Sema::PrintStats() const { 417 llvm::errs() << "\n*** Semantic Analysis Stats:\n"; 418 llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n"; 419 420 BumpAlloc.PrintStats(); 421 AnalysisWarnings.PrintStats(); 422 } 423 424 void Sema::diagnoseNullableToNonnullConversion(QualType DstType, 425 QualType SrcType, 426 SourceLocation Loc) { 427 Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context); 428 if (!ExprNullability || *ExprNullability != NullabilityKind::Nullable) 429 return; 430 431 Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context); 432 if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull) 433 return; 434 435 Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType; 436 } 437 438 void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr* E) { 439 if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer) 440 return; 441 if (E->getType()->isNullPtrType()) 442 return; 443 // nullptr only exists from C++11 on, so don't warn on its absence earlier. 444 if (!getLangOpts().CPlusPlus11) 445 return; 446 447 Diag(E->getLocStart(), diag::warn_zero_as_null_pointer_constant) 448 << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr"); 449 } 450 451 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 452 /// If there is already an implicit cast, merge into the existing one. 453 /// The result is of the given category. 454 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty, 455 CastKind Kind, ExprValueKind VK, 456 const CXXCastPath *BasePath, 457 CheckedConversionKind CCK) { 458 #ifndef NDEBUG 459 if (VK == VK_RValue && !E->isRValue()) { 460 switch (Kind) { 461 default: 462 llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast " 463 "kind"); 464 case CK_LValueToRValue: 465 case CK_ArrayToPointerDecay: 466 case CK_FunctionToPointerDecay: 467 case CK_ToVoid: 468 break; 469 } 470 } 471 assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue"); 472 #endif 473 474 diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getLocStart()); 475 diagnoseZeroToNullptrConversion(Kind, E); 476 477 QualType ExprTy = Context.getCanonicalType(E->getType()); 478 QualType TypeTy = Context.getCanonicalType(Ty); 479 480 if (ExprTy == TypeTy) 481 return E; 482 483 // C++1z [conv.array]: The temporary materialization conversion is applied. 484 // We also use this to fuel C++ DR1213, which applies to C++11 onwards. 485 if (Kind == CK_ArrayToPointerDecay && getLangOpts().CPlusPlus && 486 E->getValueKind() == VK_RValue) { 487 // The temporary is an lvalue in C++98 and an xvalue otherwise. 488 ExprResult Materialized = CreateMaterializeTemporaryExpr( 489 E->getType(), E, !getLangOpts().CPlusPlus11); 490 if (Materialized.isInvalid()) 491 return ExprError(); 492 E = Materialized.get(); 493 } 494 495 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) { 496 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) { 497 ImpCast->setType(Ty); 498 ImpCast->setValueKind(VK); 499 return E; 500 } 501 } 502 503 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK); 504 } 505 506 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 507 /// to the conversion from scalar type ScalarTy to the Boolean type. 508 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) { 509 switch (ScalarTy->getScalarTypeKind()) { 510 case Type::STK_Bool: return CK_NoOp; 511 case Type::STK_CPointer: return CK_PointerToBoolean; 512 case Type::STK_BlockPointer: return CK_PointerToBoolean; 513 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean; 514 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean; 515 case Type::STK_Integral: return CK_IntegralToBoolean; 516 case Type::STK_Floating: return CK_FloatingToBoolean; 517 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean; 518 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean; 519 } 520 return CK_Invalid; 521 } 522 523 /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector. 524 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) { 525 if (D->getMostRecentDecl()->isUsed()) 526 return true; 527 528 if (D->isExternallyVisible()) 529 return true; 530 531 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 532 // If this is a function template and none of its specializations is used, 533 // we should warn. 534 if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate()) 535 for (const auto *Spec : Template->specializations()) 536 if (ShouldRemoveFromUnused(SemaRef, Spec)) 537 return true; 538 539 // UnusedFileScopedDecls stores the first declaration. 540 // The declaration may have become definition so check again. 541 const FunctionDecl *DeclToCheck; 542 if (FD->hasBody(DeclToCheck)) 543 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 544 545 // Later redecls may add new information resulting in not having to warn, 546 // so check again. 547 DeclToCheck = FD->getMostRecentDecl(); 548 if (DeclToCheck != FD) 549 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 550 } 551 552 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 553 // If a variable usable in constant expressions is referenced, 554 // don't warn if it isn't used: if the value of a variable is required 555 // for the computation of a constant expression, it doesn't make sense to 556 // warn even if the variable isn't odr-used. (isReferenced doesn't 557 // precisely reflect that, but it's a decent approximation.) 558 if (VD->isReferenced() && 559 VD->isUsableInConstantExpressions(SemaRef->Context)) 560 return true; 561 562 if (VarTemplateDecl *Template = VD->getDescribedVarTemplate()) 563 // If this is a variable template and none of its specializations is used, 564 // we should warn. 565 for (const auto *Spec : Template->specializations()) 566 if (ShouldRemoveFromUnused(SemaRef, Spec)) 567 return true; 568 569 // UnusedFileScopedDecls stores the first declaration. 570 // The declaration may have become definition so check again. 571 const VarDecl *DeclToCheck = VD->getDefinition(); 572 if (DeclToCheck) 573 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 574 575 // Later redecls may add new information resulting in not having to warn, 576 // so check again. 577 DeclToCheck = VD->getMostRecentDecl(); 578 if (DeclToCheck != VD) 579 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 580 } 581 582 return false; 583 } 584 585 /// Obtains a sorted list of functions and variables that are undefined but 586 /// ODR-used. 587 void Sema::getUndefinedButUsed( 588 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) { 589 for (const auto &UndefinedUse : UndefinedButUsed) { 590 NamedDecl *ND = UndefinedUse.first; 591 592 // Ignore attributes that have become invalid. 593 if (ND->isInvalidDecl()) continue; 594 595 // __attribute__((weakref)) is basically a definition. 596 if (ND->hasAttr<WeakRefAttr>()) continue; 597 598 if (isa<CXXDeductionGuideDecl>(ND)) 599 continue; 600 601 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 602 if (FD->isDefined()) 603 continue; 604 if (FD->isExternallyVisible() && 605 !FD->getMostRecentDecl()->isInlined()) 606 continue; 607 } else { 608 auto *VD = cast<VarDecl>(ND); 609 if (VD->hasDefinition() != VarDecl::DeclarationOnly) 610 continue; 611 if (VD->isExternallyVisible() && !VD->getMostRecentDecl()->isInline()) 612 continue; 613 } 614 615 Undefined.push_back(std::make_pair(ND, UndefinedUse.second)); 616 } 617 } 618 619 /// checkUndefinedButUsed - Check for undefined objects with internal linkage 620 /// or that are inline. 621 static void checkUndefinedButUsed(Sema &S) { 622 if (S.UndefinedButUsed.empty()) return; 623 624 // Collect all the still-undefined entities with internal linkage. 625 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined; 626 S.getUndefinedButUsed(Undefined); 627 if (Undefined.empty()) return; 628 629 for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator 630 I = Undefined.begin(), E = Undefined.end(); I != E; ++I) { 631 NamedDecl *ND = I->first; 632 633 if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) { 634 // An exported function will always be emitted when defined, so even if 635 // the function is inline, it doesn't have to be emitted in this TU. An 636 // imported function implies that it has been exported somewhere else. 637 continue; 638 } 639 640 if (!ND->isExternallyVisible()) { 641 S.Diag(ND->getLocation(), diag::warn_undefined_internal) 642 << isa<VarDecl>(ND) << ND; 643 } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) { 644 (void)FD; 645 assert(FD->getMostRecentDecl()->isInlined() && 646 "used object requires definition but isn't inline or internal?"); 647 // FIXME: This is ill-formed; we should reject. 648 S.Diag(ND->getLocation(), diag::warn_undefined_inline) << ND; 649 } else { 650 assert(cast<VarDecl>(ND)->getMostRecentDecl()->isInline() && 651 "used var requires definition but isn't inline or internal?"); 652 S.Diag(ND->getLocation(), diag::err_undefined_inline_var) << ND; 653 } 654 if (I->second.isValid()) 655 S.Diag(I->second, diag::note_used_here); 656 } 657 658 S.UndefinedButUsed.clear(); 659 } 660 661 void Sema::LoadExternalWeakUndeclaredIdentifiers() { 662 if (!ExternalSource) 663 return; 664 665 SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs; 666 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs); 667 for (auto &WeakID : WeakIDs) 668 WeakUndeclaredIdentifiers.insert(WeakID); 669 } 670 671 672 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap; 673 674 /// \brief Returns true, if all methods and nested classes of the given 675 /// CXXRecordDecl are defined in this translation unit. 676 /// 677 /// Should only be called from ActOnEndOfTranslationUnit so that all 678 /// definitions are actually read. 679 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD, 680 RecordCompleteMap &MNCComplete) { 681 RecordCompleteMap::iterator Cache = MNCComplete.find(RD); 682 if (Cache != MNCComplete.end()) 683 return Cache->second; 684 if (!RD->isCompleteDefinition()) 685 return false; 686 bool Complete = true; 687 for (DeclContext::decl_iterator I = RD->decls_begin(), 688 E = RD->decls_end(); 689 I != E && Complete; ++I) { 690 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I)) 691 Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M)); 692 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I)) 693 // If the template function is marked as late template parsed at this 694 // point, it has not been instantiated and therefore we have not 695 // performed semantic analysis on it yet, so we cannot know if the type 696 // can be considered complete. 697 Complete = !F->getTemplatedDecl()->isLateTemplateParsed() && 698 F->getTemplatedDecl()->isDefined(); 699 else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) { 700 if (R->isInjectedClassName()) 701 continue; 702 if (R->hasDefinition()) 703 Complete = MethodsAndNestedClassesComplete(R->getDefinition(), 704 MNCComplete); 705 else 706 Complete = false; 707 } 708 } 709 MNCComplete[RD] = Complete; 710 return Complete; 711 } 712 713 /// \brief Returns true, if the given CXXRecordDecl is fully defined in this 714 /// translation unit, i.e. all methods are defined or pure virtual and all 715 /// friends, friend functions and nested classes are fully defined in this 716 /// translation unit. 717 /// 718 /// Should only be called from ActOnEndOfTranslationUnit so that all 719 /// definitions are actually read. 720 static bool IsRecordFullyDefined(const CXXRecordDecl *RD, 721 RecordCompleteMap &RecordsComplete, 722 RecordCompleteMap &MNCComplete) { 723 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD); 724 if (Cache != RecordsComplete.end()) 725 return Cache->second; 726 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete); 727 for (CXXRecordDecl::friend_iterator I = RD->friend_begin(), 728 E = RD->friend_end(); 729 I != E && Complete; ++I) { 730 // Check if friend classes and methods are complete. 731 if (TypeSourceInfo *TSI = (*I)->getFriendType()) { 732 // Friend classes are available as the TypeSourceInfo of the FriendDecl. 733 if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl()) 734 Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete); 735 else 736 Complete = false; 737 } else { 738 // Friend functions are available through the NamedDecl of FriendDecl. 739 if (const FunctionDecl *FD = 740 dyn_cast<FunctionDecl>((*I)->getFriendDecl())) 741 Complete = FD->isDefined(); 742 else 743 // This is a template friend, give up. 744 Complete = false; 745 } 746 } 747 RecordsComplete[RD] = Complete; 748 return Complete; 749 } 750 751 void Sema::emitAndClearUnusedLocalTypedefWarnings() { 752 if (ExternalSource) 753 ExternalSource->ReadUnusedLocalTypedefNameCandidates( 754 UnusedLocalTypedefNameCandidates); 755 for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) { 756 if (TD->isReferenced()) 757 continue; 758 Diag(TD->getLocation(), diag::warn_unused_local_typedef) 759 << isa<TypeAliasDecl>(TD) << TD->getDeclName(); 760 } 761 UnusedLocalTypedefNameCandidates.clear(); 762 } 763 764 /// This is called before the very first declaration in the translation unit 765 /// is parsed. Note that the ASTContext may have already injected some 766 /// declarations. 767 void Sema::ActOnStartOfTranslationUnit() { 768 if (getLangOpts().ModulesTS) { 769 SourceLocation StartOfTU = 770 SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); 771 772 // We start in the global module; all those declarations are implicitly 773 // module-private (though they do not have module linkage). 774 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 775 auto *GlobalModule = Map.createGlobalModuleForInterfaceUnit(StartOfTU); 776 assert(GlobalModule && "module creation should not fail"); 777 778 // Enter the scope of the global module. 779 ModuleScopes.push_back({}); 780 ModuleScopes.back().Module = GlobalModule; 781 VisibleModules.setVisible(GlobalModule, StartOfTU); 782 783 // All declarations created from now on are owned by the global module. 784 auto *TU = Context.getTranslationUnitDecl(); 785 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible); 786 TU->setLocalOwningModule(GlobalModule); 787 } 788 } 789 790 /// ActOnEndOfTranslationUnit - This is called at the very end of the 791 /// translation unit when EOF is reached and all but the top-level scope is 792 /// popped. 793 void Sema::ActOnEndOfTranslationUnit() { 794 assert(DelayedDiagnostics.getCurrentPool() == nullptr 795 && "reached end of translation unit with a pool attached?"); 796 797 // If code completion is enabled, don't perform any end-of-translation-unit 798 // work. 799 if (PP.isCodeCompletionEnabled()) 800 return; 801 802 // Complete translation units and modules define vtables and perform implicit 803 // instantiations. PCH files do not. 804 if (TUKind != TU_Prefix) { 805 DiagnoseUseOfUnimplementedSelectors(); 806 807 // If DefinedUsedVTables ends up marking any virtual member functions it 808 // might lead to more pending template instantiations, which we then need 809 // to instantiate. 810 DefineUsedVTables(); 811 812 // C++: Perform implicit template instantiations. 813 // 814 // FIXME: When we perform these implicit instantiations, we do not 815 // carefully keep track of the point of instantiation (C++ [temp.point]). 816 // This means that name lookup that occurs within the template 817 // instantiation will always happen at the end of the translation unit, 818 // so it will find some names that are not required to be found. This is 819 // valid, but we could do better by diagnosing if an instantiation uses a 820 // name that was not visible at its first point of instantiation. 821 if (ExternalSource) { 822 // Load pending instantiations from the external source. 823 SmallVector<PendingImplicitInstantiation, 4> Pending; 824 ExternalSource->ReadPendingInstantiations(Pending); 825 for (auto PII : Pending) 826 if (auto Func = dyn_cast<FunctionDecl>(PII.first)) 827 Func->setInstantiationIsPending(true); 828 PendingInstantiations.insert(PendingInstantiations.begin(), 829 Pending.begin(), Pending.end()); 830 } 831 PerformPendingInstantiations(); 832 833 if (LateTemplateParserCleanup) 834 LateTemplateParserCleanup(OpaqueParser); 835 836 CheckDelayedMemberExceptionSpecs(); 837 } 838 839 DiagnoseUnterminatedPragmaPack(); 840 DiagnoseUnterminatedPragmaAttribute(); 841 842 // All delayed member exception specs should be checked or we end up accepting 843 // incompatible declarations. 844 // FIXME: This is wrong for TUKind == TU_Prefix. In that case, we need to 845 // write out the lists to the AST file (if any). 846 assert(DelayedDefaultedMemberExceptionSpecs.empty()); 847 assert(DelayedExceptionSpecChecks.empty()); 848 849 // All dllexport classes should have been processed already. 850 assert(DelayedDllExportClasses.empty()); 851 852 // Remove file scoped decls that turned out to be used. 853 UnusedFileScopedDecls.erase( 854 std::remove_if(UnusedFileScopedDecls.begin(nullptr, true), 855 UnusedFileScopedDecls.end(), 856 [this](const DeclaratorDecl *DD) { 857 return ShouldRemoveFromUnused(this, DD); 858 }), 859 UnusedFileScopedDecls.end()); 860 861 if (TUKind == TU_Prefix) { 862 // Translation unit prefixes don't need any of the checking below. 863 if (!PP.isIncrementalProcessingEnabled()) 864 TUScope = nullptr; 865 return; 866 } 867 868 // Check for #pragma weak identifiers that were never declared 869 LoadExternalWeakUndeclaredIdentifiers(); 870 for (auto WeakID : WeakUndeclaredIdentifiers) { 871 if (WeakID.second.getUsed()) 872 continue; 873 874 Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(), 875 LookupOrdinaryName); 876 if (PrevDecl != nullptr && 877 !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) 878 Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type) 879 << "'weak'" << ExpectedVariableOrFunction; 880 else 881 Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared) 882 << WeakID.first; 883 } 884 885 if (LangOpts.CPlusPlus11 && 886 !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation())) 887 CheckDelegatingCtorCycles(); 888 889 if (!Diags.hasErrorOccurred()) { 890 if (ExternalSource) 891 ExternalSource->ReadUndefinedButUsed(UndefinedButUsed); 892 checkUndefinedButUsed(*this); 893 } 894 895 if (TUKind == TU_Module) { 896 // If we are building a module, resolve all of the exported declarations 897 // now. 898 if (Module *CurrentModule = PP.getCurrentModule()) { 899 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap(); 900 901 SmallVector<Module *, 2> Stack; 902 Stack.push_back(CurrentModule); 903 while (!Stack.empty()) { 904 Module *Mod = Stack.pop_back_val(); 905 906 // Resolve the exported declarations and conflicts. 907 // FIXME: Actually complain, once we figure out how to teach the 908 // diagnostic client to deal with complaints in the module map at this 909 // point. 910 ModMap.resolveExports(Mod, /*Complain=*/false); 911 ModMap.resolveUses(Mod, /*Complain=*/false); 912 ModMap.resolveConflicts(Mod, /*Complain=*/false); 913 914 // Queue the submodules, so their exports will also be resolved. 915 Stack.append(Mod->submodule_begin(), Mod->submodule_end()); 916 } 917 } 918 919 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for 920 // modules when they are built, not every time they are used. 921 emitAndClearUnusedLocalTypedefWarnings(); 922 923 // Modules don't need any of the checking below. 924 if (!PP.isIncrementalProcessingEnabled()) 925 TUScope = nullptr; 926 return; 927 } 928 929 // C99 6.9.2p2: 930 // A declaration of an identifier for an object that has file 931 // scope without an initializer, and without a storage-class 932 // specifier or with the storage-class specifier static, 933 // constitutes a tentative definition. If a translation unit 934 // contains one or more tentative definitions for an identifier, 935 // and the translation unit contains no external definition for 936 // that identifier, then the behavior is exactly as if the 937 // translation unit contains a file scope declaration of that 938 // identifier, with the composite type as of the end of the 939 // translation unit, with an initializer equal to 0. 940 llvm::SmallSet<VarDecl *, 32> Seen; 941 for (TentativeDefinitionsType::iterator 942 T = TentativeDefinitions.begin(ExternalSource), 943 TEnd = TentativeDefinitions.end(); 944 T != TEnd; ++T) 945 { 946 VarDecl *VD = (*T)->getActingDefinition(); 947 948 // If the tentative definition was completed, getActingDefinition() returns 949 // null. If we've already seen this variable before, insert()'s second 950 // return value is false. 951 if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second) 952 continue; 953 954 if (const IncompleteArrayType *ArrayT 955 = Context.getAsIncompleteArrayType(VD->getType())) { 956 // Set the length of the array to 1 (C99 6.9.2p5). 957 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 958 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 959 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), 960 One, ArrayType::Normal, 0); 961 VD->setType(T); 962 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 963 diag::err_tentative_def_incomplete_type)) 964 VD->setInvalidDecl(); 965 966 // No initialization is performed for a tentative definition. 967 CheckCompleteVariableDeclaration(VD); 968 969 // Notify the consumer that we've completed a tentative definition. 970 if (!VD->isInvalidDecl()) 971 Consumer.CompleteTentativeDefinition(VD); 972 973 } 974 975 // If there were errors, disable 'unused' warnings since they will mostly be 976 // noise. 977 if (!Diags.hasErrorOccurred()) { 978 // Output warning for unused file scoped decls. 979 for (UnusedFileScopedDeclsType::iterator 980 I = UnusedFileScopedDecls.begin(ExternalSource), 981 E = UnusedFileScopedDecls.end(); I != E; ++I) { 982 if (ShouldRemoveFromUnused(this, *I)) 983 continue; 984 985 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 986 const FunctionDecl *DiagD; 987 if (!FD->hasBody(DiagD)) 988 DiagD = FD; 989 if (DiagD->isDeleted()) 990 continue; // Deleted functions are supposed to be unused. 991 if (DiagD->isReferenced()) { 992 if (isa<CXXMethodDecl>(DiagD)) 993 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function) 994 << DiagD->getDeclName(); 995 else { 996 if (FD->getStorageClass() == SC_Static && 997 !FD->isInlineSpecified() && 998 !SourceMgr.isInMainFile( 999 SourceMgr.getExpansionLoc(FD->getLocation()))) 1000 Diag(DiagD->getLocation(), 1001 diag::warn_unneeded_static_internal_decl) 1002 << DiagD->getDeclName(); 1003 else 1004 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 1005 << /*function*/0 << DiagD->getDeclName(); 1006 } 1007 } else { 1008 if (FD->getDescribedFunctionTemplate()) 1009 Diag(DiagD->getLocation(), diag::warn_unused_template) 1010 << /*function*/0 << DiagD->getDeclName(); 1011 else 1012 Diag(DiagD->getLocation(), 1013 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function 1014 : diag::warn_unused_function) 1015 << DiagD->getDeclName(); 1016 } 1017 } else { 1018 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition(); 1019 if (!DiagD) 1020 DiagD = cast<VarDecl>(*I); 1021 if (DiagD->isReferenced()) { 1022 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 1023 << /*variable*/1 << DiagD->getDeclName(); 1024 } else if (DiagD->getType().isConstQualified()) { 1025 const SourceManager &SM = SourceMgr; 1026 if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) || 1027 !PP.getLangOpts().IsHeaderFile) 1028 Diag(DiagD->getLocation(), diag::warn_unused_const_variable) 1029 << DiagD->getDeclName(); 1030 } else { 1031 if (DiagD->getDescribedVarTemplate()) 1032 Diag(DiagD->getLocation(), diag::warn_unused_template) 1033 << /*variable*/1 << DiagD->getDeclName(); 1034 else 1035 Diag(DiagD->getLocation(), diag::warn_unused_variable) 1036 << DiagD->getDeclName(); 1037 } 1038 } 1039 } 1040 1041 emitAndClearUnusedLocalTypedefWarnings(); 1042 } 1043 1044 if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) { 1045 RecordCompleteMap RecordsComplete; 1046 RecordCompleteMap MNCComplete; 1047 for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(), 1048 E = UnusedPrivateFields.end(); I != E; ++I) { 1049 const NamedDecl *D = *I; 1050 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()); 1051 if (RD && !RD->isUnion() && 1052 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) { 1053 Diag(D->getLocation(), diag::warn_unused_private_field) 1054 << D->getDeclName(); 1055 } 1056 } 1057 } 1058 1059 if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) { 1060 if (ExternalSource) 1061 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs); 1062 for (const auto &DeletedFieldInfo : DeleteExprs) { 1063 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) { 1064 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first, 1065 DeleteExprLoc.second); 1066 } 1067 } 1068 } 1069 1070 // Check we've noticed that we're no longer parsing the initializer for every 1071 // variable. If we miss cases, then at best we have a performance issue and 1072 // at worst a rejects-valid bug. 1073 assert(ParsingInitForAutoVars.empty() && 1074 "Didn't unmark var as having its initializer parsed"); 1075 1076 if (!PP.isIncrementalProcessingEnabled()) 1077 TUScope = nullptr; 1078 } 1079 1080 1081 //===----------------------------------------------------------------------===// 1082 // Helper functions. 1083 //===----------------------------------------------------------------------===// 1084 1085 DeclContext *Sema::getFunctionLevelDeclContext() { 1086 DeclContext *DC = CurContext; 1087 1088 while (true) { 1089 if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) { 1090 DC = DC->getParent(); 1091 } else if (isa<CXXMethodDecl>(DC) && 1092 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 1093 cast<CXXRecordDecl>(DC->getParent())->isLambda()) { 1094 DC = DC->getParent()->getParent(); 1095 } 1096 else break; 1097 } 1098 1099 return DC; 1100 } 1101 1102 /// getCurFunctionDecl - If inside of a function body, this returns a pointer 1103 /// to the function decl for the function being parsed. If we're currently 1104 /// in a 'block', this returns the containing context. 1105 FunctionDecl *Sema::getCurFunctionDecl() { 1106 DeclContext *DC = getFunctionLevelDeclContext(); 1107 return dyn_cast<FunctionDecl>(DC); 1108 } 1109 1110 ObjCMethodDecl *Sema::getCurMethodDecl() { 1111 DeclContext *DC = getFunctionLevelDeclContext(); 1112 while (isa<RecordDecl>(DC)) 1113 DC = DC->getParent(); 1114 return dyn_cast<ObjCMethodDecl>(DC); 1115 } 1116 1117 NamedDecl *Sema::getCurFunctionOrMethodDecl() { 1118 DeclContext *DC = getFunctionLevelDeclContext(); 1119 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 1120 return cast<NamedDecl>(DC); 1121 return nullptr; 1122 } 1123 1124 void Sema::EmitCurrentDiagnostic(unsigned DiagID) { 1125 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here 1126 // and yet we also use the current diag ID on the DiagnosticsEngine. This has 1127 // been made more painfully obvious by the refactor that introduced this 1128 // function, but it is possible that the incoming argument can be 1129 // eliminated. If it truly cannot be (for example, there is some reentrancy 1130 // issue I am not seeing yet), then there should at least be a clarifying 1131 // comment somewhere. 1132 if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) { 1133 switch (DiagnosticIDs::getDiagnosticSFINAEResponse( 1134 Diags.getCurrentDiagID())) { 1135 case DiagnosticIDs::SFINAE_Report: 1136 // We'll report the diagnostic below. 1137 break; 1138 1139 case DiagnosticIDs::SFINAE_SubstitutionFailure: 1140 // Count this failure so that we know that template argument deduction 1141 // has failed. 1142 ++NumSFINAEErrors; 1143 1144 // Make a copy of this suppressed diagnostic and store it with the 1145 // template-deduction information. 1146 if (*Info && !(*Info)->hasSFINAEDiagnostic()) { 1147 Diagnostic DiagInfo(&Diags); 1148 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(), 1149 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 1150 } 1151 1152 Diags.setLastDiagnosticIgnored(); 1153 Diags.Clear(); 1154 return; 1155 1156 case DiagnosticIDs::SFINAE_AccessControl: { 1157 // Per C++ Core Issue 1170, access control is part of SFINAE. 1158 // Additionally, the AccessCheckingSFINAE flag can be used to temporarily 1159 // make access control a part of SFINAE for the purposes of checking 1160 // type traits. 1161 if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11) 1162 break; 1163 1164 SourceLocation Loc = Diags.getCurrentDiagLoc(); 1165 1166 // Suppress this diagnostic. 1167 ++NumSFINAEErrors; 1168 1169 // Make a copy of this suppressed diagnostic and store it with the 1170 // template-deduction information. 1171 if (*Info && !(*Info)->hasSFINAEDiagnostic()) { 1172 Diagnostic DiagInfo(&Diags); 1173 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(), 1174 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 1175 } 1176 1177 Diags.setLastDiagnosticIgnored(); 1178 Diags.Clear(); 1179 1180 // Now the diagnostic state is clear, produce a C++98 compatibility 1181 // warning. 1182 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control); 1183 1184 // The last diagnostic which Sema produced was ignored. Suppress any 1185 // notes attached to it. 1186 Diags.setLastDiagnosticIgnored(); 1187 return; 1188 } 1189 1190 case DiagnosticIDs::SFINAE_Suppress: 1191 // Make a copy of this suppressed diagnostic and store it with the 1192 // template-deduction information; 1193 if (*Info) { 1194 Diagnostic DiagInfo(&Diags); 1195 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(), 1196 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 1197 } 1198 1199 // Suppress this diagnostic. 1200 Diags.setLastDiagnosticIgnored(); 1201 Diags.Clear(); 1202 return; 1203 } 1204 } 1205 1206 // Set up the context's printing policy based on our current state. 1207 Context.setPrintingPolicy(getPrintingPolicy()); 1208 1209 // Emit the diagnostic. 1210 if (!Diags.EmitCurrentDiagnostic()) 1211 return; 1212 1213 // If this is not a note, and we're in a template instantiation 1214 // that is different from the last template instantiation where 1215 // we emitted an error, print a template instantiation 1216 // backtrace. 1217 if (!DiagnosticIDs::isBuiltinNote(DiagID)) 1218 PrintContextStack(); 1219 } 1220 1221 Sema::SemaDiagnosticBuilder 1222 Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) { 1223 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID())); 1224 PD.Emit(Builder); 1225 1226 return Builder; 1227 } 1228 1229 /// \brief Looks through the macro-expansion chain for the given 1230 /// location, looking for a macro expansion with the given name. 1231 /// If one is found, returns true and sets the location to that 1232 /// expansion loc. 1233 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) { 1234 SourceLocation loc = locref; 1235 if (!loc.isMacroID()) return false; 1236 1237 // There's no good way right now to look at the intermediate 1238 // expansions, so just jump to the expansion location. 1239 loc = getSourceManager().getExpansionLoc(loc); 1240 1241 // If that's written with the name, stop here. 1242 SmallVector<char, 16> buffer; 1243 if (getPreprocessor().getSpelling(loc, buffer) == name) { 1244 locref = loc; 1245 return true; 1246 } 1247 return false; 1248 } 1249 1250 /// \brief Determines the active Scope associated with the given declaration 1251 /// context. 1252 /// 1253 /// This routine maps a declaration context to the active Scope object that 1254 /// represents that declaration context in the parser. It is typically used 1255 /// from "scope-less" code (e.g., template instantiation, lazy creation of 1256 /// declarations) that injects a name for name-lookup purposes and, therefore, 1257 /// must update the Scope. 1258 /// 1259 /// \returns The scope corresponding to the given declaraion context, or NULL 1260 /// if no such scope is open. 1261 Scope *Sema::getScopeForContext(DeclContext *Ctx) { 1262 1263 if (!Ctx) 1264 return nullptr; 1265 1266 Ctx = Ctx->getPrimaryContext(); 1267 for (Scope *S = getCurScope(); S; S = S->getParent()) { 1268 // Ignore scopes that cannot have declarations. This is important for 1269 // out-of-line definitions of static class members. 1270 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) 1271 if (DeclContext *Entity = S->getEntity()) 1272 if (Ctx == Entity->getPrimaryContext()) 1273 return S; 1274 } 1275 1276 return nullptr; 1277 } 1278 1279 /// \brief Enter a new function scope 1280 void Sema::PushFunctionScope() { 1281 if (FunctionScopes.size() == 1) { 1282 // Use the "top" function scope rather than having to allocate 1283 // memory for a new scope. 1284 FunctionScopes.back()->Clear(); 1285 FunctionScopes.push_back(FunctionScopes.back()); 1286 if (LangOpts.OpenMP) 1287 pushOpenMPFunctionRegion(); 1288 return; 1289 } 1290 1291 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics())); 1292 if (LangOpts.OpenMP) 1293 pushOpenMPFunctionRegion(); 1294 } 1295 1296 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) { 1297 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(), 1298 BlockScope, Block)); 1299 } 1300 1301 LambdaScopeInfo *Sema::PushLambdaScope() { 1302 LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics()); 1303 FunctionScopes.push_back(LSI); 1304 return LSI; 1305 } 1306 1307 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) { 1308 if (LambdaScopeInfo *const LSI = getCurLambda()) { 1309 LSI->AutoTemplateParameterDepth = Depth; 1310 return; 1311 } 1312 llvm_unreachable( 1313 "Remove assertion if intentionally called in a non-lambda context."); 1314 } 1315 1316 void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP, 1317 const Decl *D, const BlockExpr *blkExpr) { 1318 FunctionScopeInfo *Scope = FunctionScopes.pop_back_val(); 1319 assert(!FunctionScopes.empty() && "mismatched push/pop!"); 1320 1321 if (LangOpts.OpenMP) 1322 popOpenMPFunctionRegion(Scope); 1323 1324 // Issue any analysis-based warnings. 1325 if (WP && D) 1326 AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr); 1327 else 1328 for (const auto &PUD : Scope->PossiblyUnreachableDiags) 1329 Diag(PUD.Loc, PUD.PD); 1330 1331 if (FunctionScopes.back() != Scope) 1332 delete Scope; 1333 } 1334 1335 void Sema::PushCompoundScope() { 1336 getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo()); 1337 } 1338 1339 void Sema::PopCompoundScope() { 1340 FunctionScopeInfo *CurFunction = getCurFunction(); 1341 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop"); 1342 1343 CurFunction->CompoundScopes.pop_back(); 1344 } 1345 1346 /// \brief Determine whether any errors occurred within this function/method/ 1347 /// block. 1348 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const { 1349 return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred(); 1350 } 1351 1352 BlockScopeInfo *Sema::getCurBlock() { 1353 if (FunctionScopes.empty()) 1354 return nullptr; 1355 1356 auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back()); 1357 if (CurBSI && CurBSI->TheDecl && 1358 !CurBSI->TheDecl->Encloses(CurContext)) { 1359 // We have switched contexts due to template instantiation. 1360 assert(!CodeSynthesisContexts.empty()); 1361 return nullptr; 1362 } 1363 1364 return CurBSI; 1365 } 1366 1367 LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) { 1368 if (FunctionScopes.empty()) 1369 return nullptr; 1370 1371 auto I = FunctionScopes.rbegin(); 1372 if (IgnoreNonLambdaCapturingScope) { 1373 auto E = FunctionScopes.rend(); 1374 while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I)) 1375 ++I; 1376 if (I == E) 1377 return nullptr; 1378 } 1379 auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I); 1380 if (CurLSI && CurLSI->Lambda && 1381 !CurLSI->Lambda->Encloses(CurContext)) { 1382 // We have switched contexts due to template instantiation. 1383 assert(!CodeSynthesisContexts.empty()); 1384 return nullptr; 1385 } 1386 1387 return CurLSI; 1388 } 1389 // We have a generic lambda if we parsed auto parameters, or we have 1390 // an associated template parameter list. 1391 LambdaScopeInfo *Sema::getCurGenericLambda() { 1392 if (LambdaScopeInfo *LSI = getCurLambda()) { 1393 return (LSI->AutoTemplateParams.size() || 1394 LSI->GLTemplateParameterList) ? LSI : nullptr; 1395 } 1396 return nullptr; 1397 } 1398 1399 1400 void Sema::ActOnComment(SourceRange Comment) { 1401 if (!LangOpts.RetainCommentsFromSystemHeaders && 1402 SourceMgr.isInSystemHeader(Comment.getBegin())) 1403 return; 1404 RawComment RC(SourceMgr, Comment, false, 1405 LangOpts.CommentOpts.ParseAllComments); 1406 if (RC.isAlmostTrailingComment()) { 1407 SourceRange MagicMarkerRange(Comment.getBegin(), 1408 Comment.getBegin().getLocWithOffset(3)); 1409 StringRef MagicMarkerText; 1410 switch (RC.getKind()) { 1411 case RawComment::RCK_OrdinaryBCPL: 1412 MagicMarkerText = "///<"; 1413 break; 1414 case RawComment::RCK_OrdinaryC: 1415 MagicMarkerText = "/**<"; 1416 break; 1417 default: 1418 llvm_unreachable("if this is an almost Doxygen comment, " 1419 "it should be ordinary"); 1420 } 1421 Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) << 1422 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText); 1423 } 1424 Context.addComment(RC); 1425 } 1426 1427 // Pin this vtable to this file. 1428 ExternalSemaSource::~ExternalSemaSource() {} 1429 1430 void ExternalSemaSource::ReadMethodPool(Selector Sel) { } 1431 void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { } 1432 1433 void ExternalSemaSource::ReadKnownNamespaces( 1434 SmallVectorImpl<NamespaceDecl *> &Namespaces) { 1435 } 1436 1437 void ExternalSemaSource::ReadUndefinedButUsed( 1438 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {} 1439 1440 void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector< 1441 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {} 1442 1443 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const { 1444 SourceLocation Loc = this->Loc; 1445 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation(); 1446 if (Loc.isValid()) { 1447 Loc.print(OS, S.getSourceManager()); 1448 OS << ": "; 1449 } 1450 OS << Message; 1451 1452 if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) { 1453 OS << " '"; 1454 ND->getNameForDiagnostic(OS, ND->getASTContext().getPrintingPolicy(), true); 1455 OS << "'"; 1456 } 1457 1458 OS << '\n'; 1459 } 1460 1461 /// \brief Figure out if an expression could be turned into a call. 1462 /// 1463 /// Use this when trying to recover from an error where the programmer may have 1464 /// written just the name of a function instead of actually calling it. 1465 /// 1466 /// \param E - The expression to examine. 1467 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call 1468 /// with no arguments, this parameter is set to the type returned by such a 1469 /// call; otherwise, it is set to an empty QualType. 1470 /// \param OverloadSet - If the expression is an overloaded function 1471 /// name, this parameter is populated with the decls of the various overloads. 1472 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, 1473 UnresolvedSetImpl &OverloadSet) { 1474 ZeroArgCallReturnTy = QualType(); 1475 OverloadSet.clear(); 1476 1477 const OverloadExpr *Overloads = nullptr; 1478 bool IsMemExpr = false; 1479 if (E.getType() == Context.OverloadTy) { 1480 OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E)); 1481 1482 // Ignore overloads that are pointer-to-member constants. 1483 if (FR.HasFormOfMemberPointer) 1484 return false; 1485 1486 Overloads = FR.Expression; 1487 } else if (E.getType() == Context.BoundMemberTy) { 1488 Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens()); 1489 IsMemExpr = true; 1490 } 1491 1492 bool Ambiguous = false; 1493 1494 if (Overloads) { 1495 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(), 1496 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) { 1497 OverloadSet.addDecl(*it); 1498 1499 // Check whether the function is a non-template, non-member which takes no 1500 // arguments. 1501 if (IsMemExpr) 1502 continue; 1503 if (const FunctionDecl *OverloadDecl 1504 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) { 1505 if (OverloadDecl->getMinRequiredArguments() == 0) { 1506 if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) { 1507 ZeroArgCallReturnTy = QualType(); 1508 Ambiguous = true; 1509 } else 1510 ZeroArgCallReturnTy = OverloadDecl->getReturnType(); 1511 } 1512 } 1513 } 1514 1515 // If it's not a member, use better machinery to try to resolve the call 1516 if (!IsMemExpr) 1517 return !ZeroArgCallReturnTy.isNull(); 1518 } 1519 1520 // Attempt to call the member with no arguments - this will correctly handle 1521 // member templates with defaults/deduction of template arguments, overloads 1522 // with default arguments, etc. 1523 if (IsMemExpr && !E.isTypeDependent()) { 1524 bool Suppress = getDiagnostics().getSuppressAllDiagnostics(); 1525 getDiagnostics().setSuppressAllDiagnostics(true); 1526 ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(), 1527 None, SourceLocation()); 1528 getDiagnostics().setSuppressAllDiagnostics(Suppress); 1529 if (R.isUsable()) { 1530 ZeroArgCallReturnTy = R.get()->getType(); 1531 return true; 1532 } 1533 return false; 1534 } 1535 1536 if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) { 1537 if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) { 1538 if (Fun->getMinRequiredArguments() == 0) 1539 ZeroArgCallReturnTy = Fun->getReturnType(); 1540 return true; 1541 } 1542 } 1543 1544 // We don't have an expression that's convenient to get a FunctionDecl from, 1545 // but we can at least check if the type is "function of 0 arguments". 1546 QualType ExprTy = E.getType(); 1547 const FunctionType *FunTy = nullptr; 1548 QualType PointeeTy = ExprTy->getPointeeType(); 1549 if (!PointeeTy.isNull()) 1550 FunTy = PointeeTy->getAs<FunctionType>(); 1551 if (!FunTy) 1552 FunTy = ExprTy->getAs<FunctionType>(); 1553 1554 if (const FunctionProtoType *FPT = 1555 dyn_cast_or_null<FunctionProtoType>(FunTy)) { 1556 if (FPT->getNumParams() == 0) 1557 ZeroArgCallReturnTy = FunTy->getReturnType(); 1558 return true; 1559 } 1560 return false; 1561 } 1562 1563 /// \brief Give notes for a set of overloads. 1564 /// 1565 /// A companion to tryExprAsCall. In cases when the name that the programmer 1566 /// wrote was an overloaded function, we may be able to make some guesses about 1567 /// plausible overloads based on their return types; such guesses can be handed 1568 /// off to this method to be emitted as notes. 1569 /// 1570 /// \param Overloads - The overloads to note. 1571 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to 1572 /// -fshow-overloads=best, this is the location to attach to the note about too 1573 /// many candidates. Typically this will be the location of the original 1574 /// ill-formed expression. 1575 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, 1576 const SourceLocation FinalNoteLoc) { 1577 int ShownOverloads = 0; 1578 int SuppressedOverloads = 0; 1579 for (UnresolvedSetImpl::iterator It = Overloads.begin(), 1580 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { 1581 // FIXME: Magic number for max shown overloads stolen from 1582 // OverloadCandidateSet::NoteCandidates. 1583 if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) { 1584 ++SuppressedOverloads; 1585 continue; 1586 } 1587 1588 NamedDecl *Fn = (*It)->getUnderlyingDecl(); 1589 S.Diag(Fn->getLocation(), diag::note_possible_target_of_call); 1590 ++ShownOverloads; 1591 } 1592 1593 if (SuppressedOverloads) 1594 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates) 1595 << SuppressedOverloads; 1596 } 1597 1598 static void notePlausibleOverloads(Sema &S, SourceLocation Loc, 1599 const UnresolvedSetImpl &Overloads, 1600 bool (*IsPlausibleResult)(QualType)) { 1601 if (!IsPlausibleResult) 1602 return noteOverloads(S, Overloads, Loc); 1603 1604 UnresolvedSet<2> PlausibleOverloads; 1605 for (OverloadExpr::decls_iterator It = Overloads.begin(), 1606 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { 1607 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It); 1608 QualType OverloadResultTy = OverloadDecl->getReturnType(); 1609 if (IsPlausibleResult(OverloadResultTy)) 1610 PlausibleOverloads.addDecl(It.getDecl()); 1611 } 1612 noteOverloads(S, PlausibleOverloads, Loc); 1613 } 1614 1615 /// Determine whether the given expression can be called by just 1616 /// putting parentheses after it. Notably, expressions with unary 1617 /// operators can't be because the unary operator will start parsing 1618 /// outside the call. 1619 static bool IsCallableWithAppend(Expr *E) { 1620 E = E->IgnoreImplicit(); 1621 return (!isa<CStyleCastExpr>(E) && 1622 !isa<UnaryOperator>(E) && 1623 !isa<BinaryOperator>(E) && 1624 !isa<CXXOperatorCallExpr>(E)); 1625 } 1626 1627 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 1628 bool ForceComplain, 1629 bool (*IsPlausibleResult)(QualType)) { 1630 SourceLocation Loc = E.get()->getExprLoc(); 1631 SourceRange Range = E.get()->getSourceRange(); 1632 1633 QualType ZeroArgCallTy; 1634 UnresolvedSet<4> Overloads; 1635 if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) && 1636 !ZeroArgCallTy.isNull() && 1637 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) { 1638 // At this point, we know E is potentially callable with 0 1639 // arguments and that it returns something of a reasonable type, 1640 // so we can emit a fixit and carry on pretending that E was 1641 // actually a CallExpr. 1642 SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd()); 1643 Diag(Loc, PD) 1644 << /*zero-arg*/ 1 << Range 1645 << (IsCallableWithAppend(E.get()) 1646 ? FixItHint::CreateInsertion(ParenInsertionLoc, "()") 1647 : FixItHint()); 1648 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult); 1649 1650 // FIXME: Try this before emitting the fixit, and suppress diagnostics 1651 // while doing so. 1652 E = ActOnCallExpr(nullptr, E.get(), Range.getEnd(), None, 1653 Range.getEnd().getLocWithOffset(1)); 1654 return true; 1655 } 1656 1657 if (!ForceComplain) return false; 1658 1659 Diag(Loc, PD) << /*not zero-arg*/ 0 << Range; 1660 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult); 1661 E = ExprError(); 1662 return true; 1663 } 1664 1665 IdentifierInfo *Sema::getSuperIdentifier() const { 1666 if (!Ident_super) 1667 Ident_super = &Context.Idents.get("super"); 1668 return Ident_super; 1669 } 1670 1671 IdentifierInfo *Sema::getFloat128Identifier() const { 1672 if (!Ident___float128) 1673 Ident___float128 = &Context.Idents.get("__float128"); 1674 return Ident___float128; 1675 } 1676 1677 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD, 1678 CapturedRegionKind K) { 1679 CapturingScopeInfo *CSI = new CapturedRegionScopeInfo( 1680 getDiagnostics(), S, CD, RD, CD->getContextParam(), K, 1681 (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0); 1682 CSI->ReturnType = Context.VoidTy; 1683 FunctionScopes.push_back(CSI); 1684 } 1685 1686 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() { 1687 if (FunctionScopes.empty()) 1688 return nullptr; 1689 1690 return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back()); 1691 } 1692 1693 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> & 1694 Sema::getMismatchingDeleteExpressions() const { 1695 return DeleteExprs; 1696 } 1697 1698 void Sema::setOpenCLExtensionForType(QualType T, llvm::StringRef ExtStr) { 1699 if (ExtStr.empty()) 1700 return; 1701 llvm::SmallVector<StringRef, 1> Exts; 1702 ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false); 1703 auto CanT = T.getCanonicalType().getTypePtr(); 1704 for (auto &I : Exts) 1705 OpenCLTypeExtMap[CanT].insert(I.str()); 1706 } 1707 1708 void Sema::setOpenCLExtensionForDecl(Decl *FD, StringRef ExtStr) { 1709 llvm::SmallVector<StringRef, 1> Exts; 1710 ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false); 1711 if (Exts.empty()) 1712 return; 1713 for (auto &I : Exts) 1714 OpenCLDeclExtMap[FD].insert(I.str()); 1715 } 1716 1717 void Sema::setCurrentOpenCLExtensionForType(QualType T) { 1718 if (CurrOpenCLExtension.empty()) 1719 return; 1720 setOpenCLExtensionForType(T, CurrOpenCLExtension); 1721 } 1722 1723 void Sema::setCurrentOpenCLExtensionForDecl(Decl *D) { 1724 if (CurrOpenCLExtension.empty()) 1725 return; 1726 setOpenCLExtensionForDecl(D, CurrOpenCLExtension); 1727 } 1728 1729 bool Sema::isOpenCLDisabledDecl(Decl *FD) { 1730 auto Loc = OpenCLDeclExtMap.find(FD); 1731 if (Loc == OpenCLDeclExtMap.end()) 1732 return false; 1733 for (auto &I : Loc->second) { 1734 if (!getOpenCLOptions().isEnabled(I)) 1735 return true; 1736 } 1737 return false; 1738 } 1739 1740 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> 1741 bool Sema::checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, 1742 DiagInfoT DiagInfo, MapT &Map, 1743 unsigned Selector, 1744 SourceRange SrcRange) { 1745 auto Loc = Map.find(D); 1746 if (Loc == Map.end()) 1747 return false; 1748 bool Disabled = false; 1749 for (auto &I : Loc->second) { 1750 if (I != CurrOpenCLExtension && !getOpenCLOptions().isEnabled(I)) { 1751 Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo 1752 << I << SrcRange; 1753 Disabled = true; 1754 } 1755 } 1756 return Disabled; 1757 } 1758 1759 bool Sema::checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType QT) { 1760 // Check extensions for declared types. 1761 Decl *Decl = nullptr; 1762 if (auto TypedefT = dyn_cast<TypedefType>(QT.getTypePtr())) 1763 Decl = TypedefT->getDecl(); 1764 if (auto TagT = dyn_cast<TagType>(QT.getCanonicalType().getTypePtr())) 1765 Decl = TagT->getDecl(); 1766 auto Loc = DS.getTypeSpecTypeLoc(); 1767 if (checkOpenCLDisabledTypeOrDecl(Decl, Loc, QT, OpenCLDeclExtMap)) 1768 return true; 1769 1770 // Check extensions for builtin types. 1771 return checkOpenCLDisabledTypeOrDecl(QT.getCanonicalType().getTypePtr(), Loc, 1772 QT, OpenCLTypeExtMap); 1773 } 1774 1775 bool Sema::checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E) { 1776 IdentifierInfo *FnName = D.getIdentifier(); 1777 return checkOpenCLDisabledTypeOrDecl(&D, E.getLocStart(), FnName, 1778 OpenCLDeclExtMap, 1, D.getSourceRange()); 1779 } 1780