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