clang 23.0.0git
Sema.cpp
Go to the documentation of this file.
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"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
24#include "clang/AST/StmtCXX.h"
41#include "clang/Sema/Scope.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"
51#include "clang/Sema/SemaHLSL.h"
54#include "clang/Sema/SemaM68k.h"
55#include "clang/Sema/SemaMIPS.h"
58#include "clang/Sema/SemaObjC.h"
62#include "clang/Sema/SemaPPC.h"
66#include "clang/Sema/SemaSYCL.h"
69#include "clang/Sema/SemaWasm.h"
70#include "clang/Sema/SemaX86.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
81using namespace clang;
82using namespace sema;
83
87
90 bool IncludeComments,
91 std::optional<tok::TokenKind> ExpectedToken) {
92 if (!Loc.isValid())
93 return SourceRange();
94 std::optional<Token> NextToken =
95 Lexer::findNextToken(Loc, 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
110ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
111
114 StringRef Platform) {
116 if (!SDKInfo && !WarnedDarwinSDKInfoMissing) {
117 Diag(Loc, diag::warn_missing_sdksettings_for_availability_checking)
118 << Platform;
119 WarnedDarwinSDKInfoMissing = true;
120 }
121 return SDKInfo;
122}
123
125 if (CachedDarwinSDKInfo)
126 return CachedDarwinSDKInfo->get();
127 auto SDKInfo = parseDarwinSDKInfo(
128 PP.getFileManager().getVirtualFileSystem(),
129 PP.getHeaderSearchInfo().getHeaderSearchOpts().Sysroot);
130 if (SDKInfo && *SDKInfo) {
131 CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(std::move(**SDKInfo));
132 return CachedDarwinSDKInfo->get();
133 }
134 if (!SDKInfo)
135 llvm::consumeError(SDKInfo.takeError());
136 CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>();
137 return nullptr;
138}
139
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(OS.str());
151}
152
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(Context.getBoolName())) {
161 Policy.Bool = BoolMacro->isObjectLike() &&
162 BoolMacro->getNumTokens() == 1 &&
163 BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
164 }
165 }
166
167 // Shorten the data output if needed
168 Policy.EntireContentsOfLargeArray = false;
169
170 return Policy;
171}
172
174 TUScope = S;
175 PushDeclContext(S, Context.getTranslationUnitDecl());
176}
177
178namespace clang {
179namespace sema {
180
182 Sema *S = nullptr;
185
186public:
187 void set(Sema &S) { this->S = &S; }
188
189 void reset() { S = nullptr; }
190
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(SM.getFileID(Loc));
200 if (IncludeLoc.isValid()) {
201 if (llvm::timeTraceProfilerEnabled()) {
202 OptionalFileEntryRef FE = SM.getFileEntryRefForID(SM.getFileID(Loc));
203 ProfilerStack.push_back(llvm::timeTraceAsyncProfilerBegin(
204 "Source", FE ? FE->getName() : StringRef("<unknown>")));
205 }
206
207 IncludeStack.push_back(IncludeLoc);
208 S->DiagnoseNonDefaultPragmaAlignPack(
210 IncludeLoc);
211 }
212 break;
213 }
214 case ExitFile:
215 if (!IncludeStack.empty()) {
216 if (llvm::timeTraceProfilerEnabled())
217 llvm::timeTraceProfilerEnd(ProfilerStack.pop_back_val());
218
219 S->DiagnoseNonDefaultPragmaAlignPack(
221 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.
235 diag::Flavor Flavor =
237 StringRef Group = Str.substr(2);
238
239 if (S->PP.getDiagnostics().getDiagnosticIDs()->getDiagnosticsInGroup(
240 Flavor, Group, 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().
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
270const unsigned Sema::MaxAlignmentExponent;
272
277 Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
281 ExternalSource(nullptr), StackHandler(Diags), CurScope(nullptr),
282 Ident_super(nullptr), AMDGPUPtr(std::make_unique<SemaAMDGPU>(*this)),
283 ARMPtr(std::make_unique<SemaARM>(*this)),
284 AVRPtr(std::make_unique<SemaAVR>(*this)),
285 BPFPtr(std::make_unique<SemaBPF>(*this)),
286 CodeCompletionPtr(
287 std::make_unique<SemaCodeCompletion>(*this, CodeCompleter)),
288 CUDAPtr(std::make_unique<SemaCUDA>(*this)),
289 DirectXPtr(std::make_unique<SemaDirectX>(*this)),
290 HLSLPtr(std::make_unique<SemaHLSL>(*this)),
291 HexagonPtr(std::make_unique<SemaHexagon>(*this)),
292 LoongArchPtr(std::make_unique<SemaLoongArch>(*this)),
293 M68kPtr(std::make_unique<SemaM68k>(*this)),
294 MIPSPtr(std::make_unique<SemaMIPS>(*this)),
295 MSP430Ptr(std::make_unique<SemaMSP430>(*this)),
296 NVPTXPtr(std::make_unique<SemaNVPTX>(*this)),
297 ObjCPtr(std::make_unique<SemaObjC>(*this)),
298 OpenACCPtr(std::make_unique<SemaOpenACC>(*this)),
299 OpenCLPtr(std::make_unique<SemaOpenCL>(*this)),
300 OpenMPPtr(std::make_unique<SemaOpenMP>(*this)),
301 PPCPtr(std::make_unique<SemaPPC>(*this)),
302 PseudoObjectPtr(std::make_unique<SemaPseudoObject>(*this)),
303 RISCVPtr(std::make_unique<SemaRISCV>(*this)),
304 SPIRVPtr(std::make_unique<SemaSPIRV>(*this)),
305 SYCLPtr(std::make_unique<SemaSYCL>(*this)),
306 SwiftPtr(std::make_unique<SemaSwift>(*this)),
307 SystemZPtr(std::make_unique<SemaSystemZ>(*this)),
308 WasmPtr(std::make_unique<SemaWasm>(*this)),
309 X86Ptr(std::make_unique<SemaX86>(*this)),
311 LangOpts.getMSPointerToMemberRepresentationMethod()),
312 MSStructPragmaOn(false), VtorDispStack(LangOpts.getVtorDispMode()),
321 FullyCheckedComparisonCategories(
322 static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
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(new NSAPI(Context));
337
340
341 // Tell diagnostics how to render things from the AST library.
342 Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &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(
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(std::move(Callbacks));
358 SemaPPCallbackHandler->set(*this);
359
360 CurFPFeatures.setFPEvalMethod(PP.getCurrentFPEvalMethod());
361}
362
363// Anchor Sema's type info to this TU.
364void Sema::anchor() {}
365
366void Sema::addImplicitTypedef(StringRef Name, QualType T) {
367 DeclarationName DN = &Context.Idents.get(Name);
368 if (IdResolver.begin(DN) == IdResolver.end())
369 PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
370}
371
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>(&Consumer))
381 SC->InitializeSema(*this);
382
383 // Tell the external Sema source about this Sema object.
384 if (ExternalSemaSource *ExternalSema
385 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
386 ExternalSema->InitializeSema(*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("__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("__int128_t");
402 if (IdResolver.begin(Int128) == IdResolver.end())
403 PushOnScopeChains(Context.getInt128Decl(), TUScope);
404
405 DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
406 if (IdResolver.begin(UInt128) == IdResolver.end())
407 PushOnScopeChains(Context.getUInt128Decl(), 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("SEL");
416 if (IdResolver.begin(SEL) == IdResolver.end())
417 PushOnScopeChains(Context.getObjCSelDecl(), 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("id");
422 if (IdResolver.begin(Id) == IdResolver.end())
423 PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
424
425 // Create the built-in typedef for 'Class'.
426 DeclarationName Class = &Context.Idents.get("Class");
427 if (IdResolver.begin(Class) == IdResolver.end())
428 PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
429
430 // Create the built-in forward declaratino for 'Protocol'.
431 DeclarationName Protocol = &Context.Idents.get("Protocol");
432 if (IdResolver.begin(Protocol) == IdResolver.end())
433 PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
434 }
435
436 // Create the internal type for the *StringMakeConstantString builtins.
437 DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
438 if (IdResolver.begin(ConstantString) == IdResolver.end())
439 PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
440
441 // Initialize Microsoft "predefined C++ types".
442 if (getLangOpts().MSVCCompat) {
443 if (getLangOpts().CPlusPlus &&
444 IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
445 PushOnScopeChains(Context.getMSTypeInfoTagDecl(), TUScope);
446
447 addImplicitTypedef("size_t", Context.getSizeType());
448 }
449
450 // Initialize predefined OpenCL types and supported extensions and (optional)
451 // core features.
452 if (getLangOpts().OpenCL) {
454 Context.getTargetInfo().getSupportedOpenCLOpts(), getLangOpts());
455 addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
456 addImplicitTypedef("event_t", Context.OCLEventTy);
457 auto OCLCompatibleVersion = getLangOpts().getOpenCLCompatibleVersion();
458 if (OCLCompatibleVersion >= 200) {
459 if (getLangOpts().OpenCLCPlusPlus || getLangOpts().Blocks) {
460 addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
461 addImplicitTypedef("queue_t", Context.OCLQueueTy);
462 }
463 if (getLangOpts().OpenCLPipes)
464 addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
465 addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
466 addImplicitTypedef("atomic_uint",
467 Context.getAtomicType(Context.UnsignedIntTy));
468 addImplicitTypedef("atomic_float",
469 Context.getAtomicType(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("atomic_flag", Context.getAtomicType(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(Context.getSizeType());
489 auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
490 auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
491 auto AtomicPtrDiffT =
492 Context.getAtomicType(Context.getPointerDiffType());
493 addImplicitTypedef("atomic_size_t", AtomicSizeT);
494 addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
495 addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
496 addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
497 };
498
499 if (Context.getTypeSize(Context.getSizeType()) == 32) {
500 AddPointerSizeDependentTypes();
501 }
502
503 if (getOpenCLOptions().isSupported("cl_khr_fp16", getLangOpts())) {
504 auto AtomicHalfT = Context.getAtomicType(Context.HalfTy);
505 addImplicitTypedef("atomic_half", AtomicHalfT);
506 }
507
508 std::vector<QualType> Atomic64BitTypes;
509 if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics",
510 getLangOpts()) &&
511 getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics",
512 getLangOpts())) {
513 if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) {
514 auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
515 addImplicitTypedef("atomic_double", AtomicDoubleT);
516 Atomic64BitTypes.push_back(AtomicDoubleT);
517 }
518 auto AtomicLongT = Context.getAtomicType(Context.LongTy);
519 auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
520 addImplicitTypedef("atomic_long", AtomicLongT);
521 addImplicitTypedef("atomic_ulong", AtomicULongT);
522
523
524 if (Context.getTypeSize(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("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("__builtin_ms_va_list");
580 if (IdResolver.begin(MSVaList) == IdResolver.end())
581 PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
582 }
583
584 DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
585 if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
586 PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
587}
588
590 assert(InstantiatingSpecializations.empty() &&
591 "failed to clean up an InstantiatingTemplate?");
592
594
595 // Kill all the active scopes.
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>(&Consumer))
601 SC->ForgetSema();
602
603 // Detach from the external Sema source.
604 if (ExternalSemaSource *ExternalSema
605 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
606 ExternalSema->ForgetSema();
607
608 // Delete cached satisfactions.
609 std::vector<ConstraintSatisfaction *> Satisfactions;
610 Satisfactions.reserve(SatisfactionCache.size());
611 for (auto &Node : SatisfactionCache)
612 Satisfactions.push_back(&Node);
613 for (auto *Node : Satisfactions)
614 delete Node;
615
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
627 llvm::function_ref<void()> Fn) {
628 StackHandler.runWithSufficientStackSpace(Loc, Fn);
629}
630
632 UnavailableAttr::ImplicitReason reason) {
633 // If we're not in a function, it's an error.
634 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
635 if (!fn) return false;
636
637 // If we're in template instantiation, it's an error.
639 return false;
640
641 // If that function's not in a system header, it's an error.
642 if (!Context.getSourceManager().isInSystemHeader(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(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
649 return true;
650}
651
655
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>(ExternalSource.get()))
665 Ex->AddSource(std::move(E));
666 else
667 ExternalSource = llvm::makeIntrusiveRefCnt<MultiplexExternalSemaSource>(
668 ExternalSource, std::move(E));
669}
670
671void 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
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, diag::warn_nullability_lost) << SrcType << DstType;
694}
695
696// Generate diagnostics when adding or removing effects in a type conversion.
698 SourceLocation Loc) {
699 const auto SrcFX = FunctionEffectsRef::get(SrcType);
700 const auto DstFX = FunctionEffectsRef::get(DstType);
701 if (SrcFX != DstFX) {
702 for (const auto &Diff : FunctionEffectDiffVector(SrcFX, DstFX)) {
703 if (Diff.shouldDiagnoseConversion(SrcType, SrcFX, DstType, DstFX))
704 Diag(Loc, diag::warn_invalid_add_func_effects) << Diff.effectName();
705 }
706 }
707}
708
710 // nullptr only exists from C++11 on, so don't warn on its absence earlier.
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>(EStripped))
721 return;
722
723 if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
724 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 ==
732 return;
733
734 // Ignore null pointers in defaulted comparison operators.
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(MaybeMacroLoc) &&
747 !findMacroSpelling(MaybeMacroLoc, "NULL"))
748 return;
749
750 Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
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.
759 const CXXCastPath *BasePath,
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
787 if (Context.hasAnyFunctionEffects() && !isCast(CCK) &&
788 Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
790
791 QualType ExprTy = Context.getCanonicalType(E->getType());
792 QualType TypeTy = Context.getCanonicalType(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>(E))
800 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
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.
812 E->getType(), E, !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>(E)) {
827 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
828 if (VD->getStorageClass() == SC_Register) {
829 Diag(E->getExprLoc(), 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>(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>(E) || isa<CXXStaticCastExpr>(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(SourceOBT->getBehaviorKind(), Ty);
856 }
857 }
858 }
859
860 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
862}
863
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.
881static 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>(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, 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(DeclToCheck))
900 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(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(DeclToCheck);
907 }
908
909 if (const VarDecl *VD = dyn_cast<VarDecl>(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(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, 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(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(DeclToCheck);
937 }
938
939 return false;
940}
941
942static bool isFunctionOrVarDeclExternC(const NamedDecl *ND) {
943 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
944 return FD->isExternC();
945 return cast<VarDecl>(ND)->isExternC();
946}
947
948/// Determine whether ND is an external-linkage function or variable whose
949/// type has no linkage.
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() &&
957}
958
959/// Obtains a sorted list of functions and variables that are undefined but
960/// ODR-used.
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
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>(ND)) {
983 if (FD->isDefined())
984 continue;
985 if (FD->isExternallyVisible() &&
987 !FD->getMostRecentDecl()->isInlined() &&
988 !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
989 continue;
990 if (FD->getBuiltinID())
991 continue;
992 } else {
993 const auto *VD = cast<VarDecl>(ND);
994 if (VD->hasDefinition() != VarDecl::DeclarationOnly)
995 continue;
996 if (VD->isExternallyVisible() &&
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(std::make_pair(ND, UndefinedUse.second));
1009 }
1010}
1011
1012/// checkUndefinedButUsed - Check for undefined objects with internal linkage
1013/// or that are inline.
1015 if (S.UndefinedButUsed.empty()) return;
1016
1017 // Collect all the still-undefined entities with internal linkage.
1020 S.UndefinedButUsed.clear();
1021 if (Undefined.empty()) return;
1022
1023 for (const auto &Undef : Undefined) {
1024 ValueDecl *VD = cast<ValueDecl>(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.
1038 ? diag::ext_undefined_internal_type
1039 : diag::err_undefined_internal_type)
1040 << isa<VarDecl>(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>(VD)) {
1047 auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>();
1048 if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive(
1049 llvm::omp::TraitProperty::
1050 implementation_extension_disable_implicit_base)) {
1051 const auto *Func = cast<FunctionDecl>(
1052 cast<DeclRefExpr>(DVAttr->getVariantFuncRef())->getDecl());
1053 IsImplicitBase = BaseD->isImplicit() &&
1054 Func->getIdentifier()->isMangledOpenMPVariantName();
1055 }
1056 }
1057 if (!S.getLangOpts().OpenMP || !IsImplicitBase)
1058 S.Diag(VD->getLocation(), diag::warn_undefined_internal)
1059 << isa<VarDecl>(VD) << VD;
1060 } else if (auto *FD = dyn_cast<FunctionDecl>(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(VD->getLocation(), 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(VD->getLocation(), diag::err_undefined_inline_var) << VD;
1070 }
1071 if (UseLoc.isValid())
1072 S.Diag(UseLoc, diag::note_used_here);
1073 }
1074}
1075
1077 if (!ExternalSource)
1078 return;
1079
1081 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
1082 for (auto &WeakID : WeakIDs)
1083 (void)WeakUndeclaredIdentifiers[WeakID.first].insert(WeakID.second);
1084}
1085
1086
1087typedef 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.
1095 RecordCompleteMap &MNCComplete) {
1096 RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
1097 if (Cache != MNCComplete.end())
1098 return Cache->second;
1099 if (!RD->isCompleteDefinition())
1100 return false;
1101 bool Complete = true;
1103 E = RD->decls_end();
1104 I != E && Complete; ++I) {
1105 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
1106 Complete = M->isDefined() || M->isDefaulted() ||
1107 (M->isPureVirtual() && !isa<CXXDestructorDecl>(M));
1108 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*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>(*I)) {
1116 if (R->isInjectedClassName())
1117 continue;
1118 if (R->hasDefinition())
1119 Complete = MethodsAndNestedClassesComplete(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.
1137 RecordCompleteMap &RecordsComplete,
1138 RecordCompleteMap &MNCComplete) {
1139 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
1140 if (Cache != RecordsComplete.end())
1141 return Cache->second;
1142 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
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(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>((*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
1168 if (ExternalSource)
1169 ExternalSource->ReadUnusedLocalTypedefNameCandidates(
1172 if (TD->isReferenced())
1173 continue;
1174 Diag(TD->getLocation(), diag::warn_unused_local_typedef)
1175 << isa<TypeAliasDecl>(TD) << TD->getDeclName();
1176 }
1178}
1179
1181 if (getLangOpts().CPlusPlusModules &&
1182 getLangOpts().getCompilingModule() == LangOptions::CMK_HeaderUnit)
1183 HandleStartOfHeaderUnit();
1184}
1185
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");
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.
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.
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.
1226 ExternalSource->ReadPendingInstantiations(Pending);
1227 for (auto PII : Pending)
1228 if (auto Func = dyn_cast<FunctionDecl>(PII.first))
1229 Func->setInstantiationIsPending(true);
1231 Pending.begin(), Pending.end());
1232 }
1233
1234 {
1235 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1237 }
1238
1240
1241 assert(LateParsedInstantiations.empty() &&
1242 "end of TU template instantiation should not create more "
1243 "late-parsed templates");
1244}
1245
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) {
1259
1261 !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1265
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.
1277
1278 if (LangOpts.PCHInstantiateTemplates) {
1279 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1281 }
1282 }
1283
1288
1289 // All delayed member exception specs should be checked or we end up accepting
1290 // incompatible declarations.
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.
1300 std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
1302 [this](const DeclaratorDecl *DD) {
1303 return ShouldRemoveFromUnused(this, DD);
1304 }),
1305 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
1316 for (const auto &WeakIDs : WeakUndeclaredIdentifiers) {
1317 if (WeakIDs.second.empty())
1318 continue;
1319
1320 Decl *PrevDecl = LookupSingleName(TUScope, WeakIDs.first, SourceLocation(),
1322 if (PrevDecl != nullptr &&
1323 !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
1324 for (const auto &WI : WeakIDs.second)
1325 Diag(WI.getLocation(), diag::warn_attribute_wrong_decl_type)
1326 << "'weak'" << /*isRegularKeyword=*/0 << ExpectedVariableOrFunction;
1327 else
1328 for (const auto &WI : WeakIDs.second)
1329 Diag(WI.getLocation(), diag::warn_weak_identifier_undeclared)
1330 << WeakIDs.first;
1331 }
1332
1333 if (LangOpts.CPlusPlus11 &&
1334 !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
1336
1337 if (!Diags.hasErrorOccurred()) {
1338 if (ExternalSource)
1339 ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
1340 checkUndefinedButUsed(*this);
1341 }
1342
1343 // A global-module-fragment is only permitted within a module unit.
1344 if (!ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1346 Diag(ModuleScopes.back().BeginLoc,
1347 diag::err_module_declaration_missing_after_global_module_introducer);
1348 } else if (getLangOpts().getCompilingModule() ==
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(getSourceManager().getLocForStartOfFile(
1358 getSourceManager().getMainFileID()),
1359 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)
1373 return true;
1374
1375 return false;
1376 };
1377
1378 CurrentModule->NamedModuleHasInit =
1379 DoesModNeedInit(CurrentModule) ||
1380 llvm::any_of(CurrentModule->submodules(), 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
1390 Stack.push_back(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(SubmodulesRange.begin(), 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.
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>(D)) {
1419 bool DefInPMF = false;
1420 if (auto *FDD = FD->getDefinition()) {
1421 DefInPMF = FDD->getOwningModule()->isPrivateModule();
1422 if (!DefInPMF)
1423 continue;
1424 }
1425 Diag(FD->getLocation(), 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(ModuleScopes.back().BeginLoc,
1431 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.
1450 for (TentativeDefinitionsType::iterator
1451 T = TentativeDefinitions.begin(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(VD).second)
1460 continue;
1461
1462 if (const IncompleteArrayType *ArrayT
1463 = Context.getAsIncompleteArrayType(VD->getType())) {
1464 // Set the length of the array to 1 (C99 6.9.2p5).
1465 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
1466 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
1467 QualType T = Context.getConstantArrayType(
1468 ArrayT->getElementType(), One, nullptr, ArraySizeModifier::Normal, 0);
1469 VD->setType(T);
1470 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
1471 diag::err_tentative_def_incomplete_type))
1472 VD->setInvalidDecl();
1473
1474 // No initialization is performed for a tentative definition.
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 ||
1485 DiagID = diag::warn_default_init_const;
1486
1487 bool EmitCppCompat = !Diags.isIgnored(
1488 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
1489 VD->getLocation());
1490
1491 Diag(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(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())
1504 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(Exported.NameLoc, diag::warn_failed_to_resolve_pragma) << "export";
1517 }
1518
1519 if (LangOpts.HLSL)
1520 HLSL().ActOnEndOfTranslationUnit(getASTContext().getTranslationUnitDecl());
1521 if (LangOpts.OpenACC)
1523 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(ExternalSource.get()),
1533 E = UnusedFileScopedDecls.end();
1534 I != E; ++I) {
1535 if (ShouldRemoveFromUnused(this, *I))
1536 continue;
1537
1538 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1539 const FunctionDecl *DiagD;
1540 if (!FD->hasBody(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 =
1547 DiagRange.setEnd(ASTTAL->RAngleLoc);
1548 if (DiagD->isReferenced()) {
1549 if (isa<CXXMethodDecl>(DiagD))
1550 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
1551 << DiagD << DiagRange;
1552 else {
1553 if (FD->getStorageClass() == SC_Static &&
1554 !FD->isInlineSpecified() &&
1555 !SourceMgr.isInMainFile(
1556 SourceMgr.getExpansionLoc(FD->getLocation())))
1557 Diag(DiagD->getLocation(),
1558 diag::warn_unneeded_static_internal_decl)
1559 << DiagD << DiagRange;
1560 else
1561 Diag(DiagD->getLocation(), 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(DiagD->getLocation(), diag::warn_unused_template)
1568 << /*function=*/0 << DiagD << DiagRange;
1569 else
1570 Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD)
1571 ? diag::warn_unused_member_function
1572 : diag::warn_unused_function)
1573 << DiagD << DiagRange;
1574 }
1575 } else {
1576 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
1577 if (!DiagD)
1578 DiagD = cast<VarDecl>(*I);
1579 SourceRange DiagRange = DiagD->getLocation();
1580 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(DiagD)) {
1581 if (const ASTTemplateArgumentListInfo *ASTTAL =
1582 VTSD->getTemplateArgsAsWritten())
1583 DiagRange.setEnd(ASTTAL->RAngleLoc);
1584 }
1585 if (DiagD->isReferenced()) {
1586 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1587 << /*variable=*/1 << DiagD << DiagRange;
1588 } else if (DiagD->getDescribedVarTemplate()) {
1589 Diag(DiagD->getLocation(), 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(DiagD->getLocation()) ||
1594 !PP.getLangOpts().IsHeaderFile)
1595 Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
1596 << DiagD << DiagRange;
1597 } else {
1598 Diag(DiagD->getLocation(), diag::warn_unused_variable)
1599 << DiagD << DiagRange;
1600 }
1601 }
1602 }
1603
1605 }
1606
1607 if (!Diags.isIgnored(diag::warn_unused_private_field, 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>(D->getDeclContext());
1614 if (RD && !RD->isUnion() &&
1615 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
1616 Diag(D->getLocation(), diag::warn_unused_private_field)
1617 << D->getDeclName();
1618 }
1619 }
1620 }
1621
1622 if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
1623 if (ExternalSource)
1624 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
1625 for (const auto &DeletedFieldInfo : DeleteExprs) {
1626 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
1627 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
1628 DeleteExprLoc.second);
1629 }
1630 }
1631 }
1632
1633 AnalysisWarnings.IssueWarnings(Context.getTranslationUnitDecl());
1634
1635 if (Context.hasAnyFunctionEffects())
1636 performFunctionEffectAnalysis(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(Context.getTranslationUnitDecl());
1648}
1649
1650
1651//===----------------------------------------------------------------------===//
1652// Helper functions.
1653//===----------------------------------------------------------------------===//
1654
1656 DeclContext *DC = CurContext;
1657
1658 while (true) {
1659 if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC) ||
1661 DC = DC->getParent();
1662 } else if (!AllowLambda && isa<CXXMethodDecl>(DC) &&
1663 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
1664 cast<CXXRecordDecl>(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.
1675FunctionDecl *Sema::getCurFunctionDecl(bool AllowLambda) const {
1676 DeclContext *DC = getFunctionLevelDeclContext(AllowLambda);
1677 return dyn_cast<FunctionDecl>(DC);
1678}
1679
1682 while (isa<RecordDecl>(DC))
1683 DC = DC->getParent();
1684 return dyn_cast<ObjCMethodDecl>(DC);
1685}
1686
1690 return cast<NamedDecl>(DC);
1691 return nullptr;
1692}
1693
1699
1700void 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();
1713 // We'll report the diagnostic below.
1714 break;
1715
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 DiagInfo.getLocation(),
1726 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1727
1728 Diags.setLastDiagnosticIgnored(true);
1729 return;
1730
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 DiagInfo.getLocation(),
1749 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1750
1751 Diags.setLastDiagnosticIgnored(true);
1752
1753 // Now produce a C++98 compatibility warning.
1754 Diag(Loc, 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
1763 if (DiagnosticsEngine::Level Level = getDiagnostics().getDiagnosticLevel(
1764 DiagInfo.getID(), DiagInfo.getLocation());
1766 return;
1767 // Make a copy of this suppressed diagnostic and store it with the
1768 // template-deduction information;
1769 if (Info) {
1771 DiagInfo.getLocation(),
1772 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1773 if (!Diags.getDiagnosticIDs()->isNote(DiagID))
1775 Info->addSuppressedDiagnostic(Loc, 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))
1799}
1800
1803 return true;
1804 auto *FD = dyn_cast<FunctionDecl>(CurContext);
1805 if (!FD)
1806 return false;
1807 auto Loc = DeviceDeferredDiags.find(FD);
1808 if (Loc == DeviceDeferredDiags.end())
1809 return false;
1810 for (auto PDAt : Loc->second) {
1811 if (Diags.getDiagnosticIDs()->isDefaultMappingAsError(
1812 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".
1822static void emitCallStackNotes(Sema &S, const FunctionDecl *FD) {
1823 auto FnIt = S.CUDA().DeviceKnownEmittedFns.find(FD);
1824 if (FnIt == S.CUDA().DeviceKnownEmittedFns.end())
1825 return;
1826
1827 for (const auto &CallerInfo : FnIt->second) {
1829 return;
1830 S.Diags.Report(CallerInfo.Loc, 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(CallerInfo.FD);
1833 while (NextIt != S.CUDA().DeviceKnownEmittedFns.end()) {
1835 return;
1836 const auto &Next = NextIt->second.front();
1837 S.Diags.Report(Next.Loc, diag::note_which_is_called_by) << Next.FD;
1838 NextIt = S.CUDA().DeviceKnownEmittedFns.find(Next.FD);
1839 }
1840 }
1841}
1842
1843namespace {
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///
1872class DeferredDiagnosticsEmitter
1873 : public UsedDeclVisitor<DeferredDiagnosticsEmitter> {
1874public:
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(Node);
1910 --InOMPDeviceContext;
1911 }
1912
1913 void visitUsedDecl(SourceLocation Loc, Decl *D) {
1914 if (isa<VarDecl>(D))
1915 return;
1916 if (auto *FD = dyn_cast<FunctionDecl>(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(MemberDtor->getLocation(), 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(BaseDtor->getLocation(), 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>(D))
1951 if (VD->isThisDeclarationADefinition() &&
1952 VD->needsDestruction(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(Dtor->getLocation(), Dtor);
1959 }
1960
1961 Inherited::VisitDeclStmt(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(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(FD) || InUsePath.count(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, FD, Loc);
1988 if (Caller) {
1989 auto &Callers = S.CUDA().DeviceKnownEmittedFns[FD];
1990 CanonicalDeclPtr<const FunctionDecl> CanonCaller(Caller);
1991 if (llvm::none_of(Callers, [CanonCaller](const auto &C) {
1992 return C.FD == CanonCaller;
1993 }))
1994 Callers.push_back({Caller, Loc});
1995 }
1996 if (ShouldEmitRootNode || InOMPDeviceContext)
1997 FnsToEmit.insert(FD);
1998 // Do not revisit a function if the function body has been completely
1999 // visited before.
2000 if (!Done.insert(FD).second)
2001 return;
2002 InUsePath.insert(FD);
2003 UsePath.push_back(FD);
2004 if (auto *S = FD->getBody()) {
2005 this->Visit(S);
2006 }
2007 if (CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(FD))
2008 asImpl().VisitCalledDestructors(Dtor);
2009 UsePath.pop_back();
2010 InUsePath.erase(FD);
2011 }
2012
2013 void checkRecordedDecl(Decl *D) {
2014 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2015 ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) ==
2016 Sema::FunctionEmissionStatus::Emitted;
2017 checkFunc(SourceLocation(), FD);
2018 } else
2019 checkVar(cast<VarDecl>(D));
2020 }
2021
2022 void emitDeferredDiags(const FunctionDecl *FD) {
2023 auto It = S.DeviceDeferredDiags.find(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(PD.getDiagID(), Loc) >=
2035 {
2036 DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
2037 PD.Emit(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
2052 if (ExternalSource)
2053 ExternalSource->ReadDeclsToCheckForDeferredDiags(
2055
2056 if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) ||
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
2090Sema::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 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(Diags.size());
2108 Diags.emplace_back(Loc, S.PDiag(DiagID));
2109 break;
2110 }
2111}
2112
2113Sema::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
2123Sema::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, Fn);
2134 }
2135 } else {
2136 assert((!PartialDiagId || ShowCallStack) &&
2137 "Must always show call stack for deferred diags.");
2138 }
2139}
2140
2141Sema::SemaDiagnosticBuilder
2142Sema::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
2156 FD, *this);
2157}
2158
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(Loc, Visited, D);
2170 }
2171
2173
2174 // Memcpy operations for structs containing a member with unsupported type
2175 // are ok, though.
2176 if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) {
2177 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
2178 MD->isTrivial())
2179 return;
2180
2181 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(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>(C)
2190 : dyn_cast_or_null<FunctionDecl>(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(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(Ty) == 128) {
2214 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(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(Ty) == 128 &&
2226 !Context.getTargetInfo().hasInt128Type()) ||
2227 (Ty->isBFloat16Type() && !Context.getTargetInfo().hasBFloat16Type() &&
2228 !LangOpts.CUDAIsDevice) ||
2229 LongDoubleMismatched) {
2230 PartialDiagnostic PD = PDiag(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(Ty)) << Ty
2239 << false /*return*/ << Context.getTargetInfo().getTriple().str()) {
2240 if (D)
2241 D->setInvalidDecl();
2242 }
2243 if (D)
2244 targetDiag(D->getLocation(), 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
2255 const TargetInfo &TI = Context.getTargetInfo();
2256 if (!TI.hasLongDoubleType() && UnqualTy == Context.LongDoubleTy) {
2257 PartialDiagnostic PD = PDiag(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(D->getLocation(), 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(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(D->getLocation(), diag::note_defined_here, FD) << D;
2289 }
2290
2291 if (TI.hasRISCVVTypes() && Ty->isRVVSizelessBuiltinType() && FD) {
2292 llvm::StringMap<bool> CallerFeatureMap;
2293 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
2294 RISCV().checkRVVTypeSupport(Ty, Loc, D, 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(CallerFeatureMap, FD);
2301 ARM().checkSVETypeSupport(Ty, Loc, FD, 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, 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() &
2316 Diag(Loc, 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>(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>(Ty))
2330 CheckType(FNPTy->getReturnType(), /*IsRetTy=*/true);
2331}
2332
2333bool 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);
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
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
2370 if (FunctionScopes.empty() && CachedFunctionScope) {
2371 // Use CachedFunctionScope to avoid allocating memory when possible.
2372 CachedFunctionScope->Clear();
2373 FunctionScopes.push_back(CachedFunctionScope.release());
2374 } else {
2376 }
2377 if (LangOpts.OpenMP)
2378 OpenMP().pushOpenMPFunctionRegion();
2379}
2380
2383 BlockScope, Block));
2385}
2386
2389 FunctionScopes.push_back(LSI);
2391 return LSI;
2392}
2393
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).
2408static void checkEscapingByref(VarDecl *VD, Sema &S) {
2409 QualType T = VD->getType();
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(Loc, T);
2417 if (S.getLangOpts().CPlusPlus23) {
2418 auto *E = ImplicitCastExpr::Create(S.Context, T, CK_NoOp, VarRef, nullptr,
2420 Result = S.PerformCopyInitialization(IE, SourceLocation(), E);
2421 } else {
2424 VarRef);
2425 }
2426
2427 if (!Result.isInvalid()) {
2428 Result = S.MaybeCreateExprWithCleanups(Result);
2429 Expr *Init = Result.getAs<Expr>();
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
2442static 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();
2460 S.checkNonTrivialCUnion(BC.getVariable()->getType(),
2461 BD->getCaretLocation(),
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
2482 QualType BlockType) {
2483 assert(!FunctionScopes.empty() && "mismatched push/pop!");
2484
2485 markEscapingByrefs(*FunctionScopes.back(), *this);
2486
2489
2490 if (LangOpts.OpenMP)
2491 OpenMP().popOpenMPFunctionRegion(Scope.get());
2492
2493 // Issue any analysis-based warnings.
2494 if (WP && D) {
2495 inferNoReturnAttr(*this, D);
2496 AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
2497 } else
2498 for (const auto &PUD : Scope->PossiblyUnreachableDiags)
2499 Diag(PUD.Loc, PUD.PD);
2500
2501 return Scope;
2502}
2503
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(Scope);
2511 else
2512 delete Scope;
2513}
2514
2515void Sema::PushCompoundScope(bool IsStmtExpr) {
2516 getCurFunction()->CompoundScopes.push_back(
2517 CompoundScopeInfo(IsStmtExpr, getCurFPFeatures()));
2518}
2519
2521 FunctionScopeInfo *CurFunction = getCurFunction();
2522 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
2523
2524 CurFunction->CompoundScopes.pop_back();
2525}
2526
2528 return getCurFunction()->hasUnrecoverableErrorOccurred();
2529}
2530
2532 if (!FunctionScopes.empty())
2533 FunctionScopes.back()->setHasBranchIntoScope();
2534}
2535
2537 if (!FunctionScopes.empty())
2538 FunctionScopes.back()->setHasBranchProtectedScope();
2539}
2540
2542 if (!FunctionScopes.empty())
2543 FunctionScopes.back()->setHasIndirectGoto();
2544}
2545
2547 if (!FunctionScopes.empty())
2548 FunctionScopes.back()->setHasMustTail();
2549}
2550
2552 if (FunctionScopes.empty())
2553 return nullptr;
2554
2555 auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
2556 if (CurBSI && CurBSI->TheDecl &&
2557 !CurBSI->TheDecl->Encloses(CurContext)) {
2558 // We have switched contexts due to template instantiation.
2559 assert(!CodeSynthesisContexts.empty());
2560 return nullptr;
2561 }
2562
2563 return CurBSI;
2564}
2565
2567 if (FunctionScopes.empty())
2568 return nullptr;
2569
2570 for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
2572 continue;
2573 return FunctionScopes[e];
2574 }
2575 return nullptr;
2576}
2577
2579 for (auto *Scope : llvm::reverse(FunctionScopes)) {
2580 if (auto *CSI = dyn_cast<CapturingScopeInfo>(Scope)) {
2581 auto *LSI = dyn_cast<LambdaScopeInfo>(CSI);
2582 if (LSI && LSI->Lambda && !LSI->Lambda->Encloses(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
2596LambdaScopeInfo *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>(*I) && !isa<LambdaScopeInfo>(*I))
2604 ++I;
2605 if (I == E)
2606 return nullptr;
2607 }
2608 auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
2609 if (CurLSI && CurLSI->Lambda && CurLSI->CallOperator &&
2610 !CurLSI->Lambda->Encloses(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.
2622 if (LambdaScopeInfo *LSI = getCurLambda()) {
2623 return (LSI->TemplateParams.size() ||
2624 LSI->GLTemplateParameterList) ? LSI : nullptr;
2625 }
2626 return nullptr;
2627}
2628
2629
2631 if (!LangOpts.RetainCommentsFromSystemHeaders &&
2632 SourceMgr.isInSystemHeader(Comment.getBegin()))
2633 return;
2634 RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
2636 SourceRange MagicMarkerRange(Comment.getBegin(),
2637 Comment.getBegin().getLocWithOffset(3));
2638 StringRef MagicMarkerText;
2639 switch (RC.getKind()) {
2641 MagicMarkerText = "///<";
2642 break;
2644 MagicMarkerText = "/**<";
2645 break;
2647 // FIXME: are there other scenarios that could produce an invalid
2648 // raw comment here?
2649 Diag(Comment.getBegin(), 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(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
2656 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
2657 }
2658 Context.addComment(RC);
2659}
2660
2661// Pin this vtable to this file.
2663char ExternalSemaSource::ID;
2664
2667
2671
2673 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
2674
2676 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
2677
2678bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
2680 ZeroArgCallReturnTy = QualType();
2681 OverloadSet.clear();
2682
2683 const OverloadExpr *Overloads = nullptr;
2684 bool IsMemExpr = false;
2685 if (E.getType() == Context.OverloadTy) {
2687
2688 // Ignore overloads that are pointer-to-member constants.
2690 return false;
2691
2692 Overloads = FR.Expression;
2693 } else if (E.getType() == Context.BoundMemberTy) {
2694 Overloads = dyn_cast<UnresolvedMemberExpr>(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(*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>((*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);
2738 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>(E.IgnoreParens())) {
2747 if (const auto *Fun = dyn_cast<FunctionDecl>(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>(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.
2784static 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(Fn->getLocation(), diag::note_possible_target_of_call);
2806 ++ShownOverloads;
2807 }
2808
2809 S.Diags.overloadCandidatesShown(ShownOverloads);
2810
2811 if (SuppressedOverloads)
2812 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
2813 << SuppressedOverloads;
2814}
2815
2817 const UnresolvedSetImpl &Overloads,
2818 bool (*IsPlausibleResult)(QualType)) {
2819 if (!IsPlausibleResult)
2820 return noteOverloads(S, Overloads, 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>(*It);
2826 QualType OverloadResultTy = OverloadDecl->getReturnType();
2827 if (IsPlausibleResult(OverloadResultTy))
2828 PlausibleOverloads.addDecl(It.getDecl());
2829 }
2830 noteOverloads(S, PlausibleOverloads, 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.
2837static bool IsCallableWithAppend(const Expr *E) {
2838 E = E->IgnoreImplicit();
2839 return (!isa<CStyleCastExpr>(E) &&
2840 !isa<UnaryOperator>(E) &&
2841 !isa<BinaryOperator>(E) &&
2843}
2844
2846 if (const auto *UO = dyn_cast<UnaryOperator>(E))
2847 E = UO->getSubExpr();
2848
2849 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(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>(ND))
2856 }
2857 return false;
2858}
2859
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.get(), ZeroArgCallTy, 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(Range.getEnd());
2880 Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
2881 << (IsCallableWithAppend(E.get())
2882 ? FixItHint::CreateInsertion(ParenInsertionLoc,
2883 "()")
2884 : FixItHint());
2885 if (!IsMV)
2886 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2887
2888 // FIXME: Try this before emitting the fixit, and suppress diagnostics
2889 // while doing so.
2890 E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), {},
2891 Range.getEnd().getLocWithOffset(1));
2892 return true;
2893 }
2894 }
2895 if (!ForceComplain) return false;
2896
2898 Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
2899 if (!IsMV)
2900 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2901 E = ExprError();
2902 return true;
2903}
2904
2906 if (!Ident_super)
2907 Ident_super = &Context.Idents.get("super");
2908 return Ident_super;
2909}
2910
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(CSI);
2923}
2924
2926 if (FunctionScopes.empty())
2927 return nullptr;
2928
2929 return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
2930}
2931
2932const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
2936
2938 : S(S), OldFPFeaturesState(S.CurFPFeatures),
2939 OldOverrides(S.FpPragmaStack.CurrentValue),
2940 OldEvalMethod(S.PP.getCurrentFPEvalMethod()),
2941 OldFPPragmaLocation(S.PP.getLastFPEvalPragmaLocation()) {}
2942
2944 S.CurFPFeatures = OldFPFeaturesState;
2945 S.FpPragmaStack.CurrentValue = OldOverrides;
2946 S.PP.setCurrentFPEvalMethod(OldFPPragmaLocation, OldEvalMethod);
2947}
2948
2950 assert(D.getCXXScopeSpec().isSet() &&
2951 "can only be called for qualified names");
2952
2953 auto LR = LookupResult(*this, D.getIdentifier(), D.getBeginLoc(),
2957 if (!DC)
2958 return false;
2959
2960 LookupQualifiedName(LR, DC);
2961 bool Result = llvm::all_of(LR, [](Decl *Dcl) {
2962 if (NamedDecl *ND = dyn_cast<NamedDecl>(Dcl)) {
2963 ND = ND->getUnderlyingDecl();
2964 return isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
2965 isa<UsingDecl>(ND);
2966 }
2967 return false;
2968 });
2969 return Result;
2970}
2971
2974
2975 auto *A = AnnotateAttr::Create(Context, Annot, Args.data(), Args.size(), CI);
2977 CI, MutableArrayRef<Expr *>(A->args_begin(), A->args_end()))) {
2978 return nullptr;
2979 }
2980 return A;
2981}
2982
2984 // Make sure that there is a string literal as the annotation's first
2985 // argument.
2986 StringRef Str;
2987 if (!checkStringLiteralArgumentAttr(AL, 0, Str))
2988 return nullptr;
2989
2991 Args.reserve(AL.getNumArgs() - 1);
2992 for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) {
2993 assert(!AL.isArgIdent(Idx));
2994 Args.push_back(AL.getArgAsExpr(Idx));
2995 }
2996
2997 return CreateAnnotationAttr(AL, Str, Args);
2998}
Defines the clang::ASTContext interface.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Next
The next token in the unwrapped line.
#define SM(sm)
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis functions specific to AVR.
This file declares semantic analysis functions specific to BPF.
This file declares semantic analysis for CUDA constructs.
This file declares facilities that support code completion.
This file declares semantic analysis for DirectX constructs.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis functions specific to LoongArch.
This file declares semantic analysis functions specific to M68k.
This file declares semantic analysis functions specific to MIPS.
This file declares semantic analysis functions specific to MSP430.
This file declares semantic analysis functions specific to NVPTX.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenACC constructs and clauses.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis for expressions involving.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SPIRV constructs.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to Swift.
This file declares semantic analysis functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
static void checkEscapingByref(VarDecl *VD, Sema &S)
Definition Sema.cpp:2408
static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E)
Definition Sema.cpp:2845
llvm::DenseMap< const CXXRecordDecl *, bool > RecordCompleteMap
Definition Sema.cpp:1087
static bool IsCallableWithAppend(const Expr *E)
Determine whether the given expression can be called by just putting parentheses after it.
Definition Sema.cpp:2837
static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD, RecordCompleteMap &MNCComplete)
Returns true, if all methods and nested classes of the given CXXRecordDecl are defined in this transl...
Definition Sema.cpp:1094
static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, const SourceLocation FinalNoteLoc)
Give notes for a set of overloads.
Definition Sema.cpp:2784
static bool isFunctionOrVarDeclExternC(const NamedDecl *ND)
Definition Sema.cpp:942
static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S)
Definition Sema.cpp:2442
static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D)
Used to prune the decls of Sema's UnusedFileScopedDecls vector.
Definition Sema.cpp:881
static void emitCallStackNotes(Sema &S, const FunctionDecl *FD)
Definition Sema.cpp:1822
static void notePlausibleOverloads(Sema &S, SourceLocation Loc, const UnresolvedSetImpl &Overloads, bool(*IsPlausibleResult)(QualType))
Definition Sema.cpp:2816
static void checkUndefinedButUsed(Sema &S)
checkUndefinedButUsed - Check for undefined objects with internal linkage or that are inline.
Definition Sema.cpp:1014
static bool IsRecordFullyDefined(const CXXRecordDecl *RD, RecordCompleteMap &RecordsComplete, RecordCompleteMap &MNCComplete)
Returns true, if the given CXXRecordDecl is fully defined in this translation unit,...
Definition Sema.cpp:1136
Defines the SourceManager interface.
Allows QualTypes to be sorted and hence used in maps and sets.
TypePropertyCache< Private > Cache
Definition Type.cpp:4863
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition ASTConsumer.h:35
virtual ASTMutationListener * GetASTMutationListener()
If the consumer is interested in entities getting modified after their initial creation,...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
Attr - This represents one attribute.
Definition Attr.h:46
A class which contains all the information about a particular captured value.
Definition Decl.h:4680
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4674
ArrayRef< Capture > captures() const
Definition Decl.h:4801
SourceLocation getCaretLocation() const
Definition Decl.h:4747
bool doesNotEscape() const
Definition Decl.h:4825
Represents a C++ destructor within a class.
Definition DeclCXX.h:2876
CXXFieldCollector - Used to keep track of CXXFieldDecls during parsing of C++ classes.
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2262
An iterator over the friend declarations of a class.
Definition DeclFriend.h:198
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
friend_iterator friend_begin() const
Definition DeclFriend.h:250
base_class_range bases()
Definition DeclCXX.h:608
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2131
friend_iterator friend_end() const
Definition DeclFriend.h:254
bool isSet() const
Deprecated.
Definition DeclSpec.h:199
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition Decl.h:4946
ImplicitParamDecl * getContextParam() const
Retrieve the parameter containing captured variables.
Definition Decl.h:5004
static const char * getCastKindName(CastKind CK)
Definition Expr.cpp:1951
Abstract interface for a consumer of code-completion information.
The information about the darwin SDK that was used during this compilation.
decl_iterator - Iterates through the declarations stored within this context.
Definition DeclBase.h:2330
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
decl_iterator decls_end() const
Definition DeclBase.h:2375
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_iterator decls_begin() const
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:826
decl_range decls()
Definition Stmt.h:1671
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:573
void addAttr(Attr *A)
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition DeclBase.cpp:600
bool isInvalidDecl() const
Definition DeclBase.h:588
SourceLocation getLocation() const
Definition DeclBase.h:439
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:575
bool hasAttr() const
Definition DeclBase.h:577
The name of a declaration.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1921
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2068
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2104
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2083
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2351
A little helper class used to produce diagnostics.
static SFINAEResponse getDiagnosticSFINAEResponse(unsigned DiagID)
Determines whether the given built-in diagnostic ID is for an error that is suppressed if it occurs d...
@ SFINAE_SubstitutionFailure
The diagnostic should not be reported, but it should cause template argument deduction to fail.
@ SFINAE_Suppress
The diagnostic should be suppressed entirely.
@ SFINAE_AccessControl
The diagnostic is an access-control diagnostic, which will be substitution failures in some contexts ...
@ SFINAE_Report
The diagnostic should be reported.
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
const SourceLocation & getLocation() const
unsigned getID() const
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:785
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:770
Level
The level of the diagnostic, after it has been through mapping.
Definition Diagnostic.h:237
bool hasFatalErrorOccurred() const
Definition Diagnostic.h:887
RAII object that enters a new expression evaluation context.
This represents one expression.
Definition Expr.h:112
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3090
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3078
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3086
bool isPRValue() const
Definition Expr.h:285
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
QualType getType() const
Definition Expr.h:144
An abstract interface that should be implemented by external AST sources that also provide informatio...
virtual void updateOutOfDateSelector(Selector Sel)
Load the contents of the global method pool for a given selector if necessary.
Definition Sema.cpp:2666
virtual void ReadMethodPool(Selector Sel)
Load the contents of the global method pool for a given selector.
Definition Sema.cpp:2665
virtual void ReadUndefinedButUsed(llvm::MapVector< NamedDecl *, SourceLocation > &Undefined)
Load the set of used but not defined functions or variables with internal linkage,...
Definition Sema.cpp:2672
~ExternalSemaSource() override
Definition Sema.cpp:2662
virtual void ReadKnownNamespaces(SmallVectorImpl< NamespaceDecl * > &Namespaces)
Load the set of namespaces that are known to the external source, which will be used during typo corr...
Definition Sema.cpp:2668
virtual void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 > > &)
Definition Sema.cpp:2675
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3160
StringRef getName() const
The name of this FileEntry.
Definition FileEntry.h:61
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
Represents a function declaration or definition.
Definition Decl.h:2000
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2689
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3280
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition Decl.cpp:3707
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2540
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition Decl.cpp:3703
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2385
const ASTTemplateArgumentListInfo * getTemplateSpecializationArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
Definition Decl.cpp:4340
static FunctionEffectsRef get(QualType QT)
Extract the effects from a Type if it is a function, block, or member function pointer,...
Definition TypeBase.h:9366
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5357
Declaration of a template function.
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4553
QualType getReturnType() const
Definition TypeBase.h:4893
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3856
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2073
Represents a C array with an unspecified size.
Definition TypeBase.h:3959
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type)
@ CMK_HeaderUnit
Compiling a module header unit.
@ CMK_ModuleInterface
Compiling a C++ modules interface unit.
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
static std::optional< Token > findNextToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeComments=false)
Finds the token that comes right after the given location.
Definition Lexer.cpp:1339
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition Lexer.cpp:858
Represents the results of name lookup.
Definition Lookup.h:147
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:39
Abstract interface for a module loader.
bool resolveExports(Module *Mod, bool Complain)
Resolve all of the unresolved exports in the given module.
bool resolveConflicts(Module *Mod, bool Complain)
Resolve all of the unresolved conflicts in the given module.
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Describes a module or submodule.
Definition Module.h:251
bool isNamedModuleInterfaceHasInit() const
Definition Module.h:791
bool isInterfaceOrPartition() const
Definition Module.h:778
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Definition Module.h:565
llvm::iterator_range< submodule_iterator > submodules()
Definition Module.h:945
@ PrivateModuleFragment
This is the private module fragment within some C++ module.
Definition Module.h:287
@ ExplicitGlobalModuleFragment
This is the explicit Global Module Fragment of a modular TU.
Definition Module.h:284
static const unsigned NumNSNumberLiteralMethods
Definition NSAPI.h:191
This represents a decl that may have a name.
Definition Decl.h:274
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition Decl.h:429
NamedDecl * getMostRecentDecl()
Definition Decl.h:501
bool isExternallyVisible() const
Definition Decl.h:433
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
void addSupport(const llvm::StringMap< bool > &FeaturesMap, const LangOptions &Opts)
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition ExprCXX.h:3129
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3190
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3220
decls_iterator decls_begin() const
Definition ExprCXX.h:3222
decls_iterator decls_end() const
Definition ExprCXX.h:3225
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition PPCallbacks.h:37
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
Definition ParsedAttr.h:371
bool isArgIdent(unsigned Arg) const
Definition ParsedAttr.h:385
Expr * getArgAsExpr(unsigned Arg) const
Definition ParsedAttr.h:383
void Emit(const DiagnosticBuilder &DB) const
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition Type.h:85
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition Type.h:79
QualType getCanonicalType() const
Definition TypeBase.h:8483
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8525
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8504
bool hasUnsupportedSplice(const SourceManager &SourceMgr) const
@ RCK_OrdinaryC
Any normal C comment.
@ RCK_Invalid
Invalid comment.
@ RCK_OrdinaryBCPL
Any normal BCPL comments.
bool isAlmostTrailingComment() const LLVM_READONLY
Returns true if it is a probable typo:
CommentKind getKind() const LLVM_READONLY
Represents a struct/union/class.
Definition Decl.h:4327
field_range fields() const
Definition Decl.h:4530
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
Smart pointer class that efficiently represents Objective-C method names.
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
@ K_Immediate
Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
Definition SemaBase.h:117
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaBase(Sema &S)
Definition SemaBase.cpp:7
const LangOptions & getLangOpts() const
Definition SemaBase.cpp:11
DiagnosticsEngine & getDiagnostics() const
Definition SemaBase.cpp:10
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
llvm::DenseMap< CanonicalDeclPtr< const FunctionDecl >, llvm::SmallVector< FunctionDeclAndLoc, 1 > > DeviceKnownEmittedFns
An inverse call graph, mapping known-emitted functions to their known-emitted callers (plus the locat...
Definition SemaCUDA.h:83
An abstract interface that should be implemented by clients that read ASTs and then require further s...
void ActOnEndOfTranslationUnit(TranslationUnitDecl *TU)
ObjCMethodDecl * NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]
The Objective-C NSNumber methods used to create NSNumber literals.
Definition SemaObjC.h:606
void DiagnoseUseOfUnimplementedSelectors()
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
void ActOnEndOfTranslationUnit(TranslationUnitDecl *TU)
void DiagnoseUnterminatedOpenMPDeclareTarget()
Report unterminated 'omp declare target' or 'omp begin declare target' at the end of a compilation un...
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1378
sema::DelayedDiagnosticPool * getCurrentPool() const
Returns the current delayed-diagnostics pool.
Definition Sema.h:1393
Custom deleter to allow FunctionScopeInfos to be kept alive for a short time after they've been poppe...
Definition Sema.h:1065
void operator()(sema::FunctionScopeInfo *Scope) const
Definition Sema.cpp:2505
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12520
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12564
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition Sema.h:3616
bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs (unless they are value dependent ...
Definition SemaAttr.cpp:509
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13663
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13117
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2578
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1133
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition Sema.h:10114
void LoadExternalWeakUndeclaredIdentifiers()
Load weak undeclared identifiers from the external source.
Definition Sema.cpp:1076
bool isExternalWithNoLinkageType(const ValueDecl *VD) const
Determine if VD, which must be a variable or function, is an external symbol that nonetheless can't b...
Definition Sema.cpp:950
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition Sema.cpp:2678
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9385
const Decl * PragmaAttributeCurrentTargetDecl
The declaration that is currently receiving an attribute from the pragma attribute stack.
Definition Sema.h:2133
OpaquePtr< QualType > TypeTy
Definition Sema.h:1293
void addImplicitTypedef(StringRef Name, QualType T)
Definition Sema.cpp:366
void PrintContextStack()
Definition Sema.h:13750
SemaOpenMP & OpenMP()
Definition Sema.h:1525
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition Sema.h:6334
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition Sema.h:1254
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3598
void emitAndClearUnusedLocalTypedefWarnings()
Definition Sema.cpp:1167
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition Sema.h:6551
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition Sema.h:1243
SemaCUDA & CUDA()
Definition Sema.h:1465
void Initialize()
Perform initialization that occurs after the parser has been initialized but before it parses anythin...
Definition Sema.cpp:372
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1236
Preprocessor & getPreprocessor() const
Definition Sema.h:938
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2350
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2068
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2062
void setFunctionHasBranchIntoScope()
Definition Sema.cpp:2531
void ActOnComment(SourceRange Comment)
Definition Sema.cpp:2630
void ActOnEndOfTranslationUnit()
ActOnEndOfTranslationUnit - This is called at the very end of the translation unit when EOF is reache...
Definition Sema.cpp:1246
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2069
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
void ActOnTranslationUnitScope(Scope *S)
Scope actions.
Definition Sema.cpp:173
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
SemaSYCL & SYCL()
Definition Sema.h:1550
IdentifierInfo * getSuperIdentifier() const
Definition Sema.cpp:2905
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1675
void DiagnosePrecisionLossInComplexDivision()
bool DisableTypoCorrection
Tracks whether we are in a context where typo correction is disabled.
Definition Sema.h:9325
ASTContext & Context
Definition Sema.h:1300
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition Sema.cpp:681
llvm::DenseMap< IdentifierInfo *, PendingPragmaInfo > PendingExportedNames
Definition Sema.h:2350
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
SemaObjC & ObjC()
Definition Sema.h:1510
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain=false, bool(*IsPlausibleResult)(QualType)=nullptr)
Try to recover by turning the given expression into a call.
Definition Sema.cpp:2860
SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags
Diagnostics that are emitted only if we discover that the given function must be codegen'ed.
Definition Sema.h:1435
void CheckDelayedMemberExceptionSpecs()
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
ClassTemplateDecl * StdCoroutineTraitsCache
The C++ "std::coroutine_traits" template, which is defined in <coroutine_traits>
Definition Sema.h:3191
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2065
UnusedFileScopedDeclsType UnusedFileScopedDecls
The set of file scoped decls seen so far that have not been used and must warn if not used.
Definition Sema.h:3606
ASTContext & getASTContext() const
Definition Sema.h:939
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1073
void addExternalSource(IntrusiveRefCntPtr< ExternalSemaSource > E)
Registers an external source.
Definition Sema.cpp:656
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition Sema.h:6577
SmallVector< std::pair< FunctionDecl *, FunctionDecl * >, 2 > DelayedEquivalentExceptionSpecChecks
All the function redeclarations seen during a class definition that had their exception spec checks d...
Definition Sema.h:6661
PragmaStack< StringLiteral * > ConstSegStack
Definition Sema.h:2061
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:757
unsigned TyposCorrected
The number of typos corrected by CorrectTypo.
Definition Sema.h:9328
static const unsigned MaxAlignmentExponent
The maximum alignment, same as in llvm::Value.
Definition Sema.h:1226
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1204
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1680
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition Sema.cpp:2621
void setFunctionHasIndirectGoto()
Definition Sema.cpp:2541
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1694
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2369
FPOptions & getCurFPFeatures()
Definition Sema.h:934
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition Sema.h:8368
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
sema::LambdaScopeInfo * PushLambdaScope()
Definition Sema.cpp:2387
void PopCompoundScope()
Definition Sema.cpp:2520
api_notes::APINotesManager APINotes
Definition Sema.h:1304
const LangOptions & getLangOpts() const
Definition Sema.h:932
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2481
SemaOpenACC & OpenACC()
Definition Sema.h:1515
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
ASTConsumer & getASTConsumer() const
Definition Sema.h:940
void * OpaqueParser
Definition Sema.h:1344
Preprocessor & PP
Definition Sema.h:1299
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
threadSafety::BeforeSet * ThreadSafetyDeclCache
Definition Sema.h:1339
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition Sema.cpp:2159
const LangOptions & LangOpts
Definition Sema.h:1298
std::unique_ptr< sema::FunctionScopeInfo > CachedFunctionScope
Definition Sema.h:1232
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2596
static const uint64_t MaximumAlignment
Definition Sema.h:1227
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6555
SemaHLSL & HLSL()
Definition Sema.h:1475
bool CollectStats
Flag indicating whether or not to collect detailed statistics.
Definition Sema.h:1230
void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind)
Definition Sema.cpp:1186
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName, unsigned Index)
Invent a new identifier for parameters of abbreviated templates.
Definition Sema.cpp:140
SemaRISCV & RISCV()
Definition Sema.h:1540
SmallVector< PendingImplicitInstantiation, 1 > LateParsedInstantiations
Queue of implicit template instantiations that cannot be performed eagerly.
Definition Sema.h:14081
void performFunctionEffectAnalysis(TranslationUnitDecl *TU)
PragmaStack< AlignPackInfo > AlignPackStack
Definition Sema.h:2050
SmallVector< std::pair< const CXXMethodDecl *, const CXXMethodDecl * >, 2 > DelayedOverridingExceptionSpecChecks
All the overriding functions seen during a class definition that had their exception spec checks dela...
Definition Sema.h:6653
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2060
DeclContext * getCurLexicalContext() const
Definition Sema.h:1137
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1687
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition Sema.cpp:864
llvm::SmallSetVector< Decl *, 4 > DeclsToCheckForDeferredDiags
Function or variable declarations to be checked for whether the deferred diagnostics should be emitte...
Definition Sema.h:4803
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1333
void PushCompoundScope(bool IsStmtExpr)
Definition Sema.cpp:2515
bool isDeclaratorFunctionLike(Declarator &D)
Determine whether.
Definition Sema.cpp:2949
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2333
StringLiteral * CurInitSeg
Last section used with pragma init_seg.
Definition Sema.h:2103
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9911
static bool isCast(CheckedConversionKind CCK)
Definition Sema.h:2564
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition Sema.cpp:2551
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1438
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
ClassTemplateDecl * StdTypeIdentity
The C++ "std::type_identity" template, which is defined in <type_traits>.
Definition Sema.h:6581
SemaOpenCL & OpenCL()
Definition Sema.h:1520
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8231
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1655
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
bool GlobalNewDeleteDeclared
A flag to remember whether the implicit forms of operator new and delete have been declared.
Definition Sema.h:8427
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition Sema.h:3620
bool MSStructPragmaOn
Definition Sema.h:1824
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
Definition Sema.h:13694
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14029
SourceManager & getSourceManager() const
Definition Sema.h:937
bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason)
makeUnavailableInSystemHeader - There is an error in the current context.
Definition Sema.cpp:631
void getUndefinedButUsed(SmallVectorImpl< std::pair< NamedDecl *, SourceLocation > > &Undefined)
Obtain a sorted list of functions that are undefined but ODR-used.
Definition Sema.cpp:961
void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn when implicitly changing function effects.
Definition Sema.cpp:697
void PerformPendingInstantiations(bool LocalOnly=false, bool AtEndOfTU=true)
Performs template instantiation for all implicit template instantiations we have seen until this poin...
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value, bool SupressSimplerImplicitMoves=false)
Perform the initialization of a potentially-movable value, which is the result of return value.
CanThrowResult canThrow(const Stmt *E)
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
@ NTCUK_Destruct
Definition Sema.h:4130
@ NTCUK_Copy
Definition Sema.h:4131
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition Sema.cpp:2381
PragmaStack< MSVtorDispMode > VtorDispStack
Whether to insert vtordisps prior to virtual bases in the Microsoft C++ ABI.
Definition Sema.h:2049
void * VisContext
VisContext - Manages the stack for #pragma GCC visibility.
Definition Sema.h:2110
bool isSFINAEContext() const
Definition Sema.h:13762
UnsignedOrNone ArgPackSubstIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition Sema.h:13718
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel=0)
Definition Sema.cpp:2911
void emitDeferredDiags()
Definition Sema.cpp:2051
void setFunctionHasMustTail()
Definition Sema.cpp:2546
RecordDecl * CXXTypeInfoDecl
The C++ "type_info" declaration, which is defined in <typeinfo>.
Definition Sema.h:8423
void CheckCompleteVariableDeclaration(VarDecl *VD)
void setFunctionHasBranchProtectedScope()
Definition Sema.cpp:2536
RedeclarationKind forRedeclarationInCurContext() const
void ActOnStartOfTranslationUnit()
This is called before the very first declaration in the translation unit is parsed.
Definition Sema.cpp:1180
IntrusiveRefCntPtr< ExternalSemaSource > ExternalSource
Source of additional semantic information.
Definition Sema.h:1576
ASTConsumer & Consumer
Definition Sema.h:1301
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4689
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1338
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1801
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14077
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with the preprocessor.
Definition Sema.cpp:110
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6793
std::pair< SourceLocation, bool > DeleteExprLoc
Definition Sema.h:980
void RecordParsingTemplateParameterDepth(unsigned Depth)
This is used to inform Sema what the current TemplateParameterDepth is during Parsing.
Definition Sema.cpp:2394
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1259
void DiagnoseUnterminatedPragmaAttribute()
void FreeVisContext()
FreeVisContext - Deallocate and null out VisContext.
LateTemplateParserCB * LateTemplateParser
Definition Sema.h:1343
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
llvm::MapVector< FieldDecl *, DeleteLocs > DeleteExprs
Delete-expressions to be analyzed at the end of translation unit.
Definition Sema.h:8434
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition Sema.h:3613
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
DarwinSDKInfo * getDarwinSDKInfoForAvailabilityChecking()
Definition Sema.cpp:124
const llvm::MapVector< FieldDecl *, DeleteLocs > & getMismatchingDeleteExpressions() const
Retrieves list of suspicious delete-expressions that will be checked at the end of translation unit.
Definition Sema.cpp:2933
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8371
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
SourceManager & SourceMgr
Definition Sema.h:1303
DiagnosticsEngine & Diags
Definition Sema.h:1302
void DiagnoseUnterminatedPragmaAlignPack()
Definition SemaAttr.cpp:595
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:933
FPOptions CurFPFeatures
Definition Sema.h:1296
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2059
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Attr * CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef< Expr * > Args)
CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
Definition Sema.cpp:2972
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition Sema.h:6589
void PrintStats() const
Print out statistics about the semantic analysis.
Definition Sema.cpp:671
LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod
Controls member pointer representation format under the MS ABI.
Definition Sema.h:1822
llvm::BumpPtrAllocator BumpAlloc
Definition Sema.h:1245
SourceRange getRangeForNextToken(SourceLocation Loc, bool IncludeMacros, bool IncludeComments, std::optional< tok::TokenKind > ExpectedToken=std::nullopt)
Calls Lexer::findNextToken() to find the next token, and if the locations of both ends of the token c...
Definition Sema.cpp:89
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:626
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition Sema.h:6333
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition Sema.h:3588
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2142
DeclarationName VAListTagName
VAListTagName - The declaration name corresponding to __va_list_tag.
Definition Sema.h:1357
sema::FunctionScopeInfo * getEnclosingFunction() const
Definition Sema.cpp:2566
sema::CapturedRegionScopeInfo * getCurCapturedRegion()
Retrieve the current captured region, if any.
Definition Sema.cpp:2925
void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E)
Warn when implicitly casting 0 to nullptr.
Definition Sema.cpp:709
void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB)
Cause the built diagnostic to be emitted on the DiagosticsEngine.
Definition Sema.cpp:1700
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
IdentifierResolver IdResolver
Definition Sema.h:3511
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2527
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument E is a ASCII string literal.
SemaARM & ARM()
Definition Sema.h:1445
llvm::DenseSet< InstantiatingSpecializationsKey > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition Sema.h:13666
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:652
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Definition Sema.h:13759
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void setEnd(SourceLocation e)
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3818
bool isUnion() const
Definition Decl.h:3928
Exposes information about the current target.
Definition TargetInfo.h:227
virtual bool hasLongDoubleType() const
Determine whether the long double type is supported on this target.
Definition TargetInfo.h:736
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual bool hasFPReturn() const
Determine whether return of a floating point value is supported on this target.
Definition TargetInfo.h:740
bool hasRISCVVTypes() const
Returns whether or not the RISC-V V built-in types are available on this target.
A container of type source information.
Definition TypeBase.h:8402
The base class of the type hierarchy.
Definition TypeBase.h:1866
bool isFloat16Type() const
Definition TypeBase.h:9043
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9078
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2617
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9328
bool isFloat128Type() const
Definition TypeBase.h:9063
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isBitIntType() const
Definition TypeBase.h:8943
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2832
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition Type.cpp:2406
bool isIbm128Type() const
Definition TypeBase.h:9067
bool isOverflowBehaviorType() const
Definition TypeBase.h:8839
bool isBFloat16Type() const
Definition TypeBase.h:9055
bool isStructureOrClassType() const
Definition Type.cpp:707
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2357
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2638
Linkage getLinkage() const
Determine the linkage of this type.
Definition Type.cpp:4971
@ STK_FloatingComplex
Definition TypeBase.h:2814
@ STK_ObjCObjectPointer
Definition TypeBase.h:2808
@ STK_IntegralComplex
Definition TypeBase.h:2813
@ STK_MemberPointer
Definition TypeBase.h:2809
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
bool isNullPtrType() const
Definition TypeBase.h:9071
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5097
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
A set of unresolved declarations.
UnresolvedSetIterator iterator
void addDecl(NamedDecl *D)
A set of unresolved declarations.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:926
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2822
void setEscapingByref()
Definition Decl.h:1607
VarDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2378
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition Decl.h:1342
const Expr * getInit() const
Definition Decl.h:1368
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition Decl.cpp:2357
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1295
StorageDuration getStorageDuration() const
Get the storage duration of this variable, per C++ [basic.stc].
Definition Decl.h:1229
bool isEscapingByref() const
Indicates the capture is a __block variable that is captured by a block that can potentially escape (...
Definition Decl.cpp:2710
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1358
Declaration of a variable template.
Represents a GCC generic vector type.
Definition TypeBase.h:4225
Retains information about a block that is currently being parsed.
Definition ScopeInfo.h:794
Retains information about a captured region.
Definition ScopeInfo.h:820
Contains information about the compound statement currently being parsed.
Definition ScopeInfo.h:67
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
SmallVector< CompoundScopeInfo, 4 > CompoundScopes
The stack of currently active compound statement scopes in the function.
Definition ScopeInfo.h:228
llvm::SmallPtrSet< const BlockDecl *, 1 > Blocks
The set of blocks that are introduced in this function.
Definition ScopeInfo.h:231
llvm::TinyPtrVector< VarDecl * > ByrefBlockVars
The set of __block variables that are introduced in this function.
Definition ScopeInfo.h:234
void FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType, FileID PrevFID) override
Callback invoked whenever a source file is entered or exited.
Definition Sema.cpp:191
void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace, diag::Severity Mapping, StringRef Str) override
Callback invoked when a #pragma gcc diagnostic directive is read.
Definition Sema.cpp:228
Provides information about an attempted template argument deduction, whose success or failure was des...
void addSuppressedDiagnostic(SourceLocation Loc, PartialDiagnostic PD)
Add a new diagnostic to the set of diagnostics.
void addSFINAEDiagnostic(SourceLocation Loc, PartialDiagnostic PD)
Set the diagnostic which caused the SFINAE failure.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Flavor
Flavors of diagnostics we can emit.
@ WarningOrError
A diagnostic that indicates a problem or potential problem.
@ Remark
A diagnostic that indicates normal progress through compilation.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Severity
Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs to either Ignore (nothing),...
void threadSafetyCleanup(BeforeSet *Cache)
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:208
@ CPlusPlus
@ CPlusPlus11
@ ExpectedVariableOrFunction
@ Nullable
Values of this type can be null.
Definition Specifiers.h:352
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
Expected< std::optional< DarwinSDKInfo > > parseDarwinSDKInfo(llvm::vfs::FileSystem &VFS, StringRef SDKRootPath)
Parse the SDK information from the SDKSettings.json file.
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:636
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
CapturedRegionKind
The different kinds of captured statement.
@ CR_OpenMP
@ SC_Register
Definition Specifiers.h:257
@ SC_Static
Definition Specifiers.h:252
void inferNoReturnAttr(Sema &S, Decl *D)
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:342
@ SD_Static
Static storage duration.
Definition Specifiers.h:343
@ Result
The result type of a method or function.
Definition TypeBase.h:905
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TUFragmentKind
Definition Sema.h:487
@ Private
The private module fragment, between 'module :private;' and the end of the translation unit.
Definition Sema.h:496
@ Global
The global module fragment, between 'module;' and a module-declaration.
Definition Sema.h:489
@ Normal
A normal translation unit fragment.
Definition Sema.h:493
ExprResult ExprError()
Definition Ownership.h:265
@ OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
Definition Sema.h:581
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
TranslationUnitKind
Describes the kind of translation unit being processed.
@ TU_ClangModule
The translation unit is a clang module.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
ComparisonCategoryType
An enumeration representing the different comparison categories types.
void FormatASTNodeDiagnosticArgument(DiagnosticsEngine::ArgumentKind Kind, intptr_t Val, StringRef Modifier, StringRef Argument, ArrayRef< DiagnosticsEngine::ArgumentValue > PrevArgs, SmallVectorImpl< char > &Output, void *Cookie, ArrayRef< intptr_t > QualTypeVals)
DiagnosticsEngine argument formatting function for diagnostics that involve AST nodes.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:150
bool isExternalFormalLinkage(Linkage L)
Definition Linkage.h:117
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4204
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4207
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5967
bool IsArmStreamingFunction(const FunctionDecl *FD, bool IncludeLocallyStreaming)
Returns whether the given FunctionDecl has an __arm[_locally]_streaming attribute.
Definition Decl.cpp:6100
bool isExternallyVisible(Linkage L)
Definition Linkage.h:90
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
CheckedConversionKind
The kind of conversion being performed.
Definition Sema.h:438
unsigned long uint64_t
#define false
Definition stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Describes how types, statements, expressions, and declarations should be printed.
unsigned Bool
Whether we can use 'bool' rather than '_Bool' (even if the language doesn't actually have 'bool',...
unsigned EntireContentsOfLargeArray
Whether to print the entire array initializers, especially on non-type template parameters,...
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13256
Information from a C++ pragma export, for a symbol that we haven't seen the declaration for yet.
Definition Sema.h:2345