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