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