| 1 | //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This file implements the actions class which performs semantic analysis and |
| 10 | // builds an AST out of a parse stream. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #include "UsedDeclVisitor.h" |
| 15 | #include "clang/AST/ASTContext.h" |
| 16 | #include "clang/AST/ASTDiagnostic.h" |
| 17 | #include "clang/AST/Decl.h" |
| 18 | #include "clang/AST/DeclCXX.h" |
| 19 | #include "clang/AST/DeclFriend.h" |
| 20 | #include "clang/AST/DeclObjC.h" |
| 21 | #include "clang/AST/Expr.h" |
| 22 | #include "clang/AST/ExprCXX.h" |
| 23 | #include "clang/AST/PrettyDeclStackTrace.h" |
| 24 | #include "clang/AST/StmtCXX.h" |
| 25 | #include "clang/AST/TypeOrdering.h" |
| 26 | #include "clang/Basic/DarwinSDKInfo.h" |
| 27 | #include "clang/Basic/DiagnosticOptions.h" |
| 28 | #include "clang/Basic/PartialDiagnostic.h" |
| 29 | #include "clang/Basic/SourceManager.h" |
| 30 | #include "clang/Basic/TargetInfo.h" |
| 31 | #include "clang/Lex/HeaderSearch.h" |
| 32 | #include "clang/Lex/HeaderSearchOptions.h" |
| 33 | #include "clang/Lex/Preprocessor.h" |
| 34 | #include "clang/Sema/CXXFieldCollector.h" |
| 35 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
| 36 | #include "clang/Sema/ExternalSemaSource.h" |
| 37 | #include "clang/Sema/Initialization.h" |
| 38 | #include "clang/Sema/MultiplexExternalSemaSource.h" |
| 39 | #include "clang/Sema/ObjCMethodList.h" |
| 40 | #include "clang/Sema/RISCVIntrinsicManager.h" |
| 41 | #include "clang/Sema/Scope.h" |
| 42 | #include "clang/Sema/ScopeInfo.h" |
| 43 | #include "clang/Sema/SemaAMDGPU.h" |
| 44 | #include "clang/Sema/SemaARM.h" |
| 45 | #include "clang/Sema/SemaAVR.h" |
| 46 | #include "clang/Sema/SemaBPF.h" |
| 47 | #include "clang/Sema/SemaCUDA.h" |
| 48 | #include "clang/Sema/SemaCodeCompletion.h" |
| 49 | #include "clang/Sema/SemaConsumer.h" |
| 50 | #include "clang/Sema/SemaDirectX.h" |
| 51 | #include "clang/Sema/SemaHLSL.h" |
| 52 | #include "clang/Sema/SemaHexagon.h" |
| 53 | #include "clang/Sema/SemaLoongArch.h" |
| 54 | #include "clang/Sema/SemaM68k.h" |
| 55 | #include "clang/Sema/SemaMIPS.h" |
| 56 | #include "clang/Sema/SemaMSP430.h" |
| 57 | #include "clang/Sema/SemaNVPTX.h" |
| 58 | #include "clang/Sema/SemaObjC.h" |
| 59 | #include "clang/Sema/SemaOpenACC.h" |
| 60 | #include "clang/Sema/SemaOpenCL.h" |
| 61 | #include "clang/Sema/SemaOpenMP.h" |
| 62 | #include "clang/Sema/SemaPPC.h" |
| 63 | #include "clang/Sema/SemaPseudoObject.h" |
| 64 | #include "clang/Sema/SemaRISCV.h" |
| 65 | #include "clang/Sema/SemaSPIRV.h" |
| 66 | #include "clang/Sema/SemaSYCL.h" |
| 67 | #include "clang/Sema/SemaSwift.h" |
| 68 | #include "clang/Sema/SemaSystemZ.h" |
| 69 | #include "clang/Sema/SemaWasm.h" |
| 70 | #include "clang/Sema/SemaX86.h" |
| 71 | #include "clang/Sema/TemplateDeduction.h" |
| 72 | #include "clang/Sema/TemplateInstCallback.h" |
| 73 | #include "clang/Sema/TypoCorrection.h" |
| 74 | #include "llvm/ADT/DenseMap.h" |
| 75 | #include "llvm/ADT/STLExtras.h" |
| 76 | #include "llvm/ADT/SetVector.h" |
| 77 | #include "llvm/ADT/SmallPtrSet.h" |
| 78 | #include "llvm/Support/TimeProfiler.h" |
| 79 | #include <optional> |
| 80 | |
| 81 | using namespace clang; |
| 82 | using namespace sema; |
| 83 | |
| 84 | SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) { |
| 85 | return Lexer::getLocForEndOfToken(Loc, Offset, SM: SourceMgr, LangOpts); |
| 86 | } |
| 87 | |
| 88 | SourceRange |
| 89 | Sema::getRangeForNextToken(SourceLocation Loc, bool IncludeMacros, |
| 90 | bool , |
| 91 | std::optional<tok::TokenKind> ExpectedToken) { |
| 92 | if (!Loc.isValid()) |
| 93 | return SourceRange(); |
| 94 | std::optional<Token> NextToken = |
| 95 | Lexer::findNextToken(Loc, SM: SourceMgr, LangOpts, IncludeComments); |
| 96 | if (!NextToken) |
| 97 | return SourceRange(); |
| 98 | if (ExpectedToken && NextToken->getKind() != *ExpectedToken) |
| 99 | return SourceRange(); |
| 100 | SourceLocation TokenStart = NextToken->getLocation(); |
| 101 | SourceLocation TokenEnd = NextToken->getLastLoc(); |
| 102 | if (!TokenStart.isValid() || !TokenEnd.isValid()) |
| 103 | return SourceRange(); |
| 104 | if (!IncludeMacros && (TokenStart.isMacroID() || TokenEnd.isMacroID())) |
| 105 | return SourceRange(); |
| 106 | |
| 107 | return SourceRange(TokenStart, TokenEnd); |
| 108 | } |
| 109 | |
| 110 | ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); } |
| 111 | |
| 112 | DarwinSDKInfo * |
| 113 | Sema::getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc, |
| 114 | StringRef Platform) { |
| 115 | auto *SDKInfo = getDarwinSDKInfoForAvailabilityChecking(); |
| 116 | if (!SDKInfo && !WarnedDarwinSDKInfoMissing) { |
| 117 | Diag(Loc, DiagID: diag::warn_missing_sdksettings_for_availability_checking) |
| 118 | << Platform; |
| 119 | WarnedDarwinSDKInfoMissing = true; |
| 120 | } |
| 121 | return SDKInfo; |
| 122 | } |
| 123 | |
| 124 | DarwinSDKInfo *Sema::getDarwinSDKInfoForAvailabilityChecking() { |
| 125 | if (CachedDarwinSDKInfo) |
| 126 | return CachedDarwinSDKInfo->get(); |
| 127 | auto SDKInfo = parseDarwinSDKInfo( |
| 128 | VFS&: PP.getFileManager().getVirtualFileSystem(), |
| 129 | SDKRootPath: PP.getHeaderSearchInfo().getHeaderSearchOpts().Sysroot); |
| 130 | if (SDKInfo && *SDKInfo) { |
| 131 | CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(args: std::move(**SDKInfo)); |
| 132 | return CachedDarwinSDKInfo->get(); |
| 133 | } |
| 134 | if (!SDKInfo) |
| 135 | llvm::consumeError(Err: SDKInfo.takeError()); |
| 136 | CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>(); |
| 137 | return nullptr; |
| 138 | } |
| 139 | |
| 140 | IdentifierInfo *Sema::InventAbbreviatedTemplateParameterTypeName( |
| 141 | const IdentifierInfo *ParamName, unsigned int Index) { |
| 142 | std::string InventedName; |
| 143 | llvm::raw_string_ostream OS(InventedName); |
| 144 | |
| 145 | if (!ParamName) |
| 146 | OS << "auto:" << Index + 1; |
| 147 | else |
| 148 | OS << ParamName->getName() << ":auto" ; |
| 149 | |
| 150 | return &Context.Idents.get(Name: OS.str()); |
| 151 | } |
| 152 | |
| 153 | PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context, |
| 154 | const Preprocessor &PP) { |
| 155 | PrintingPolicy Policy = Context.getPrintingPolicy(); |
| 156 | // In diagnostics, we print _Bool as bool if the latter is defined as the |
| 157 | // former. |
| 158 | Policy.Bool = Context.getLangOpts().Bool; |
| 159 | if (!Policy.Bool) { |
| 160 | if (const MacroInfo *BoolMacro = PP.getMacroInfo(II: Context.getBoolName())) { |
| 161 | Policy.Bool = BoolMacro->isObjectLike() && |
| 162 | BoolMacro->getNumTokens() == 1 && |
| 163 | BoolMacro->getReplacementToken(Tok: 0).is(K: tok::kw__Bool); |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | // Shorten the data output if needed |
| 168 | Policy.EntireContentsOfLargeArray = false; |
| 169 | |
| 170 | return Policy; |
| 171 | } |
| 172 | |
| 173 | void Sema::ActOnTranslationUnitScope(Scope *S) { |
| 174 | TUScope = S; |
| 175 | PushDeclContext(S, DC: Context.getTranslationUnitDecl()); |
| 176 | } |
| 177 | |
| 178 | namespace clang { |
| 179 | namespace sema { |
| 180 | |
| 181 | class SemaPPCallbacks : public PPCallbacks { |
| 182 | Sema *S = nullptr; |
| 183 | llvm::SmallVector<SourceLocation, 8> IncludeStack; |
| 184 | llvm::SmallVector<llvm::TimeTraceProfilerEntry *, 8> ProfilerStack; |
| 185 | |
| 186 | public: |
| 187 | void set(Sema &S) { this->S = &S; } |
| 188 | |
| 189 | void reset() { S = nullptr; } |
| 190 | |
| 191 | void FileChanged(SourceLocation Loc, FileChangeReason Reason, |
| 192 | SrcMgr::CharacteristicKind FileType, |
| 193 | FileID PrevFID) override { |
| 194 | if (!S) |
| 195 | return; |
| 196 | switch (Reason) { |
| 197 | case EnterFile: { |
| 198 | SourceManager &SM = S->getSourceManager(); |
| 199 | SourceLocation IncludeLoc = SM.getIncludeLoc(FID: SM.getFileID(SpellingLoc: Loc)); |
| 200 | if (IncludeLoc.isValid()) { |
| 201 | if (llvm::timeTraceProfilerEnabled()) { |
| 202 | OptionalFileEntryRef FE = SM.getFileEntryRefForID(FID: SM.getFileID(SpellingLoc: Loc)); |
| 203 | ProfilerStack.push_back(Elt: llvm::timeTraceAsyncProfilerBegin( |
| 204 | Name: "Source" , Detail: FE ? FE->getName() : StringRef("<unknown>" ))); |
| 205 | } |
| 206 | |
| 207 | IncludeStack.push_back(Elt: IncludeLoc); |
| 208 | S->DiagnoseNonDefaultPragmaAlignPack( |
| 209 | Kind: Sema::PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude, |
| 210 | IncludeLoc); |
| 211 | } |
| 212 | break; |
| 213 | } |
| 214 | case ExitFile: |
| 215 | if (!IncludeStack.empty()) { |
| 216 | if (llvm::timeTraceProfilerEnabled()) |
| 217 | llvm::timeTraceProfilerEnd(E: ProfilerStack.pop_back_val()); |
| 218 | |
| 219 | S->DiagnoseNonDefaultPragmaAlignPack( |
| 220 | Kind: Sema::PragmaAlignPackDiagnoseKind::ChangedStateAtExit, |
| 221 | IncludeLoc: IncludeStack.pop_back_val()); |
| 222 | } |
| 223 | break; |
| 224 | default: |
| 225 | break; |
| 226 | } |
| 227 | } |
| 228 | void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace, |
| 229 | diag::Severity Mapping, StringRef Str) override { |
| 230 | // If one of the analysis-based diagnostics was enabled while processing |
| 231 | // a function, we want to note it in the analysis-based warnings so they |
| 232 | // can be run at the end of the function body even if the analysis warnings |
| 233 | // are disabled at that point. |
| 234 | SmallVector<diag::kind, 256> GroupDiags; |
| 235 | diag::Flavor Flavor = |
| 236 | Str[1] == 'W' ? diag::Flavor::WarningOrError : diag::Flavor::Remark; |
| 237 | StringRef Group = Str.substr(Start: 2); |
| 238 | |
| 239 | if (S->PP.getDiagnostics().getDiagnosticIDs()->getDiagnosticsInGroup( |
| 240 | Flavor, Group, Diags&: GroupDiags)) |
| 241 | return; |
| 242 | |
| 243 | for (diag::kind K : GroupDiags) { |
| 244 | // Note: the cases in this switch should be kept in sync with the |
| 245 | // diagnostics in AnalysisBasedWarnings::getPolicyInEffectAt(). |
| 246 | AnalysisBasedWarnings::Policy &Override = |
| 247 | S->AnalysisWarnings.getPolicyOverrides(); |
| 248 | switch (K) { |
| 249 | default: break; |
| 250 | case diag::warn_unreachable: |
| 251 | case diag::warn_unreachable_break: |
| 252 | case diag::warn_unreachable_return: |
| 253 | case diag::warn_unreachable_loop_increment: |
| 254 | Override.enableCheckUnreachable = true; |
| 255 | break; |
| 256 | case diag::warn_double_lock: |
| 257 | Override.enableThreadSafetyAnalysis = true; |
| 258 | break; |
| 259 | case diag::warn_use_in_invalid_state: |
| 260 | Override.enableConsumedAnalysis = true; |
| 261 | break; |
| 262 | } |
| 263 | } |
| 264 | } |
| 265 | }; |
| 266 | |
| 267 | } // end namespace sema |
| 268 | } // end namespace clang |
| 269 | |
| 270 | const unsigned Sema::MaxAlignmentExponent; |
| 271 | const uint64_t Sema::MaximumAlignment; |
| 272 | |
| 273 | Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, |
| 274 | TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter) |
| 275 | : SemaBase(*this), CollectStats(false), TUKind(TUKind), |
| 276 | CurFPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp), |
| 277 | Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()), |
| 278 | SourceMgr(PP.getSourceManager()), APINotes(SourceMgr, LangOpts), |
| 279 | AnalysisWarnings(*this), ThreadSafetyDeclCache(nullptr), |
| 280 | LateTemplateParser(nullptr), OpaqueParser(nullptr), CurContext(nullptr), |
| 281 | ExternalSource(nullptr), StackHandler(Diags), CurScope(nullptr), |
| 282 | Ident_super(nullptr), AMDGPUPtr(std::make_unique<SemaAMDGPU>(args&: *this)), |
| 283 | ARMPtr(std::make_unique<SemaARM>(args&: *this)), |
| 284 | AVRPtr(std::make_unique<SemaAVR>(args&: *this)), |
| 285 | BPFPtr(std::make_unique<SemaBPF>(args&: *this)), |
| 286 | CodeCompletionPtr( |
| 287 | std::make_unique<SemaCodeCompletion>(args&: *this, args&: CodeCompleter)), |
| 288 | CUDAPtr(std::make_unique<SemaCUDA>(args&: *this)), |
| 289 | DirectXPtr(std::make_unique<SemaDirectX>(args&: *this)), |
| 290 | HLSLPtr(std::make_unique<SemaHLSL>(args&: *this)), |
| 291 | HexagonPtr(std::make_unique<SemaHexagon>(args&: *this)), |
| 292 | LoongArchPtr(std::make_unique<SemaLoongArch>(args&: *this)), |
| 293 | M68kPtr(std::make_unique<SemaM68k>(args&: *this)), |
| 294 | MIPSPtr(std::make_unique<SemaMIPS>(args&: *this)), |
| 295 | MSP430Ptr(std::make_unique<SemaMSP430>(args&: *this)), |
| 296 | NVPTXPtr(std::make_unique<SemaNVPTX>(args&: *this)), |
| 297 | ObjCPtr(std::make_unique<SemaObjC>(args&: *this)), |
| 298 | OpenACCPtr(std::make_unique<SemaOpenACC>(args&: *this)), |
| 299 | OpenCLPtr(std::make_unique<SemaOpenCL>(args&: *this)), |
| 300 | OpenMPPtr(std::make_unique<SemaOpenMP>(args&: *this)), |
| 301 | PPCPtr(std::make_unique<SemaPPC>(args&: *this)), |
| 302 | PseudoObjectPtr(std::make_unique<SemaPseudoObject>(args&: *this)), |
| 303 | RISCVPtr(std::make_unique<SemaRISCV>(args&: *this)), |
| 304 | SPIRVPtr(std::make_unique<SemaSPIRV>(args&: *this)), |
| 305 | SYCLPtr(std::make_unique<SemaSYCL>(args&: *this)), |
| 306 | SwiftPtr(std::make_unique<SemaSwift>(args&: *this)), |
| 307 | SystemZPtr(std::make_unique<SemaSystemZ>(args&: *this)), |
| 308 | WasmPtr(std::make_unique<SemaWasm>(args&: *this)), |
| 309 | X86Ptr(std::make_unique<SemaX86>(args&: *this)), |
| 310 | MSPointerToMemberRepresentationMethod( |
| 311 | LangOpts.getMSPointerToMemberRepresentationMethod()), |
| 312 | MSStructPragmaOn(false), VtorDispStack(LangOpts.getVtorDispMode()), |
| 313 | AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack)), |
| 314 | DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr), |
| 315 | CodeSegStack(nullptr), StrictGuardStackCheckStack(false), |
| 316 | FpPragmaStack(FPOptionsOverride()), CurInitSeg(nullptr), |
| 317 | VisContext(nullptr), PragmaAttributeCurrentTargetDecl(nullptr), |
| 318 | StdCoroutineTraitsCache(nullptr), IdResolver(pp), |
| 319 | OriginalLexicalContext(nullptr), StdInitializerList(nullptr), |
| 320 | StdTypeIdentity(nullptr), |
| 321 | FullyCheckedComparisonCategories( |
| 322 | static_cast<unsigned>(ComparisonCategoryType::Last) + 1), |
| 323 | StdSourceLocationImplDecl(nullptr), CXXTypeInfoDecl(nullptr), |
| 324 | GlobalNewDeleteDeclared(false), DisableTypoCorrection(false), |
| 325 | TyposCorrected(0), IsBuildingRecoveryCallExpr(false), |
| 326 | CurrentInstantiationScope(nullptr), NonInstantiationEntries(0), |
| 327 | ArgPackSubstIndex(std::nullopt), SatisfactionCache(Context) { |
| 328 | assert(pp.TUKind == TUKind); |
| 329 | TUScope = nullptr; |
| 330 | |
| 331 | LoadedExternalKnownNamespaces = false; |
| 332 | for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I) |
| 333 | ObjC().NSNumberLiteralMethods[I] = nullptr; |
| 334 | |
| 335 | if (getLangOpts().ObjC) |
| 336 | ObjC().NSAPIObj.reset(p: new NSAPI(Context)); |
| 337 | |
| 338 | if (getLangOpts().CPlusPlus) |
| 339 | FieldCollector.reset(p: new CXXFieldCollector()); |
| 340 | |
| 341 | // Tell diagnostics how to render things from the AST library. |
| 342 | Diags.SetArgToStringFn(Fn: &FormatASTNodeDiagnosticArgument, Cookie: &Context); |
| 343 | |
| 344 | // This evaluation context exists to ensure that there's always at least one |
| 345 | // valid evaluation context available. It is never removed from the |
| 346 | // evaluation stack. |
| 347 | ExprEvalContexts.emplace_back( |
| 348 | Args: ExpressionEvaluationContext::PotentiallyEvaluated, Args: 0, Args: CleanupInfo{}, |
| 349 | Args: nullptr, Args: ExpressionEvaluationContextRecord::EK_Other); |
| 350 | |
| 351 | // Initialization of data sharing attributes stack for OpenMP |
| 352 | OpenMP().InitDataSharingAttributesStack(); |
| 353 | |
| 354 | std::unique_ptr<sema::SemaPPCallbacks> Callbacks = |
| 355 | std::make_unique<sema::SemaPPCallbacks>(); |
| 356 | SemaPPCallbackHandler = Callbacks.get(); |
| 357 | PP.addPPCallbacks(C: std::move(Callbacks)); |
| 358 | SemaPPCallbackHandler->set(*this); |
| 359 | |
| 360 | CurFPFeatures.setFPEvalMethod(PP.getCurrentFPEvalMethod()); |
| 361 | } |
| 362 | |
| 363 | // Anchor Sema's type info to this TU. |
| 364 | void Sema::anchor() {} |
| 365 | |
| 366 | void Sema::addImplicitTypedef(StringRef Name, QualType T) { |
| 367 | DeclarationName DN = &Context.Idents.get(Name); |
| 368 | if (IdResolver.begin(Name: DN) == IdResolver.end()) |
| 369 | PushOnScopeChains(D: Context.buildImplicitTypedef(T, Name), S: TUScope); |
| 370 | } |
| 371 | |
| 372 | void Sema::Initialize() { |
| 373 | // Create BuiltinVaListDecl *before* ExternalSemaSource::InitializeSema(this) |
| 374 | // because during initialization ASTReader can emit globals that require |
| 375 | // name mangling. And the name mangling uses BuiltinVaListDecl. |
| 376 | if (Context.getTargetInfo().hasBuiltinMSVaList()) |
| 377 | (void)Context.getBuiltinMSVaListDecl(); |
| 378 | (void)Context.getBuiltinVaListDecl(); |
| 379 | |
| 380 | if (SemaConsumer *SC = dyn_cast<SemaConsumer>(Val: &Consumer)) |
| 381 | SC->InitializeSema(S&: *this); |
| 382 | |
| 383 | // Tell the external Sema source about this Sema object. |
| 384 | if (ExternalSemaSource *ExternalSema |
| 385 | = dyn_cast_or_null<ExternalSemaSource>(Val: Context.getExternalSource())) |
| 386 | ExternalSema->InitializeSema(S&: *this); |
| 387 | |
| 388 | // This needs to happen after ExternalSemaSource::InitializeSema(this) or we |
| 389 | // will not be able to merge any duplicate __va_list_tag decls correctly. |
| 390 | VAListTagName = PP.getIdentifierInfo(Name: "__va_list_tag" ); |
| 391 | |
| 392 | if (!TUScope) |
| 393 | return; |
| 394 | |
| 395 | // Initialize predefined 128-bit integer types, if needed. |
| 396 | if (Context.getTargetInfo().hasInt128Type() || |
| 397 | (Context.getAuxTargetInfo() && |
| 398 | Context.getAuxTargetInfo()->hasInt128Type())) { |
| 399 | // If either of the 128-bit integer types are unavailable to name lookup, |
| 400 | // define them now. |
| 401 | DeclarationName Int128 = &Context.Idents.get(Name: "__int128_t" ); |
| 402 | if (IdResolver.begin(Name: Int128) == IdResolver.end()) |
| 403 | PushOnScopeChains(D: Context.getInt128Decl(), S: TUScope); |
| 404 | |
| 405 | DeclarationName UInt128 = &Context.Idents.get(Name: "__uint128_t" ); |
| 406 | if (IdResolver.begin(Name: UInt128) == IdResolver.end()) |
| 407 | PushOnScopeChains(D: Context.getUInt128Decl(), S: TUScope); |
| 408 | } |
| 409 | |
| 410 | |
| 411 | // Initialize predefined Objective-C types: |
| 412 | if (getLangOpts().ObjC) { |
| 413 | // If 'SEL' does not yet refer to any declarations, make it refer to the |
| 414 | // predefined 'SEL'. |
| 415 | DeclarationName SEL = &Context.Idents.get(Name: "SEL" ); |
| 416 | if (IdResolver.begin(Name: SEL) == IdResolver.end()) |
| 417 | PushOnScopeChains(D: Context.getObjCSelDecl(), S: TUScope); |
| 418 | |
| 419 | // If 'id' does not yet refer to any declarations, make it refer to the |
| 420 | // predefined 'id'. |
| 421 | DeclarationName Id = &Context.Idents.get(Name: "id" ); |
| 422 | if (IdResolver.begin(Name: Id) == IdResolver.end()) |
| 423 | PushOnScopeChains(D: Context.getObjCIdDecl(), S: TUScope); |
| 424 | |
| 425 | // Create the built-in typedef for 'Class'. |
| 426 | DeclarationName Class = &Context.Idents.get(Name: "Class" ); |
| 427 | if (IdResolver.begin(Name: Class) == IdResolver.end()) |
| 428 | PushOnScopeChains(D: Context.getObjCClassDecl(), S: TUScope); |
| 429 | |
| 430 | // Create the built-in forward declaratino for 'Protocol'. |
| 431 | DeclarationName Protocol = &Context.Idents.get(Name: "Protocol" ); |
| 432 | if (IdResolver.begin(Name: Protocol) == IdResolver.end()) |
| 433 | PushOnScopeChains(D: Context.getObjCProtocolDecl(), S: TUScope); |
| 434 | } |
| 435 | |
| 436 | // Create the internal type for the *StringMakeConstantString builtins. |
| 437 | DeclarationName ConstantString = &Context.Idents.get(Name: "__NSConstantString" ); |
| 438 | if (IdResolver.begin(Name: ConstantString) == IdResolver.end()) |
| 439 | PushOnScopeChains(D: Context.getCFConstantStringDecl(), S: TUScope); |
| 440 | |
| 441 | // Initialize Microsoft "predefined C++ types". |
| 442 | if (getLangOpts().MSVCCompat) { |
| 443 | if (getLangOpts().CPlusPlus && |
| 444 | IdResolver.begin(Name: &Context.Idents.get(Name: "type_info" )) == IdResolver.end()) |
| 445 | PushOnScopeChains(D: Context.getMSTypeInfoTagDecl(), S: TUScope); |
| 446 | |
| 447 | addImplicitTypedef(Name: "size_t" , T: Context.getSizeType()); |
| 448 | } |
| 449 | |
| 450 | // Initialize predefined OpenCL types and supported extensions and (optional) |
| 451 | // core features. |
| 452 | if (getLangOpts().OpenCL) { |
| 453 | getOpenCLOptions().addSupport( |
| 454 | FeaturesMap: Context.getTargetInfo().getSupportedOpenCLOpts(), Opts: getLangOpts()); |
| 455 | addImplicitTypedef(Name: "sampler_t" , T: Context.OCLSamplerTy); |
| 456 | addImplicitTypedef(Name: "event_t" , T: Context.OCLEventTy); |
| 457 | auto OCLCompatibleVersion = getLangOpts().getOpenCLCompatibleVersion(); |
| 458 | if (OCLCompatibleVersion >= 200) { |
| 459 | if (getLangOpts().OpenCLCPlusPlus || getLangOpts().Blocks) { |
| 460 | addImplicitTypedef(Name: "clk_event_t" , T: Context.OCLClkEventTy); |
| 461 | addImplicitTypedef(Name: "queue_t" , T: Context.OCLQueueTy); |
| 462 | } |
| 463 | if (getLangOpts().OpenCLPipes) |
| 464 | addImplicitTypedef(Name: "reserve_id_t" , T: Context.OCLReserveIDTy); |
| 465 | addImplicitTypedef(Name: "atomic_int" , T: Context.getAtomicType(T: Context.IntTy)); |
| 466 | addImplicitTypedef(Name: "atomic_uint" , |
| 467 | T: Context.getAtomicType(T: Context.UnsignedIntTy)); |
| 468 | addImplicitTypedef(Name: "atomic_float" , |
| 469 | T: Context.getAtomicType(T: Context.FloatTy)); |
| 470 | // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as |
| 471 | // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide. |
| 472 | addImplicitTypedef(Name: "atomic_flag" , T: Context.getAtomicType(T: Context.IntTy)); |
| 473 | |
| 474 | |
| 475 | // OpenCL v2.0 s6.13.11.6: |
| 476 | // - The atomic_long and atomic_ulong types are supported if the |
| 477 | // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics |
| 478 | // extensions are supported. |
| 479 | // - The atomic_double type is only supported if double precision |
| 480 | // is supported and the cl_khr_int64_base_atomics and |
| 481 | // cl_khr_int64_extended_atomics extensions are supported. |
| 482 | // - If the device address space is 64-bits, the data types |
| 483 | // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and |
| 484 | // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and |
| 485 | // cl_khr_int64_extended_atomics extensions are supported. |
| 486 | |
| 487 | auto AddPointerSizeDependentTypes = [&]() { |
| 488 | auto AtomicSizeT = Context.getAtomicType(T: Context.getSizeType()); |
| 489 | auto AtomicIntPtrT = Context.getAtomicType(T: Context.getIntPtrType()); |
| 490 | auto AtomicUIntPtrT = Context.getAtomicType(T: Context.getUIntPtrType()); |
| 491 | auto AtomicPtrDiffT = |
| 492 | Context.getAtomicType(T: Context.getPointerDiffType()); |
| 493 | addImplicitTypedef(Name: "atomic_size_t" , T: AtomicSizeT); |
| 494 | addImplicitTypedef(Name: "atomic_intptr_t" , T: AtomicIntPtrT); |
| 495 | addImplicitTypedef(Name: "atomic_uintptr_t" , T: AtomicUIntPtrT); |
| 496 | addImplicitTypedef(Name: "atomic_ptrdiff_t" , T: AtomicPtrDiffT); |
| 497 | }; |
| 498 | |
| 499 | if (Context.getTypeSize(T: Context.getSizeType()) == 32) { |
| 500 | AddPointerSizeDependentTypes(); |
| 501 | } |
| 502 | |
| 503 | if (getOpenCLOptions().isSupported(Ext: "cl_khr_fp16" , LO: getLangOpts())) { |
| 504 | auto AtomicHalfT = Context.getAtomicType(T: Context.HalfTy); |
| 505 | addImplicitTypedef(Name: "atomic_half" , T: AtomicHalfT); |
| 506 | } |
| 507 | |
| 508 | std::vector<QualType> Atomic64BitTypes; |
| 509 | if (getOpenCLOptions().isSupported(Ext: "cl_khr_int64_base_atomics" , |
| 510 | LO: getLangOpts()) && |
| 511 | getOpenCLOptions().isSupported(Ext: "cl_khr_int64_extended_atomics" , |
| 512 | LO: getLangOpts())) { |
| 513 | if (getOpenCLOptions().isSupported(Ext: "cl_khr_fp64" , LO: getLangOpts())) { |
| 514 | auto AtomicDoubleT = Context.getAtomicType(T: Context.DoubleTy); |
| 515 | addImplicitTypedef(Name: "atomic_double" , T: AtomicDoubleT); |
| 516 | Atomic64BitTypes.push_back(x: AtomicDoubleT); |
| 517 | } |
| 518 | auto AtomicLongT = Context.getAtomicType(T: Context.LongTy); |
| 519 | auto AtomicULongT = Context.getAtomicType(T: Context.UnsignedLongTy); |
| 520 | addImplicitTypedef(Name: "atomic_long" , T: AtomicLongT); |
| 521 | addImplicitTypedef(Name: "atomic_ulong" , T: AtomicULongT); |
| 522 | |
| 523 | |
| 524 | if (Context.getTypeSize(T: Context.getSizeType()) == 64) { |
| 525 | AddPointerSizeDependentTypes(); |
| 526 | } |
| 527 | } |
| 528 | } |
| 529 | |
| 530 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
| 531 | if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) { \ |
| 532 | addImplicitTypedef(#ExtType, Context.Id##Ty); \ |
| 533 | } |
| 534 | #include "clang/Basic/OpenCLExtensionTypes.def" |
| 535 | } |
| 536 | |
| 537 | if (Context.getTargetInfo().hasAArch64ACLETypes() || |
| 538 | (Context.getAuxTargetInfo() && |
| 539 | Context.getAuxTargetInfo()->hasAArch64ACLETypes())) { |
| 540 | #define SVE_TYPE(Name, Id, SingletonId) \ |
| 541 | addImplicitTypedef(#Name, Context.SingletonId); |
| 542 | #define NEON_VECTOR_TYPE(Name, BaseType, ElBits, NumEls, VectorKind) \ |
| 543 | addImplicitTypedef( \ |
| 544 | #Name, Context.getVectorType(Context.BaseType, NumEls, VectorKind)); |
| 545 | #include "clang/Basic/AArch64ACLETypes.def" |
| 546 | } |
| 547 | |
| 548 | if (Context.getTargetInfo().getTriple().isPPC64()) { |
| 549 | #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \ |
| 550 | addImplicitTypedef(#Name, Context.Id##Ty); |
| 551 | #include "clang/Basic/PPCTypes.def" |
| 552 | #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \ |
| 553 | addImplicitTypedef(#Name, Context.Id##Ty); |
| 554 | #include "clang/Basic/PPCTypes.def" |
| 555 | } |
| 556 | |
| 557 | if (Context.getTargetInfo().hasRISCVVTypes()) { |
| 558 | #define RVV_TYPE(Name, Id, SingletonId) \ |
| 559 | addImplicitTypedef(Name, Context.SingletonId); |
| 560 | #include "clang/Basic/RISCVVTypes.def" |
| 561 | } |
| 562 | |
| 563 | if (Context.getTargetInfo().getTriple().isWasm() && |
| 564 | Context.getTargetInfo().hasFeature(Feature: "reference-types" )) { |
| 565 | #define WASM_TYPE(Name, Id, SingletonId) \ |
| 566 | addImplicitTypedef(Name, Context.SingletonId); |
| 567 | #include "clang/Basic/WebAssemblyReferenceTypes.def" |
| 568 | } |
| 569 | |
| 570 | if (Context.getTargetInfo().getTriple().isAMDGPU() || |
| 571 | (Context.getAuxTargetInfo() && |
| 572 | Context.getAuxTargetInfo()->getTriple().isAMDGPU())) { |
| 573 | #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \ |
| 574 | addImplicitTypedef(Name, Context.SingletonId); |
| 575 | #include "clang/Basic/AMDGPUTypes.def" |
| 576 | } |
| 577 | |
| 578 | if (Context.getTargetInfo().hasBuiltinMSVaList()) { |
| 579 | DeclarationName MSVaList = &Context.Idents.get(Name: "__builtin_ms_va_list" ); |
| 580 | if (IdResolver.begin(Name: MSVaList) == IdResolver.end()) |
| 581 | PushOnScopeChains(D: Context.getBuiltinMSVaListDecl(), S: TUScope); |
| 582 | } |
| 583 | |
| 584 | DeclarationName BuiltinVaList = &Context.Idents.get(Name: "__builtin_va_list" ); |
| 585 | if (IdResolver.begin(Name: BuiltinVaList) == IdResolver.end()) |
| 586 | PushOnScopeChains(D: Context.getBuiltinVaListDecl(), S: TUScope); |
| 587 | } |
| 588 | |
| 589 | Sema::~Sema() { |
| 590 | assert(InstantiatingSpecializations.empty() && |
| 591 | "failed to clean up an InstantiatingTemplate?" ); |
| 592 | |
| 593 | if (VisContext) FreeVisContext(); |
| 594 | |
| 595 | // Kill all the active scopes. |
| 596 | for (sema::FunctionScopeInfo *FSI : FunctionScopes) |
| 597 | delete FSI; |
| 598 | |
| 599 | // Tell the SemaConsumer to forget about us; we're going out of scope. |
| 600 | if (SemaConsumer *SC = dyn_cast<SemaConsumer>(Val: &Consumer)) |
| 601 | SC->ForgetSema(); |
| 602 | |
| 603 | // Detach from the external Sema source. |
| 604 | if (ExternalSemaSource *ExternalSema |
| 605 | = dyn_cast_or_null<ExternalSemaSource>(Val: Context.getExternalSource())) |
| 606 | ExternalSema->ForgetSema(); |
| 607 | |
| 608 | // Delete cached satisfactions. |
| 609 | std::vector<ConstraintSatisfaction *> Satisfactions; |
| 610 | Satisfactions.reserve(n: SatisfactionCache.size()); |
| 611 | for (auto &Node : SatisfactionCache) |
| 612 | Satisfactions.push_back(x: &Node); |
| 613 | for (auto *Node : Satisfactions) |
| 614 | delete Node; |
| 615 | |
| 616 | threadSafety::threadSafetyCleanup(Cache: ThreadSafetyDeclCache); |
| 617 | |
| 618 | // Destroys data sharing attributes stack for OpenMP |
| 619 | OpenMP().DestroyDataSharingAttributesStack(); |
| 620 | |
| 621 | // Detach from the PP callback handler which outlives Sema since it's owned |
| 622 | // by the preprocessor. |
| 623 | SemaPPCallbackHandler->reset(); |
| 624 | } |
| 625 | |
| 626 | void Sema::runWithSufficientStackSpace(SourceLocation Loc, |
| 627 | llvm::function_ref<void()> Fn) { |
| 628 | StackHandler.runWithSufficientStackSpace(Loc, Fn); |
| 629 | } |
| 630 | |
| 631 | bool Sema::(SourceLocation loc, |
| 632 | UnavailableAttr::ImplicitReason reason) { |
| 633 | // If we're not in a function, it's an error. |
| 634 | FunctionDecl *fn = dyn_cast<FunctionDecl>(Val: CurContext); |
| 635 | if (!fn) return false; |
| 636 | |
| 637 | // If we're in template instantiation, it's an error. |
| 638 | if (inTemplateInstantiation()) |
| 639 | return false; |
| 640 | |
| 641 | // If that function's not in a system header, it's an error. |
| 642 | if (!Context.getSourceManager().isInSystemHeader(Loc: loc)) |
| 643 | return false; |
| 644 | |
| 645 | // If the function is already unavailable, it's not an error. |
| 646 | if (fn->hasAttr<UnavailableAttr>()) return true; |
| 647 | |
| 648 | fn->addAttr(A: UnavailableAttr::CreateImplicit(Ctx&: Context, Message: "" , ImplicitReason: reason, Range: loc)); |
| 649 | return true; |
| 650 | } |
| 651 | |
| 652 | ASTMutationListener *Sema::getASTMutationListener() const { |
| 653 | return getASTConsumer().GetASTMutationListener(); |
| 654 | } |
| 655 | |
| 656 | void Sema::addExternalSource(IntrusiveRefCntPtr<ExternalSemaSource> E) { |
| 657 | assert(E && "Cannot use with NULL ptr" ); |
| 658 | |
| 659 | if (!ExternalSource) { |
| 660 | ExternalSource = std::move(E); |
| 661 | return; |
| 662 | } |
| 663 | |
| 664 | if (auto *Ex = dyn_cast<MultiplexExternalSemaSource>(Val: ExternalSource.get())) |
| 665 | Ex->AddSource(Source: std::move(E)); |
| 666 | else |
| 667 | ExternalSource = llvm::makeIntrusiveRefCnt<MultiplexExternalSemaSource>( |
| 668 | A&: ExternalSource, A: std::move(E)); |
| 669 | } |
| 670 | |
| 671 | void Sema::PrintStats() const { |
| 672 | llvm::errs() << "\n*** Semantic Analysis Stats:\n" ; |
| 673 | if (SFINAETrap *Trap = getSFINAEContext()) |
| 674 | llvm::errs() << int(Trap->hasErrorOccurred()) |
| 675 | << " SFINAE diagnostics trapped.\n" ; |
| 676 | |
| 677 | BumpAlloc.PrintStats(); |
| 678 | AnalysisWarnings.PrintStats(); |
| 679 | } |
| 680 | |
| 681 | void Sema::diagnoseNullableToNonnullConversion(QualType DstType, |
| 682 | QualType SrcType, |
| 683 | SourceLocation Loc) { |
| 684 | std::optional<NullabilityKind> ExprNullability = SrcType->getNullability(); |
| 685 | if (!ExprNullability || (*ExprNullability != NullabilityKind::Nullable && |
| 686 | *ExprNullability != NullabilityKind::NullableResult)) |
| 687 | return; |
| 688 | |
| 689 | std::optional<NullabilityKind> TypeNullability = DstType->getNullability(); |
| 690 | if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull) |
| 691 | return; |
| 692 | |
| 693 | Diag(Loc, DiagID: diag::warn_nullability_lost) << SrcType << DstType; |
| 694 | } |
| 695 | |
| 696 | // Generate diagnostics when adding or removing effects in a type conversion. |
| 697 | void Sema::diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType, |
| 698 | SourceLocation Loc) { |
| 699 | const auto SrcFX = FunctionEffectsRef::get(QT: SrcType); |
| 700 | const auto DstFX = FunctionEffectsRef::get(QT: DstType); |
| 701 | if (SrcFX != DstFX) { |
| 702 | for (const auto &Diff : FunctionEffectDiffVector(SrcFX, DstFX)) { |
| 703 | if (Diff.shouldDiagnoseConversion(SrcType, SrcFX, DstType, DstFX)) |
| 704 | Diag(Loc, DiagID: diag::warn_invalid_add_func_effects) << Diff.effectName(); |
| 705 | } |
| 706 | } |
| 707 | } |
| 708 | |
| 709 | void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E) { |
| 710 | // nullptr only exists from C++11 on, so don't warn on its absence earlier. |
| 711 | if (!getLangOpts().CPlusPlus11) |
| 712 | return; |
| 713 | |
| 714 | if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer) |
| 715 | return; |
| 716 | |
| 717 | const Expr *EStripped = E->IgnoreParenImpCasts(); |
| 718 | if (EStripped->getType()->isNullPtrType()) |
| 719 | return; |
| 720 | if (isa<GNUNullExpr>(Val: EStripped)) |
| 721 | return; |
| 722 | |
| 723 | if (Diags.isIgnored(DiagID: diag::warn_zero_as_null_pointer_constant, |
| 724 | Loc: E->getBeginLoc())) |
| 725 | return; |
| 726 | |
| 727 | // Don't diagnose the conversion from a 0 literal to a null pointer argument |
| 728 | // in a synthesized call to operator<=>. |
| 729 | if (!CodeSynthesisContexts.empty() && |
| 730 | CodeSynthesisContexts.back().Kind == |
| 731 | CodeSynthesisContext::RewritingOperatorAsSpaceship) |
| 732 | return; |
| 733 | |
| 734 | // Ignore null pointers in defaulted comparison operators. |
| 735 | FunctionDecl *FD = getCurFunctionDecl(); |
| 736 | if (FD && FD->isDefaulted()) { |
| 737 | return; |
| 738 | } |
| 739 | |
| 740 | // If it is a macro from system header, and if the macro name is not "NULL", |
| 741 | // do not warn. |
| 742 | // Note that uses of "NULL" will be ignored above on systems that define it |
| 743 | // as __null. |
| 744 | SourceLocation MaybeMacroLoc = E->getBeginLoc(); |
| 745 | if (Diags.getSuppressSystemWarnings() && |
| 746 | SourceMgr.isInSystemMacro(loc: MaybeMacroLoc) && |
| 747 | !findMacroSpelling(loc&: MaybeMacroLoc, name: "NULL" )) |
| 748 | return; |
| 749 | |
| 750 | Diag(Loc: E->getBeginLoc(), DiagID: diag::warn_zero_as_null_pointer_constant) |
| 751 | << FixItHint::CreateReplacement(RemoveRange: E->getSourceRange(), Code: "nullptr" ); |
| 752 | } |
| 753 | |
| 754 | /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. |
| 755 | /// If there is already an implicit cast, merge into the existing one. |
| 756 | /// The result is of the given category. |
| 757 | ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty, |
| 758 | CastKind Kind, ExprValueKind VK, |
| 759 | const CXXCastPath *BasePath, |
| 760 | CheckedConversionKind CCK) { |
| 761 | #ifndef NDEBUG |
| 762 | if (VK == VK_PRValue && !E->isPRValue()) { |
| 763 | switch (Kind) { |
| 764 | default: |
| 765 | llvm_unreachable( |
| 766 | ("can't implicitly cast glvalue to prvalue with this cast " |
| 767 | "kind: " + |
| 768 | std::string(CastExpr::getCastKindName(Kind))) |
| 769 | .c_str()); |
| 770 | case CK_Dependent: |
| 771 | case CK_LValueToRValue: |
| 772 | case CK_ArrayToPointerDecay: |
| 773 | case CK_FunctionToPointerDecay: |
| 774 | case CK_ToVoid: |
| 775 | case CK_NonAtomicToAtomic: |
| 776 | case CK_HLSLArrayRValue: |
| 777 | case CK_HLSLAggregateSplatCast: |
| 778 | break; |
| 779 | } |
| 780 | } |
| 781 | assert((VK == VK_PRValue || Kind == CK_Dependent || !E->isPRValue()) && |
| 782 | "can't cast prvalue to glvalue" ); |
| 783 | #endif |
| 784 | |
| 785 | diagnoseNullableToNonnullConversion(DstType: Ty, SrcType: E->getType(), Loc: E->getBeginLoc()); |
| 786 | diagnoseZeroToNullptrConversion(Kind, E); |
| 787 | if (Context.hasAnyFunctionEffects() && !isCast(CCK) && |
| 788 | Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer) |
| 789 | diagnoseFunctionEffectConversion(DstType: Ty, SrcType: E->getType(), Loc: E->getBeginLoc()); |
| 790 | |
| 791 | QualType ExprTy = Context.getCanonicalType(T: E->getType()); |
| 792 | QualType TypeTy = Context.getCanonicalType(T: Ty); |
| 793 | |
| 794 | // This cast is used in place of a regular LValue to RValue cast for |
| 795 | // HLSL Array Parameter Types. It needs to be emitted even if |
| 796 | // ExprTy == TypeTy, except if E is an HLSLOutArgExpr |
| 797 | // Emitting a cast in that case will prevent HLSLOutArgExpr from |
| 798 | // being handled properly in EmitCallArg |
| 799 | if (Kind == CK_HLSLArrayRValue && !isa<HLSLOutArgExpr>(Val: E)) |
| 800 | return ImplicitCastExpr::Create(Context, T: Ty, Kind, Operand: E, BasePath, Cat: VK, |
| 801 | FPO: CurFPFeatureOverrides()); |
| 802 | |
| 803 | if (ExprTy == TypeTy) |
| 804 | return E; |
| 805 | |
| 806 | if (Kind == CK_ArrayToPointerDecay) { |
| 807 | // C++1z [conv.array]: The temporary materialization conversion is applied. |
| 808 | // We also use this to fuel C++ DR1213, which applies to C++11 onwards. |
| 809 | if (getLangOpts().CPlusPlus && E->isPRValue()) { |
| 810 | // The temporary is an lvalue in C++98 and an xvalue otherwise. |
| 811 | ExprResult Materialized = CreateMaterializeTemporaryExpr( |
| 812 | T: E->getType(), Temporary: E, BoundToLvalueReference: !getLangOpts().CPlusPlus11); |
| 813 | if (Materialized.isInvalid()) |
| 814 | return ExprError(); |
| 815 | E = Materialized.get(); |
| 816 | } |
| 817 | // C17 6.7.1p6 footnote 124: The implementation can treat any register |
| 818 | // declaration simply as an auto declaration. However, whether or not |
| 819 | // addressable storage is actually used, the address of any part of an |
| 820 | // object declared with storage-class specifier register cannot be |
| 821 | // computed, either explicitly(by use of the unary & operator as discussed |
| 822 | // in 6.5.3.2) or implicitly(by converting an array name to a pointer as |
| 823 | // discussed in 6.3.2.1).Thus, the only operator that can be applied to an |
| 824 | // array declared with storage-class specifier register is sizeof. |
| 825 | if (VK == VK_PRValue && !getLangOpts().CPlusPlus && !E->isPRValue()) { |
| 826 | if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) { |
| 827 | if (const auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl())) { |
| 828 | if (VD->getStorageClass() == SC_Register) { |
| 829 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_typecheck_address_of) |
| 830 | << /*register variable*/ 3 << E->getSourceRange(); |
| 831 | return ExprError(); |
| 832 | } |
| 833 | } |
| 834 | } |
| 835 | } |
| 836 | } |
| 837 | |
| 838 | if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Val: E)) { |
| 839 | if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) { |
| 840 | ImpCast->setType(Ty); |
| 841 | ImpCast->setValueKind(VK); |
| 842 | return E; |
| 843 | } |
| 844 | } |
| 845 | |
| 846 | bool IsExplicitCast = isa<CStyleCastExpr>(Val: E) || isa<CXXStaticCastExpr>(Val: E) || |
| 847 | isa<CXXFunctionalCastExpr>(Val: E); |
| 848 | |
| 849 | if ((Kind == CK_IntegralCast || Kind == CK_IntegralToBoolean || |
| 850 | (Kind == CK_NoOp && E->getType()->isIntegerType() && |
| 851 | Ty->isIntegerType())) && |
| 852 | IsExplicitCast) { |
| 853 | if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) { |
| 854 | if (Ty->isIntegerType() && !Ty->isOverflowBehaviorType()) { |
| 855 | Ty = Context.getOverflowBehaviorType(Kind: SourceOBT->getBehaviorKind(), Wrapped: Ty); |
| 856 | } |
| 857 | } |
| 858 | } |
| 859 | |
| 860 | return ImplicitCastExpr::Create(Context, T: Ty, Kind, Operand: E, BasePath, Cat: VK, |
| 861 | FPO: CurFPFeatureOverrides()); |
| 862 | } |
| 863 | |
| 864 | CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) { |
| 865 | switch (ScalarTy->getScalarTypeKind()) { |
| 866 | case Type::STK_Bool: return CK_NoOp; |
| 867 | case Type::STK_CPointer: return CK_PointerToBoolean; |
| 868 | case Type::STK_BlockPointer: return CK_PointerToBoolean; |
| 869 | case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean; |
| 870 | case Type::STK_MemberPointer: return CK_MemberPointerToBoolean; |
| 871 | case Type::STK_Integral: return CK_IntegralToBoolean; |
| 872 | case Type::STK_Floating: return CK_FloatingToBoolean; |
| 873 | case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean; |
| 874 | case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean; |
| 875 | case Type::STK_FixedPoint: return CK_FixedPointToBoolean; |
| 876 | } |
| 877 | llvm_unreachable("unknown scalar type kind" ); |
| 878 | } |
| 879 | |
| 880 | /// Used to prune the decls of Sema's UnusedFileScopedDecls vector. |
| 881 | static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) { |
| 882 | if (D->getMostRecentDecl()->isUsed()) |
| 883 | return true; |
| 884 | |
| 885 | if (D->isExternallyVisible()) |
| 886 | return true; |
| 887 | |
| 888 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) { |
| 889 | // If this is a function template and none of its specializations is used, |
| 890 | // we should warn. |
| 891 | if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate()) |
| 892 | for (const auto *Spec : Template->specializations()) |
| 893 | if (ShouldRemoveFromUnused(SemaRef, D: Spec)) |
| 894 | return true; |
| 895 | |
| 896 | // UnusedFileScopedDecls stores the first declaration. |
| 897 | // The declaration may have become definition so check again. |
| 898 | const FunctionDecl *DeclToCheck; |
| 899 | if (FD->hasBody(Definition&: DeclToCheck)) |
| 900 | return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(D: DeclToCheck); |
| 901 | |
| 902 | // Later redecls may add new information resulting in not having to warn, |
| 903 | // so check again. |
| 904 | DeclToCheck = FD->getMostRecentDecl(); |
| 905 | if (DeclToCheck != FD) |
| 906 | return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(D: DeclToCheck); |
| 907 | } |
| 908 | |
| 909 | if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) { |
| 910 | // If a variable usable in constant expressions is referenced, |
| 911 | // don't warn if it isn't used: if the value of a variable is required |
| 912 | // for the computation of a constant expression, it doesn't make sense to |
| 913 | // warn even if the variable isn't odr-used. (isReferenced doesn't |
| 914 | // precisely reflect that, but it's a decent approximation.) |
| 915 | if (VD->isReferenced() && |
| 916 | VD->mightBeUsableInConstantExpressions(C: SemaRef->Context)) |
| 917 | return true; |
| 918 | |
| 919 | if (VarTemplateDecl *Template = VD->getDescribedVarTemplate()) |
| 920 | // If this is a variable template and none of its specializations is used, |
| 921 | // we should warn. |
| 922 | for (const auto *Spec : Template->specializations()) |
| 923 | if (ShouldRemoveFromUnused(SemaRef, D: Spec)) |
| 924 | return true; |
| 925 | |
| 926 | // UnusedFileScopedDecls stores the first declaration. |
| 927 | // The declaration may have become definition so check again. |
| 928 | const VarDecl *DeclToCheck = VD->getDefinition(); |
| 929 | if (DeclToCheck) |
| 930 | return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(D: DeclToCheck); |
| 931 | |
| 932 | // Later redecls may add new information resulting in not having to warn, |
| 933 | // so check again. |
| 934 | DeclToCheck = VD->getMostRecentDecl(); |
| 935 | if (DeclToCheck != VD) |
| 936 | return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(D: DeclToCheck); |
| 937 | } |
| 938 | |
| 939 | return false; |
| 940 | } |
| 941 | |
| 942 | static bool isFunctionOrVarDeclExternC(const NamedDecl *ND) { |
| 943 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND)) |
| 944 | return FD->isExternC(); |
| 945 | return cast<VarDecl>(Val: ND)->isExternC(); |
| 946 | } |
| 947 | |
| 948 | /// Determine whether ND is an external-linkage function or variable whose |
| 949 | /// type has no linkage. |
| 950 | bool Sema::isExternalWithNoLinkageType(const ValueDecl *VD) const { |
| 951 | // Note: it's not quite enough to check whether VD has UniqueExternalLinkage, |
| 952 | // because we also want to catch the case where its type has VisibleNoLinkage, |
| 953 | // which does not affect the linkage of VD. |
| 954 | return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() && |
| 955 | !isExternalFormalLinkage(L: VD->getType()->getLinkage()) && |
| 956 | !isFunctionOrVarDeclExternC(ND: VD); |
| 957 | } |
| 958 | |
| 959 | /// Obtains a sorted list of functions and variables that are undefined but |
| 960 | /// ODR-used. |
| 961 | void Sema::getUndefinedButUsed( |
| 962 | SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) { |
| 963 | for (const auto &UndefinedUse : UndefinedButUsed) { |
| 964 | NamedDecl *ND = UndefinedUse.first; |
| 965 | |
| 966 | // Ignore attributes that have become invalid. |
| 967 | if (ND->isInvalidDecl()) continue; |
| 968 | |
| 969 | // __attribute__((weakref)) is basically a definition. |
| 970 | if (ND->hasAttr<WeakRefAttr>()) continue; |
| 971 | |
| 972 | if (isa<CXXDeductionGuideDecl>(Val: ND)) |
| 973 | continue; |
| 974 | |
| 975 | if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) { |
| 976 | // An exported function will always be emitted when defined, so even if |
| 977 | // the function is inline, it doesn't have to be emitted in this TU. An |
| 978 | // imported function implies that it has been exported somewhere else. |
| 979 | continue; |
| 980 | } |
| 981 | |
| 982 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND)) { |
| 983 | if (FD->isDefined()) |
| 984 | continue; |
| 985 | if (FD->isExternallyVisible() && |
| 986 | !isExternalWithNoLinkageType(VD: FD) && |
| 987 | !FD->getMostRecentDecl()->isInlined() && |
| 988 | !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>()) |
| 989 | continue; |
| 990 | if (FD->getBuiltinID()) |
| 991 | continue; |
| 992 | } else { |
| 993 | const auto *VD = cast<VarDecl>(Val: ND); |
| 994 | if (VD->hasDefinition() != VarDecl::DeclarationOnly) |
| 995 | continue; |
| 996 | if (VD->isExternallyVisible() && |
| 997 | !isExternalWithNoLinkageType(VD) && |
| 998 | !VD->getMostRecentDecl()->isInline() && |
| 999 | !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>()) |
| 1000 | continue; |
| 1001 | |
| 1002 | // Skip VarDecls that lack formal definitions but which we know are in |
| 1003 | // fact defined somewhere. |
| 1004 | if (VD->isKnownToBeDefined()) |
| 1005 | continue; |
| 1006 | } |
| 1007 | |
| 1008 | Undefined.push_back(Elt: std::make_pair(x&: ND, y: UndefinedUse.second)); |
| 1009 | } |
| 1010 | } |
| 1011 | |
| 1012 | /// checkUndefinedButUsed - Check for undefined objects with internal linkage |
| 1013 | /// or that are inline. |
| 1014 | static void checkUndefinedButUsed(Sema &S) { |
| 1015 | if (S.UndefinedButUsed.empty()) return; |
| 1016 | |
| 1017 | // Collect all the still-undefined entities with internal linkage. |
| 1018 | SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined; |
| 1019 | S.getUndefinedButUsed(Undefined); |
| 1020 | S.UndefinedButUsed.clear(); |
| 1021 | if (Undefined.empty()) return; |
| 1022 | |
| 1023 | for (const auto &Undef : Undefined) { |
| 1024 | ValueDecl *VD = cast<ValueDecl>(Val: Undef.first); |
| 1025 | SourceLocation UseLoc = Undef.second; |
| 1026 | |
| 1027 | if (S.isExternalWithNoLinkageType(VD)) { |
| 1028 | // C++ [basic.link]p8: |
| 1029 | // A type without linkage shall not be used as the type of a variable |
| 1030 | // or function with external linkage unless |
| 1031 | // -- the entity has C language linkage |
| 1032 | // -- the entity is not odr-used or is defined in the same TU |
| 1033 | // |
| 1034 | // As an extension, accept this in cases where the type is externally |
| 1035 | // visible, since the function or variable actually can be defined in |
| 1036 | // another translation unit in that case. |
| 1037 | S.Diag(Loc: VD->getLocation(), DiagID: isExternallyVisible(L: VD->getType()->getLinkage()) |
| 1038 | ? diag::ext_undefined_internal_type |
| 1039 | : diag::err_undefined_internal_type) |
| 1040 | << isa<VarDecl>(Val: VD) << VD; |
| 1041 | } else if (!VD->isExternallyVisible()) { |
| 1042 | // FIXME: We can promote this to an error. The function or variable can't |
| 1043 | // be defined anywhere else, so the program must necessarily violate the |
| 1044 | // one definition rule. |
| 1045 | bool IsImplicitBase = false; |
| 1046 | if (const auto *BaseD = dyn_cast<FunctionDecl>(Val: VD)) { |
| 1047 | auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>(); |
| 1048 | if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive( |
| 1049 | TP: llvm::omp::TraitProperty:: |
| 1050 | implementation_extension_disable_implicit_base)) { |
| 1051 | const auto *Func = cast<FunctionDecl>( |
| 1052 | Val: cast<DeclRefExpr>(Val: DVAttr->getVariantFuncRef())->getDecl()); |
| 1053 | IsImplicitBase = BaseD->isImplicit() && |
| 1054 | Func->getIdentifier()->isMangledOpenMPVariantName(); |
| 1055 | } |
| 1056 | } |
| 1057 | if (!S.getLangOpts().OpenMP || !IsImplicitBase) |
| 1058 | S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_undefined_internal) |
| 1059 | << isa<VarDecl>(Val: VD) << VD; |
| 1060 | } else if (auto *FD = dyn_cast<FunctionDecl>(Val: VD)) { |
| 1061 | (void)FD; |
| 1062 | assert(FD->getMostRecentDecl()->isInlined() && |
| 1063 | "used object requires definition but isn't inline or internal?" ); |
| 1064 | // FIXME: This is ill-formed; we should reject. |
| 1065 | S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_undefined_inline) << VD; |
| 1066 | } else { |
| 1067 | assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() && |
| 1068 | "used var requires definition but isn't inline or internal?" ); |
| 1069 | S.Diag(Loc: VD->getLocation(), DiagID: diag::err_undefined_inline_var) << VD; |
| 1070 | } |
| 1071 | if (UseLoc.isValid()) |
| 1072 | S.Diag(Loc: UseLoc, DiagID: diag::note_used_here); |
| 1073 | } |
| 1074 | } |
| 1075 | |
| 1076 | void Sema::LoadExternalWeakUndeclaredIdentifiers() { |
| 1077 | if (!ExternalSource) |
| 1078 | return; |
| 1079 | |
| 1080 | SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs; |
| 1081 | ExternalSource->ReadWeakUndeclaredIdentifiers(WI&: WeakIDs); |
| 1082 | for (auto &WeakID : WeakIDs) |
| 1083 | (void)WeakUndeclaredIdentifiers[WeakID.first].insert(X: WeakID.second); |
| 1084 | } |
| 1085 | |
| 1086 | |
| 1087 | typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap; |
| 1088 | |
| 1089 | /// Returns true, if all methods and nested classes of the given |
| 1090 | /// CXXRecordDecl are defined in this translation unit. |
| 1091 | /// |
| 1092 | /// Should only be called from ActOnEndOfTranslationUnit so that all |
| 1093 | /// definitions are actually read. |
| 1094 | static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD, |
| 1095 | RecordCompleteMap &MNCComplete) { |
| 1096 | RecordCompleteMap::iterator Cache = MNCComplete.find(Val: RD); |
| 1097 | if (Cache != MNCComplete.end()) |
| 1098 | return Cache->second; |
| 1099 | if (!RD->isCompleteDefinition()) |
| 1100 | return false; |
| 1101 | bool Complete = true; |
| 1102 | for (DeclContext::decl_iterator I = RD->decls_begin(), |
| 1103 | E = RD->decls_end(); |
| 1104 | I != E && Complete; ++I) { |
| 1105 | if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Val: *I)) |
| 1106 | Complete = M->isDefined() || M->isDefaulted() || |
| 1107 | (M->isPureVirtual() && !isa<CXXDestructorDecl>(Val: M)); |
| 1108 | else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(Val: *I)) |
| 1109 | // If the template function is marked as late template parsed at this |
| 1110 | // point, it has not been instantiated and therefore we have not |
| 1111 | // performed semantic analysis on it yet, so we cannot know if the type |
| 1112 | // can be considered complete. |
| 1113 | Complete = !F->getTemplatedDecl()->isLateTemplateParsed() && |
| 1114 | F->getTemplatedDecl()->isDefined(); |
| 1115 | else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(Val: *I)) { |
| 1116 | if (R->isInjectedClassName()) |
| 1117 | continue; |
| 1118 | if (R->hasDefinition()) |
| 1119 | Complete = MethodsAndNestedClassesComplete(RD: R->getDefinition(), |
| 1120 | MNCComplete); |
| 1121 | else |
| 1122 | Complete = false; |
| 1123 | } |
| 1124 | } |
| 1125 | MNCComplete[RD] = Complete; |
| 1126 | return Complete; |
| 1127 | } |
| 1128 | |
| 1129 | /// Returns true, if the given CXXRecordDecl is fully defined in this |
| 1130 | /// translation unit, i.e. all methods are defined or pure virtual and all |
| 1131 | /// friends, friend functions and nested classes are fully defined in this |
| 1132 | /// translation unit. |
| 1133 | /// |
| 1134 | /// Should only be called from ActOnEndOfTranslationUnit so that all |
| 1135 | /// definitions are actually read. |
| 1136 | static bool IsRecordFullyDefined(const CXXRecordDecl *RD, |
| 1137 | RecordCompleteMap &RecordsComplete, |
| 1138 | RecordCompleteMap &MNCComplete) { |
| 1139 | RecordCompleteMap::iterator Cache = RecordsComplete.find(Val: RD); |
| 1140 | if (Cache != RecordsComplete.end()) |
| 1141 | return Cache->second; |
| 1142 | bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete); |
| 1143 | for (CXXRecordDecl::friend_iterator I = RD->friend_begin(), |
| 1144 | E = RD->friend_end(); |
| 1145 | I != E && Complete; ++I) { |
| 1146 | // Check if friend classes and methods are complete. |
| 1147 | if (TypeSourceInfo *TSI = (*I)->getFriendType()) { |
| 1148 | // Friend classes are available as the TypeSourceInfo of the FriendDecl. |
| 1149 | if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl()) |
| 1150 | Complete = MethodsAndNestedClassesComplete(RD: FriendD, MNCComplete); |
| 1151 | else |
| 1152 | Complete = false; |
| 1153 | } else { |
| 1154 | // Friend functions are available through the NamedDecl of FriendDecl. |
| 1155 | if (const FunctionDecl *FD = |
| 1156 | dyn_cast<FunctionDecl>(Val: (*I)->getFriendDecl())) |
| 1157 | Complete = FD->isDefined(); |
| 1158 | else |
| 1159 | // This is a template friend, give up. |
| 1160 | Complete = false; |
| 1161 | } |
| 1162 | } |
| 1163 | RecordsComplete[RD] = Complete; |
| 1164 | return Complete; |
| 1165 | } |
| 1166 | |
| 1167 | void Sema::emitAndClearUnusedLocalTypedefWarnings() { |
| 1168 | if (ExternalSource) |
| 1169 | ExternalSource->ReadUnusedLocalTypedefNameCandidates( |
| 1170 | Decls&: UnusedLocalTypedefNameCandidates); |
| 1171 | for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) { |
| 1172 | if (TD->isReferenced()) |
| 1173 | continue; |
| 1174 | Diag(Loc: TD->getLocation(), DiagID: diag::warn_unused_local_typedef) |
| 1175 | << isa<TypeAliasDecl>(Val: TD) << TD->getDeclName(); |
| 1176 | } |
| 1177 | UnusedLocalTypedefNameCandidates.clear(); |
| 1178 | } |
| 1179 | |
| 1180 | void Sema::ActOnStartOfTranslationUnit() { |
| 1181 | if (getLangOpts().CPlusPlusModules && |
| 1182 | getLangOpts().getCompilingModule() == LangOptions::CMK_HeaderUnit) |
| 1183 | HandleStartOfHeaderUnit(); |
| 1184 | } |
| 1185 | |
| 1186 | void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) { |
| 1187 | if (Kind == TUFragmentKind::Global) { |
| 1188 | // Perform Pending Instantiations at the end of global module fragment so |
| 1189 | // that the module ownership of TU-level decls won't get messed. |
| 1190 | llvm::TimeTraceScope TimeScope("PerformPendingInstantiations" ); |
| 1191 | PerformPendingInstantiations(); |
| 1192 | return; |
| 1193 | } |
| 1194 | |
| 1195 | // Transfer late parsed template instantiations over to the pending template |
| 1196 | // instantiation list. During normal compilation, the late template parser |
| 1197 | // will be installed and instantiating these templates will succeed. |
| 1198 | // |
| 1199 | // If we are building a TU prefix for serialization, it is also safe to |
| 1200 | // transfer these over, even though they are not parsed. The end of the TU |
| 1201 | // should be outside of any eager template instantiation scope, so when this |
| 1202 | // AST is deserialized, these templates will not be parsed until the end of |
| 1203 | // the combined TU. |
| 1204 | PendingInstantiations.insert(position: PendingInstantiations.end(), |
| 1205 | first: LateParsedInstantiations.begin(), |
| 1206 | last: LateParsedInstantiations.end()); |
| 1207 | LateParsedInstantiations.clear(); |
| 1208 | |
| 1209 | // If DefinedUsedVTables ends up marking any virtual member functions it |
| 1210 | // might lead to more pending template instantiations, which we then need |
| 1211 | // to instantiate. |
| 1212 | DefineUsedVTables(); |
| 1213 | |
| 1214 | // C++: Perform implicit template instantiations. |
| 1215 | // |
| 1216 | // FIXME: When we perform these implicit instantiations, we do not |
| 1217 | // carefully keep track of the point of instantiation (C++ [temp.point]). |
| 1218 | // This means that name lookup that occurs within the template |
| 1219 | // instantiation will always happen at the end of the translation unit, |
| 1220 | // so it will find some names that are not required to be found. This is |
| 1221 | // valid, but we could do better by diagnosing if an instantiation uses a |
| 1222 | // name that was not visible at its first point of instantiation. |
| 1223 | if (ExternalSource) { |
| 1224 | // Load pending instantiations from the external source. |
| 1225 | SmallVector<PendingImplicitInstantiation, 4> Pending; |
| 1226 | ExternalSource->ReadPendingInstantiations(Pending); |
| 1227 | for (auto PII : Pending) |
| 1228 | if (auto Func = dyn_cast<FunctionDecl>(Val: PII.first)) |
| 1229 | Func->setInstantiationIsPending(true); |
| 1230 | PendingInstantiations.insert(position: PendingInstantiations.begin(), |
| 1231 | first: Pending.begin(), last: Pending.end()); |
| 1232 | } |
| 1233 | |
| 1234 | { |
| 1235 | llvm::TimeTraceScope TimeScope("PerformPendingInstantiations" ); |
| 1236 | PerformPendingInstantiations(); |
| 1237 | } |
| 1238 | |
| 1239 | emitDeferredDiags(); |
| 1240 | |
| 1241 | assert(LateParsedInstantiations.empty() && |
| 1242 | "end of TU template instantiation should not create more " |
| 1243 | "late-parsed templates" ); |
| 1244 | } |
| 1245 | |
| 1246 | void Sema::ActOnEndOfTranslationUnit() { |
| 1247 | assert(DelayedDiagnostics.getCurrentPool() == nullptr |
| 1248 | && "reached end of translation unit with a pool attached?" ); |
| 1249 | |
| 1250 | // If code completion is enabled, don't perform any end-of-translation-unit |
| 1251 | // work. |
| 1252 | if (PP.isCodeCompletionEnabled()) |
| 1253 | return; |
| 1254 | |
| 1255 | // Complete translation units and modules define vtables and perform implicit |
| 1256 | // instantiations. PCH files do not. |
| 1257 | if (TUKind != TU_Prefix) { |
| 1258 | ObjC().DiagnoseUseOfUnimplementedSelectors(); |
| 1259 | |
| 1260 | ActOnEndOfTranslationUnitFragment( |
| 1261 | Kind: !ModuleScopes.empty() && ModuleScopes.back().Module->Kind == |
| 1262 | Module::PrivateModuleFragment |
| 1263 | ? TUFragmentKind::Private |
| 1264 | : TUFragmentKind::Normal); |
| 1265 | |
| 1266 | CheckDelayedMemberExceptionSpecs(); |
| 1267 | } else { |
| 1268 | // If we are building a TU prefix for serialization, it is safe to transfer |
| 1269 | // these over, even though they are not parsed. The end of the TU should be |
| 1270 | // outside of any eager template instantiation scope, so when this AST is |
| 1271 | // deserialized, these templates will not be parsed until the end of the |
| 1272 | // combined TU. |
| 1273 | PendingInstantiations.insert(position: PendingInstantiations.end(), |
| 1274 | first: LateParsedInstantiations.begin(), |
| 1275 | last: LateParsedInstantiations.end()); |
| 1276 | LateParsedInstantiations.clear(); |
| 1277 | |
| 1278 | if (LangOpts.PCHInstantiateTemplates) { |
| 1279 | llvm::TimeTraceScope TimeScope("PerformPendingInstantiations" ); |
| 1280 | PerformPendingInstantiations(); |
| 1281 | } |
| 1282 | } |
| 1283 | |
| 1284 | DiagnoseUnterminatedPragmaAlignPack(); |
| 1285 | DiagnoseUnterminatedPragmaAttribute(); |
| 1286 | OpenMP().DiagnoseUnterminatedOpenMPDeclareTarget(); |
| 1287 | DiagnosePrecisionLossInComplexDivision(); |
| 1288 | |
| 1289 | // All delayed member exception specs should be checked or we end up accepting |
| 1290 | // incompatible declarations. |
| 1291 | assert(DelayedOverridingExceptionSpecChecks.empty()); |
| 1292 | assert(DelayedEquivalentExceptionSpecChecks.empty()); |
| 1293 | |
| 1294 | // All dllexport classes should have been processed already. |
| 1295 | assert(DelayedDllExportClasses.empty()); |
| 1296 | assert(DelayedDllExportMemberFunctions.empty()); |
| 1297 | |
| 1298 | // Remove file scoped decls that turned out to be used. |
| 1299 | UnusedFileScopedDecls.erase( |
| 1300 | From: std::remove_if(first: UnusedFileScopedDecls.begin(source: nullptr, LocalOnly: true), |
| 1301 | last: UnusedFileScopedDecls.end(), |
| 1302 | pred: [this](const DeclaratorDecl *DD) { |
| 1303 | return ShouldRemoveFromUnused(SemaRef: this, D: DD); |
| 1304 | }), |
| 1305 | To: UnusedFileScopedDecls.end()); |
| 1306 | |
| 1307 | if (TUKind == TU_Prefix) { |
| 1308 | // Translation unit prefixes don't need any of the checking below. |
| 1309 | if (!PP.isIncrementalProcessingEnabled()) |
| 1310 | TUScope = nullptr; |
| 1311 | return; |
| 1312 | } |
| 1313 | |
| 1314 | // Check for #pragma weak identifiers that were never declared |
| 1315 | LoadExternalWeakUndeclaredIdentifiers(); |
| 1316 | for (const auto &WeakIDs : WeakUndeclaredIdentifiers) { |
| 1317 | if (WeakIDs.second.empty()) |
| 1318 | continue; |
| 1319 | |
| 1320 | Decl *PrevDecl = LookupSingleName(S: TUScope, Name: WeakIDs.first, Loc: SourceLocation(), |
| 1321 | NameKind: LookupOrdinaryName); |
| 1322 | if (PrevDecl != nullptr && |
| 1323 | !(isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) |
| 1324 | for (const auto &WI : WeakIDs.second) |
| 1325 | Diag(Loc: WI.getLocation(), DiagID: diag::warn_attribute_wrong_decl_type) |
| 1326 | << "'weak'" << /*isRegularKeyword=*/0 << ExpectedVariableOrFunction; |
| 1327 | else |
| 1328 | for (const auto &WI : WeakIDs.second) |
| 1329 | Diag(Loc: WI.getLocation(), DiagID: diag::warn_weak_identifier_undeclared) |
| 1330 | << WeakIDs.first; |
| 1331 | } |
| 1332 | |
| 1333 | if (LangOpts.CPlusPlus11 && |
| 1334 | !Diags.isIgnored(DiagID: diag::warn_delegating_ctor_cycle, Loc: SourceLocation())) |
| 1335 | CheckDelegatingCtorCycles(); |
| 1336 | |
| 1337 | if (!Diags.hasErrorOccurred()) { |
| 1338 | if (ExternalSource) |
| 1339 | ExternalSource->ReadUndefinedButUsed(Undefined&: UndefinedButUsed); |
| 1340 | checkUndefinedButUsed(S&: *this); |
| 1341 | } |
| 1342 | |
| 1343 | // A global-module-fragment is only permitted within a module unit. |
| 1344 | if (!ModuleScopes.empty() && ModuleScopes.back().Module->Kind == |
| 1345 | Module::ExplicitGlobalModuleFragment) { |
| 1346 | Diag(Loc: ModuleScopes.back().BeginLoc, |
| 1347 | DiagID: diag::err_module_declaration_missing_after_global_module_introducer); |
| 1348 | } else if (getLangOpts().getCompilingModule() == |
| 1349 | LangOptions::CMK_ModuleInterface && |
| 1350 | // We can't use ModuleScopes here since ModuleScopes is always |
| 1351 | // empty if we're compiling the BMI. |
| 1352 | !getASTContext().getCurrentNamedModule()) { |
| 1353 | // If we are building a module interface unit, we should have seen the |
| 1354 | // module declaration. |
| 1355 | // |
| 1356 | // FIXME: Make a better guess as to where to put the module declaration. |
| 1357 | Diag(Loc: getSourceManager().getLocForStartOfFile( |
| 1358 | FID: getSourceManager().getMainFileID()), |
| 1359 | DiagID: diag::err_module_declaration_missing); |
| 1360 | } |
| 1361 | |
| 1362 | // Now we can decide whether the modules we're building need an initializer. |
| 1363 | if (Module *CurrentModule = getCurrentModule(); |
| 1364 | CurrentModule && CurrentModule->isInterfaceOrPartition()) { |
| 1365 | auto DoesModNeedInit = [this](Module *M) { |
| 1366 | if (!getASTContext().getModuleInitializers(M).empty()) |
| 1367 | return true; |
| 1368 | for (auto [Exported, _] : M->Exports) |
| 1369 | if (Exported->isNamedModuleInterfaceHasInit()) |
| 1370 | return true; |
| 1371 | for (Module *I : M->Imports) |
| 1372 | if (I->isNamedModuleInterfaceHasInit()) |
| 1373 | return true; |
| 1374 | |
| 1375 | return false; |
| 1376 | }; |
| 1377 | |
| 1378 | CurrentModule->NamedModuleHasInit = |
| 1379 | DoesModNeedInit(CurrentModule) || |
| 1380 | llvm::any_of(Range: CurrentModule->submodules(), P: DoesModNeedInit); |
| 1381 | } |
| 1382 | |
| 1383 | if (TUKind == TU_ClangModule) { |
| 1384 | // If we are building a module, resolve all of the exported declarations |
| 1385 | // now. |
| 1386 | if (Module *CurrentModule = PP.getCurrentModule()) { |
| 1387 | ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap(); |
| 1388 | |
| 1389 | SmallVector<Module *, 2> Stack; |
| 1390 | Stack.push_back(Elt: CurrentModule); |
| 1391 | while (!Stack.empty()) { |
| 1392 | Module *Mod = Stack.pop_back_val(); |
| 1393 | |
| 1394 | // Resolve the exported declarations and conflicts. |
| 1395 | // FIXME: Actually complain, once we figure out how to teach the |
| 1396 | // diagnostic client to deal with complaints in the module map at this |
| 1397 | // point. |
| 1398 | ModMap.resolveExports(Mod, /*Complain=*/false); |
| 1399 | ModMap.resolveUses(Mod, /*Complain=*/false); |
| 1400 | ModMap.resolveConflicts(Mod, /*Complain=*/false); |
| 1401 | |
| 1402 | // Queue the submodules, so their exports will also be resolved. |
| 1403 | auto SubmodulesRange = Mod->submodules(); |
| 1404 | Stack.append(in_start: SubmodulesRange.begin(), in_end: SubmodulesRange.end()); |
| 1405 | } |
| 1406 | } |
| 1407 | |
| 1408 | // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for |
| 1409 | // modules when they are built, not every time they are used. |
| 1410 | emitAndClearUnusedLocalTypedefWarnings(); |
| 1411 | } |
| 1412 | |
| 1413 | // C++ standard modules. Diagnose cases where a function is declared inline |
| 1414 | // in the module purview but has no definition before the end of the TU or |
| 1415 | // the start of a Private Module Fragment (if one is present). |
| 1416 | if (!PendingInlineFuncDecls.empty()) { |
| 1417 | for (auto *D : PendingInlineFuncDecls) { |
| 1418 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
| 1419 | bool DefInPMF = false; |
| 1420 | if (auto *FDD = FD->getDefinition()) { |
| 1421 | DefInPMF = FDD->getOwningModule()->isPrivateModule(); |
| 1422 | if (!DefInPMF) |
| 1423 | continue; |
| 1424 | } |
| 1425 | Diag(Loc: FD->getLocation(), DiagID: diag::err_export_inline_not_defined) |
| 1426 | << DefInPMF; |
| 1427 | // If we have a PMF it should be at the end of the ModuleScopes. |
| 1428 | if (DefInPMF && |
| 1429 | ModuleScopes.back().Module->Kind == Module::PrivateModuleFragment) { |
| 1430 | Diag(Loc: ModuleScopes.back().BeginLoc, |
| 1431 | DiagID: diag::note_private_module_fragment); |
| 1432 | } |
| 1433 | } |
| 1434 | } |
| 1435 | PendingInlineFuncDecls.clear(); |
| 1436 | } |
| 1437 | |
| 1438 | // C99 6.9.2p2: |
| 1439 | // A declaration of an identifier for an object that has file |
| 1440 | // scope without an initializer, and without a storage-class |
| 1441 | // specifier or with the storage-class specifier static, |
| 1442 | // constitutes a tentative definition. If a translation unit |
| 1443 | // contains one or more tentative definitions for an identifier, |
| 1444 | // and the translation unit contains no external definition for |
| 1445 | // that identifier, then the behavior is exactly as if the |
| 1446 | // translation unit contains a file scope declaration of that |
| 1447 | // identifier, with the composite type as of the end of the |
| 1448 | // translation unit, with an initializer equal to 0. |
| 1449 | llvm::SmallPtrSet<VarDecl *, 32> Seen; |
| 1450 | for (TentativeDefinitionsType::iterator |
| 1451 | T = TentativeDefinitions.begin(source: ExternalSource.get()), |
| 1452 | TEnd = TentativeDefinitions.end(); |
| 1453 | T != TEnd; ++T) { |
| 1454 | VarDecl *VD = (*T)->getActingDefinition(); |
| 1455 | |
| 1456 | // If the tentative definition was completed, getActingDefinition() returns |
| 1457 | // null. If we've already seen this variable before, insert()'s second |
| 1458 | // return value is false. |
| 1459 | if (!VD || VD->isInvalidDecl() || !Seen.insert(Ptr: VD).second) |
| 1460 | continue; |
| 1461 | |
| 1462 | if (const IncompleteArrayType *ArrayT |
| 1463 | = Context.getAsIncompleteArrayType(T: VD->getType())) { |
| 1464 | // Set the length of the array to 1 (C99 6.9.2p5). |
| 1465 | Diag(Loc: VD->getLocation(), DiagID: diag::warn_tentative_incomplete_array); |
| 1466 | llvm::APInt One(Context.getTypeSize(T: Context.getSizeType()), true); |
| 1467 | QualType T = Context.getConstantArrayType( |
| 1468 | EltTy: ArrayT->getElementType(), ArySize: One, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
| 1469 | VD->setType(T); |
| 1470 | } else if (RequireCompleteType(Loc: VD->getLocation(), T: VD->getType(), |
| 1471 | DiagID: diag::err_tentative_def_incomplete_type)) |
| 1472 | VD->setInvalidDecl(); |
| 1473 | |
| 1474 | // No initialization is performed for a tentative definition. |
| 1475 | CheckCompleteVariableDeclaration(VD); |
| 1476 | |
| 1477 | // In C, if the definition is const-qualified and has no initializer, it |
| 1478 | // is left uninitialized unless it has static or thread storage duration. |
| 1479 | QualType Type = VD->getType(); |
| 1480 | if (!VD->isInvalidDecl() && !getLangOpts().CPlusPlus && |
| 1481 | Type.isConstQualified() && !VD->getAnyInitializer()) { |
| 1482 | unsigned DiagID = diag::warn_default_init_const_unsafe; |
| 1483 | if (VD->getStorageDuration() == SD_Static || |
| 1484 | VD->getStorageDuration() == SD_Thread) |
| 1485 | DiagID = diag::warn_default_init_const; |
| 1486 | |
| 1487 | bool EmitCppCompat = !Diags.isIgnored( |
| 1488 | DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit, |
| 1489 | Loc: VD->getLocation()); |
| 1490 | |
| 1491 | Diag(Loc: VD->getLocation(), DiagID) << Type << EmitCppCompat; |
| 1492 | } |
| 1493 | |
| 1494 | // Notify the consumer that we've completed a tentative definition. |
| 1495 | if (!VD->isInvalidDecl()) |
| 1496 | Consumer.CompleteTentativeDefinition(D: VD); |
| 1497 | } |
| 1498 | |
| 1499 | // In incremental mode, tentative definitions belong to the current |
| 1500 | // partial translation unit (PTU). Once they have been completed and |
| 1501 | // emitted to codegen, drop them to prevent re-emission in future PTUs. |
| 1502 | if (PP.isIncrementalProcessingEnabled()) |
| 1503 | TentativeDefinitions.erase(From: TentativeDefinitions.begin(source: ExternalSource.get()), |
| 1504 | To: TentativeDefinitions.end()); |
| 1505 | |
| 1506 | for (auto *D : ExternalDeclarations) { |
| 1507 | if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed()) |
| 1508 | continue; |
| 1509 | |
| 1510 | Consumer.CompleteExternalDeclaration(D); |
| 1511 | } |
| 1512 | |
| 1513 | // Visit all pending #pragma export. |
| 1514 | for (const PendingPragmaInfo &Exported : PendingExportedNames.values()) { |
| 1515 | if (!Exported.Used) |
| 1516 | Diag(Loc: Exported.NameLoc, DiagID: diag::warn_failed_to_resolve_pragma) << "export" ; |
| 1517 | } |
| 1518 | |
| 1519 | if (LangOpts.HLSL) |
| 1520 | HLSL().ActOnEndOfTranslationUnit(TU: getASTContext().getTranslationUnitDecl()); |
| 1521 | if (LangOpts.OpenACC) |
| 1522 | OpenACC().ActOnEndOfTranslationUnit( |
| 1523 | TU: getASTContext().getTranslationUnitDecl()); |
| 1524 | |
| 1525 | // If there were errors, disable 'unused' warnings since they will mostly be |
| 1526 | // noise. Don't warn for a use from a module: either we should warn on all |
| 1527 | // file-scope declarations in modules or not at all, but whether the |
| 1528 | // declaration is used is immaterial. |
| 1529 | if (!Diags.hasErrorOccurred() && TUKind != TU_ClangModule) { |
| 1530 | // Output warning for unused file scoped decls. |
| 1531 | for (UnusedFileScopedDeclsType::iterator |
| 1532 | I = UnusedFileScopedDecls.begin(source: ExternalSource.get()), |
| 1533 | E = UnusedFileScopedDecls.end(); |
| 1534 | I != E; ++I) { |
| 1535 | if (ShouldRemoveFromUnused(SemaRef: this, D: *I)) |
| 1536 | continue; |
| 1537 | |
| 1538 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *I)) { |
| 1539 | const FunctionDecl *DiagD; |
| 1540 | if (!FD->hasBody(Definition&: DiagD)) |
| 1541 | DiagD = FD; |
| 1542 | if (DiagD->isDeleted()) |
| 1543 | continue; // Deleted functions are supposed to be unused. |
| 1544 | SourceRange DiagRange = DiagD->getLocation(); |
| 1545 | if (const ASTTemplateArgumentListInfo *ASTTAL = |
| 1546 | DiagD->getTemplateSpecializationArgsAsWritten()) |
| 1547 | DiagRange.setEnd(ASTTAL->RAngleLoc); |
| 1548 | if (DiagD->isReferenced()) { |
| 1549 | if (isa<CXXMethodDecl>(Val: DiagD)) |
| 1550 | Diag(Loc: DiagD->getLocation(), DiagID: diag::warn_unneeded_member_function) |
| 1551 | << DiagD << DiagRange; |
| 1552 | else { |
| 1553 | if (FD->getStorageClass() == SC_Static && |
| 1554 | !FD->isInlineSpecified() && |
| 1555 | !SourceMgr.isInMainFile( |
| 1556 | Loc: SourceMgr.getExpansionLoc(Loc: FD->getLocation()))) |
| 1557 | Diag(Loc: DiagD->getLocation(), |
| 1558 | DiagID: diag::warn_unneeded_static_internal_decl) |
| 1559 | << DiagD << DiagRange; |
| 1560 | else |
| 1561 | Diag(Loc: DiagD->getLocation(), DiagID: diag::warn_unneeded_internal_decl) |
| 1562 | << /*function=*/0 << DiagD << DiagRange; |
| 1563 | } |
| 1564 | } else if (!FD->isTargetMultiVersion() || |
| 1565 | FD->isTargetMultiVersionDefault()) { |
| 1566 | if (FD->getDescribedFunctionTemplate()) |
| 1567 | Diag(Loc: DiagD->getLocation(), DiagID: diag::warn_unused_template) |
| 1568 | << /*function=*/0 << DiagD << DiagRange; |
| 1569 | else |
| 1570 | Diag(Loc: DiagD->getLocation(), DiagID: isa<CXXMethodDecl>(Val: DiagD) |
| 1571 | ? diag::warn_unused_member_function |
| 1572 | : diag::warn_unused_function) |
| 1573 | << DiagD << DiagRange; |
| 1574 | } |
| 1575 | } else { |
| 1576 | const VarDecl *DiagD = cast<VarDecl>(Val: *I)->getDefinition(); |
| 1577 | if (!DiagD) |
| 1578 | DiagD = cast<VarDecl>(Val: *I); |
| 1579 | SourceRange DiagRange = DiagD->getLocation(); |
| 1580 | if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: DiagD)) { |
| 1581 | if (const ASTTemplateArgumentListInfo *ASTTAL = |
| 1582 | VTSD->getTemplateArgsAsWritten()) |
| 1583 | DiagRange.setEnd(ASTTAL->RAngleLoc); |
| 1584 | } |
| 1585 | if (DiagD->isReferenced()) { |
| 1586 | Diag(Loc: DiagD->getLocation(), DiagID: diag::warn_unneeded_internal_decl) |
| 1587 | << /*variable=*/1 << DiagD << DiagRange; |
| 1588 | } else if (DiagD->getDescribedVarTemplate()) { |
| 1589 | Diag(Loc: DiagD->getLocation(), DiagID: diag::warn_unused_template) |
| 1590 | << /*variable=*/1 << DiagD << DiagRange; |
| 1591 | } else if (DiagD->getType().isConstQualified()) { |
| 1592 | const SourceManager &SM = SourceMgr; |
| 1593 | if (SM.getMainFileID() != SM.getFileID(SpellingLoc: DiagD->getLocation()) || |
| 1594 | !PP.getLangOpts().IsHeaderFile) |
| 1595 | Diag(Loc: DiagD->getLocation(), DiagID: diag::warn_unused_const_variable) |
| 1596 | << DiagD << DiagRange; |
| 1597 | } else { |
| 1598 | Diag(Loc: DiagD->getLocation(), DiagID: diag::warn_unused_variable) |
| 1599 | << DiagD << DiagRange; |
| 1600 | } |
| 1601 | } |
| 1602 | } |
| 1603 | |
| 1604 | emitAndClearUnusedLocalTypedefWarnings(); |
| 1605 | } |
| 1606 | |
| 1607 | if (!Diags.isIgnored(DiagID: diag::warn_unused_private_field, Loc: SourceLocation())) { |
| 1608 | // FIXME: Load additional unused private field candidates from the external |
| 1609 | // source. |
| 1610 | RecordCompleteMap RecordsComplete; |
| 1611 | RecordCompleteMap MNCComplete; |
| 1612 | for (const NamedDecl *D : UnusedPrivateFields) { |
| 1613 | const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext()); |
| 1614 | if (RD && !RD->isUnion() && |
| 1615 | IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) { |
| 1616 | Diag(Loc: D->getLocation(), DiagID: diag::warn_unused_private_field) |
| 1617 | << D->getDeclName(); |
| 1618 | } |
| 1619 | } |
| 1620 | } |
| 1621 | |
| 1622 | if (!Diags.isIgnored(DiagID: diag::warn_mismatched_delete_new, Loc: SourceLocation())) { |
| 1623 | if (ExternalSource) |
| 1624 | ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs); |
| 1625 | for (const auto &DeletedFieldInfo : DeleteExprs) { |
| 1626 | for (const auto &DeleteExprLoc : DeletedFieldInfo.second) { |
| 1627 | AnalyzeDeleteExprMismatch(Field: DeletedFieldInfo.first, DeleteLoc: DeleteExprLoc.first, |
| 1628 | DeleteWasArrayForm: DeleteExprLoc.second); |
| 1629 | } |
| 1630 | } |
| 1631 | } |
| 1632 | |
| 1633 | AnalysisWarnings.IssueWarnings(D: Context.getTranslationUnitDecl()); |
| 1634 | |
| 1635 | if (Context.hasAnyFunctionEffects()) |
| 1636 | performFunctionEffectAnalysis(TU: Context.getTranslationUnitDecl()); |
| 1637 | |
| 1638 | // Check we've noticed that we're no longer parsing the initializer for every |
| 1639 | // variable. If we miss cases, then at best we have a performance issue and |
| 1640 | // at worst a rejects-valid bug. |
| 1641 | assert(ParsingInitForAutoVars.empty() && |
| 1642 | "Didn't unmark var as having its initializer parsed" ); |
| 1643 | |
| 1644 | if (!PP.isIncrementalProcessingEnabled()) |
| 1645 | TUScope = nullptr; |
| 1646 | |
| 1647 | checkExposure(TU: Context.getTranslationUnitDecl()); |
| 1648 | } |
| 1649 | |
| 1650 | |
| 1651 | //===----------------------------------------------------------------------===// |
| 1652 | // Helper functions. |
| 1653 | //===----------------------------------------------------------------------===// |
| 1654 | |
| 1655 | DeclContext *Sema::getFunctionLevelDeclContext(bool AllowLambda) const { |
| 1656 | DeclContext *DC = CurContext; |
| 1657 | |
| 1658 | while (true) { |
| 1659 | if (isa<BlockDecl>(Val: DC) || isa<EnumDecl>(Val: DC) || isa<CapturedDecl>(Val: DC) || |
| 1660 | isa<RequiresExprBodyDecl>(Val: DC)) { |
| 1661 | DC = DC->getParent(); |
| 1662 | } else if (!AllowLambda && isa<CXXMethodDecl>(Val: DC) && |
| 1663 | cast<CXXMethodDecl>(Val: DC)->getOverloadedOperator() == OO_Call && |
| 1664 | cast<CXXRecordDecl>(Val: DC->getParent())->isLambda()) { |
| 1665 | DC = DC->getParent()->getParent(); |
| 1666 | } else break; |
| 1667 | } |
| 1668 | |
| 1669 | return DC; |
| 1670 | } |
| 1671 | |
| 1672 | /// getCurFunctionDecl - If inside of a function body, this returns a pointer |
| 1673 | /// to the function decl for the function being parsed. If we're currently |
| 1674 | /// in a 'block', this returns the containing context. |
| 1675 | FunctionDecl *Sema::getCurFunctionDecl(bool AllowLambda) const { |
| 1676 | DeclContext *DC = getFunctionLevelDeclContext(AllowLambda); |
| 1677 | return dyn_cast<FunctionDecl>(Val: DC); |
| 1678 | } |
| 1679 | |
| 1680 | ObjCMethodDecl *Sema::getCurMethodDecl() { |
| 1681 | DeclContext *DC = getFunctionLevelDeclContext(); |
| 1682 | while (isa<RecordDecl>(Val: DC)) |
| 1683 | DC = DC->getParent(); |
| 1684 | return dyn_cast<ObjCMethodDecl>(Val: DC); |
| 1685 | } |
| 1686 | |
| 1687 | NamedDecl *Sema::getCurFunctionOrMethodDecl() const { |
| 1688 | DeclContext *DC = getFunctionLevelDeclContext(); |
| 1689 | if (isa<ObjCMethodDecl>(Val: DC) || isa<FunctionDecl>(Val: DC)) |
| 1690 | return cast<NamedDecl>(Val: DC); |
| 1691 | return nullptr; |
| 1692 | } |
| 1693 | |
| 1694 | LangAS Sema::getDefaultCXXMethodAddrSpace() const { |
| 1695 | if (getLangOpts().OpenCL) |
| 1696 | return getASTContext().getDefaultOpenCLPointeeAddrSpace(); |
| 1697 | return LangAS::Default; |
| 1698 | } |
| 1699 | |
| 1700 | void Sema::EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB) { |
| 1701 | // FIXME: It doesn't make sense to me that DiagID is an incoming argument here |
| 1702 | // and yet we also use the current diag ID on the DiagnosticsEngine. This has |
| 1703 | // been made more painfully obvious by the refactor that introduced this |
| 1704 | // function, but it is possible that the incoming argument can be |
| 1705 | // eliminated. If it truly cannot be (for example, there is some reentrancy |
| 1706 | // issue I am not seeing yet), then there should at least be a clarifying |
| 1707 | // comment somewhere. |
| 1708 | Diagnostic DiagInfo(&Diags, DB); |
| 1709 | if (SFINAETrap *Trap = getSFINAEContext()) { |
| 1710 | sema::TemplateDeductionInfo *Info = Trap->getDeductionInfo(); |
| 1711 | switch (DiagnosticIDs::getDiagnosticSFINAEResponse(DiagID: DiagInfo.getID())) { |
| 1712 | case DiagnosticIDs::SFINAE_Report: |
| 1713 | // We'll report the diagnostic below. |
| 1714 | break; |
| 1715 | |
| 1716 | case DiagnosticIDs::SFINAE_SubstitutionFailure: |
| 1717 | // Count this failure so that we know that template argument deduction |
| 1718 | // has failed. |
| 1719 | Trap->setErrorOccurred(); |
| 1720 | |
| 1721 | // Make a copy of this suppressed diagnostic and store it with the |
| 1722 | // template-deduction information. |
| 1723 | if (Info && !Info->hasSFINAEDiagnostic()) |
| 1724 | Info->addSFINAEDiagnostic( |
| 1725 | Loc: DiagInfo.getLocation(), |
| 1726 | PD: PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); |
| 1727 | |
| 1728 | Diags.setLastDiagnosticIgnored(true); |
| 1729 | return; |
| 1730 | |
| 1731 | case DiagnosticIDs::SFINAE_AccessControl: { |
| 1732 | // Per C++ Core Issue 1170, access control is part of SFINAE. |
| 1733 | // Additionally, the WithAccessChecking flag can be used to temporarily |
| 1734 | // make access control a part of SFINAE for the purposes of checking |
| 1735 | // type traits. |
| 1736 | if (!Trap->withAccessChecking() && !getLangOpts().CPlusPlus11) |
| 1737 | break; |
| 1738 | |
| 1739 | SourceLocation Loc = DiagInfo.getLocation(); |
| 1740 | |
| 1741 | // Suppress this diagnostic. |
| 1742 | Trap->setErrorOccurred(); |
| 1743 | |
| 1744 | // Make a copy of this suppressed diagnostic and store it with the |
| 1745 | // template-deduction information. |
| 1746 | if (Info && !Info->hasSFINAEDiagnostic()) |
| 1747 | Info->addSFINAEDiagnostic( |
| 1748 | Loc: DiagInfo.getLocation(), |
| 1749 | PD: PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); |
| 1750 | |
| 1751 | Diags.setLastDiagnosticIgnored(true); |
| 1752 | |
| 1753 | // Now produce a C++98 compatibility warning. |
| 1754 | Diag(Loc, DiagID: diag::warn_cxx98_compat_sfinae_access_control); |
| 1755 | |
| 1756 | // The last diagnostic which Sema produced was ignored. Suppress any |
| 1757 | // notes attached to it. |
| 1758 | Diags.setLastDiagnosticIgnored(true); |
| 1759 | return; |
| 1760 | } |
| 1761 | |
| 1762 | case DiagnosticIDs::SFINAE_Suppress: |
| 1763 | if (DiagnosticsEngine::Level Level = getDiagnostics().getDiagnosticLevel( |
| 1764 | DiagID: DiagInfo.getID(), Loc: DiagInfo.getLocation()); |
| 1765 | Level == DiagnosticsEngine::Ignored) |
| 1766 | return; |
| 1767 | // Make a copy of this suppressed diagnostic and store it with the |
| 1768 | // template-deduction information; |
| 1769 | if (Info) { |
| 1770 | Info->addSuppressedDiagnostic( |
| 1771 | Loc: DiagInfo.getLocation(), |
| 1772 | PD: PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); |
| 1773 | if (!Diags.getDiagnosticIDs()->isNote(DiagID)) |
| 1774 | PrintContextStack(DiagFunc: [Info](SourceLocation Loc, PartialDiagnostic PD) { |
| 1775 | Info->addSuppressedDiagnostic(Loc, PD: std::move(PD)); |
| 1776 | }); |
| 1777 | } |
| 1778 | |
| 1779 | // Suppress this diagnostic. |
| 1780 | Diags.setLastDiagnosticIgnored(true); |
| 1781 | return; |
| 1782 | } |
| 1783 | } |
| 1784 | |
| 1785 | // Copy the diagnostic printing policy over the ASTContext printing policy. |
| 1786 | // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292 |
| 1787 | Context.setPrintingPolicy(getPrintingPolicy()); |
| 1788 | |
| 1789 | // Emit the diagnostic. |
| 1790 | if (!Diags.EmitDiagnostic(DB)) |
| 1791 | return; |
| 1792 | |
| 1793 | // If this is not a note, and we're in a template instantiation |
| 1794 | // that is different from the last template instantiation where |
| 1795 | // we emitted an error, print a template instantiation |
| 1796 | // backtrace. |
| 1797 | if (!Diags.getDiagnosticIDs()->isNote(DiagID)) |
| 1798 | PrintContextStack(); |
| 1799 | } |
| 1800 | |
| 1801 | bool Sema::hasUncompilableErrorOccurred() const { |
| 1802 | if (getDiagnostics().hasUncompilableErrorOccurred()) |
| 1803 | return true; |
| 1804 | auto *FD = dyn_cast<FunctionDecl>(Val: CurContext); |
| 1805 | if (!FD) |
| 1806 | return false; |
| 1807 | auto Loc = DeviceDeferredDiags.find(Val: FD); |
| 1808 | if (Loc == DeviceDeferredDiags.end()) |
| 1809 | return false; |
| 1810 | for (auto PDAt : Loc->second) { |
| 1811 | if (Diags.getDiagnosticIDs()->isDefaultMappingAsError( |
| 1812 | DiagID: PDAt.second.getDiagID())) |
| 1813 | return true; |
| 1814 | } |
| 1815 | return false; |
| 1816 | } |
| 1817 | |
| 1818 | // Print notes showing how we can reach FD starting from an a priori |
| 1819 | // known-callable function. When a function has multiple callers, emit |
| 1820 | // each call chain separately. The first note in each chain uses |
| 1821 | // "called by" and subsequent notes use "which is called by". |
| 1822 | static void emitCallStackNotes(Sema &S, const FunctionDecl *FD) { |
| 1823 | auto FnIt = S.CUDA().DeviceKnownEmittedFns.find(Val: FD); |
| 1824 | if (FnIt == S.CUDA().DeviceKnownEmittedFns.end()) |
| 1825 | return; |
| 1826 | |
| 1827 | for (const auto &CallerInfo : FnIt->second) { |
| 1828 | if (S.Diags.hasFatalErrorOccurred()) |
| 1829 | return; |
| 1830 | S.Diags.Report(Loc: CallerInfo.Loc, DiagID: diag::note_called_by) << CallerInfo.FD; |
| 1831 | // Walk up the rest of the chain using "which is called by". |
| 1832 | auto NextIt = S.CUDA().DeviceKnownEmittedFns.find(Val: CallerInfo.FD); |
| 1833 | while (NextIt != S.CUDA().DeviceKnownEmittedFns.end()) { |
| 1834 | if (S.Diags.hasFatalErrorOccurred()) |
| 1835 | return; |
| 1836 | const auto &Next = NextIt->second.front(); |
| 1837 | S.Diags.Report(Loc: Next.Loc, DiagID: diag::note_which_is_called_by) << Next.FD; |
| 1838 | NextIt = S.CUDA().DeviceKnownEmittedFns.find(Val: Next.FD); |
| 1839 | } |
| 1840 | } |
| 1841 | } |
| 1842 | |
| 1843 | namespace { |
| 1844 | |
| 1845 | /// Helper class that emits deferred diagnostic messages if an entity directly |
| 1846 | /// or indirectly using the function that causes the deferred diagnostic |
| 1847 | /// messages is known to be emitted. |
| 1848 | /// |
| 1849 | /// During parsing of AST, certain diagnostic messages are recorded as deferred |
| 1850 | /// diagnostics since it is unknown whether the functions containing such |
| 1851 | /// diagnostics will be emitted. A list of potentially emitted functions and |
| 1852 | /// variables that may potentially trigger emission of functions are also |
| 1853 | /// recorded. DeferredDiagnosticsEmitter recursively visits used functions |
| 1854 | /// by each function to emit deferred diagnostics. |
| 1855 | /// |
| 1856 | /// During the visit, certain OpenMP directives or initializer of variables |
| 1857 | /// with certain OpenMP attributes will cause subsequent visiting of any |
| 1858 | /// functions enter a state which is called OpenMP device context in this |
| 1859 | /// implementation. The state is exited when the directive or initializer is |
| 1860 | /// exited. This state can change the emission states of subsequent uses |
| 1861 | /// of functions. |
| 1862 | /// |
| 1863 | /// Conceptually the functions or variables to be visited form a use graph |
| 1864 | /// where the parent node uses the child node. At any point of the visit, |
| 1865 | /// the tree nodes traversed from the tree root to the current node form a use |
| 1866 | /// stack. The emission state of the current node depends on two factors: |
| 1867 | /// 1. the emission state of the root node |
| 1868 | /// 2. whether the current node is in OpenMP device context |
| 1869 | /// If the function is decided to be emitted, its contained deferred diagnostics |
| 1870 | /// are emitted, together with the information about the use stack. |
| 1871 | /// |
| 1872 | class DeferredDiagnosticsEmitter |
| 1873 | : public UsedDeclVisitor<DeferredDiagnosticsEmitter> { |
| 1874 | public: |
| 1875 | typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited; |
| 1876 | |
| 1877 | // Whether the function is already in the current use-path. |
| 1878 | llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> InUsePath; |
| 1879 | |
| 1880 | // The current use-path. |
| 1881 | llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath; |
| 1882 | |
| 1883 | // Whether the visiting of the function has been done. Done[0] is for the |
| 1884 | // case not in OpenMP device context. Done[1] is for the case in OpenMP |
| 1885 | // device context. We need two sets because diagnostics emission may be |
| 1886 | // different depending on whether it is in OpenMP device context. |
| 1887 | llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2]; |
| 1888 | |
| 1889 | // Functions that need their deferred diagnostics emitted. Collected |
| 1890 | // during the graph walk and emitted afterwards so that all callers |
| 1891 | // are known when producing call chain notes. |
| 1892 | llvm::SetVector<CanonicalDeclPtr<const FunctionDecl>> FnsToEmit; |
| 1893 | |
| 1894 | // Emission state of the root node of the current use graph. |
| 1895 | bool ShouldEmitRootNode; |
| 1896 | |
| 1897 | // Current OpenMP device context level. It is initialized to 0 and each |
| 1898 | // entering of device context increases it by 1 and each exit decreases |
| 1899 | // it by 1. Non-zero value indicates it is currently in device context. |
| 1900 | unsigned InOMPDeviceContext; |
| 1901 | |
| 1902 | DeferredDiagnosticsEmitter(Sema &S) |
| 1903 | : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {} |
| 1904 | |
| 1905 | bool shouldVisitDiscardedStmt() const { return false; } |
| 1906 | |
| 1907 | void VisitOMPTargetDirective(OMPTargetDirective *Node) { |
| 1908 | ++InOMPDeviceContext; |
| 1909 | Inherited::VisitOMPTargetDirective(S: Node); |
| 1910 | --InOMPDeviceContext; |
| 1911 | } |
| 1912 | |
| 1913 | void visitUsedDecl(SourceLocation Loc, Decl *D) { |
| 1914 | if (isa<VarDecl>(Val: D)) |
| 1915 | return; |
| 1916 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) |
| 1917 | checkFunc(Loc, FD); |
| 1918 | else |
| 1919 | Inherited::visitUsedDecl(Loc, D); |
| 1920 | } |
| 1921 | |
| 1922 | // Visitor member and parent dtors called by this dtor. |
| 1923 | void VisitCalledDestructors(CXXDestructorDecl *DD) { |
| 1924 | const CXXRecordDecl *RD = DD->getParent(); |
| 1925 | |
| 1926 | // Visit the dtors of all members |
| 1927 | for (const FieldDecl *FD : RD->fields()) { |
| 1928 | QualType FT = FD->getType(); |
| 1929 | if (const auto *ClassDecl = FT->getAsCXXRecordDecl(); |
| 1930 | ClassDecl && |
| 1931 | (ClassDecl->isBeingDefined() || ClassDecl->isCompleteDefinition())) |
| 1932 | if (CXXDestructorDecl *MemberDtor = ClassDecl->getDestructor()) |
| 1933 | asImpl().visitUsedDecl(Loc: MemberDtor->getLocation(), D: MemberDtor); |
| 1934 | } |
| 1935 | |
| 1936 | // Also visit base class dtors |
| 1937 | for (const auto &Base : RD->bases()) { |
| 1938 | QualType BaseType = Base.getType(); |
| 1939 | if (const auto *BaseDecl = BaseType->getAsCXXRecordDecl(); |
| 1940 | BaseDecl && |
| 1941 | (BaseDecl->isBeingDefined() || BaseDecl->isCompleteDefinition())) |
| 1942 | if (CXXDestructorDecl *BaseDtor = BaseDecl->getDestructor()) |
| 1943 | asImpl().visitUsedDecl(Loc: BaseDtor->getLocation(), D: BaseDtor); |
| 1944 | } |
| 1945 | } |
| 1946 | |
| 1947 | void VisitDeclStmt(DeclStmt *DS) { |
| 1948 | // Visit dtors called by variables that need destruction |
| 1949 | for (auto *D : DS->decls()) |
| 1950 | if (auto *VD = dyn_cast<VarDecl>(Val: D)) |
| 1951 | if (VD->isThisDeclarationADefinition() && |
| 1952 | VD->needsDestruction(Ctx: S.Context)) { |
| 1953 | QualType VT = VD->getType(); |
| 1954 | if (const auto *ClassDecl = VT->getAsCXXRecordDecl(); |
| 1955 | ClassDecl && (ClassDecl->isBeingDefined() || |
| 1956 | ClassDecl->isCompleteDefinition())) |
| 1957 | if (CXXDestructorDecl *Dtor = ClassDecl->getDestructor()) |
| 1958 | asImpl().visitUsedDecl(Loc: Dtor->getLocation(), D: Dtor); |
| 1959 | } |
| 1960 | |
| 1961 | Inherited::VisitDeclStmt(S: DS); |
| 1962 | } |
| 1963 | void checkVar(VarDecl *VD) { |
| 1964 | assert(VD->isFileVarDecl() && |
| 1965 | "Should only check file-scope variables" ); |
| 1966 | if (auto *Init = VD->getInit()) { |
| 1967 | auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD); |
| 1968 | bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || |
| 1969 | *DevTy == OMPDeclareTargetDeclAttr::DT_Any); |
| 1970 | if (IsDev) |
| 1971 | ++InOMPDeviceContext; |
| 1972 | this->Visit(S: Init); |
| 1973 | if (IsDev) |
| 1974 | --InOMPDeviceContext; |
| 1975 | } |
| 1976 | } |
| 1977 | |
| 1978 | void checkFunc(SourceLocation Loc, FunctionDecl *FD) { |
| 1979 | auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0]; |
| 1980 | FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back(); |
| 1981 | if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) || |
| 1982 | S.shouldIgnoreInHostDeviceCheck(Callee: FD) || InUsePath.count(Ptr: FD)) |
| 1983 | return; |
| 1984 | // Finalize analysis of OpenMP-specific constructs. |
| 1985 | if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 && |
| 1986 | (ShouldEmitRootNode || InOMPDeviceContext)) |
| 1987 | S.OpenMP().finalizeOpenMPDelayedAnalysis(Caller, Callee: FD, Loc); |
| 1988 | if (Caller) { |
| 1989 | auto &Callers = S.CUDA().DeviceKnownEmittedFns[FD]; |
| 1990 | CanonicalDeclPtr<const FunctionDecl> CanonCaller(Caller); |
| 1991 | if (llvm::none_of(Range&: Callers, P: [CanonCaller](const auto &C) { |
| 1992 | return C.FD == CanonCaller; |
| 1993 | })) |
| 1994 | Callers.push_back(Elt: {.FD: Caller, .Loc: Loc}); |
| 1995 | } |
| 1996 | if (ShouldEmitRootNode || InOMPDeviceContext) |
| 1997 | FnsToEmit.insert(X: FD); |
| 1998 | // Do not revisit a function if the function body has been completely |
| 1999 | // visited before. |
| 2000 | if (!Done.insert(Ptr: FD).second) |
| 2001 | return; |
| 2002 | InUsePath.insert(Ptr: FD); |
| 2003 | UsePath.push_back(Elt: FD); |
| 2004 | if (auto *S = FD->getBody()) { |
| 2005 | this->Visit(S); |
| 2006 | } |
| 2007 | if (CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(Val: FD)) |
| 2008 | asImpl().VisitCalledDestructors(DD: Dtor); |
| 2009 | UsePath.pop_back(); |
| 2010 | InUsePath.erase(Ptr: FD); |
| 2011 | } |
| 2012 | |
| 2013 | void checkRecordedDecl(Decl *D) { |
| 2014 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
| 2015 | ShouldEmitRootNode = S.getEmissionStatus(Decl: FD, /*Final=*/true) == |
| 2016 | Sema::FunctionEmissionStatus::Emitted; |
| 2017 | checkFunc(Loc: SourceLocation(), FD); |
| 2018 | } else |
| 2019 | checkVar(VD: cast<VarDecl>(Val: D)); |
| 2020 | } |
| 2021 | |
| 2022 | void emitDeferredDiags(const FunctionDecl *FD) { |
| 2023 | auto It = S.DeviceDeferredDiags.find(Val: FD); |
| 2024 | if (It == S.DeviceDeferredDiags.end()) |
| 2025 | return; |
| 2026 | bool HasWarningOrError = false; |
| 2027 | for (PartialDiagnosticAt &PDAt : It->second) { |
| 2028 | if (S.Diags.hasFatalErrorOccurred()) |
| 2029 | return; |
| 2030 | const SourceLocation &Loc = PDAt.first; |
| 2031 | const PartialDiagnostic &PD = PDAt.second; |
| 2032 | HasWarningOrError |= |
| 2033 | S.getDiagnostics().getDiagnosticLevel(DiagID: PD.getDiagID(), Loc) >= |
| 2034 | DiagnosticsEngine::Warning; |
| 2035 | { |
| 2036 | DiagnosticBuilder Builder(S.Diags.Report(Loc, DiagID: PD.getDiagID())); |
| 2037 | PD.Emit(DB: Builder); |
| 2038 | } |
| 2039 | } |
| 2040 | if (HasWarningOrError) |
| 2041 | emitCallStackNotes(S, FD); |
| 2042 | } |
| 2043 | |
| 2044 | void emitCollectedDiags() { |
| 2045 | for (const auto &FD : FnsToEmit) |
| 2046 | emitDeferredDiags(FD); |
| 2047 | } |
| 2048 | }; |
| 2049 | } // namespace |
| 2050 | |
| 2051 | void Sema::emitDeferredDiags() { |
| 2052 | if (ExternalSource) |
| 2053 | ExternalSource->ReadDeclsToCheckForDeferredDiags( |
| 2054 | Decls&: DeclsToCheckForDeferredDiags); |
| 2055 | |
| 2056 | if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) || |
| 2057 | DeclsToCheckForDeferredDiags.empty()) |
| 2058 | return; |
| 2059 | |
| 2060 | DeferredDiagnosticsEmitter DDE(*this); |
| 2061 | for (auto *D : DeclsToCheckForDeferredDiags) |
| 2062 | DDE.checkRecordedDecl(D); |
| 2063 | DDE.emitCollectedDiags(); |
| 2064 | } |
| 2065 | |
| 2066 | // In CUDA, there are some constructs which may appear in semantically-valid |
| 2067 | // code, but trigger errors if we ever generate code for the function in which |
| 2068 | // they appear. Essentially every construct you're not allowed to use on the |
| 2069 | // device falls into this category, because you are allowed to use these |
| 2070 | // constructs in a __host__ __device__ function, but only if that function is |
| 2071 | // never codegen'ed on the device. |
| 2072 | // |
| 2073 | // To handle semantic checking for these constructs, we keep track of the set of |
| 2074 | // functions we know will be emitted, either because we could tell a priori that |
| 2075 | // they would be emitted, or because they were transitively called by a |
| 2076 | // known-emitted function. |
| 2077 | // |
| 2078 | // We also keep a partial call graph of which not-known-emitted functions call |
| 2079 | // which other not-known-emitted functions. |
| 2080 | // |
| 2081 | // When we see something which is illegal if the current function is emitted |
| 2082 | // (usually by way of DiagIfDeviceCode, DiagIfHostCode, or |
| 2083 | // CheckCall), we first check if the current function is known-emitted. If |
| 2084 | // so, we immediately output the diagnostic. |
| 2085 | // |
| 2086 | // Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags |
| 2087 | // until we discover that the function is known-emitted, at which point we take |
| 2088 | // it out of this map and emit the diagnostic. |
| 2089 | |
| 2090 | Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K, SourceLocation Loc, |
| 2091 | unsigned DiagID, |
| 2092 | const FunctionDecl *Fn, |
| 2093 | Sema &S) |
| 2094 | : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn), |
| 2095 | ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) { |
| 2096 | switch (K) { |
| 2097 | case K_Nop: |
| 2098 | break; |
| 2099 | case K_Immediate: |
| 2100 | case K_ImmediateWithCallStack: |
| 2101 | ImmediateDiag.emplace( |
| 2102 | args: ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID)); |
| 2103 | break; |
| 2104 | case K_Deferred: |
| 2105 | assert(Fn && "Must have a function to attach the deferred diag to." ); |
| 2106 | auto &Diags = S.DeviceDeferredDiags[Fn]; |
| 2107 | PartialDiagId.emplace(args: Diags.size()); |
| 2108 | Diags.emplace_back(args&: Loc, args: S.PDiag(DiagID)); |
| 2109 | break; |
| 2110 | } |
| 2111 | } |
| 2112 | |
| 2113 | Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D) |
| 2114 | : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn), |
| 2115 | ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag), |
| 2116 | PartialDiagId(D.PartialDiagId) { |
| 2117 | // Clean the previous diagnostics. |
| 2118 | D.ShowCallStack = false; |
| 2119 | D.ImmediateDiag.reset(); |
| 2120 | D.PartialDiagId.reset(); |
| 2121 | } |
| 2122 | |
| 2123 | Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() { |
| 2124 | if (ImmediateDiag) { |
| 2125 | // Emit our diagnostic and, if it was a warning or error, output a callstack |
| 2126 | // if Fn isn't a priori known-emitted. |
| 2127 | ImmediateDiag.reset(); // Emit the immediate diag. |
| 2128 | |
| 2129 | if (ShowCallStack) { |
| 2130 | bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel( |
| 2131 | DiagID, Loc) >= DiagnosticsEngine::Warning; |
| 2132 | if (IsWarningOrError) |
| 2133 | emitCallStackNotes(S, FD: Fn); |
| 2134 | } |
| 2135 | } else { |
| 2136 | assert((!PartialDiagId || ShowCallStack) && |
| 2137 | "Must always show call stack for deferred diags." ); |
| 2138 | } |
| 2139 | } |
| 2140 | |
| 2141 | Sema::SemaDiagnosticBuilder |
| 2142 | Sema::targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD) { |
| 2143 | FD = FD ? FD : getCurFunctionDecl(); |
| 2144 | if (LangOpts.OpenMP) |
| 2145 | return LangOpts.OpenMPIsTargetDevice |
| 2146 | ? OpenMP().diagIfOpenMPDeviceCode(Loc, DiagID, FD) |
| 2147 | : OpenMP().diagIfOpenMPHostCode(Loc, DiagID, FD); |
| 2148 | if (getLangOpts().CUDA) |
| 2149 | return getLangOpts().CUDAIsDevice ? CUDA().DiagIfDeviceCode(Loc, DiagID) |
| 2150 | : CUDA().DiagIfHostCode(Loc, DiagID); |
| 2151 | |
| 2152 | if (getLangOpts().SYCLIsDevice) |
| 2153 | return SYCL().DiagIfDeviceCode(Loc, DiagID); |
| 2154 | |
| 2155 | return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc, DiagID, |
| 2156 | FD, *this); |
| 2157 | } |
| 2158 | |
| 2159 | void Sema::checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D) { |
| 2160 | if (isUnevaluatedContext() || Ty.isNull()) |
| 2161 | return; |
| 2162 | |
| 2163 | // The original idea behind checkTypeSupport function is that unused |
| 2164 | // declarations can be replaced with an array of bytes of the same size during |
| 2165 | // codegen, such replacement doesn't seem to be possible for types without |
| 2166 | // constant byte size like zero length arrays. So, do a deep check for SYCL. |
| 2167 | if (D && LangOpts.SYCLIsDevice) { |
| 2168 | llvm::DenseSet<QualType> Visited; |
| 2169 | SYCL().deepTypeCheckForDevice(UsedAt: Loc, Visited, DeclToCheck: D); |
| 2170 | } |
| 2171 | |
| 2172 | Decl *C = cast<Decl>(Val: getCurLexicalContext()); |
| 2173 | |
| 2174 | // Memcpy operations for structs containing a member with unsupported type |
| 2175 | // are ok, though. |
| 2176 | if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: C)) { |
| 2177 | if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) && |
| 2178 | MD->isTrivial()) |
| 2179 | return; |
| 2180 | |
| 2181 | if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: MD)) |
| 2182 | if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial()) |
| 2183 | return; |
| 2184 | } |
| 2185 | |
| 2186 | // Try to associate errors with the lexical context, if that is a function, or |
| 2187 | // the value declaration otherwise. |
| 2188 | const FunctionDecl *FD = isa<FunctionDecl>(Val: C) |
| 2189 | ? cast<FunctionDecl>(Val: C) |
| 2190 | : dyn_cast_or_null<FunctionDecl>(Val: D); |
| 2191 | |
| 2192 | auto CheckDeviceType = [&](QualType Ty) { |
| 2193 | if (Ty->isDependentType()) |
| 2194 | return; |
| 2195 | |
| 2196 | if (Ty->isBitIntType()) { |
| 2197 | if (!Context.getTargetInfo().hasBitIntType()) { |
| 2198 | PartialDiagnostic PD = PDiag(DiagID: diag::err_target_unsupported_type); |
| 2199 | if (D) |
| 2200 | PD << D; |
| 2201 | else |
| 2202 | PD << "expression" ; |
| 2203 | targetDiag(Loc, PD, FD) |
| 2204 | << false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/ |
| 2205 | << Ty << Context.getTargetInfo().getTriple().str(); |
| 2206 | } |
| 2207 | return; |
| 2208 | } |
| 2209 | |
| 2210 | // Check if we are dealing with two 'long double' but with different |
| 2211 | // semantics. |
| 2212 | bool LongDoubleMismatched = false; |
| 2213 | if (Ty->isRealFloatingType() && Context.getTypeSize(T: Ty) == 128) { |
| 2214 | const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(T: Ty); |
| 2215 | if ((&Sem != &llvm::APFloat::PPCDoubleDouble() && |
| 2216 | !Context.getTargetInfo().hasFloat128Type()) || |
| 2217 | (&Sem == &llvm::APFloat::PPCDoubleDouble() && |
| 2218 | !Context.getTargetInfo().hasIbm128Type())) |
| 2219 | LongDoubleMismatched = true; |
| 2220 | } |
| 2221 | |
| 2222 | if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) || |
| 2223 | (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) || |
| 2224 | (Ty->isIbm128Type() && !Context.getTargetInfo().hasIbm128Type()) || |
| 2225 | (Ty->isIntegerType() && Context.getTypeSize(T: Ty) == 128 && |
| 2226 | !Context.getTargetInfo().hasInt128Type()) || |
| 2227 | (Ty->isBFloat16Type() && !Context.getTargetInfo().hasBFloat16Type() && |
| 2228 | !LangOpts.CUDAIsDevice) || |
| 2229 | LongDoubleMismatched) { |
| 2230 | PartialDiagnostic PD = PDiag(DiagID: diag::err_target_unsupported_type); |
| 2231 | if (D) |
| 2232 | PD << D; |
| 2233 | else |
| 2234 | PD << "expression" ; |
| 2235 | |
| 2236 | if (targetDiag(Loc, PD, FD) |
| 2237 | << true /*show bit size*/ |
| 2238 | << static_cast<unsigned>(Context.getTypeSize(T: Ty)) << Ty |
| 2239 | << false /*return*/ << Context.getTargetInfo().getTriple().str()) { |
| 2240 | if (D) |
| 2241 | D->setInvalidDecl(); |
| 2242 | } |
| 2243 | if (D) |
| 2244 | targetDiag(Loc: D->getLocation(), DiagID: diag::note_defined_here, FD) << D; |
| 2245 | } |
| 2246 | }; |
| 2247 | |
| 2248 | auto CheckType = [&](QualType Ty, bool IsRetTy = false) { |
| 2249 | if (LangOpts.SYCLIsDevice || |
| 2250 | (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice) || |
| 2251 | LangOpts.CUDAIsDevice) |
| 2252 | CheckDeviceType(Ty); |
| 2253 | |
| 2254 | QualType UnqualTy = Ty.getCanonicalType().getUnqualifiedType(); |
| 2255 | const TargetInfo &TI = Context.getTargetInfo(); |
| 2256 | if (!TI.hasLongDoubleType() && UnqualTy == Context.LongDoubleTy) { |
| 2257 | PartialDiagnostic PD = PDiag(DiagID: diag::err_target_unsupported_type); |
| 2258 | if (D) |
| 2259 | PD << D; |
| 2260 | else |
| 2261 | PD << "expression" ; |
| 2262 | |
| 2263 | if (Diag(Loc, PD) << false /*show bit size*/ << 0 << Ty |
| 2264 | << false /*return*/ |
| 2265 | << TI.getTriple().str()) { |
| 2266 | if (D) |
| 2267 | D->setInvalidDecl(); |
| 2268 | } |
| 2269 | if (D) |
| 2270 | targetDiag(Loc: D->getLocation(), DiagID: diag::note_defined_here, FD) << D; |
| 2271 | } |
| 2272 | |
| 2273 | bool IsDouble = UnqualTy == Context.DoubleTy; |
| 2274 | bool IsFloat = UnqualTy == Context.FloatTy; |
| 2275 | if (IsRetTy && !TI.hasFPReturn() && (IsDouble || IsFloat)) { |
| 2276 | PartialDiagnostic PD = PDiag(DiagID: diag::err_target_unsupported_type); |
| 2277 | if (D) |
| 2278 | PD << D; |
| 2279 | else |
| 2280 | PD << "expression" ; |
| 2281 | |
| 2282 | if (Diag(Loc, PD) << false /*show bit size*/ << 0 << Ty << true /*return*/ |
| 2283 | << TI.getTriple().str()) { |
| 2284 | if (D) |
| 2285 | D->setInvalidDecl(); |
| 2286 | } |
| 2287 | if (D) |
| 2288 | targetDiag(Loc: D->getLocation(), DiagID: diag::note_defined_here, FD) << D; |
| 2289 | } |
| 2290 | |
| 2291 | if (TI.hasRISCVVTypes() && Ty->isRVVSizelessBuiltinType() && FD) { |
| 2292 | llvm::StringMap<bool> CallerFeatureMap; |
| 2293 | Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD); |
| 2294 | RISCV().checkRVVTypeSupport(Ty, Loc, D, FeatureMap: CallerFeatureMap); |
| 2295 | } |
| 2296 | |
| 2297 | // Don't allow SVE types in functions without a SVE target. |
| 2298 | if (Ty->isSVESizelessBuiltinType() && FD) { |
| 2299 | llvm::StringMap<bool> CallerFeatureMap; |
| 2300 | Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD); |
| 2301 | ARM().checkSVETypeSupport(Ty, Loc, FD, FeatureMap: CallerFeatureMap); |
| 2302 | } |
| 2303 | |
| 2304 | if (auto *VT = Ty->getAs<VectorType>(); |
| 2305 | VT && FD && |
| 2306 | (VT->getVectorKind() == VectorKind::SveFixedLengthData || |
| 2307 | VT->getVectorKind() == VectorKind::SveFixedLengthPredicate) && |
| 2308 | (LangOpts.VScaleMin != LangOpts.VScaleStreamingMin || |
| 2309 | LangOpts.VScaleMax != LangOpts.VScaleStreamingMax)) { |
| 2310 | if (IsArmStreamingFunction(FD, /*IncludeLocallyStreaming=*/true)) { |
| 2311 | Diag(Loc, DiagID: diag::err_sve_fixed_vector_in_streaming_function) |
| 2312 | << Ty << /*Streaming*/ 0; |
| 2313 | } else if (const auto *FTy = FD->getType()->getAs<FunctionProtoType>()) { |
| 2314 | if (FTy->getAArch64SMEAttributes() & |
| 2315 | FunctionType::SME_PStateSMCompatibleMask) { |
| 2316 | Diag(Loc, DiagID: diag::err_sve_fixed_vector_in_streaming_function) |
| 2317 | << Ty << /*StreamingCompatible*/ 1; |
| 2318 | } |
| 2319 | } |
| 2320 | } |
| 2321 | }; |
| 2322 | |
| 2323 | CheckType(Ty); |
| 2324 | if (const auto *FPTy = dyn_cast<FunctionProtoType>(Val&: Ty)) { |
| 2325 | for (const auto &ParamTy : FPTy->param_types()) |
| 2326 | CheckType(ParamTy); |
| 2327 | CheckType(FPTy->getReturnType(), /*IsRetTy=*/true); |
| 2328 | } |
| 2329 | if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Val&: Ty)) |
| 2330 | CheckType(FNPTy->getReturnType(), /*IsRetTy=*/true); |
| 2331 | } |
| 2332 | |
| 2333 | bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) { |
| 2334 | SourceLocation loc = locref; |
| 2335 | if (!loc.isMacroID()) return false; |
| 2336 | |
| 2337 | // There's no good way right now to look at the intermediate |
| 2338 | // expansions, so just jump to the expansion location. |
| 2339 | loc = getSourceManager().getExpansionLoc(Loc: loc); |
| 2340 | |
| 2341 | // If that's written with the name, stop here. |
| 2342 | SmallString<16> buffer; |
| 2343 | if (getPreprocessor().getSpelling(loc, buffer) == name) { |
| 2344 | locref = loc; |
| 2345 | return true; |
| 2346 | } |
| 2347 | return false; |
| 2348 | } |
| 2349 | |
| 2350 | Scope *Sema::getScopeForContext(DeclContext *Ctx) { |
| 2351 | |
| 2352 | if (!Ctx) |
| 2353 | return nullptr; |
| 2354 | |
| 2355 | Ctx = Ctx->getPrimaryContext(); |
| 2356 | for (Scope *S = getCurScope(); S; S = S->getParent()) { |
| 2357 | // Ignore scopes that cannot have declarations. This is important for |
| 2358 | // out-of-line definitions of static class members. |
| 2359 | if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) |
| 2360 | if (DeclContext *Entity = S->getEntity()) |
| 2361 | if (Ctx == Entity->getPrimaryContext()) |
| 2362 | return S; |
| 2363 | } |
| 2364 | |
| 2365 | return nullptr; |
| 2366 | } |
| 2367 | |
| 2368 | /// Enter a new function scope |
| 2369 | void Sema::PushFunctionScope() { |
| 2370 | if (FunctionScopes.empty() && CachedFunctionScope) { |
| 2371 | // Use CachedFunctionScope to avoid allocating memory when possible. |
| 2372 | CachedFunctionScope->Clear(); |
| 2373 | FunctionScopes.push_back(Elt: CachedFunctionScope.release()); |
| 2374 | } else { |
| 2375 | FunctionScopes.push_back(Elt: new FunctionScopeInfo(getDiagnostics())); |
| 2376 | } |
| 2377 | if (LangOpts.OpenMP) |
| 2378 | OpenMP().pushOpenMPFunctionRegion(); |
| 2379 | } |
| 2380 | |
| 2381 | void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) { |
| 2382 | FunctionScopes.push_back(Elt: new BlockScopeInfo(getDiagnostics(), |
| 2383 | BlockScope, Block)); |
| 2384 | CapturingFunctionScopes++; |
| 2385 | } |
| 2386 | |
| 2387 | LambdaScopeInfo *Sema::PushLambdaScope() { |
| 2388 | LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics()); |
| 2389 | FunctionScopes.push_back(Elt: LSI); |
| 2390 | CapturingFunctionScopes++; |
| 2391 | return LSI; |
| 2392 | } |
| 2393 | |
| 2394 | void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) { |
| 2395 | if (LambdaScopeInfo *const LSI = getCurLambda()) { |
| 2396 | LSI->AutoTemplateParameterDepth = Depth; |
| 2397 | return; |
| 2398 | } |
| 2399 | llvm_unreachable( |
| 2400 | "Remove assertion if intentionally called in a non-lambda context." ); |
| 2401 | } |
| 2402 | |
| 2403 | // Check that the type of the VarDecl has an accessible copy constructor and |
| 2404 | // resolve its destructor's exception specification. |
| 2405 | // This also performs initialization of block variables when they are moved |
| 2406 | // to the heap. It uses the same rules as applicable for implicit moves |
| 2407 | // according to the C++ standard in effect ([class.copy.elision]p3). |
| 2408 | static void checkEscapingByref(VarDecl *VD, Sema &S) { |
| 2409 | QualType T = VD->getType(); |
| 2410 | EnterExpressionEvaluationContext scope( |
| 2411 | S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
| 2412 | SourceLocation Loc = VD->getLocation(); |
| 2413 | Expr *VarRef = |
| 2414 | new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc); |
| 2415 | ExprResult Result; |
| 2416 | auto IE = InitializedEntity::InitializeBlock(BlockVarLoc: Loc, Type: T); |
| 2417 | if (S.getLangOpts().CPlusPlus23) { |
| 2418 | auto *E = ImplicitCastExpr::Create(Context: S.Context, T, Kind: CK_NoOp, Operand: VarRef, BasePath: nullptr, |
| 2419 | Cat: VK_XValue, FPO: FPOptionsOverride()); |
| 2420 | Result = S.PerformCopyInitialization(Entity: IE, EqualLoc: SourceLocation(), Init: E); |
| 2421 | } else { |
| 2422 | Result = S.PerformMoveOrCopyInitialization( |
| 2423 | Entity: IE, NRInfo: Sema::NamedReturnInfo{.Candidate: VD, .S: Sema::NamedReturnInfo::MoveEligible}, |
| 2424 | Value: VarRef); |
| 2425 | } |
| 2426 | |
| 2427 | if (!Result.isInvalid()) { |
| 2428 | Result = S.MaybeCreateExprWithCleanups(SubExpr: Result); |
| 2429 | Expr *Init = Result.getAs<Expr>(); |
| 2430 | S.Context.setBlockVarCopyInit(VD, CopyExpr: Init, CanThrow: S.canThrow(E: Init)); |
| 2431 | } |
| 2432 | |
| 2433 | // The destructor's exception specification is needed when IRGen generates |
| 2434 | // block copy/destroy functions. Resolve it here. |
| 2435 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) |
| 2436 | if (CXXDestructorDecl *DD = RD->getDestructor()) { |
| 2437 | auto *FPT = DD->getType()->castAs<FunctionProtoType>(); |
| 2438 | S.ResolveExceptionSpec(Loc, FPT); |
| 2439 | } |
| 2440 | } |
| 2441 | |
| 2442 | static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) { |
| 2443 | // Set the EscapingByref flag of __block variables captured by |
| 2444 | // escaping blocks. |
| 2445 | for (const BlockDecl *BD : FSI.Blocks) { |
| 2446 | for (const BlockDecl::Capture &BC : BD->captures()) { |
| 2447 | VarDecl *VD = BC.getVariable(); |
| 2448 | if (VD->hasAttr<BlocksAttr>()) { |
| 2449 | // Nothing to do if this is a __block variable captured by a |
| 2450 | // non-escaping block. |
| 2451 | if (BD->doesNotEscape()) |
| 2452 | continue; |
| 2453 | VD->setEscapingByref(); |
| 2454 | } |
| 2455 | // Check whether the captured variable is or contains an object of |
| 2456 | // non-trivial C union type. |
| 2457 | QualType CapType = BC.getVariable()->getType(); |
| 2458 | if (CapType.hasNonTrivialToPrimitiveDestructCUnion() || |
| 2459 | CapType.hasNonTrivialToPrimitiveCopyCUnion()) |
| 2460 | S.checkNonTrivialCUnion(QT: BC.getVariable()->getType(), |
| 2461 | Loc: BD->getCaretLocation(), |
| 2462 | UseContext: NonTrivialCUnionContext::BlockCapture, |
| 2463 | NonTrivialKind: Sema::NTCUK_Destruct | Sema::NTCUK_Copy); |
| 2464 | } |
| 2465 | } |
| 2466 | |
| 2467 | for (VarDecl *VD : FSI.ByrefBlockVars) { |
| 2468 | // __block variables might require us to capture a copy-initializer. |
| 2469 | if (!VD->isEscapingByref()) |
| 2470 | continue; |
| 2471 | // It's currently invalid to ever have a __block variable with an |
| 2472 | // array type; should we diagnose that here? |
| 2473 | // Regardless, we don't want to ignore array nesting when |
| 2474 | // constructing this copy. |
| 2475 | if (VD->getType()->isStructureOrClassType()) |
| 2476 | checkEscapingByref(VD, S); |
| 2477 | } |
| 2478 | } |
| 2479 | |
| 2480 | Sema::PoppedFunctionScopePtr |
| 2481 | Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP, Decl *D, |
| 2482 | QualType BlockType) { |
| 2483 | assert(!FunctionScopes.empty() && "mismatched push/pop!" ); |
| 2484 | |
| 2485 | markEscapingByrefs(FSI: *FunctionScopes.back(), S&: *this); |
| 2486 | |
| 2487 | PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(), |
| 2488 | PoppedFunctionScopeDeleter(this)); |
| 2489 | |
| 2490 | if (LangOpts.OpenMP) |
| 2491 | OpenMP().popOpenMPFunctionRegion(OldFSI: Scope.get()); |
| 2492 | |
| 2493 | // Issue any analysis-based warnings. |
| 2494 | if (WP && D) { |
| 2495 | inferNoReturnAttr(S&: *this, D); |
| 2496 | AnalysisWarnings.IssueWarnings(P: *WP, fscope: Scope.get(), D, BlockType); |
| 2497 | } else |
| 2498 | for (const auto &PUD : Scope->PossiblyUnreachableDiags) |
| 2499 | Diag(Loc: PUD.Loc, PD: PUD.PD); |
| 2500 | |
| 2501 | return Scope; |
| 2502 | } |
| 2503 | |
| 2504 | void Sema::PoppedFunctionScopeDeleter:: |
| 2505 | operator()(sema::FunctionScopeInfo *Scope) const { |
| 2506 | if (!Scope->isPlainFunction()) |
| 2507 | Self->CapturingFunctionScopes--; |
| 2508 | // Stash the function scope for later reuse if it's for a normal function. |
| 2509 | if (Scope->isPlainFunction() && !Self->CachedFunctionScope) |
| 2510 | Self->CachedFunctionScope.reset(p: Scope); |
| 2511 | else |
| 2512 | delete Scope; |
| 2513 | } |
| 2514 | |
| 2515 | void Sema::PushCompoundScope(bool IsStmtExpr) { |
| 2516 | getCurFunction()->CompoundScopes.push_back( |
| 2517 | Elt: CompoundScopeInfo(IsStmtExpr, getCurFPFeatures())); |
| 2518 | } |
| 2519 | |
| 2520 | void Sema::PopCompoundScope() { |
| 2521 | FunctionScopeInfo *CurFunction = getCurFunction(); |
| 2522 | assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop" ); |
| 2523 | |
| 2524 | CurFunction->CompoundScopes.pop_back(); |
| 2525 | } |
| 2526 | |
| 2527 | bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const { |
| 2528 | return getCurFunction()->hasUnrecoverableErrorOccurred(); |
| 2529 | } |
| 2530 | |
| 2531 | void Sema::setFunctionHasBranchIntoScope() { |
| 2532 | if (!FunctionScopes.empty()) |
| 2533 | FunctionScopes.back()->setHasBranchIntoScope(); |
| 2534 | } |
| 2535 | |
| 2536 | void Sema::setFunctionHasBranchProtectedScope() { |
| 2537 | if (!FunctionScopes.empty()) |
| 2538 | FunctionScopes.back()->setHasBranchProtectedScope(); |
| 2539 | } |
| 2540 | |
| 2541 | void Sema::setFunctionHasIndirectGoto() { |
| 2542 | if (!FunctionScopes.empty()) |
| 2543 | FunctionScopes.back()->setHasIndirectGoto(); |
| 2544 | } |
| 2545 | |
| 2546 | void Sema::setFunctionHasMustTail() { |
| 2547 | if (!FunctionScopes.empty()) |
| 2548 | FunctionScopes.back()->setHasMustTail(); |
| 2549 | } |
| 2550 | |
| 2551 | BlockScopeInfo *Sema::getCurBlock() { |
| 2552 | if (FunctionScopes.empty()) |
| 2553 | return nullptr; |
| 2554 | |
| 2555 | auto CurBSI = dyn_cast<BlockScopeInfo>(Val: FunctionScopes.back()); |
| 2556 | if (CurBSI && CurBSI->TheDecl && |
| 2557 | !CurBSI->TheDecl->Encloses(DC: CurContext)) { |
| 2558 | // We have switched contexts due to template instantiation. |
| 2559 | assert(!CodeSynthesisContexts.empty()); |
| 2560 | return nullptr; |
| 2561 | } |
| 2562 | |
| 2563 | return CurBSI; |
| 2564 | } |
| 2565 | |
| 2566 | FunctionScopeInfo *Sema::getEnclosingFunction() const { |
| 2567 | if (FunctionScopes.empty()) |
| 2568 | return nullptr; |
| 2569 | |
| 2570 | for (int e = FunctionScopes.size() - 1; e >= 0; --e) { |
| 2571 | if (isa<sema::BlockScopeInfo>(Val: FunctionScopes[e])) |
| 2572 | continue; |
| 2573 | return FunctionScopes[e]; |
| 2574 | } |
| 2575 | return nullptr; |
| 2576 | } |
| 2577 | |
| 2578 | CapturingScopeInfo *Sema::getEnclosingLambdaOrBlock() const { |
| 2579 | for (auto *Scope : llvm::reverse(C: FunctionScopes)) { |
| 2580 | if (auto *CSI = dyn_cast<CapturingScopeInfo>(Val: Scope)) { |
| 2581 | auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI); |
| 2582 | if (LSI && LSI->Lambda && !LSI->Lambda->Encloses(DC: CurContext) && |
| 2583 | LSI->AfterParameterList) { |
| 2584 | // We have switched contexts due to template instantiation. |
| 2585 | // FIXME: We should swap out the FunctionScopes during code synthesis |
| 2586 | // so that we don't need to check for this. |
| 2587 | assert(!CodeSynthesisContexts.empty()); |
| 2588 | return nullptr; |
| 2589 | } |
| 2590 | return CSI; |
| 2591 | } |
| 2592 | } |
| 2593 | return nullptr; |
| 2594 | } |
| 2595 | |
| 2596 | LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) { |
| 2597 | if (FunctionScopes.empty()) |
| 2598 | return nullptr; |
| 2599 | |
| 2600 | auto I = FunctionScopes.rbegin(); |
| 2601 | if (IgnoreNonLambdaCapturingScope) { |
| 2602 | auto E = FunctionScopes.rend(); |
| 2603 | while (I != E && isa<CapturingScopeInfo>(Val: *I) && !isa<LambdaScopeInfo>(Val: *I)) |
| 2604 | ++I; |
| 2605 | if (I == E) |
| 2606 | return nullptr; |
| 2607 | } |
| 2608 | auto *CurLSI = dyn_cast<LambdaScopeInfo>(Val: *I); |
| 2609 | if (CurLSI && CurLSI->Lambda && CurLSI->CallOperator && |
| 2610 | !CurLSI->Lambda->Encloses(DC: CurContext) && CurLSI->AfterParameterList) { |
| 2611 | // We have switched contexts due to template instantiation. |
| 2612 | assert(!CodeSynthesisContexts.empty()); |
| 2613 | return nullptr; |
| 2614 | } |
| 2615 | |
| 2616 | return CurLSI; |
| 2617 | } |
| 2618 | |
| 2619 | // We have a generic lambda if we parsed auto parameters, or we have |
| 2620 | // an associated template parameter list. |
| 2621 | LambdaScopeInfo *Sema::getCurGenericLambda() { |
| 2622 | if (LambdaScopeInfo *LSI = getCurLambda()) { |
| 2623 | return (LSI->TemplateParams.size() || |
| 2624 | LSI->GLTemplateParameterList) ? LSI : nullptr; |
| 2625 | } |
| 2626 | return nullptr; |
| 2627 | } |
| 2628 | |
| 2629 | |
| 2630 | void Sema::(SourceRange ) { |
| 2631 | if (!LangOpts.RetainCommentsFromSystemHeaders && |
| 2632 | SourceMgr.isInSystemHeader(Loc: Comment.getBegin())) |
| 2633 | return; |
| 2634 | RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false); |
| 2635 | if (RC.isAlmostTrailingComment() || RC.hasUnsupportedSplice(SourceMgr)) { |
| 2636 | SourceRange MagicMarkerRange(Comment.getBegin(), |
| 2637 | Comment.getBegin().getLocWithOffset(Offset: 3)); |
| 2638 | StringRef MagicMarkerText; |
| 2639 | switch (RC.getKind()) { |
| 2640 | case RawComment::RCK_OrdinaryBCPL: |
| 2641 | MagicMarkerText = "///<" ; |
| 2642 | break; |
| 2643 | case RawComment::RCK_OrdinaryC: |
| 2644 | MagicMarkerText = "/**<" ; |
| 2645 | break; |
| 2646 | case RawComment::RCK_Invalid: |
| 2647 | // FIXME: are there other scenarios that could produce an invalid |
| 2648 | // raw comment here? |
| 2649 | Diag(Loc: Comment.getBegin(), DiagID: diag::warn_splice_in_doxygen_comment); |
| 2650 | return; |
| 2651 | default: |
| 2652 | llvm_unreachable("if this is an almost Doxygen comment, " |
| 2653 | "it should be ordinary" ); |
| 2654 | } |
| 2655 | Diag(Loc: Comment.getBegin(), DiagID: diag::warn_not_a_doxygen_trailing_member_comment) << |
| 2656 | FixItHint::CreateReplacement(RemoveRange: MagicMarkerRange, Code: MagicMarkerText); |
| 2657 | } |
| 2658 | Context.addComment(RC); |
| 2659 | } |
| 2660 | |
| 2661 | // Pin this vtable to this file. |
| 2662 | ExternalSemaSource::~ExternalSemaSource() {} |
| 2663 | char ExternalSemaSource::ID; |
| 2664 | |
| 2665 | void ExternalSemaSource::ReadMethodPool(Selector Sel) { } |
| 2666 | void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { } |
| 2667 | |
| 2668 | void ExternalSemaSource::ReadKnownNamespaces( |
| 2669 | SmallVectorImpl<NamespaceDecl *> &Namespaces) { |
| 2670 | } |
| 2671 | |
| 2672 | void ExternalSemaSource::ReadUndefinedButUsed( |
| 2673 | llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {} |
| 2674 | |
| 2675 | void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector< |
| 2676 | FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {} |
| 2677 | |
| 2678 | bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, |
| 2679 | UnresolvedSetImpl &OverloadSet) { |
| 2680 | ZeroArgCallReturnTy = QualType(); |
| 2681 | OverloadSet.clear(); |
| 2682 | |
| 2683 | const OverloadExpr *Overloads = nullptr; |
| 2684 | bool IsMemExpr = false; |
| 2685 | if (E.getType() == Context.OverloadTy) { |
| 2686 | OverloadExpr::FindResult FR = OverloadExpr::find(E: &E); |
| 2687 | |
| 2688 | // Ignore overloads that are pointer-to-member constants. |
| 2689 | if (FR.HasFormOfMemberPointer) |
| 2690 | return false; |
| 2691 | |
| 2692 | Overloads = FR.Expression; |
| 2693 | } else if (E.getType() == Context.BoundMemberTy) { |
| 2694 | Overloads = dyn_cast<UnresolvedMemberExpr>(Val: E.IgnoreParens()); |
| 2695 | IsMemExpr = true; |
| 2696 | } |
| 2697 | |
| 2698 | bool Ambiguous = false; |
| 2699 | bool IsMV = false; |
| 2700 | |
| 2701 | if (Overloads) { |
| 2702 | for (OverloadExpr::decls_iterator it = Overloads->decls_begin(), |
| 2703 | DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) { |
| 2704 | OverloadSet.addDecl(D: *it); |
| 2705 | |
| 2706 | // Check whether the function is a non-template, non-member which takes no |
| 2707 | // arguments. |
| 2708 | if (IsMemExpr) |
| 2709 | continue; |
| 2710 | if (const FunctionDecl *OverloadDecl |
| 2711 | = dyn_cast<FunctionDecl>(Val: (*it)->getUnderlyingDecl())) { |
| 2712 | if (OverloadDecl->getMinRequiredArguments() == 0) { |
| 2713 | if (!ZeroArgCallReturnTy.isNull() && !Ambiguous && |
| 2714 | (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() || |
| 2715 | OverloadDecl->isCPUSpecificMultiVersion()))) { |
| 2716 | ZeroArgCallReturnTy = QualType(); |
| 2717 | Ambiguous = true; |
| 2718 | } else { |
| 2719 | ZeroArgCallReturnTy = OverloadDecl->getReturnType(); |
| 2720 | IsMV = OverloadDecl->isCPUDispatchMultiVersion() || |
| 2721 | OverloadDecl->isCPUSpecificMultiVersion(); |
| 2722 | } |
| 2723 | } |
| 2724 | } |
| 2725 | } |
| 2726 | |
| 2727 | // If it's not a member, use better machinery to try to resolve the call |
| 2728 | if (!IsMemExpr) |
| 2729 | return !ZeroArgCallReturnTy.isNull(); |
| 2730 | } |
| 2731 | |
| 2732 | // Attempt to call the member with no arguments - this will correctly handle |
| 2733 | // member templates with defaults/deduction of template arguments, overloads |
| 2734 | // with default arguments, etc. |
| 2735 | if (IsMemExpr && !E.isTypeDependent()) { |
| 2736 | Sema::TentativeAnalysisScope Trap(*this); |
| 2737 | ExprResult R = BuildCallToMemberFunction(S: nullptr, MemExpr: &E, LParenLoc: SourceLocation(), Args: {}, |
| 2738 | RParenLoc: SourceLocation()); |
| 2739 | if (R.isUsable()) { |
| 2740 | ZeroArgCallReturnTy = R.get()->getType(); |
| 2741 | return true; |
| 2742 | } |
| 2743 | return false; |
| 2744 | } |
| 2745 | |
| 2746 | if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E.IgnoreParens())) { |
| 2747 | if (const auto *Fun = dyn_cast<FunctionDecl>(Val: DeclRef->getDecl())) { |
| 2748 | if (Fun->getMinRequiredArguments() == 0) |
| 2749 | ZeroArgCallReturnTy = Fun->getReturnType(); |
| 2750 | return true; |
| 2751 | } |
| 2752 | } |
| 2753 | |
| 2754 | // We don't have an expression that's convenient to get a FunctionDecl from, |
| 2755 | // but we can at least check if the type is "function of 0 arguments". |
| 2756 | QualType ExprTy = E.getType(); |
| 2757 | const FunctionType *FunTy = nullptr; |
| 2758 | QualType PointeeTy = ExprTy->getPointeeType(); |
| 2759 | if (!PointeeTy.isNull()) |
| 2760 | FunTy = PointeeTy->getAs<FunctionType>(); |
| 2761 | if (!FunTy) |
| 2762 | FunTy = ExprTy->getAs<FunctionType>(); |
| 2763 | |
| 2764 | if (const auto *FPT = dyn_cast_if_present<FunctionProtoType>(Val: FunTy)) { |
| 2765 | if (FPT->getNumParams() == 0) |
| 2766 | ZeroArgCallReturnTy = FunTy->getReturnType(); |
| 2767 | return true; |
| 2768 | } |
| 2769 | return false; |
| 2770 | } |
| 2771 | |
| 2772 | /// Give notes for a set of overloads. |
| 2773 | /// |
| 2774 | /// A companion to tryExprAsCall. In cases when the name that the programmer |
| 2775 | /// wrote was an overloaded function, we may be able to make some guesses about |
| 2776 | /// plausible overloads based on their return types; such guesses can be handed |
| 2777 | /// off to this method to be emitted as notes. |
| 2778 | /// |
| 2779 | /// \param Overloads - The overloads to note. |
| 2780 | /// \param FinalNoteLoc - If we've suppressed printing some overloads due to |
| 2781 | /// -fshow-overloads=best, this is the location to attach to the note about too |
| 2782 | /// many candidates. Typically this will be the location of the original |
| 2783 | /// ill-formed expression. |
| 2784 | static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, |
| 2785 | const SourceLocation FinalNoteLoc) { |
| 2786 | unsigned ShownOverloads = 0; |
| 2787 | unsigned SuppressedOverloads = 0; |
| 2788 | for (UnresolvedSetImpl::iterator It = Overloads.begin(), |
| 2789 | DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { |
| 2790 | if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) { |
| 2791 | ++SuppressedOverloads; |
| 2792 | continue; |
| 2793 | } |
| 2794 | |
| 2795 | const NamedDecl *Fn = (*It)->getUnderlyingDecl(); |
| 2796 | // Don't print overloads for non-default multiversioned functions. |
| 2797 | if (const auto *FD = Fn->getAsFunction()) { |
| 2798 | if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() && |
| 2799 | !FD->getAttr<TargetAttr>()->isDefaultVersion()) |
| 2800 | continue; |
| 2801 | if (FD->isMultiVersion() && FD->hasAttr<TargetVersionAttr>() && |
| 2802 | !FD->getAttr<TargetVersionAttr>()->isDefaultVersion()) |
| 2803 | continue; |
| 2804 | } |
| 2805 | S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_possible_target_of_call); |
| 2806 | ++ShownOverloads; |
| 2807 | } |
| 2808 | |
| 2809 | S.Diags.overloadCandidatesShown(N: ShownOverloads); |
| 2810 | |
| 2811 | if (SuppressedOverloads) |
| 2812 | S.Diag(Loc: FinalNoteLoc, DiagID: diag::note_ovl_too_many_candidates) |
| 2813 | << SuppressedOverloads; |
| 2814 | } |
| 2815 | |
| 2816 | static void notePlausibleOverloads(Sema &S, SourceLocation Loc, |
| 2817 | const UnresolvedSetImpl &Overloads, |
| 2818 | bool (*IsPlausibleResult)(QualType)) { |
| 2819 | if (!IsPlausibleResult) |
| 2820 | return noteOverloads(S, Overloads, FinalNoteLoc: Loc); |
| 2821 | |
| 2822 | UnresolvedSet<2> PlausibleOverloads; |
| 2823 | for (OverloadExpr::decls_iterator It = Overloads.begin(), |
| 2824 | DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { |
| 2825 | const auto *OverloadDecl = cast<FunctionDecl>(Val: *It); |
| 2826 | QualType OverloadResultTy = OverloadDecl->getReturnType(); |
| 2827 | if (IsPlausibleResult(OverloadResultTy)) |
| 2828 | PlausibleOverloads.addDecl(D: It.getDecl()); |
| 2829 | } |
| 2830 | noteOverloads(S, Overloads: PlausibleOverloads, FinalNoteLoc: Loc); |
| 2831 | } |
| 2832 | |
| 2833 | /// Determine whether the given expression can be called by just |
| 2834 | /// putting parentheses after it. Notably, expressions with unary |
| 2835 | /// operators can't be because the unary operator will start parsing |
| 2836 | /// outside the call. |
| 2837 | static bool IsCallableWithAppend(const Expr *E) { |
| 2838 | E = E->IgnoreImplicit(); |
| 2839 | return (!isa<CStyleCastExpr>(Val: E) && |
| 2840 | !isa<UnaryOperator>(Val: E) && |
| 2841 | !isa<BinaryOperator>(Val: E) && |
| 2842 | !isa<CXXOperatorCallExpr>(Val: E)); |
| 2843 | } |
| 2844 | |
| 2845 | static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) { |
| 2846 | if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) |
| 2847 | E = UO->getSubExpr(); |
| 2848 | |
| 2849 | if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) { |
| 2850 | if (ULE->getNumDecls() == 0) |
| 2851 | return false; |
| 2852 | |
| 2853 | const NamedDecl *ND = *ULE->decls_begin(); |
| 2854 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND)) |
| 2855 | return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion(); |
| 2856 | } |
| 2857 | return false; |
| 2858 | } |
| 2859 | |
| 2860 | bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, |
| 2861 | bool ForceComplain, |
| 2862 | bool (*IsPlausibleResult)(QualType)) { |
| 2863 | SourceLocation Loc = E.get()->getExprLoc(); |
| 2864 | SourceRange Range = E.get()->getSourceRange(); |
| 2865 | UnresolvedSet<4> Overloads; |
| 2866 | |
| 2867 | // If this is a SFINAE context, don't try anything that might trigger ADL |
| 2868 | // prematurely. |
| 2869 | if (!isSFINAEContext()) { |
| 2870 | QualType ZeroArgCallTy; |
| 2871 | if (tryExprAsCall(E&: *E.get(), ZeroArgCallReturnTy&: ZeroArgCallTy, OverloadSet&: Overloads) && |
| 2872 | !ZeroArgCallTy.isNull() && |
| 2873 | (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) { |
| 2874 | // At this point, we know E is potentially callable with 0 |
| 2875 | // arguments and that it returns something of a reasonable type, |
| 2876 | // so we can emit a fixit and carry on pretending that E was |
| 2877 | // actually a CallExpr. |
| 2878 | SourceLocation ParenInsertionLoc = getLocForEndOfToken(Loc: Range.getEnd()); |
| 2879 | bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E: E.get()); |
| 2880 | Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range |
| 2881 | << (IsCallableWithAppend(E: E.get()) |
| 2882 | ? FixItHint::CreateInsertion(InsertionLoc: ParenInsertionLoc, |
| 2883 | Code: "()" ) |
| 2884 | : FixItHint()); |
| 2885 | if (!IsMV) |
| 2886 | notePlausibleOverloads(S&: *this, Loc, Overloads, IsPlausibleResult); |
| 2887 | |
| 2888 | // FIXME: Try this before emitting the fixit, and suppress diagnostics |
| 2889 | // while doing so. |
| 2890 | E = BuildCallExpr(S: nullptr, Fn: E.get(), LParenLoc: Range.getEnd(), ArgExprs: {}, |
| 2891 | RParenLoc: Range.getEnd().getLocWithOffset(Offset: 1)); |
| 2892 | return true; |
| 2893 | } |
| 2894 | } |
| 2895 | if (!ForceComplain) return false; |
| 2896 | |
| 2897 | bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E: E.get()); |
| 2898 | Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range; |
| 2899 | if (!IsMV) |
| 2900 | notePlausibleOverloads(S&: *this, Loc, Overloads, IsPlausibleResult); |
| 2901 | E = ExprError(); |
| 2902 | return true; |
| 2903 | } |
| 2904 | |
| 2905 | IdentifierInfo *Sema::getSuperIdentifier() const { |
| 2906 | if (!Ident_super) |
| 2907 | Ident_super = &Context.Idents.get(Name: "super" ); |
| 2908 | return Ident_super; |
| 2909 | } |
| 2910 | |
| 2911 | void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD, |
| 2912 | CapturedRegionKind K, |
| 2913 | unsigned OpenMPCaptureLevel) { |
| 2914 | auto *CSI = new CapturedRegionScopeInfo( |
| 2915 | getDiagnostics(), S, CD, RD, CD->getContextParam(), K, |
| 2916 | (getLangOpts().OpenMP && K == CR_OpenMP) |
| 2917 | ? OpenMP().getOpenMPNestingLevel() |
| 2918 | : 0, |
| 2919 | OpenMPCaptureLevel); |
| 2920 | CSI->ReturnType = Context.VoidTy; |
| 2921 | FunctionScopes.push_back(Elt: CSI); |
| 2922 | CapturingFunctionScopes++; |
| 2923 | } |
| 2924 | |
| 2925 | CapturedRegionScopeInfo *Sema::getCurCapturedRegion() { |
| 2926 | if (FunctionScopes.empty()) |
| 2927 | return nullptr; |
| 2928 | |
| 2929 | return dyn_cast<CapturedRegionScopeInfo>(Val: FunctionScopes.back()); |
| 2930 | } |
| 2931 | |
| 2932 | const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> & |
| 2933 | Sema::getMismatchingDeleteExpressions() const { |
| 2934 | return DeleteExprs; |
| 2935 | } |
| 2936 | |
| 2937 | Sema::FPFeaturesStateRAII::FPFeaturesStateRAII(Sema &S) |
| 2938 | : S(S), OldFPFeaturesState(S.CurFPFeatures), |
| 2939 | OldOverrides(S.FpPragmaStack.CurrentValue), |
| 2940 | OldEvalMethod(S.PP.getCurrentFPEvalMethod()), |
| 2941 | OldFPPragmaLocation(S.PP.getLastFPEvalPragmaLocation()) {} |
| 2942 | |
| 2943 | Sema::FPFeaturesStateRAII::~FPFeaturesStateRAII() { |
| 2944 | S.CurFPFeatures = OldFPFeaturesState; |
| 2945 | S.FpPragmaStack.CurrentValue = OldOverrides; |
| 2946 | S.PP.setCurrentFPEvalMethod(PragmaLoc: OldFPPragmaLocation, Val: OldEvalMethod); |
| 2947 | } |
| 2948 | |
| 2949 | bool Sema::isDeclaratorFunctionLike(Declarator &D) { |
| 2950 | assert(D.getCXXScopeSpec().isSet() && |
| 2951 | "can only be called for qualified names" ); |
| 2952 | |
| 2953 | auto LR = LookupResult(*this, D.getIdentifier(), D.getBeginLoc(), |
| 2954 | LookupOrdinaryName, forRedeclarationInCurContext()); |
| 2955 | DeclContext *DC = computeDeclContext(SS: D.getCXXScopeSpec(), |
| 2956 | EnteringContext: !D.getDeclSpec().isFriendSpecified()); |
| 2957 | if (!DC) |
| 2958 | return false; |
| 2959 | |
| 2960 | LookupQualifiedName(R&: LR, LookupCtx: DC); |
| 2961 | bool Result = llvm::all_of(Range&: LR, P: [](Decl *Dcl) { |
| 2962 | if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: Dcl)) { |
| 2963 | ND = ND->getUnderlyingDecl(); |
| 2964 | return isa<FunctionDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND) || |
| 2965 | isa<UsingDecl>(Val: ND); |
| 2966 | } |
| 2967 | return false; |
| 2968 | }); |
| 2969 | return Result; |
| 2970 | } |
| 2971 | |
| 2972 | Attr *Sema::CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot, |
| 2973 | MutableArrayRef<Expr *> Args) { |
| 2974 | |
| 2975 | auto *A = AnnotateAttr::Create(Ctx&: Context, Annotation: Annot, Args: Args.data(), ArgsSize: Args.size(), CommonInfo: CI); |
| 2976 | if (!ConstantFoldAttrArgs( |
| 2977 | CI, Args: MutableArrayRef<Expr *>(A->args_begin(), A->args_end()))) { |
| 2978 | return nullptr; |
| 2979 | } |
| 2980 | return A; |
| 2981 | } |
| 2982 | |
| 2983 | Attr *Sema::CreateAnnotationAttr(const ParsedAttr &AL) { |
| 2984 | // Make sure that there is a string literal as the annotation's first |
| 2985 | // argument. |
| 2986 | StringRef Str; |
| 2987 | if (!checkStringLiteralArgumentAttr(Attr: AL, ArgNum: 0, Str)) |
| 2988 | return nullptr; |
| 2989 | |
| 2990 | llvm::SmallVector<Expr *, 4> Args; |
| 2991 | Args.reserve(N: AL.getNumArgs() - 1); |
| 2992 | for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) { |
| 2993 | assert(!AL.isArgIdent(Idx)); |
| 2994 | Args.push_back(Elt: AL.getArgAsExpr(Arg: Idx)); |
| 2995 | } |
| 2996 | |
| 2997 | return CreateAnnotationAttr(CI: AL, Annot: Str, Args); |
| 2998 | } |
| 2999 | |