clang 17.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"
29#include "clang/Basic/Stack.h"
42#include "clang/Sema/Scope.h"
49#include "llvm/ADT/DenseMap.h"
50#include "llvm/ADT/STLExtras.h"
51#include "llvm/ADT/SmallPtrSet.h"
52#include "llvm/Support/TimeProfiler.h"
53#include <optional>
54
55using namespace clang;
56using namespace sema;
57
60}
61
63
66 StringRef Platform) {
68 if (!SDKInfo && !WarnedDarwinSDKInfoMissing) {
69 Diag(Loc, diag::warn_missing_sdksettings_for_availability_checking)
70 << Platform;
71 WarnedDarwinSDKInfoMissing = true;
72 }
73 return SDKInfo;
74}
75
77 if (CachedDarwinSDKInfo)
78 return CachedDarwinSDKInfo->get();
79 auto SDKInfo = parseDarwinSDKInfo(
82 if (SDKInfo && *SDKInfo) {
83 CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(std::move(**SDKInfo));
84 return CachedDarwinSDKInfo->get();
85 }
86 if (!SDKInfo)
87 llvm::consumeError(SDKInfo.takeError());
88 CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>();
89 return nullptr;
90}
91
94 unsigned int Index) {
95 std::string InventedName;
96 llvm::raw_string_ostream OS(InventedName);
97
98 if (!ParamName)
99 OS << "auto:" << Index + 1;
100 else
101 OS << ParamName->getName() << ":auto";
102
103 OS.flush();
104 return &Context.Idents.get(OS.str());
105}
106
108 const Preprocessor &PP) {
110 // In diagnostics, we print _Bool as bool if the latter is defined as the
111 // former.
112 Policy.Bool = Context.getLangOpts().Bool;
113 if (!Policy.Bool) {
114 if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
115 Policy.Bool = BoolMacro->isObjectLike() &&
116 BoolMacro->getNumTokens() == 1 &&
117 BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
118 }
119 }
120
121 // Shorten the data output if needed
122 Policy.EntireContentsOfLargeArray = false;
123
124 return Policy;
125}
126
128 TUScope = S;
130}
131
132namespace clang {
133namespace sema {
134
136 Sema *S = nullptr;
138
139public:
140 void set(Sema &S) { this->S = &S; }
141
142 void reset() { S = nullptr; }
143
146 FileID PrevFID) override {
147 if (!S)
148 return;
149 switch (Reason) {
150 case EnterFile: {
152 SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
153 if (IncludeLoc.isValid()) {
154 if (llvm::timeTraceProfilerEnabled()) {
155 const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
156 llvm::timeTraceProfilerBegin(
157 "Source", FE != nullptr ? FE->getName() : StringRef("<unknown>"));
158 }
159
160 IncludeStack.push_back(IncludeLoc);
163 IncludeLoc);
164 }
165 break;
166 }
167 case ExitFile:
168 if (!IncludeStack.empty()) {
169 if (llvm::timeTraceProfilerEnabled())
170 llvm::timeTraceProfilerEnd();
171
174 IncludeStack.pop_back_val());
175 }
176 break;
177 default:
178 break;
179 }
180 }
181};
182
183} // end namespace sema
184} // end namespace clang
185
186const unsigned Sema::MaxAlignmentExponent;
188
189Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
190 TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
191 : ExternalSource(nullptr), CurFPFeatures(pp.getLangOpts()),
192 LangOpts(pp.getLangOpts()), PP(pp), Context(ctxt), Consumer(consumer),
193 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
194 CollectStats(false), CodeCompleter(CodeCompleter), CurContext(nullptr),
195 OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
196 MSPointerToMemberRepresentationMethod(
197 LangOpts.getMSPointerToMemberRepresentationMethod()),
198 VtorDispStack(LangOpts.getVtorDispMode()),
199 AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack)),
200 DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
201 CodeSegStack(nullptr), StrictGuardStackCheckStack(false),
202 FpPragmaStack(FPOptionsOverride()), CurInitSeg(nullptr),
203 VisContext(nullptr), PragmaAttributeCurrentTargetDecl(nullptr),
204 IsBuildingRecoveryCallExpr(false), LateTemplateParser(nullptr),
205 LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
206 StdInitializerList(nullptr),
207 StdCoroutineTraitsCache(nullptr), CXXTypeInfoDecl(nullptr),
208 MSVCGuidDecl(nullptr), StdSourceLocationImplDecl(nullptr),
209 NSNumberDecl(nullptr), NSValueDecl(nullptr), NSStringDecl(nullptr),
210 StringWithUTF8StringMethod(nullptr),
211 ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
212 ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
213 DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
214 TUKind(TUKind), NumSFINAEErrors(0),
215 FullyCheckedComparisonCategories(
216 static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
217 SatisfactionCache(Context), AccessCheckingSFINAE(false),
218 InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
219 ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
220 DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
221 ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
222 CurScope(nullptr), Ident_super(nullptr) {
223 assert(pp.TUKind == TUKind);
224 TUScope = nullptr;
226
227 LoadedExternalKnownNamespaces = false;
228 for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
229 NSNumberLiteralMethods[I] = nullptr;
230
231 if (getLangOpts().ObjC)
232 NSAPIObj.reset(new NSAPI(Context));
233
236
237 // Tell diagnostics how to render things from the AST library.
239
240 // This evaluation context exists to ensure that there's always at least one
241 // valid evaluation context available. It is never removed from the
242 // evaluation stack.
243 ExprEvalContexts.emplace_back(
246
247 // Initialization of data sharing attributes stack for OpenMP
248 InitDataSharingAttributesStack();
249
250 std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
251 std::make_unique<sema::SemaPPCallbacks>();
252 SemaPPCallbackHandler = Callbacks.get();
253 PP.addPPCallbacks(std::move(Callbacks));
254 SemaPPCallbackHandler->set(*this);
255
256 CurFPFeatures.setFPEvalMethod(PP.getCurrentFPEvalMethod());
257}
258
259// Anchor Sema's type info to this TU.
261
262void Sema::addImplicitTypedef(StringRef Name, QualType T) {
263 DeclarationName DN = &Context.Idents.get(Name);
264 if (IdResolver.begin(DN) == IdResolver.end())
266}
267
269 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
270 SC->InitializeSema(*this);
271
272 // Tell the external Sema source about this Sema object.
273 if (ExternalSemaSource *ExternalSema
274 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
275 ExternalSema->InitializeSema(*this);
276
277 // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
278 // will not be able to merge any duplicate __va_list_tag decls correctly.
279 VAListTagName = PP.getIdentifierInfo("__va_list_tag");
280
281 if (!TUScope)
282 return;
283
284 // Initialize predefined 128-bit integer types, if needed.
288 // If either of the 128-bit integer types are unavailable to name lookup,
289 // define them now.
290 DeclarationName Int128 = &Context.Idents.get("__int128_t");
291 if (IdResolver.begin(Int128) == IdResolver.end())
293
294 DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
295 if (IdResolver.begin(UInt128) == IdResolver.end())
297 }
298
299
300 // Initialize predefined Objective-C types:
301 if (getLangOpts().ObjC) {
302 // If 'SEL' does not yet refer to any declarations, make it refer to the
303 // predefined 'SEL'.
304 DeclarationName SEL = &Context.Idents.get("SEL");
305 if (IdResolver.begin(SEL) == IdResolver.end())
307
308 // If 'id' does not yet refer to any declarations, make it refer to the
309 // predefined 'id'.
311 if (IdResolver.begin(Id) == IdResolver.end())
313
314 // Create the built-in typedef for 'Class'.
315 DeclarationName Class = &Context.Idents.get("Class");
316 if (IdResolver.begin(Class) == IdResolver.end())
318
319 // Create the built-in forward declaratino for 'Protocol'.
320 DeclarationName Protocol = &Context.Idents.get("Protocol");
321 if (IdResolver.begin(Protocol) == IdResolver.end())
323 }
324
325 // Create the internal type for the *StringMakeConstantString builtins.
326 DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
327 if (IdResolver.begin(ConstantString) == IdResolver.end())
329
330 // Initialize Microsoft "predefined C++ types".
331 if (getLangOpts().MSVCCompat) {
332 if (getLangOpts().CPlusPlus &&
333 IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
335 TUScope);
336
338 }
339
340 // Initialize predefined OpenCL types and supported extensions and (optional)
341 // core features.
342 if (getLangOpts().OpenCL) {
347 auto OCLCompatibleVersion = getLangOpts().getOpenCLCompatibleVersion();
348 if (OCLCompatibleVersion >= 200) {
349 if (getLangOpts().OpenCLCPlusPlus || getLangOpts().Blocks) {
352 }
353 if (getLangOpts().OpenCLPipes)
356 addImplicitTypedef("atomic_uint",
358 addImplicitTypedef("atomic_float",
360 // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
361 // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
363
364
365 // OpenCL v2.0 s6.13.11.6:
366 // - The atomic_long and atomic_ulong types are supported if the
367 // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
368 // extensions are supported.
369 // - The atomic_double type is only supported if double precision
370 // is supported and the cl_khr_int64_base_atomics and
371 // cl_khr_int64_extended_atomics extensions are supported.
372 // - If the device address space is 64-bits, the data types
373 // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
374 // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
375 // cl_khr_int64_extended_atomics extensions are supported.
376
377 auto AddPointerSizeDependentTypes = [&]() {
378 auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
379 auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
380 auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
381 auto AtomicPtrDiffT =
383 addImplicitTypedef("atomic_size_t", AtomicSizeT);
384 addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
385 addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
386 addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
387 };
388
389 if (Context.getTypeSize(Context.getSizeType()) == 32) {
390 AddPointerSizeDependentTypes();
391 }
392
393 if (getOpenCLOptions().isSupported("cl_khr_fp16", getLangOpts())) {
394 auto AtomicHalfT = Context.getAtomicType(Context.HalfTy);
395 addImplicitTypedef("atomic_half", AtomicHalfT);
396 }
397
398 std::vector<QualType> Atomic64BitTypes;
399 if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics",
400 getLangOpts()) &&
401 getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics",
402 getLangOpts())) {
403 if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) {
404 auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
405 addImplicitTypedef("atomic_double", AtomicDoubleT);
406 Atomic64BitTypes.push_back(AtomicDoubleT);
407 }
408 auto AtomicLongT = Context.getAtomicType(Context.LongTy);
409 auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
410 addImplicitTypedef("atomic_long", AtomicLongT);
411 addImplicitTypedef("atomic_ulong", AtomicULongT);
412
413
414 if (Context.getTypeSize(Context.getSizeType()) == 64) {
415 AddPointerSizeDependentTypes();
416 }
417 }
418 }
419
420#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
421 if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) { \
422 addImplicitTypedef(#ExtType, Context.Id##Ty); \
423 }
424#include "clang/Basic/OpenCLExtensionTypes.def"
425 }
426
428#define SVE_TYPE(Name, Id, SingletonId) \
429 addImplicitTypedef(Name, Context.SingletonId);
430#include "clang/Basic/AArch64SVEACLETypes.def"
431 }
432
433 if (Context.getTargetInfo().getTriple().isPPC64()) {
434#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
435 addImplicitTypedef(#Name, Context.Id##Ty);
436#include "clang/Basic/PPCTypes.def"
437#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
438 addImplicitTypedef(#Name, Context.Id##Ty);
439#include "clang/Basic/PPCTypes.def"
440 }
441
443#define RVV_TYPE(Name, Id, SingletonId) \
444 addImplicitTypedef(Name, Context.SingletonId);
445#include "clang/Basic/RISCVVTypes.def"
446 }
447
448 if (Context.getTargetInfo().getTriple().isWasm() &&
449 Context.getTargetInfo().hasFeature("reference-types")) {
450#define WASM_TYPE(Name, Id, SingletonId) \
451 addImplicitTypedef(Name, Context.SingletonId);
452#include "clang/Basic/WebAssemblyReferenceTypes.def"
453 }
454
456 DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
457 if (IdResolver.begin(MSVaList) == IdResolver.end())
459 }
460
461 DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
462 if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
464}
465
467 assert(InstantiatingSpecializations.empty() &&
468 "failed to clean up an InstantiatingTemplate?");
469
471
472 // Kill all the active scopes.
474 delete FSI;
475
476 // Tell the SemaConsumer to forget about us; we're going out of scope.
477 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
478 SC->ForgetSema();
479
480 // Detach from the external Sema source.
481 if (ExternalSemaSource *ExternalSema
482 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
483 ExternalSema->ForgetSema();
484
485 // Delete cached satisfactions.
486 std::vector<ConstraintSatisfaction *> Satisfactions;
487 Satisfactions.reserve(Satisfactions.size());
488 for (auto &Node : SatisfactionCache)
489 Satisfactions.push_back(&Node);
490 for (auto *Node : Satisfactions)
491 delete Node;
492
494
495 // Destroys data sharing attributes stack for OpenMP
496 DestroyDataSharingAttributesStack();
497
498 // Detach from the PP callback handler which outlives Sema since it's owned
499 // by the preprocessor.
500 SemaPPCallbackHandler->reset();
501}
502
504 // Only warn about this once.
506 Diag(Loc, diag::warn_stack_exhausted);
508 }
509}
510
512 llvm::function_ref<void()> Fn) {
514}
515
516/// makeUnavailableInSystemHeader - There is an error in the current
517/// context. If we're still in a system header, and we can plausibly
518/// make the relevant declaration unavailable instead of erroring, do
519/// so and return true.
521 UnavailableAttr::ImplicitReason reason) {
522 // If we're not in a function, it's an error.
523 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
524 if (!fn) return false;
525
526 // If we're in template instantiation, it's an error.
528 return false;
529
530 // If that function's not in a system header, it's an error.
532 return false;
533
534 // If the function is already unavailable, it's not an error.
535 if (fn->hasAttr<UnavailableAttr>()) return true;
536
537 fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
538 return true;
539}
540
543}
544
545///Registers an external source. If an external source already exists,
546/// creates a multiplex external source and appends to it.
547///
548///\param[in] E - A non-null external sema source.
549///
551 assert(E && "Cannot use with NULL ptr");
552
553 if (!ExternalSource) {
554 ExternalSource = E;
555 return;
556 }
557
558 if (auto *Ex = dyn_cast<MultiplexExternalSemaSource>(ExternalSource))
559 Ex->AddSource(E);
560 else
561 ExternalSource = new MultiplexExternalSemaSource(ExternalSource.get(), E);
562}
563
564/// Print out statistics about the semantic analysis.
565void Sema::PrintStats() const {
566 llvm::errs() << "\n*** Semantic Analysis Stats:\n";
567 llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
568
569 BumpAlloc.PrintStats();
571}
572
574 QualType SrcType,
575 SourceLocation Loc) {
576 std::optional<NullabilityKind> ExprNullability = SrcType->getNullability();
577 if (!ExprNullability || (*ExprNullability != NullabilityKind::Nullable &&
578 *ExprNullability != NullabilityKind::NullableResult))
579 return;
580
581 std::optional<NullabilityKind> TypeNullability = DstType->getNullability();
582 if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
583 return;
584
585 Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
586}
587
589 // nullptr only exists from C++11 on, so don't warn on its absence earlier.
591 return;
592
593 if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
594 return;
596 return;
597
598 if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
599 E->getBeginLoc()))
600 return;
601
602 // Don't diagnose the conversion from a 0 literal to a null pointer argument
603 // in a synthesized call to operator<=>.
604 if (!CodeSynthesisContexts.empty() &&
605 CodeSynthesisContexts.back().Kind ==
607 return;
608
609 // Ignore null pointers in defaulted comparison operators.
611 if (FD && FD->isDefaulted()) {
612 return;
613 }
614
615 // If it is a macro from system header, and if the macro name is not "NULL",
616 // do not warn.
617 SourceLocation MaybeMacroLoc = E->getBeginLoc();
619 SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
620 !findMacroSpelling(MaybeMacroLoc, "NULL"))
621 return;
622
623 Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
625}
626
627/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
628/// If there is already an implicit cast, merge into the existing one.
629/// The result is of the given category.
631 CastKind Kind, ExprValueKind VK,
632 const CXXCastPath *BasePath,
634#ifndef NDEBUG
635 if (VK == VK_PRValue && !E->isPRValue()) {
636 switch (Kind) {
637 default:
638 llvm_unreachable(
639 ("can't implicitly cast glvalue to prvalue with this cast "
640 "kind: " +
641 std::string(CastExpr::getCastKindName(Kind)))
642 .c_str());
643 case CK_Dependent:
644 case CK_LValueToRValue:
645 case CK_ArrayToPointerDecay:
646 case CK_FunctionToPointerDecay:
647 case CK_ToVoid:
648 case CK_NonAtomicToAtomic:
649 break;
650 }
651 }
652 assert((VK == VK_PRValue || Kind == CK_Dependent || !E->isPRValue()) &&
653 "can't cast prvalue to glvalue");
654#endif
655
658
661
662 if (ExprTy == TypeTy)
663 return E;
664
665 if (Kind == CK_ArrayToPointerDecay) {
666 // C++1z [conv.array]: The temporary materialization conversion is applied.
667 // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
668 if (getLangOpts().CPlusPlus && E->isPRValue()) {
669 // The temporary is an lvalue in C++98 and an xvalue otherwise.
671 E->getType(), E, !getLangOpts().CPlusPlus11);
672 if (Materialized.isInvalid())
673 return ExprError();
674 E = Materialized.get();
675 }
676 // C17 6.7.1p6 footnote 124: The implementation can treat any register
677 // declaration simply as an auto declaration. However, whether or not
678 // addressable storage is actually used, the address of any part of an
679 // object declared with storage-class specifier register cannot be
680 // computed, either explicitly(by use of the unary & operator as discussed
681 // in 6.5.3.2) or implicitly(by converting an array name to a pointer as
682 // discussed in 6.3.2.1).Thus, the only operator that can be applied to an
683 // array declared with storage-class specifier register is sizeof.
684 if (VK == VK_PRValue && !getLangOpts().CPlusPlus && !E->isPRValue()) {
685 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
686 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
687 if (VD->getStorageClass() == SC_Register) {
688 Diag(E->getExprLoc(), diag::err_typecheck_address_of)
689 << /*register variable*/ 3 << E->getSourceRange();
690 return ExprError();
691 }
692 }
693 }
694 }
695 }
696
697 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
698 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
699 ImpCast->setType(Ty);
700 ImpCast->setValueKind(VK);
701 return E;
702 }
703 }
704
705 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
707}
708
709/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
710/// to the conversion from scalar type ScalarTy to the Boolean type.
712 switch (ScalarTy->getScalarTypeKind()) {
713 case Type::STK_Bool: return CK_NoOp;
714 case Type::STK_CPointer: return CK_PointerToBoolean;
715 case Type::STK_BlockPointer: return CK_PointerToBoolean;
716 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
717 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
718 case Type::STK_Integral: return CK_IntegralToBoolean;
719 case Type::STK_Floating: return CK_FloatingToBoolean;
720 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
721 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
722 case Type::STK_FixedPoint: return CK_FixedPointToBoolean;
723 }
724 llvm_unreachable("unknown scalar type kind");
725}
726
727/// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
728static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
729 if (D->getMostRecentDecl()->isUsed())
730 return true;
731
732 if (D->isExternallyVisible())
733 return true;
734
735 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
736 // If this is a function template and none of its specializations is used,
737 // we should warn.
738 if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
739 for (const auto *Spec : Template->specializations())
740 if (ShouldRemoveFromUnused(SemaRef, Spec))
741 return true;
742
743 // UnusedFileScopedDecls stores the first declaration.
744 // The declaration may have become definition so check again.
745 const FunctionDecl *DeclToCheck;
746 if (FD->hasBody(DeclToCheck))
747 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
748
749 // Later redecls may add new information resulting in not having to warn,
750 // so check again.
751 DeclToCheck = FD->getMostRecentDecl();
752 if (DeclToCheck != FD)
753 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
754 }
755
756 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
757 // If a variable usable in constant expressions is referenced,
758 // don't warn if it isn't used: if the value of a variable is required
759 // for the computation of a constant expression, it doesn't make sense to
760 // warn even if the variable isn't odr-used. (isReferenced doesn't
761 // precisely reflect that, but it's a decent approximation.)
762 if (VD->isReferenced() &&
763 VD->mightBeUsableInConstantExpressions(SemaRef->Context))
764 return true;
765
766 if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
767 // If this is a variable template and none of its specializations is used,
768 // we should warn.
769 for (const auto *Spec : Template->specializations())
770 if (ShouldRemoveFromUnused(SemaRef, Spec))
771 return true;
772
773 // UnusedFileScopedDecls stores the first declaration.
774 // The declaration may have become definition so check again.
775 const VarDecl *DeclToCheck = VD->getDefinition();
776 if (DeclToCheck)
777 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
778
779 // Later redecls may add new information resulting in not having to warn,
780 // so check again.
781 DeclToCheck = VD->getMostRecentDecl();
782 if (DeclToCheck != VD)
783 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
784 }
785
786 return false;
787}
788
789static bool isFunctionOrVarDeclExternC(const NamedDecl *ND) {
790 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
791 return FD->isExternC();
792 return cast<VarDecl>(ND)->isExternC();
793}
794
795/// Determine whether ND is an external-linkage function or variable whose
796/// type has no linkage.
798 // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
799 // because we also want to catch the case where its type has VisibleNoLinkage,
800 // which does not affect the linkage of VD.
801 return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&
804}
805
806/// Obtains a sorted list of functions and variables that are undefined but
807/// ODR-used.
809 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
810 for (const auto &UndefinedUse : UndefinedButUsed) {
811 NamedDecl *ND = UndefinedUse.first;
812
813 // Ignore attributes that have become invalid.
814 if (ND->isInvalidDecl()) continue;
815
816 // __attribute__((weakref)) is basically a definition.
817 if (ND->hasAttr<WeakRefAttr>()) continue;
818
819 if (isa<CXXDeductionGuideDecl>(ND))
820 continue;
821
822 if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
823 // An exported function will always be emitted when defined, so even if
824 // the function is inline, it doesn't have to be emitted in this TU. An
825 // imported function implies that it has been exported somewhere else.
826 continue;
827 }
828
829 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
830 if (FD->isDefined())
831 continue;
832 if (FD->isExternallyVisible() &&
834 !FD->getMostRecentDecl()->isInlined() &&
835 !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
836 continue;
837 if (FD->getBuiltinID())
838 continue;
839 } else {
840 auto *VD = cast<VarDecl>(ND);
841 if (VD->hasDefinition() != VarDecl::DeclarationOnly)
842 continue;
843 if (VD->isExternallyVisible() &&
845 !VD->getMostRecentDecl()->isInline() &&
846 !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
847 continue;
848
849 // Skip VarDecls that lack formal definitions but which we know are in
850 // fact defined somewhere.
851 if (VD->isKnownToBeDefined())
852 continue;
853 }
854
855 Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
856 }
857}
858
859/// checkUndefinedButUsed - Check for undefined objects with internal linkage
860/// or that are inline.
862 if (S.UndefinedButUsed.empty()) return;
863
864 // Collect all the still-undefined entities with internal linkage.
866 S.getUndefinedButUsed(Undefined);
867 if (Undefined.empty()) return;
868
869 for (const auto &Undef : Undefined) {
870 ValueDecl *VD = cast<ValueDecl>(Undef.first);
871 SourceLocation UseLoc = Undef.second;
872
873 if (S.isExternalWithNoLinkageType(VD)) {
874 // C++ [basic.link]p8:
875 // A type without linkage shall not be used as the type of a variable
876 // or function with external linkage unless
877 // -- the entity has C language linkage
878 // -- the entity is not odr-used or is defined in the same TU
879 //
880 // As an extension, accept this in cases where the type is externally
881 // visible, since the function or variable actually can be defined in
882 // another translation unit in that case.
884 ? diag::ext_undefined_internal_type
885 : diag::err_undefined_internal_type)
886 << isa<VarDecl>(VD) << VD;
887 } else if (!VD->isExternallyVisible()) {
888 // FIXME: We can promote this to an error. The function or variable can't
889 // be defined anywhere else, so the program must necessarily violate the
890 // one definition rule.
891 bool IsImplicitBase = false;
892 if (const auto *BaseD = dyn_cast<FunctionDecl>(VD)) {
893 auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>();
894 if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive(
895 llvm::omp::TraitProperty::
896 implementation_extension_disable_implicit_base)) {
897 const auto *Func = cast<FunctionDecl>(
898 cast<DeclRefExpr>(DVAttr->getVariantFuncRef())->getDecl());
899 IsImplicitBase = BaseD->isImplicit() &&
900 Func->getIdentifier()->isMangledOpenMPVariantName();
901 }
902 }
903 if (!S.getLangOpts().OpenMP || !IsImplicitBase)
904 S.Diag(VD->getLocation(), diag::warn_undefined_internal)
905 << isa<VarDecl>(VD) << VD;
906 } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
907 (void)FD;
908 assert(FD->getMostRecentDecl()->isInlined() &&
909 "used object requires definition but isn't inline or internal?");
910 // FIXME: This is ill-formed; we should reject.
911 S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
912 } else {
913 assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
914 "used var requires definition but isn't inline or internal?");
915 S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
916 }
917 if (UseLoc.isValid())
918 S.Diag(UseLoc, diag::note_used_here);
919 }
920
921 S.UndefinedButUsed.clear();
922}
923
925 if (!ExternalSource)
926 return;
927
929 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
930 for (auto &WeakID : WeakIDs)
931 (void)WeakUndeclaredIdentifiers[WeakID.first].insert(WeakID.second);
932}
933
934
935typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
936
937/// Returns true, if all methods and nested classes of the given
938/// CXXRecordDecl are defined in this translation unit.
939///
940/// Should only be called from ActOnEndOfTranslationUnit so that all
941/// definitions are actually read.
943 RecordCompleteMap &MNCComplete) {
944 RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
945 if (Cache != MNCComplete.end())
946 return Cache->second;
947 if (!RD->isCompleteDefinition())
948 return false;
949 bool Complete = true;
951 E = RD->decls_end();
952 I != E && Complete; ++I) {
953 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
954 Complete = M->isDefined() || M->isDefaulted() ||
955 (M->isPure() && !isa<CXXDestructorDecl>(M));
956 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
957 // If the template function is marked as late template parsed at this
958 // point, it has not been instantiated and therefore we have not
959 // performed semantic analysis on it yet, so we cannot know if the type
960 // can be considered complete.
961 Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
962 F->getTemplatedDecl()->isDefined();
963 else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
964 if (R->isInjectedClassName())
965 continue;
966 if (R->hasDefinition())
967 Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
968 MNCComplete);
969 else
970 Complete = false;
971 }
972 }
973 MNCComplete[RD] = Complete;
974 return Complete;
975}
976
977/// Returns true, if the given CXXRecordDecl is fully defined in this
978/// translation unit, i.e. all methods are defined or pure virtual and all
979/// friends, friend functions and nested classes are fully defined in this
980/// translation unit.
981///
982/// Should only be called from ActOnEndOfTranslationUnit so that all
983/// definitions are actually read.
985 RecordCompleteMap &RecordsComplete,
986 RecordCompleteMap &MNCComplete) {
987 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
988 if (Cache != RecordsComplete.end())
989 return Cache->second;
990 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
992 E = RD->friend_end();
993 I != E && Complete; ++I) {
994 // Check if friend classes and methods are complete.
995 if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
996 // Friend classes are available as the TypeSourceInfo of the FriendDecl.
997 if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
998 Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
999 else
1000 Complete = false;
1001 } else {
1002 // Friend functions are available through the NamedDecl of FriendDecl.
1003 if (const FunctionDecl *FD =
1004 dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
1005 Complete = FD->isDefined();
1006 else
1007 // This is a template friend, give up.
1008 Complete = false;
1009 }
1010 }
1011 RecordsComplete[RD] = Complete;
1012 return Complete;
1013}
1014
1016 if (ExternalSource)
1017 ExternalSource->ReadUnusedLocalTypedefNameCandidates(
1020 if (TD->isReferenced())
1021 continue;
1022 Diag(TD->getLocation(), diag::warn_unused_local_typedef)
1023 << isa<TypeAliasDecl>(TD) << TD->getDeclName();
1024 }
1026}
1027
1028/// This is called before the very first declaration in the translation unit
1029/// is parsed. Note that the ASTContext may have already injected some
1030/// declarations.
1032 if (getLangOpts().CPlusPlusModules &&
1033 getLangOpts().getCompilingModule() == LangOptions::CMK_HeaderUnit)
1034 HandleStartOfHeaderUnit();
1035}
1036
1038 // No explicit actions are required at the end of the global module fragment.
1039 if (Kind == TUFragmentKind::Global)
1040 return;
1041
1042 // Transfer late parsed template instantiations over to the pending template
1043 // instantiation list. During normal compilation, the late template parser
1044 // will be installed and instantiating these templates will succeed.
1045 //
1046 // If we are building a TU prefix for serialization, it is also safe to
1047 // transfer these over, even though they are not parsed. The end of the TU
1048 // should be outside of any eager template instantiation scope, so when this
1049 // AST is deserialized, these templates will not be parsed until the end of
1050 // the combined TU.
1055
1056 // If DefinedUsedVTables ends up marking any virtual member functions it
1057 // might lead to more pending template instantiations, which we then need
1058 // to instantiate.
1060
1061 // C++: Perform implicit template instantiations.
1062 //
1063 // FIXME: When we perform these implicit instantiations, we do not
1064 // carefully keep track of the point of instantiation (C++ [temp.point]).
1065 // This means that name lookup that occurs within the template
1066 // instantiation will always happen at the end of the translation unit,
1067 // so it will find some names that are not required to be found. This is
1068 // valid, but we could do better by diagnosing if an instantiation uses a
1069 // name that was not visible at its first point of instantiation.
1070 if (ExternalSource) {
1071 // Load pending instantiations from the external source.
1073 ExternalSource->ReadPendingInstantiations(Pending);
1074 for (auto PII : Pending)
1075 if (auto Func = dyn_cast<FunctionDecl>(PII.first))
1076 Func->setInstantiationIsPending(true);
1078 Pending.begin(), Pending.end());
1079 }
1080
1081 {
1082 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1084 }
1085
1087
1088 assert(LateParsedInstantiations.empty() &&
1089 "end of TU template instantiation should not create more "
1090 "late-parsed templates");
1091
1092 // Report diagnostics for uncorrected delayed typos. Ideally all of them
1093 // should have been corrected by that time, but it is very hard to cover all
1094 // cases in practice.
1095 for (const auto &Typo : DelayedTypos) {
1096 // We pass an empty TypoCorrection to indicate no correction was performed.
1097 Typo.second.DiagHandler(TypoCorrection());
1098 }
1099 DelayedTypos.clear();
1100}
1101
1102/// ActOnEndOfTranslationUnit - This is called at the very end of the
1103/// translation unit when EOF is reached and all but the top-level scope is
1104/// popped.
1106 assert(DelayedDiagnostics.getCurrentPool() == nullptr
1107 && "reached end of translation unit with a pool attached?");
1108
1109 // If code completion is enabled, don't perform any end-of-translation-unit
1110 // work.
1112 return;
1113
1114 // Complete translation units and modules define vtables and perform implicit
1115 // instantiations. PCH files do not.
1116 if (TUKind != TU_Prefix) {
1118
1120 !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1124
1127
1129 } else {
1130 // If we are building a TU prefix for serialization, it is safe to transfer
1131 // these over, even though they are not parsed. The end of the TU should be
1132 // outside of any eager template instantiation scope, so when this AST is
1133 // deserialized, these templates will not be parsed until the end of the
1134 // combined TU.
1139
1140 if (LangOpts.PCHInstantiateTemplates) {
1141 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1143 }
1144 }
1145
1149
1150 // All delayed member exception specs should be checked or we end up accepting
1151 // incompatible declarations.
1154
1155 // All dllexport classes should have been processed already.
1156 assert(DelayedDllExportClasses.empty());
1157 assert(DelayedDllExportMemberFunctions.empty());
1158
1159 // Remove file scoped decls that turned out to be used.
1161 std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
1163 [this](const DeclaratorDecl *DD) {
1164 return ShouldRemoveFromUnused(this, DD);
1165 }),
1167
1168 if (TUKind == TU_Prefix) {
1169 // Translation unit prefixes don't need any of the checking below.
1171 TUScope = nullptr;
1172 return;
1173 }
1174
1175 // Check for #pragma weak identifiers that were never declared
1177 for (const auto &WeakIDs : WeakUndeclaredIdentifiers) {
1178 if (WeakIDs.second.empty())
1179 continue;
1180
1181 Decl *PrevDecl = LookupSingleName(TUScope, WeakIDs.first, SourceLocation(),
1183 if (PrevDecl != nullptr &&
1184 !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
1185 for (const auto &WI : WeakIDs.second)
1186 Diag(WI.getLocation(), diag::warn_attribute_wrong_decl_type)
1187 << "'weak'" << /*isRegularKeyword=*/0 << ExpectedVariableOrFunction;
1188 else
1189 for (const auto &WI : WeakIDs.second)
1190 Diag(WI.getLocation(), diag::warn_weak_identifier_undeclared)
1191 << WeakIDs.first;
1192 }
1193
1194 if (LangOpts.CPlusPlus11 &&
1195 !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
1197
1198 if (!Diags.hasErrorOccurred()) {
1199 if (ExternalSource)
1200 ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
1201 checkUndefinedButUsed(*this);
1202 }
1203
1204 // A global-module-fragment is only permitted within a module unit.
1205 bool DiagnosedMissingModuleDeclaration = false;
1206 if (!ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1208 Diag(ModuleScopes.back().BeginLoc,
1209 diag::err_module_declaration_missing_after_global_module_introducer);
1210 DiagnosedMissingModuleDeclaration = true;
1211 }
1212
1213 if (TUKind == TU_Module) {
1214 // If we are building a module interface unit, we need to have seen the
1215 // module declaration by now.
1216 if (getLangOpts().getCompilingModule() ==
1218 !isCurrentModulePurview() && !DiagnosedMissingModuleDeclaration) {
1219 // FIXME: Make a better guess as to where to put the module declaration.
1220 Diag(getSourceManager().getLocForStartOfFile(
1221 getSourceManager().getMainFileID()),
1222 diag::err_module_declaration_missing);
1223 }
1224
1225 // If we are building a module, resolve all of the exported declarations
1226 // now.
1227 if (Module *CurrentModule = PP.getCurrentModule()) {
1229
1231 Stack.push_back(CurrentModule);
1232 while (!Stack.empty()) {
1233 Module *Mod = Stack.pop_back_val();
1234
1235 // Resolve the exported declarations and conflicts.
1236 // FIXME: Actually complain, once we figure out how to teach the
1237 // diagnostic client to deal with complaints in the module map at this
1238 // point.
1239 ModMap.resolveExports(Mod, /*Complain=*/false);
1240 ModMap.resolveUses(Mod, /*Complain=*/false);
1241 ModMap.resolveConflicts(Mod, /*Complain=*/false);
1242
1243 // Queue the submodules, so their exports will also be resolved.
1244 auto SubmodulesRange = Mod->submodules();
1245 Stack.append(SubmodulesRange.begin(), SubmodulesRange.end());
1246 }
1247 }
1248
1249 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
1250 // modules when they are built, not every time they are used.
1252 }
1253
1254 // C++ standard modules. Diagnose cases where a function is declared inline
1255 // in the module purview but has no definition before the end of the TU or
1256 // the start of a Private Module Fragment (if one is present).
1257 if (!PendingInlineFuncDecls.empty()) {
1258 for (auto *D : PendingInlineFuncDecls) {
1259 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1260 bool DefInPMF = false;
1261 if (auto *FDD = FD->getDefinition()) {
1262 assert(FDD->getOwningModule() &&
1263 FDD->getOwningModule()->isModulePurview());
1264 DefInPMF = FDD->getOwningModule()->isPrivateModule();
1265 if (!DefInPMF)
1266 continue;
1267 }
1268 Diag(FD->getLocation(), diag::err_export_inline_not_defined)
1269 << DefInPMF;
1270 // If we have a PMF it should be at the end of the ModuleScopes.
1271 if (DefInPMF &&
1272 ModuleScopes.back().Module->Kind == Module::PrivateModuleFragment) {
1273 Diag(ModuleScopes.back().BeginLoc,
1274 diag::note_private_module_fragment);
1275 }
1276 }
1277 }
1278 PendingInlineFuncDecls.clear();
1279 }
1280
1281 // C99 6.9.2p2:
1282 // A declaration of an identifier for an object that has file
1283 // scope without an initializer, and without a storage-class
1284 // specifier or with the storage-class specifier static,
1285 // constitutes a tentative definition. If a translation unit
1286 // contains one or more tentative definitions for an identifier,
1287 // and the translation unit contains no external definition for
1288 // that identifier, then the behavior is exactly as if the
1289 // translation unit contains a file scope declaration of that
1290 // identifier, with the composite type as of the end of the
1291 // translation unit, with an initializer equal to 0.
1292 llvm::SmallSet<VarDecl *, 32> Seen;
1293 for (TentativeDefinitionsType::iterator
1294 T = TentativeDefinitions.begin(ExternalSource.get()),
1295 TEnd = TentativeDefinitions.end();
1296 T != TEnd; ++T) {
1297 VarDecl *VD = (*T)->getActingDefinition();
1298
1299 // If the tentative definition was completed, getActingDefinition() returns
1300 // null. If we've already seen this variable before, insert()'s second
1301 // return value is false.
1302 if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
1303 continue;
1304
1305 if (const IncompleteArrayType *ArrayT
1307 // Set the length of the array to 1 (C99 6.9.2p5).
1308 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
1309 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
1310 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), One,
1311 nullptr, ArrayType::Normal, 0);
1312 VD->setType(T);
1313 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
1314 diag::err_tentative_def_incomplete_type))
1315 VD->setInvalidDecl();
1316
1317 // No initialization is performed for a tentative definition.
1319
1320 // Notify the consumer that we've completed a tentative definition.
1321 if (!VD->isInvalidDecl())
1323 }
1324
1325 for (auto *D : ExternalDeclarations) {
1326 if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed())
1327 continue;
1328
1330 }
1331
1332 // If there were errors, disable 'unused' warnings since they will mostly be
1333 // noise. Don't warn for a use from a module: either we should warn on all
1334 // file-scope declarations in modules or not at all, but whether the
1335 // declaration is used is immaterial.
1336 if (!Diags.hasErrorOccurred() && TUKind != TU_Module) {
1337 // Output warning for unused file scoped decls.
1338 for (UnusedFileScopedDeclsType::iterator
1339 I = UnusedFileScopedDecls.begin(ExternalSource.get()),
1341 I != E; ++I) {
1342 if (ShouldRemoveFromUnused(this, *I))
1343 continue;
1344
1345 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1346 const FunctionDecl *DiagD;
1347 if (!FD->hasBody(DiagD))
1348 DiagD = FD;
1349 if (DiagD->isDeleted())
1350 continue; // Deleted functions are supposed to be unused.
1351 if (DiagD->isReferenced()) {
1352 if (isa<CXXMethodDecl>(DiagD))
1353 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
1354 << DiagD;
1355 else {
1356 if (FD->getStorageClass() == SC_Static &&
1357 !FD->isInlineSpecified() &&
1359 SourceMgr.getExpansionLoc(FD->getLocation())))
1360 Diag(DiagD->getLocation(),
1361 diag::warn_unneeded_static_internal_decl)
1362 << DiagD;
1363 else
1364 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1365 << /*function*/ 0 << DiagD;
1366 }
1367 } else {
1368 if (FD->getDescribedFunctionTemplate())
1369 Diag(DiagD->getLocation(), diag::warn_unused_template)
1370 << /*function*/ 0 << DiagD;
1371 else
1372 Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD)
1373 ? diag::warn_unused_member_function
1374 : diag::warn_unused_function)
1375 << DiagD;
1376 }
1377 } else {
1378 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
1379 if (!DiagD)
1380 DiagD = cast<VarDecl>(*I);
1381 if (DiagD->isReferenced()) {
1382 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1383 << /*variable*/ 1 << DiagD;
1384 } else if (DiagD->getType().isConstQualified()) {
1385 const SourceManager &SM = SourceMgr;
1386 if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
1388 Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
1389 << DiagD;
1390 } else {
1391 if (DiagD->getDescribedVarTemplate())
1392 Diag(DiagD->getLocation(), diag::warn_unused_template)
1393 << /*variable*/ 1 << DiagD;
1394 else
1395 Diag(DiagD->getLocation(), diag::warn_unused_variable) << DiagD;
1396 }
1397 }
1398 }
1399
1401 }
1402
1403 if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
1404 // FIXME: Load additional unused private field candidates from the external
1405 // source.
1406 RecordCompleteMap RecordsComplete;
1407 RecordCompleteMap MNCComplete;
1408 for (const NamedDecl *D : UnusedPrivateFields) {
1409 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1410 if (RD && !RD->isUnion() &&
1411 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
1412 Diag(D->getLocation(), diag::warn_unused_private_field)
1413 << D->getDeclName();
1414 }
1415 }
1416 }
1417
1418 if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
1419 if (ExternalSource)
1420 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
1421 for (const auto &DeletedFieldInfo : DeleteExprs) {
1422 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
1423 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
1424 DeleteExprLoc.second);
1425 }
1426 }
1427 }
1428
1430
1431 // Check we've noticed that we're no longer parsing the initializer for every
1432 // variable. If we miss cases, then at best we have a performance issue and
1433 // at worst a rejects-valid bug.
1434 assert(ParsingInitForAutoVars.empty() &&
1435 "Didn't unmark var as having its initializer parsed");
1436
1438 TUScope = nullptr;
1439}
1440
1441
1442//===----------------------------------------------------------------------===//
1443// Helper functions.
1444//===----------------------------------------------------------------------===//
1445
1447 DeclContext *DC = CurContext;
1448
1449 while (true) {
1450 if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC) ||
1451 isa<RequiresExprBodyDecl>(DC)) {
1452 DC = DC->getParent();
1453 } else if (!AllowLambda && isa<CXXMethodDecl>(DC) &&
1454 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
1455 cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
1456 DC = DC->getParent()->getParent();
1457 } else break;
1458 }
1459
1460 return DC;
1461}
1462
1463/// getCurFunctionDecl - If inside of a function body, this returns a pointer
1464/// to the function decl for the function being parsed. If we're currently
1465/// in a 'block', this returns the containing context.
1466FunctionDecl *Sema::getCurFunctionDecl(bool AllowLambda) const {
1467 DeclContext *DC = getFunctionLevelDeclContext(AllowLambda);
1468 return dyn_cast<FunctionDecl>(DC);
1469}
1470
1473 while (isa<RecordDecl>(DC))
1474 DC = DC->getParent();
1475 return dyn_cast<ObjCMethodDecl>(DC);
1476}
1477
1480 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
1481 return cast<NamedDecl>(DC);
1482 return nullptr;
1483}
1484
1486 if (getLangOpts().OpenCL)
1488 return LangAS::Default;
1489}
1490
1491void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
1492 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1493 // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1494 // been made more painfully obvious by the refactor that introduced this
1495 // function, but it is possible that the incoming argument can be
1496 // eliminated. If it truly cannot be (for example, there is some reentrancy
1497 // issue I am not seeing yet), then there should at least be a clarifying
1498 // comment somewhere.
1499 if (std::optional<TemplateDeductionInfo *> Info = isSFINAEContext()) {
1503 // We'll report the diagnostic below.
1504 break;
1505
1507 // Count this failure so that we know that template argument deduction
1508 // has failed.
1510
1511 // Make a copy of this suppressed diagnostic and store it with the
1512 // template-deduction information.
1513 if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1514 Diagnostic DiagInfo(&Diags);
1515 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1517 }
1518
1520 Diags.Clear();
1521 return;
1522
1524 // Per C++ Core Issue 1170, access control is part of SFINAE.
1525 // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
1526 // make access control a part of SFINAE for the purposes of checking
1527 // type traits.
1529 break;
1530
1532
1533 // Suppress this diagnostic.
1535
1536 // Make a copy of this suppressed diagnostic and store it with the
1537 // template-deduction information.
1538 if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1539 Diagnostic DiagInfo(&Diags);
1540 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1542 }
1543
1545 Diags.Clear();
1546
1547 // Now the diagnostic state is clear, produce a C++98 compatibility
1548 // warning.
1549 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1550
1551 // The last diagnostic which Sema produced was ignored. Suppress any
1552 // notes attached to it.
1554 return;
1555 }
1556
1558 // Make a copy of this suppressed diagnostic and store it with the
1559 // template-deduction information;
1560 if (*Info) {
1561 Diagnostic DiagInfo(&Diags);
1562 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1564 }
1565
1566 // Suppress this diagnostic.
1568 Diags.Clear();
1569 return;
1570 }
1571 }
1572
1573 // Copy the diagnostic printing policy over the ASTContext printing policy.
1574 // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292
1576
1577 // Emit the diagnostic.
1579 return;
1580
1581 // If this is not a note, and we're in a template instantiation
1582 // that is different from the last template instantiation where
1583 // we emitted an error, print a template instantiation
1584 // backtrace.
1585 if (!DiagnosticIDs::isBuiltinNote(DiagID))
1587}
1588
1590Sema::Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint) {
1591 return Diag(Loc, PD.getDiagID(), DeferHint) << PD;
1592}
1593
1596 return true;
1597 auto *FD = dyn_cast<FunctionDecl>(CurContext);
1598 if (!FD)
1599 return false;
1600 auto Loc = DeviceDeferredDiags.find(FD);
1601 if (Loc == DeviceDeferredDiags.end())
1602 return false;
1603 for (auto PDAt : Loc->second) {
1604 if (DiagnosticIDs::isDefaultMappingAsError(PDAt.second.getDiagID()))
1605 return true;
1606 }
1607 return false;
1608}
1609
1610// Print notes showing how we can reach FD starting from an a priori
1611// known-callable function.
1612static void emitCallStackNotes(Sema &S, const FunctionDecl *FD) {
1613 auto FnIt = S.DeviceKnownEmittedFns.find(FD);
1614 while (FnIt != S.DeviceKnownEmittedFns.end()) {
1615 // Respect error limit.
1617 return;
1618 DiagnosticBuilder Builder(
1619 S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
1620 Builder << FnIt->second.FD;
1621 FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD);
1622 }
1623}
1624
1625namespace {
1626
1627/// Helper class that emits deferred diagnostic messages if an entity directly
1628/// or indirectly using the function that causes the deferred diagnostic
1629/// messages is known to be emitted.
1630///
1631/// During parsing of AST, certain diagnostic messages are recorded as deferred
1632/// diagnostics since it is unknown whether the functions containing such
1633/// diagnostics will be emitted. A list of potentially emitted functions and
1634/// variables that may potentially trigger emission of functions are also
1635/// recorded. DeferredDiagnosticsEmitter recursively visits used functions
1636/// by each function to emit deferred diagnostics.
1637///
1638/// During the visit, certain OpenMP directives or initializer of variables
1639/// with certain OpenMP attributes will cause subsequent visiting of any
1640/// functions enter a state which is called OpenMP device context in this
1641/// implementation. The state is exited when the directive or initializer is
1642/// exited. This state can change the emission states of subsequent uses
1643/// of functions.
1644///
1645/// Conceptually the functions or variables to be visited form a use graph
1646/// where the parent node uses the child node. At any point of the visit,
1647/// the tree nodes traversed from the tree root to the current node form a use
1648/// stack. The emission state of the current node depends on two factors:
1649/// 1. the emission state of the root node
1650/// 2. whether the current node is in OpenMP device context
1651/// If the function is decided to be emitted, its contained deferred diagnostics
1652/// are emitted, together with the information about the use stack.
1653///
1654class DeferredDiagnosticsEmitter
1655 : public UsedDeclVisitor<DeferredDiagnosticsEmitter> {
1656public:
1658
1659 // Whether the function is already in the current use-path.
1661
1662 // The current use-path.
1664
1665 // Whether the visiting of the function has been done. Done[0] is for the
1666 // case not in OpenMP device context. Done[1] is for the case in OpenMP
1667 // device context. We need two sets because diagnostics emission may be
1668 // different depending on whether it is in OpenMP device context.
1670
1671 // Emission state of the root node of the current use graph.
1672 bool ShouldEmitRootNode;
1673
1674 // Current OpenMP device context level. It is initialized to 0 and each
1675 // entering of device context increases it by 1 and each exit decreases
1676 // it by 1. Non-zero value indicates it is currently in device context.
1677 unsigned InOMPDeviceContext;
1678
1679 DeferredDiagnosticsEmitter(Sema &S)
1680 : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
1681
1682 bool shouldVisitDiscardedStmt() const { return false; }
1683
1684 void VisitOMPTargetDirective(OMPTargetDirective *Node) {
1685 ++InOMPDeviceContext;
1686 Inherited::VisitOMPTargetDirective(Node);
1687 --InOMPDeviceContext;
1688 }
1689
1690 void visitUsedDecl(SourceLocation Loc, Decl *D) {
1691 if (isa<VarDecl>(D))
1692 return;
1693 if (auto *FD = dyn_cast<FunctionDecl>(D))
1694 checkFunc(Loc, FD);
1695 else
1696 Inherited::visitUsedDecl(Loc, D);
1697 }
1698
1699 void checkVar(VarDecl *VD) {
1700 assert(VD->isFileVarDecl() &&
1701 "Should only check file-scope variables");
1702 if (auto *Init = VD->getInit()) {
1703 auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);
1704 bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
1705 *DevTy == OMPDeclareTargetDeclAttr::DT_Any);
1706 if (IsDev)
1707 ++InOMPDeviceContext;
1708 this->Visit(Init);
1709 if (IsDev)
1710 --InOMPDeviceContext;
1711 }
1712 }
1713
1714 void checkFunc(SourceLocation Loc, FunctionDecl *FD) {
1715 auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0];
1716 FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back();
1717 if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) ||
1718 S.shouldIgnoreInHostDeviceCheck(FD) || InUsePath.count(FD))
1719 return;
1720 // Finalize analysis of OpenMP-specific constructs.
1721 if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 &&
1722 (ShouldEmitRootNode || InOMPDeviceContext))
1723 S.finalizeOpenMPDelayedAnalysis(Caller, FD, Loc);
1724 if (Caller)
1725 S.DeviceKnownEmittedFns[FD] = {Caller, Loc};
1726 // Always emit deferred diagnostics for the direct users. This does not
1727 // lead to explosion of diagnostics since each user is visited at most
1728 // twice.
1729 if (ShouldEmitRootNode || InOMPDeviceContext)
1730 emitDeferredDiags(FD, Caller);
1731 // Do not revisit a function if the function body has been completely
1732 // visited before.
1733 if (!Done.insert(FD).second)
1734 return;
1735 InUsePath.insert(FD);
1736 UsePath.push_back(FD);
1737 if (auto *S = FD->getBody()) {
1738 this->Visit(S);
1739 }
1740 UsePath.pop_back();
1741 InUsePath.erase(FD);
1742 }
1743
1744 void checkRecordedDecl(Decl *D) {
1745 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1746 ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) ==
1747 Sema::FunctionEmissionStatus::Emitted;
1748 checkFunc(SourceLocation(), FD);
1749 } else
1750 checkVar(cast<VarDecl>(D));
1751 }
1752
1753 // Emit any deferred diagnostics for FD
1754 void emitDeferredDiags(FunctionDecl *FD, bool ShowCallStack) {
1755 auto It = S.DeviceDeferredDiags.find(FD);
1756 if (It == S.DeviceDeferredDiags.end())
1757 return;
1758 bool HasWarningOrError = false;
1759 bool FirstDiag = true;
1760 for (PartialDiagnosticAt &PDAt : It->second) {
1761 // Respect error limit.
1763 return;
1764 const SourceLocation &Loc = PDAt.first;
1765 const PartialDiagnostic &PD = PDAt.second;
1766 HasWarningOrError |=
1769 {
1770 DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
1771 PD.Emit(Builder);
1772 }
1773 // Emit the note on the first diagnostic in case too many diagnostics
1774 // cause the note not emitted.
1775 if (FirstDiag && HasWarningOrError && ShowCallStack) {
1776 emitCallStackNotes(S, FD);
1777 FirstDiag = false;
1778 }
1779 }
1780 }
1781};
1782} // namespace
1783
1785 if (ExternalSource)
1786 ExternalSource->ReadDeclsToCheckForDeferredDiags(
1787 DeclsToCheckForDeferredDiags);
1788
1789 if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) ||
1790 DeclsToCheckForDeferredDiags.empty())
1791 return;
1792
1793 DeferredDiagnosticsEmitter DDE(*this);
1794 for (auto *D : DeclsToCheckForDeferredDiags)
1795 DDE.checkRecordedDecl(D);
1796}
1797
1798// In CUDA, there are some constructs which may appear in semantically-valid
1799// code, but trigger errors if we ever generate code for the function in which
1800// they appear. Essentially every construct you're not allowed to use on the
1801// device falls into this category, because you are allowed to use these
1802// constructs in a __host__ __device__ function, but only if that function is
1803// never codegen'ed on the device.
1804//
1805// To handle semantic checking for these constructs, we keep track of the set of
1806// functions we know will be emitted, either because we could tell a priori that
1807// they would be emitted, or because they were transitively called by a
1808// known-emitted function.
1809//
1810// We also keep a partial call graph of which not-known-emitted functions call
1811// which other not-known-emitted functions.
1812//
1813// When we see something which is illegal if the current function is emitted
1814// (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
1815// CheckCUDACall), we first check if the current function is known-emitted. If
1816// so, we immediately output the diagnostic.
1817//
1818// Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags
1819// until we discover that the function is known-emitted, at which point we take
1820// it out of this map and emit the diagnostic.
1821
1823 unsigned DiagID,
1824 const FunctionDecl *Fn,
1825 Sema &S)
1826 : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
1827 ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
1828 switch (K) {
1829 case K_Nop:
1830 break;
1831 case K_Immediate:
1833 ImmediateDiag.emplace(
1834 ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID));
1835 break;
1836 case K_Deferred:
1837 assert(Fn && "Must have a function to attach the deferred diag to.");
1838 auto &Diags = S.DeviceDeferredDiags[Fn];
1839 PartialDiagId.emplace(Diags.size());
1840 Diags.emplace_back(Loc, S.PDiag(DiagID));
1841 break;
1842 }
1843}
1844
1846 : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
1847 ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
1848 PartialDiagId(D.PartialDiagId) {
1849 // Clean the previous diagnostics.
1850 D.ShowCallStack = false;
1851 D.ImmediateDiag.reset();
1852 D.PartialDiagId.reset();
1853}
1854
1856 if (ImmediateDiag) {
1857 // Emit our diagnostic and, if it was a warning or error, output a callstack
1858 // if Fn isn't a priori known-emitted.
1859 bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
1860 DiagID, Loc) >= DiagnosticsEngine::Warning;
1861 ImmediateDiag.reset(); // Emit the immediate diag.
1862 if (IsWarningOrError && ShowCallStack)
1863 emitCallStackNotes(S, Fn);
1864 } else {
1865 assert((!PartialDiagId || ShowCallStack) &&
1866 "Must always show call stack for deferred diags.");
1867 }
1868}
1869
1871Sema::targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD) {
1872 FD = FD ? FD : getCurFunctionDecl();
1873 if (LangOpts.OpenMP)
1874 return LangOpts.OpenMPIsDevice ? diagIfOpenMPDeviceCode(Loc, DiagID, FD)
1875 : diagIfOpenMPHostCode(Loc, DiagID, FD);
1876 if (getLangOpts().CUDA)
1877 return getLangOpts().CUDAIsDevice ? CUDADiagIfDeviceCode(Loc, DiagID)
1878 : CUDADiagIfHostCode(Loc, DiagID);
1879
1880 if (getLangOpts().SYCLIsDevice)
1881 return SYCLDiagIfDeviceCode(Loc, DiagID);
1882
1884 FD, *this);
1885}
1886
1888 bool DeferHint) {
1889 bool IsError = Diags.getDiagnosticIDs()->isDefaultMappingAsError(DiagID);
1890 bool ShouldDefer = getLangOpts().CUDA && LangOpts.GPUDeferDiag &&
1892 (DeferHint || DeferDiags || !IsError);
1893 auto SetIsLastErrorImmediate = [&](bool Flag) {
1894 if (IsError)
1895 IsLastErrorImmediate = Flag;
1896 };
1897 if (!ShouldDefer) {
1898 SetIsLastErrorImmediate(true);
1900 DiagID, getCurFunctionDecl(), *this);
1901 }
1902
1903 SemaDiagnosticBuilder DB = getLangOpts().CUDAIsDevice
1904 ? CUDADiagIfDeviceCode(Loc, DiagID)
1905 : CUDADiagIfHostCode(Loc, DiagID);
1906 SetIsLastErrorImmediate(DB.isImmediate());
1907 return DB;
1908}
1909
1911 if (isUnevaluatedContext() || Ty.isNull())
1912 return;
1913
1914 // The original idea behind checkTypeSupport function is that unused
1915 // declarations can be replaced with an array of bytes of the same size during
1916 // codegen, such replacement doesn't seem to be possible for types without
1917 // constant byte size like zero length arrays. So, do a deep check for SYCL.
1918 if (D && LangOpts.SYCLIsDevice) {
1921 }
1922
1923 Decl *C = cast<Decl>(getCurLexicalContext());
1924
1925 // Memcpy operations for structs containing a member with unsupported type
1926 // are ok, though.
1927 if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) {
1928 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
1929 MD->isTrivial())
1930 return;
1931
1932 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD))
1933 if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial())
1934 return;
1935 }
1936
1937 // Try to associate errors with the lexical context, if that is a function, or
1938 // the value declaration otherwise.
1939 const FunctionDecl *FD = isa<FunctionDecl>(C)
1940 ? cast<FunctionDecl>(C)
1941 : dyn_cast_or_null<FunctionDecl>(D);
1942
1943 auto CheckDeviceType = [&](QualType Ty) {
1944 if (Ty->isDependentType())
1945 return;
1946
1947 if (Ty->isBitIntType()) {
1949 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
1950 if (D)
1951 PD << D;
1952 else
1953 PD << "expression";
1954 targetDiag(Loc, PD, FD)
1955 << false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/
1956 << Ty << Context.getTargetInfo().getTriple().str();
1957 }
1958 return;
1959 }
1960
1961 // Check if we are dealing with two 'long double' but with different
1962 // semantics.
1963 bool LongDoubleMismatched = false;
1964 if (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128) {
1965 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(Ty);
1966 if ((&Sem != &llvm::APFloat::PPCDoubleDouble() &&
1968 (&Sem == &llvm::APFloat::PPCDoubleDouble() &&
1970 LongDoubleMismatched = true;
1971 }
1972
1973 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
1976 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1979 !LangOpts.CUDAIsDevice) ||
1980 LongDoubleMismatched) {
1981 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
1982 if (D)
1983 PD << D;
1984 else
1985 PD << "expression";
1986
1987 if (targetDiag(Loc, PD, FD)
1988 << true /*show bit size*/
1989 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1990 << false /*return*/ << Context.getTargetInfo().getTriple().str()) {
1991 if (D)
1992 D->setInvalidDecl();
1993 }
1994 if (D)
1995 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
1996 }
1997 };
1998
1999 auto CheckType = [&](QualType Ty, bool IsRetTy = false) {
2000 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice) ||
2001 LangOpts.CUDAIsDevice)
2002 CheckDeviceType(Ty);
2003
2005 const TargetInfo &TI = Context.getTargetInfo();
2006 if (!TI.hasLongDoubleType() && UnqualTy == Context.LongDoubleTy) {
2007 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2008 if (D)
2009 PD << D;
2010 else
2011 PD << "expression";
2012
2013 if (Diag(Loc, PD, FD)
2014 << false /*show bit size*/ << 0 << Ty << false /*return*/
2015 << TI.getTriple().str()) {
2016 if (D)
2017 D->setInvalidDecl();
2018 }
2019 if (D)
2020 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2021 }
2022
2023 bool IsDouble = UnqualTy == Context.DoubleTy;
2024 bool IsFloat = UnqualTy == Context.FloatTy;
2025 if (IsRetTy && !TI.hasFPReturn() && (IsDouble || IsFloat)) {
2026 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2027 if (D)
2028 PD << D;
2029 else
2030 PD << "expression";
2031
2032 if (Diag(Loc, PD, FD)
2033 << false /*show bit size*/ << 0 << Ty << true /*return*/
2034 << TI.getTriple().str()) {
2035 if (D)
2036 D->setInvalidDecl();
2037 }
2038 if (D)
2039 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2040 }
2041
2042 // RISC-V vector builtin types (RISCVVTypes.def)
2043 if (Ty->isRVVType(/* Bitwidth */ 64, /* IsFloat */ false) &&
2044 !TI.hasFeature("zve64x"))
2045 Diag(Loc, diag::err_riscv_type_requires_extension, FD) << Ty << "zve64x";
2046 if (Ty->isRVVType(/* Bitwidth */ 16, /* IsFloat */ true) &&
2047 !TI.hasFeature("experimental-zvfh"))
2048 Diag(Loc, diag::err_riscv_type_requires_extension, FD)
2049 << Ty << "zvfh";
2050 if (Ty->isRVVType(/* Bitwidth */ 32, /* IsFloat */ true) &&
2051 !TI.hasFeature("zve32f"))
2052 Diag(Loc, diag::err_riscv_type_requires_extension, FD) << Ty << "zve32f";
2053 if (Ty->isRVVType(/* Bitwidth */ 64, /* IsFloat */ true) &&
2054 !TI.hasFeature("zve64d"))
2055 Diag(Loc, diag::err_riscv_type_requires_extension, FD) << Ty << "zve64d";
2056
2057 // Don't allow SVE types in functions without a SVE target.
2058 if (Ty->isSVESizelessBuiltinType() && FD && FD->hasBody()) {
2059 llvm::StringMap<bool> CallerFeatureMap;
2060 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
2062 "sve", CallerFeatureMap))
2063 Diag(D->getLocation(), diag::err_sve_vector_in_non_sve_target) << Ty;
2064 }
2065 };
2066
2067 CheckType(Ty);
2068 if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
2069 for (const auto &ParamTy : FPTy->param_types())
2070 CheckType(ParamTy);
2071 CheckType(FPTy->getReturnType(), /*IsRetTy=*/true);
2072 }
2073 if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Ty))
2074 CheckType(FNPTy->getReturnType(), /*IsRetTy=*/true);
2075}
2076
2077/// Looks through the macro-expansion chain for the given
2078/// location, looking for a macro expansion with the given name.
2079/// If one is found, returns true and sets the location to that
2080/// expansion loc.
2081bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
2082 SourceLocation loc = locref;
2083 if (!loc.isMacroID()) return false;
2084
2085 // There's no good way right now to look at the intermediate
2086 // expansions, so just jump to the expansion location.
2087 loc = getSourceManager().getExpansionLoc(loc);
2088
2089 // If that's written with the name, stop here.
2090 SmallString<16> buffer;
2091 if (getPreprocessor().getSpelling(loc, buffer) == name) {
2092 locref = loc;
2093 return true;
2094 }
2095 return false;
2096}
2097
2098/// Determines the active Scope associated with the given declaration
2099/// context.
2100///
2101/// This routine maps a declaration context to the active Scope object that
2102/// represents that declaration context in the parser. It is typically used
2103/// from "scope-less" code (e.g., template instantiation, lazy creation of
2104/// declarations) that injects a name for name-lookup purposes and, therefore,
2105/// must update the Scope.
2106///
2107/// \returns The scope corresponding to the given declaraion context, or NULL
2108/// if no such scope is open.
2110
2111 if (!Ctx)
2112 return nullptr;
2113
2114 Ctx = Ctx->getPrimaryContext();
2115 for (Scope *S = getCurScope(); S; S = S->getParent()) {
2116 // Ignore scopes that cannot have declarations. This is important for
2117 // out-of-line definitions of static class members.
2118 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
2119 if (DeclContext *Entity = S->getEntity())
2120 if (Ctx == Entity->getPrimaryContext())
2121 return S;
2122 }
2123
2124 return nullptr;
2125}
2126
2127/// Enter a new function scope
2129 if (FunctionScopes.empty() && CachedFunctionScope) {
2130 // Use CachedFunctionScope to avoid allocating memory when possible.
2131 CachedFunctionScope->Clear();
2132 FunctionScopes.push_back(CachedFunctionScope.release());
2133 } else {
2135 }
2136 if (LangOpts.OpenMP)
2137 pushOpenMPFunctionRegion();
2138}
2139
2142 BlockScope, Block));
2144}
2145
2148 FunctionScopes.push_back(LSI);
2150 return LSI;
2151}
2152
2154 if (LambdaScopeInfo *const LSI = getCurLambda()) {
2155 LSI->AutoTemplateParameterDepth = Depth;
2156 return;
2157 }
2158 llvm_unreachable(
2159 "Remove assertion if intentionally called in a non-lambda context.");
2160}
2161
2162// Check that the type of the VarDecl has an accessible copy constructor and
2163// resolve its destructor's exception specification.
2164// This also performs initialization of block variables when they are moved
2165// to the heap. It uses the same rules as applicable for implicit moves
2166// according to the C++ standard in effect ([class.copy.elision]p3).
2167static void checkEscapingByref(VarDecl *VD, Sema &S) {
2168 QualType T = VD->getType();
2171 SourceLocation Loc = VD->getLocation();
2172 Expr *VarRef =
2173 new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
2175 auto IE = InitializedEntity::InitializeBlock(Loc, T);
2176 if (S.getLangOpts().CPlusPlus23) {
2177 auto *E = ImplicitCastExpr::Create(S.Context, T, CK_NoOp, VarRef, nullptr,
2180 } else {
2183 VarRef);
2184 }
2185
2186 if (!Result.isInvalid()) {
2188 Expr *Init = Result.getAs<Expr>();
2189 S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init));
2190 }
2191
2192 // The destructor's exception specification is needed when IRGen generates
2193 // block copy/destroy functions. Resolve it here.
2194 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2195 if (CXXDestructorDecl *DD = RD->getDestructor()) {
2196 auto *FPT = DD->getType()->getAs<FunctionProtoType>();
2197 S.ResolveExceptionSpec(Loc, FPT);
2198 }
2199}
2200
2201static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
2202 // Set the EscapingByref flag of __block variables captured by
2203 // escaping blocks.
2204 for (const BlockDecl *BD : FSI.Blocks) {
2205 for (const BlockDecl::Capture &BC : BD->captures()) {
2206 VarDecl *VD = BC.getVariable();
2207 if (VD->hasAttr<BlocksAttr>()) {
2208 // Nothing to do if this is a __block variable captured by a
2209 // non-escaping block.
2210 if (BD->doesNotEscape())
2211 continue;
2212 VD->setEscapingByref();
2213 }
2214 // Check whether the captured variable is or contains an object of
2215 // non-trivial C union type.
2216 QualType CapType = BC.getVariable()->getType();
2219 S.checkNonTrivialCUnion(BC.getVariable()->getType(),
2220 BD->getCaretLocation(),
2223 }
2224 }
2225
2226 for (VarDecl *VD : FSI.ByrefBlockVars) {
2227 // __block variables might require us to capture a copy-initializer.
2228 if (!VD->isEscapingByref())
2229 continue;
2230 // It's currently invalid to ever have a __block variable with an
2231 // array type; should we diagnose that here?
2232 // Regardless, we don't want to ignore array nesting when
2233 // constructing this copy.
2234 if (VD->getType()->isStructureOrClassType())
2235 checkEscapingByref(VD, S);
2236 }
2237}
2238
2239/// Pop a function (or block or lambda or captured region) scope from the stack.
2240///
2241/// \param WP The warning policy to use for CFG-based warnings, or null if such
2242/// warnings should not be produced.
2243/// \param D The declaration corresponding to this function scope, if producing
2244/// CFG-based warnings.
2245/// \param BlockType The type of the block expression, if D is a BlockDecl.
2248 const Decl *D, QualType BlockType) {
2249 assert(!FunctionScopes.empty() && "mismatched push/pop!");
2250
2251 markEscapingByrefs(*FunctionScopes.back(), *this);
2252
2255
2256 if (LangOpts.OpenMP)
2257 popOpenMPFunctionRegion(Scope.get());
2258
2259 // Issue any analysis-based warnings.
2260 if (WP && D)
2261 AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
2262 else
2263 for (const auto &PUD : Scope->PossiblyUnreachableDiags)
2264 Diag(PUD.Loc, PUD.PD);
2265
2266 return Scope;
2267}
2268
2271 if (!Scope->isPlainFunction())
2272 Self->CapturingFunctionScopes--;
2273 // Stash the function scope for later reuse if it's for a normal function.
2274 if (Scope->isPlainFunction() && !Self->CachedFunctionScope)
2275 Self->CachedFunctionScope.reset(Scope);
2276 else
2277 delete Scope;
2278}
2279
2280void Sema::PushCompoundScope(bool IsStmtExpr) {
2281 getCurFunction()->CompoundScopes.push_back(
2282 CompoundScopeInfo(IsStmtExpr, getCurFPFeatures()));
2283}
2284
2286 FunctionScopeInfo *CurFunction = getCurFunction();
2287 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
2288
2289 CurFunction->CompoundScopes.pop_back();
2290}
2291
2292/// Determine whether any errors occurred within this function/method/
2293/// block.
2296}
2297
2299 if (!FunctionScopes.empty())
2300 FunctionScopes.back()->setHasBranchIntoScope();
2301}
2302
2304 if (!FunctionScopes.empty())
2305 FunctionScopes.back()->setHasBranchProtectedScope();
2306}
2307
2309 if (!FunctionScopes.empty())
2310 FunctionScopes.back()->setHasIndirectGoto();
2311}
2312
2314 if (!FunctionScopes.empty())
2315 FunctionScopes.back()->setHasMustTail();
2316}
2317
2319 if (FunctionScopes.empty())
2320 return nullptr;
2321
2322 auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
2323 if (CurBSI && CurBSI->TheDecl &&
2324 !CurBSI->TheDecl->Encloses(CurContext)) {
2325 // We have switched contexts due to template instantiation.
2326 assert(!CodeSynthesisContexts.empty());
2327 return nullptr;
2328 }
2329
2330 return CurBSI;
2331}
2332
2334 if (FunctionScopes.empty())
2335 return nullptr;
2336
2337 for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
2338 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
2339 continue;
2340 return FunctionScopes[e];
2341 }
2342 return nullptr;
2343}
2344
2346 for (auto *Scope : llvm::reverse(FunctionScopes)) {
2347 if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope)) {
2348 if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&
2349 LSI->AfterParameterList) {
2350 // We have switched contexts due to template instantiation.
2351 // FIXME: We should swap out the FunctionScopes during code synthesis
2352 // so that we don't need to check for this.
2353 assert(!CodeSynthesisContexts.empty());
2354 return nullptr;
2355 }
2356 return LSI;
2357 }
2358 }
2359 return nullptr;
2360}
2361
2362LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
2363 if (FunctionScopes.empty())
2364 return nullptr;
2365
2366 auto I = FunctionScopes.rbegin();
2367 if (IgnoreNonLambdaCapturingScope) {
2368 auto E = FunctionScopes.rend();
2369 while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
2370 ++I;
2371 if (I == E)
2372 return nullptr;
2373 }
2374 auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
2375 if (CurLSI && CurLSI->Lambda && CurLSI->CallOperator &&
2376 !CurLSI->Lambda->Encloses(CurContext) && CurLSI->AfterParameterList) {
2377 // We have switched contexts due to template instantiation.
2378 assert(!CodeSynthesisContexts.empty());
2379 return nullptr;
2380 }
2381
2382 return CurLSI;
2383}
2384
2385// We have a generic lambda if we parsed auto parameters, or we have
2386// an associated template parameter list.
2388 if (LambdaScopeInfo *LSI = getCurLambda()) {
2389 return (LSI->TemplateParams.size() ||
2390 LSI->GLTemplateParameterList) ? LSI : nullptr;
2391 }
2392 return nullptr;
2393}
2394
2395
2397 if (!LangOpts.RetainCommentsFromSystemHeaders &&
2399 return;
2400 RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
2402 SourceRange MagicMarkerRange(Comment.getBegin(),
2403 Comment.getBegin().getLocWithOffset(3));
2404 StringRef MagicMarkerText;
2405 switch (RC.getKind()) {
2407 MagicMarkerText = "///<";
2408 break;
2410 MagicMarkerText = "/**<";
2411 break;
2413 // FIXME: are there other scenarios that could produce an invalid
2414 // raw comment here?
2415 Diag(Comment.getBegin(), diag::warn_splice_in_doxygen_comment);
2416 return;
2417 default:
2418 llvm_unreachable("if this is an almost Doxygen comment, "
2419 "it should be ordinary");
2420 }
2421 Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
2422 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
2423 }
2424 Context.addComment(RC);
2425}
2426
2427// Pin this vtable to this file.
2429char ExternalSemaSource::ID;
2430
2433
2436}
2437
2439 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
2440
2442 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
2443
2444/// Figure out if an expression could be turned into a call.
2445///
2446/// Use this when trying to recover from an error where the programmer may have
2447/// written just the name of a function instead of actually calling it.
2448///
2449/// \param E - The expression to examine.
2450/// \param ZeroArgCallReturnTy - If the expression can be turned into a call
2451/// with no arguments, this parameter is set to the type returned by such a
2452/// call; otherwise, it is set to an empty QualType.
2453/// \param OverloadSet - If the expression is an overloaded function
2454/// name, this parameter is populated with the decls of the various overloads.
2455bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
2456 UnresolvedSetImpl &OverloadSet) {
2457 ZeroArgCallReturnTy = QualType();
2458 OverloadSet.clear();
2459
2460 const OverloadExpr *Overloads = nullptr;
2461 bool IsMemExpr = false;
2462 if (E.getType() == Context.OverloadTy) {
2463 OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
2464
2465 // Ignore overloads that are pointer-to-member constants.
2467 return false;
2468
2469 Overloads = FR.Expression;
2470 } else if (E.getType() == Context.BoundMemberTy) {
2471 Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
2472 IsMemExpr = true;
2473 }
2474
2475 bool Ambiguous = false;
2476 bool IsMV = false;
2477
2478 if (Overloads) {
2479 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
2480 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
2481 OverloadSet.addDecl(*it);
2482
2483 // Check whether the function is a non-template, non-member which takes no
2484 // arguments.
2485 if (IsMemExpr)
2486 continue;
2487 if (const FunctionDecl *OverloadDecl
2488 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
2489 if (OverloadDecl->getMinRequiredArguments() == 0) {
2490 if (!ZeroArgCallReturnTy.isNull() && !Ambiguous &&
2491 (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||
2492 OverloadDecl->isCPUSpecificMultiVersion()))) {
2493 ZeroArgCallReturnTy = QualType();
2494 Ambiguous = true;
2495 } else {
2496 ZeroArgCallReturnTy = OverloadDecl->getReturnType();
2497 IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
2498 OverloadDecl->isCPUSpecificMultiVersion();
2499 }
2500 }
2501 }
2502 }
2503
2504 // If it's not a member, use better machinery to try to resolve the call
2505 if (!IsMemExpr)
2506 return !ZeroArgCallReturnTy.isNull();
2507 }
2508
2509 // Attempt to call the member with no arguments - this will correctly handle
2510 // member templates with defaults/deduction of template arguments, overloads
2511 // with default arguments, etc.
2512 if (IsMemExpr && !E.isTypeDependent()) {
2513 Sema::TentativeAnalysisScope Trap(*this);
2515 std::nullopt, SourceLocation());
2516 if (R.isUsable()) {
2517 ZeroArgCallReturnTy = R.get()->getType();
2518 return true;
2519 }
2520 return false;
2521 }
2522
2523 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
2524 if (const auto *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
2525 if (Fun->getMinRequiredArguments() == 0)
2526 ZeroArgCallReturnTy = Fun->getReturnType();
2527 return true;
2528 }
2529 }
2530
2531 // We don't have an expression that's convenient to get a FunctionDecl from,
2532 // but we can at least check if the type is "function of 0 arguments".
2533 QualType ExprTy = E.getType();
2534 const FunctionType *FunTy = nullptr;
2535 QualType PointeeTy = ExprTy->getPointeeType();
2536 if (!PointeeTy.isNull())
2537 FunTy = PointeeTy->getAs<FunctionType>();
2538 if (!FunTy)
2539 FunTy = ExprTy->getAs<FunctionType>();
2540
2541 if (const auto *FPT = dyn_cast_if_present<FunctionProtoType>(FunTy)) {
2542 if (FPT->getNumParams() == 0)
2543 ZeroArgCallReturnTy = FunTy->getReturnType();
2544 return true;
2545 }
2546 return false;
2547}
2548
2549/// Give notes for a set of overloads.
2550///
2551/// A companion to tryExprAsCall. In cases when the name that the programmer
2552/// wrote was an overloaded function, we may be able to make some guesses about
2553/// plausible overloads based on their return types; such guesses can be handed
2554/// off to this method to be emitted as notes.
2555///
2556/// \param Overloads - The overloads to note.
2557/// \param FinalNoteLoc - If we've suppressed printing some overloads due to
2558/// -fshow-overloads=best, this is the location to attach to the note about too
2559/// many candidates. Typically this will be the location of the original
2560/// ill-formed expression.
2561static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
2562 const SourceLocation FinalNoteLoc) {
2563 unsigned ShownOverloads = 0;
2564 unsigned SuppressedOverloads = 0;
2565 for (UnresolvedSetImpl::iterator It = Overloads.begin(),
2566 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2567 if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) {
2568 ++SuppressedOverloads;
2569 continue;
2570 }
2571
2572 const NamedDecl *Fn = (*It)->getUnderlyingDecl();
2573 // Don't print overloads for non-default multiversioned functions.
2574 if (const auto *FD = Fn->getAsFunction()) {
2575 if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() &&
2576 !FD->getAttr<TargetAttr>()->isDefaultVersion())
2577 continue;
2578 if (FD->isMultiVersion() && FD->hasAttr<TargetVersionAttr>() &&
2579 !FD->getAttr<TargetVersionAttr>()->isDefaultVersion())
2580 continue;
2581 }
2582 S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
2583 ++ShownOverloads;
2584 }
2585
2586 S.Diags.overloadCandidatesShown(ShownOverloads);
2587
2588 if (SuppressedOverloads)
2589 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
2590 << SuppressedOverloads;
2591}
2592
2594 const UnresolvedSetImpl &Overloads,
2595 bool (*IsPlausibleResult)(QualType)) {
2596 if (!IsPlausibleResult)
2597 return noteOverloads(S, Overloads, Loc);
2598
2599 UnresolvedSet<2> PlausibleOverloads;
2600 for (OverloadExpr::decls_iterator It = Overloads.begin(),
2601 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2602 const auto *OverloadDecl = cast<FunctionDecl>(*It);
2603 QualType OverloadResultTy = OverloadDecl->getReturnType();
2604 if (IsPlausibleResult(OverloadResultTy))
2605 PlausibleOverloads.addDecl(It.getDecl());
2606 }
2607 noteOverloads(S, PlausibleOverloads, Loc);
2608}
2609
2610/// Determine whether the given expression can be called by just
2611/// putting parentheses after it. Notably, expressions with unary
2612/// operators can't be because the unary operator will start parsing
2613/// outside the call.
2614static bool IsCallableWithAppend(const Expr *E) {
2615 E = E->IgnoreImplicit();
2616 return (!isa<CStyleCastExpr>(E) &&
2617 !isa<UnaryOperator>(E) &&
2618 !isa<BinaryOperator>(E) &&
2619 !isa<CXXOperatorCallExpr>(E));
2620}
2621
2623 if (const auto *UO = dyn_cast<UnaryOperator>(E))
2624 E = UO->getSubExpr();
2625
2626 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2627 if (ULE->getNumDecls() == 0)
2628 return false;
2629
2630 const NamedDecl *ND = *ULE->decls_begin();
2631 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2633 }
2634 return false;
2635}
2636
2638 bool ForceComplain,
2639 bool (*IsPlausibleResult)(QualType)) {
2640 SourceLocation Loc = E.get()->getExprLoc();
2641 SourceRange Range = E.get()->getSourceRange();
2642 UnresolvedSet<4> Overloads;
2643
2644 // If this is a SFINAE context, don't try anything that might trigger ADL
2645 // prematurely.
2646 if (!isSFINAEContext()) {
2647 QualType ZeroArgCallTy;
2648 if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
2649 !ZeroArgCallTy.isNull() &&
2650 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
2651 // At this point, we know E is potentially callable with 0
2652 // arguments and that it returns something of a reasonable type,
2653 // so we can emit a fixit and carry on pretending that E was
2654 // actually a CallExpr.
2655 SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
2657 Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
2658 << (IsCallableWithAppend(E.get())
2659 ? FixItHint::CreateInsertion(ParenInsertionLoc,
2660 "()")
2661 : FixItHint());
2662 if (!IsMV)
2663 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2664
2665 // FIXME: Try this before emitting the fixit, and suppress diagnostics
2666 // while doing so.
2667 E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), std::nullopt,
2668 Range.getEnd().getLocWithOffset(1));
2669 return true;
2670 }
2671 }
2672 if (!ForceComplain) return false;
2673
2675 Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
2676 if (!IsMV)
2677 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2678 E = ExprError();
2679 return true;
2680}
2681
2683 if (!Ident_super)
2684 Ident_super = &Context.Idents.get("super");
2685 return Ident_super;
2686}
2687
2690 unsigned OpenMPCaptureLevel) {
2691 auto *CSI = new CapturedRegionScopeInfo(
2692 getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
2693 (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0,
2694 OpenMPCaptureLevel);
2695 CSI->ReturnType = Context.VoidTy;
2696 FunctionScopes.push_back(CSI);
2698}
2699
2701 if (FunctionScopes.empty())
2702 return nullptr;
2703
2704 return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
2705}
2706
2707const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
2709 return DeleteExprs;
2710}
2711
2713 : S(S), OldFPFeaturesState(S.CurFPFeatures),
2714 OldOverrides(S.FpPragmaStack.CurrentValue),
2715 OldEvalMethod(S.PP.getCurrentFPEvalMethod()),
2716 OldFPPragmaLocation(S.PP.getLastFPEvalPragmaLocation()) {}
2717
2719 S.CurFPFeatures = OldFPFeaturesState;
2720 S.FpPragmaStack.CurrentValue = OldOverrides;
2721 S.PP.setCurrentFPEvalMethod(OldFPPragmaLocation, OldEvalMethod);
2722}
2723
2725 assert(D.getCXXScopeSpec().isSet() &&
2726 "can only be called for qualified names");
2727
2728 auto LR = LookupResult(*this, D.getIdentifier(), D.getBeginLoc(),
2732 if (!DC)
2733 return false;
2734
2735 LookupQualifiedName(LR, DC);
2736 bool Result = std::all_of(LR.begin(), LR.end(), [](Decl *Dcl) {
2737 if (NamedDecl *ND = dyn_cast<NamedDecl>(Dcl)) {
2738 ND = ND->getUnderlyingDecl();
2739 return isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
2740 isa<UsingDecl>(ND);
2741 }
2742 return false;
2743 });
2744 return Result;
2745}
Defines the clang::ASTContext interface.
int Id
Definition: ASTDiff.cpp:190
DynTypedNode Node
#define SM(sm)
Definition: Cuda.cpp:80
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::Expr interface and subclasses for C++ expressions.
unsigned Offset
Definition: Format.cpp:2800
llvm::DenseSet< const void * > Visited
Definition: HTMLLogger.cpp:168
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
static void checkEscapingByref(VarDecl *VD, Sema &S)
Definition: Sema.cpp:2167
static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E)
Definition: Sema.cpp:2622
llvm::DenseMap< const CXXRecordDecl *, bool > RecordCompleteMap
Definition: Sema.cpp:935
static bool IsCallableWithAppend(const Expr *E)
Determine whether the given expression can be called by just putting parentheses after it.
Definition: Sema.cpp:2614
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:942
static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, const SourceLocation FinalNoteLoc)
Give notes for a set of overloads.
Definition: Sema.cpp:2561
static bool isFunctionOrVarDeclExternC(const NamedDecl *ND)
Definition: Sema.cpp:789
static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S)
Definition: Sema.cpp:2201
static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D)
Used to prune the decls of Sema's UnusedFileScopedDecls vector.
Definition: Sema.cpp:728
static void emitCallStackNotes(Sema &S, const FunctionDecl *FD)
Definition: Sema.cpp:1612
static void notePlausibleOverloads(Sema &S, SourceLocation Loc, const UnresolvedSetImpl &Overloads, bool(*IsPlausibleResult)(QualType))
Definition: Sema.cpp:2593
static void checkUndefinedButUsed(Sema &S)
checkUndefinedButUsed - Check for undefined objects with internal linkage or that are inline.
Definition: Sema.cpp:861
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:984
Defines the SourceManager interface.
Defines utilities for dealing with stack allocation and stack space.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:33
virtual void CompleteTentativeDefinition(VarDecl *D)
CompleteTentativeDefinition - Callback invoked at the end of a translation unit to notify the consume...
Definition: ASTConsumer.h:103
virtual ASTMutationListener * GetASTMutationListener()
If the consumer is interested in entities getting modified after their initial creation,...
Definition: ASTConsumer.h:128
virtual void CompleteExternalDeclaration(VarDecl *D)
CompleteExternalDeclaration - Callback invoked at the end of a translation unit to notify the consume...
Definition: ASTConsumer.h:108
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
SourceManager & getSourceManager()
Definition: ASTContext.h:691
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1059
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
CanQualType LongTy
Definition: ASTContext.h:1086
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefDecl * getCFConstantStringDecl() const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
CanQualType FloatTy
Definition: ASTContext.h:1089
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2524
CanQualType DoubleTy
Definition: ASTContext.h:1089
CanQualType LongDoubleTy
Definition: ASTContext.h:1089
void addComment(const RawComment &RC)
Definition: ASTContext.cpp:385
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2723
IdentifierTable & Idents
Definition: ASTContext.h:630
const LangOptions & getLangOpts() const
Definition: ASTContext.h:761
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
PartialDiagnostic::DiagStorageAllocator & getDiagAllocator()
Definition: ASTContext.h:739
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:744
CanQualType UnsignedLongTy
Definition: ASTContext.h:1087
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType BoundMemberTy
Definition: ASTContext.h:1105
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
CanQualType IntTy
Definition: ASTContext.h:1086
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
Definition: ASTContext.h:1383
CanQualType OverloadTy
Definition: ASTContext.h:1105
CanQualType OCLClkEventTy
Definition: ASTContext.h:1113
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:683
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2296
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
CanQualType OCLSamplerTy
Definition: ASTContext.h:1113
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1077
CanQualType UnsignedIntTy
Definition: ASTContext.h:1087
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1114
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:743
CanQualType OCLQueueTy
Definition: ASTContext.h:1114
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1166
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
IdentifierInfo * getBoolName() const
Retrieve the identifier 'bool'.
Definition: ASTContext.h:1890
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=TTK_Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
CanQualType HalfTy
Definition: ASTContext.h:1101
CanQualType OCLEventTy
Definition: ASTContext.h:1113
void setPrintingPolicy(const clang::PrintingPolicy &Policy)
Definition: ASTContext.h:687
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
bool isInvalid() const
Definition: Ownership.h:165
bool isUsable() const
Definition: Ownership.h:166
PtrTy get() const
Definition: Ownership.h:169
A class which contains all the information about a particular captured value.
Definition: Decl.h:4376
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4370
ArrayRef< Capture > captures() const
Definition: Decl.h:4497
SourceLocation getCaretLocation() const
Definition: Decl.h:4443
bool doesNotEscape() const
Definition: Decl.h:4521
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2755
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:2035
An iterator over the friend declarations of a class.
Definition: DeclFriend.h:185
Represents a C++ struct/union/class.
Definition: DeclCXX.h:254
friend_iterator friend_begin() const
Definition: DeclFriend.h:237
friend_iterator friend_end() const
Definition: DeclFriend.h:241
bool isSet() const
Deprecated.
Definition: DeclSpec.h:227
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:4562
ImplicitParamDecl * getContextParam() const
Retrieve the parameter containing captured variables.
Definition: Decl.h:4624
const char * getCastKindName() const
Definition: Expr.h:3543
Abstract interface for a consumer of code-completion information.
The information about the darwin SDK that was used during this compilation.
Definition: DarwinSDKInfo.h:29
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:2156
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1402
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1944
decl_iterator decls_end() const
Definition: DeclBase.h:2201
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1299
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1498
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1237
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:784
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
T * getAttr() const
Definition: DeclBase.h:556
void addAttr(Attr *A)
Definition: DeclBase.cpp:904
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:133
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:483
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:228
bool isInvalidDecl() const
Definition: DeclBase.h:571
SourceLocation getLocation() const
Definition: DeclBase.h:432
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:458
bool hasAttr() const
Definition: DeclBase.h:560
The name of a declaration.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:765
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1850
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1986
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2022
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:2001
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2268
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1266
static SFINAEResponse getDiagnosticSFINAEResponse(unsigned DiagID)
Determines whether the given built-in diagnostic ID is for an error that is suppressed if it occurs d...
static bool isDefaultMappingAsError(unsigned DiagID)
Return true if the specified diagnostic is mapped to errors by default.
static bool isBuiltinNote(unsigned DiagID)
Determine whether the given built-in diagnostic ID is a Note.
@ 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.
static bool isDeferrable(unsigned DiagID)
Whether the diagnostic message can be deferred.
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1566
const SourceLocation & getLocation() const
Definition: Diagnostic.h:1577
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1542
void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie)
Definition: Diagnostic.h:884
bool hasErrorOccurred() const
Definition: Diagnostic.h:838
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition: Diagnostic.h:741
void setLastDiagnosticIgnored(bool Ignored)
Pretend that the last diagnostic issued was ignored, so any subsequent notes will be suppressed,...
Definition: Diagnostic.h:756
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition: Diagnostic.h:726
SourceLocation getCurrentDiagLoc() const
Definition: Diagnostic.h:1059
void Clear()
Clear out the current diagnostic.
Definition: Diagnostic.h:977
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:845
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:911
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:926
bool EmitCurrentDiagnostic(bool Force=false)
Emit the current diagnostic and clear the diagnostic state.
Definition: Diagnostic.cpp:514
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:685
unsigned getCurrentDiagID() const
Definition: Diagnostic.h:1057
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition: Diagnostic.h:552
RAII object that enters a new expression evaluation context.
This represents one expression.
Definition: Expr.h:110
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:186
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3057
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3045
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3053
bool isPRValue() const
Definition: Expr.h:272
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:330
QualType getType() const
Definition: Expr.h:142
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:2432
virtual void ReadMethodPool(Selector Sel)
Load the contents of the global method pool for a given selector.
Definition: Sema.cpp:2431
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:2438
~ExternalSemaSource() override
Definition: Sema.cpp:2428
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:2434
virtual void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 > > &)
Definition: Sema.cpp:2441
Represents difference between two FPOptions values.
Definition: LangOptions.h:806
Represents a member of a struct/union/class.
Definition: Decl.h:2960
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:353
StringRef getName() const
Definition: FileEntry.h:384
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
llvm::vfs::FileSystem & getVirtualFileSystem() const
Definition: FileManager.h:245
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
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:134
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:97
Represents a function declaration or definition.
Definition: Decl.h:1917
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2532
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3139
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3478
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2435
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3474
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2280
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3059
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4056
Declaration of a template function.
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3709
QualType getReturnType() const
Definition: Type.h:3974
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:798
HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized.
Definition: HeaderSearch.h:354
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
iterator begin(DeclarationName Name)
Returns an iterator over decls with the name 'Name'.
iterator end()
Returns the end iterator.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3642
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2068
Represents a C array with an unspecified size.
Definition: Type.h:3149
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type)
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i....
Definition: LangOptions.h:474
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:446
@ CMK_HeaderUnit
Compiling a module header unit.
Definition: LangOptions.h:115
@ CMK_ModuleInterface
Compiling a C++ modules interface unit.
Definition: LangOptions.h:118
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:63
void erase(iterator From, iterator To)
iterator begin(Source *source, bool LocalOnly=false)
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:786
Represents the results of name lookup.
Definition: Lookup.h:46
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:39
Abstract interface for a module loader.
Definition: ModuleLoader.h:82
bool resolveExports(Module *Mod, bool Complain)
Resolve all of the unresolved exports in the given module.
Definition: ModuleMap.cpp:1384
bool resolveConflicts(Module *Mod, bool Complain)
Resolve all of the unresolved conflicts in the given module.
Definition: ModuleMap.cpp:1410
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Definition: ModuleMap.cpp:1397
Describes a module or submodule.
Definition: Module.h:98
llvm::iterator_range< submodule_iterator > submodules()
Definition: Module.h:745
@ PrivateModuleFragment
This is the private module fragment within some C++ module.
Definition: Module.h:134
@ ExplicitGlobalModuleFragment
This is the explicit Global Module Fragment of a modular TU.
Definition: Module.h:131
An abstract interface that should be implemented by external AST sources that also provide informatio...
static const unsigned NumNSNumberLiteralMethods
Definition: NSAPI.h:191
This represents a decl that may have a name.
Definition: Decl.h:247
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:457
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition: Decl.h:401
NamedDecl * getMostRecentDecl()
Definition: Decl.h:471
bool isExternallyVisible() const
Definition: Decl.h:405
This represents '#pragma omp target' directive.
Definition: StmtOpenMP.h:3097
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:138
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:2962
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3022
decls_iterator decls_begin() const
Definition: ExprCXX.h:3054
decls_iterator decls_end() const
Definition: ExprCXX.h:3057
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition: PPCallbacks.h:35
void Emit(const DiagnosticBuilder &DB) const
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
LangOptions::FPEvalMethodKind getCurrentFPEvalMethod() const
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Preprocessor.h:282
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with this preprocessor.
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
void setCurrentFPEvalMethod(SourceLocation PragmaLoc, LangOptions::FPEvalMethodKind Val)
FileManager & getFileManager() const
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
HeaderSearch & getHeaderSearchInfo() const
const LangOptions & getLangOpts() const
A (possibly-)qualified type.
Definition: Type.h:736
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:6810
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:803
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:6804
QualType getCanonicalType() const
Definition: Type.h:6716
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6757
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6736
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:4027
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
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:78
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:60
Smart pointer class that efficiently represents Objective-C method names.
An abstract interface that should be implemented by clients that read ASTs and then require further s...
Definition: SemaConsumer.h:25
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition: Sema.h:949
sema::DelayedDiagnosticPool * getCurrentPool() const
Returns the current delayed-diagnostics pool.
Definition: Sema.h:964
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1704
Custom deleter to allow FunctionScopeInfos to be kept alive for a short time after they've been poppe...
Definition: Sema.h:1982
void operator()(sema::FunctionScopeInfo *Scope) const
Definition: Sema.cpp:2270
A generic diagnostic builder for errors which may or may not be deferred.
Definition: Sema.h:1775
SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID, const FunctionDecl *Fn, Sema &S)
Definition: Sema.cpp:1822
@ K_Nop
Emit no diagnostics.
Definition: Sema.h:1779
@ K_Deferred
Create a deferred diagnostic, which is emitted only if the function it's attached to is codegen'ed.
Definition: Sema.h:1789
@ K_ImmediateWithCallStack
Emit the diagnostic immediately, and, if it's a warning or error, also emit a call stack showing how ...
Definition: Sema.h:1785
@ K_Immediate
Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
Definition: Sema.h:1781
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:9846
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:356
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:9433
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:13839
void LoadExternalWeakUndeclaredIdentifiers()
Load weak undeclared identifiers from the external source.
Definition: Sema.cpp:924
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:797
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition: Sema.cpp:2455
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:4308
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:908
@ NTCUC_BlockCapture
Definition: Sema.h:3028
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1887
void addImplicitTypedef(StringRef Name, QualType T)
Definition: Sema.cpp:262
void PrintContextStack()
Definition: Sema.h:9719
void CheckDelegatingCtorCycles()
bool IsLastErrorImmediate
Is the last error level diagnostic immediate.
Definition: Sema.h:1885
void DiagnoseUnterminatedOpenMPDeclareTarget()
Report unterminated 'omp declare target' or 'omp begin declare target' at the end of a compilation un...
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:1471
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:853
void emitAndClearUnusedLocalTypedefWarnings()
Definition: Sema.cpp:1015
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition: Sema.h:844
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:1170
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition: Sema.h:810
llvm::DenseMap< CanonicalDeclPtr< const FunctionDecl >, std::vector< PartialDiagnosticAt > > DeviceDeferredDiags
Diagnostics that are emitted only if we discover that the given function must be codegen'ed.
Definition: Sema.h:13035
void Initialize()
Perform initialization that occurs after the parser has been initialized but before it parses anythin...
Definition: Sema.cpp:268
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:873
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:803
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2247
Preprocessor & getPreprocessor() const
Definition: Sema.h:1666
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2109
llvm::DenseSet< std::pair< Decl *, unsigned > > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition: Sema.h:9436
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition: Sema.h:702
void setFunctionHasBranchIntoScope()
Definition: Sema.cpp:2298
virtual void anchor()
This virtual key function only exists to limit the emission of debug info describing the Sema class.
Definition: Sema.cpp:260
void ActOnComment(SourceRange Comment)
Definition: Sema.cpp:2396
void ActOnEndOfTranslationUnit()
ActOnEndOfTranslationUnit - This is called at the very end of the translation unit when EOF is reache...
Definition: Sema.cpp:1105
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:703
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)
Definition: Sema.cpp:127
IdentifierInfo * getSuperIdentifier() const
Definition: Sema.cpp:2682
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:1466
ASTContext & Context
Definition: Sema.h:407
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:573
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1664
SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as host cod...
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:2637
void CheckDelayedMemberExceptionSpecs()
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1537
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:894
ASTContext & getASTContext() const
Definition: Sema.h:1667
void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, const FunctionDecl *Callee, SourceLocation Loc)
Finishes analysis of the deferred functions calls that may be declared as host/nohost during device/h...
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition: Sema.h:1049
SmallVector< VarDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition: Sema.h:886
static const unsigned MaxAlignmentExponent
The maximum alignment, same as in llvm::Value.
Definition: Sema.h:395
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
Definition: SemaDecl.cpp:20015
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:3276
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1471
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition: Sema.cpp:2387
unsigned NumSFINAEErrors
The number of SFINAE diagnostics that have been trapped.
Definition: Sema.h:1476
void setFunctionHasIndirectGoto()
Definition: Sema.cpp:2308
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1485
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2128
void EmitCurrentDiagnostic(unsigned DiagID)
Cause the active diagnostic on the DiagosticsEngine to be emitted.
Definition: Sema.cpp:1491
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition: Sema.h:1991
FPOptions & getCurFPFeatures()
Definition: Sema.h:1662
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:58
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:2146
void PopCompoundScope()
Definition: Sema.cpp:2285
const LangOptions & getLangOpts() const
Definition: Sema.h:1660
SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
Definition: SemaCUDA.cpp:725
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
ASTConsumer & getASTConsumer() const
Definition: Sema.h:1668
void * OpaqueParser
Definition: Sema.h:928
Preprocessor & PP
Definition: Sema.h:406
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.
Definition: SemaExpr.cpp:7011
threadSafety::BeforeSet * ThreadSafetyDeclCache
Definition: Sema.h:9883
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:1910
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:630
ObjCMethodDecl * NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]
The Objective-C NSNumber methods used to create NSNumber literals.
Definition: Sema.h:1185
const LangOptions & LangOpts
Definition: Sema.h:405
std::unique_ptr< sema::FunctionScopeInfo > CachedFunctionScope
Definition: Sema.h:799
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2362
static const uint64_t MaximumAlignment
Definition: Sema.h:396
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:916
void PerformPendingInstantiations(bool LocalOnly=false)
Performs template instantiation for all implicit template instantiations we have seen until this poin...
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:849
void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind)
Definition: Sema.cpp:1037
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1895
SemaDiagnosticBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
SmallVector< PendingImplicitInstantiation, 1 > LateParsedInstantiations
Queue of implicit template instantiations that cannot be performed eagerly.
Definition: Sema.h:9901
DeclContext * getCurLexicalContext() const
Definition: Sema.h:13849
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1478
void deepTypeCheckForSYCLDevice(SourceLocation UsedAt, llvm::DenseSet< QualType > Visited, ValueDecl *DeclToCheck)
Definition: SemaSYCL.cpp:42
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:711
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1998
void PushCompoundScope(bool IsStmtExpr)
Definition: Sema.cpp:2280
bool isDeclaratorFunctionLike(Declarator &D)
Determine whether.
Definition: Sema.cpp:2724
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
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:2081
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:13880
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:19935
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2318
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:419
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:8359
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:9744
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1446
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
CheckedConversionKind
The kind of conversion being performed.
Definition: Sema.h:12292
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:9715
SourceManager & getSourceManager() const
Definition: Sema.h:1665
bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason)
makeUnavailableInSystemHeader - There is an error in the current context.
Definition: Sema.cpp:520
void getUndefinedButUsed(SmallVectorImpl< std::pair< NamedDecl *, SourceLocation > > &Undefined)
Obtain a sorted list of functions that are undefined but ODR-used.
Definition: Sema.cpp:808
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.
Definition: SemaStmt.cpp:3529
void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, SourceLocation IncludeLoc)
Definition: SemaAttr.cpp:436
RedeclarationKind forRedeclarationInCurContext() const
Definition: Sema.h:4371
CanThrowResult canThrow(const Stmt *E)
bool AccessCheckingSFINAE
When true, access checking violations are treated as SFINAE failures rather than hard errors.
Definition: Sema.h:7990
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
@ NTCUK_Destruct
Definition: Sema.h:3042
@ NTCUK_Copy
Definition: Sema.h:3043
SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as host cod...
Definition: SemaCUDA.cpp:755
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition: Sema.cpp:2140
void * VisContext
VisContext - Manages the stack for #pragma GCC visibility.
Definition: Sema.h:737
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel=0)
Definition: Sema.cpp:2688
void emitDeferredDiags()
Definition: Sema.cpp:1784
void setFunctionHasMustTail()
Definition: Sema.cpp:2313
bool WarnedStackExhausted
Definition: Sema.h:1623
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:13945
TUFragmentKind
Definition: Sema.h:1947
@ Global
The global module fragment, between 'module;' and a module-declaration.
Definition: Sema.h:1949
@ Private
The private module fragment, between 'module :private;' and the end of the translation unit.
Definition: Sema.h:1956
@ Normal
A normal translation unit fragment.
Definition: Sema.h:1953
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2303
void ActOnStartOfTranslationUnit()
This is called before the very first declaration in the translation unit is parsed.
Definition: Sema.cpp:1031
ASTConsumer & Consumer
Definition: Sema.h:408
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:9882
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1594
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:9897
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with the preprocessor.
Definition: Sema.cpp:62
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
std::pair< SourceLocation, bool > DeleteExprLoc
Delete-expressions to be analyzed at the end of translation unit.
Definition: Sema.h:860
void RecordParsingTemplateParameterDepth(unsigned Depth)
This is used to inform Sema what the current TemplateParameterDepth is during Parsing.
Definition: Sema.cpp:2153
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8882
void DiagnoseUseOfUnimplementedSelectors()
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:1138
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
void DiagnoseUnterminatedPragmaAttribute()
Definition: SemaAttr.cpp:1133
void FreeVisContext()
FreeVisContext - Deallocate and null out VisContext.
Definition: SemaAttr.cpp:1239
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
llvm::MapVector< FieldDecl *, DeleteLocs > DeleteExprs
Definition: Sema.h:862
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:883
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
bool DeferDiags
Whether deferrable diagnostics should be deferred.
Definition: Sema.h:1899
DarwinSDKInfo * getDarwinSDKInfoForAvailabilityChecking()
Definition: Sema.cpp:76
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:2708
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:1402
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1344
SourceManager & SourceMgr
Definition: Sema.h:410
DiagnosticsEngine & Diags
Definition: Sema.h:409
void DiagnoseUnterminatedPragmaAlignPack()
Definition: SemaAttr.cpp:475
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:1661
FPOptions CurFPFeatures
Definition: Sema.h:403
LateTemplateParserCleanupCB * LateTemplateParserCleanup
Definition: Sema.h:927
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition: Sema.h:13881
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10389
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:1496
void PrintStats() const
Print out statistics about the semantic analysis.
Definition: Sema.cpp:565
llvm::BumpPtrAllocator BumpAlloc
Definition: Sema.h:1473
sema::LambdaScopeInfo * getEnclosingLambda() const
Get the innermost lambda enclosing the current location, if any.
Definition: Sema.cpp:2345
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:511
void addExternalSource(ExternalSemaSource *E)
Registers an external source.
Definition: Sema.cpp:550
IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName, unsigned Index)
Invent a new identifier for parameters of abbreviated templates.
Definition: Sema.cpp:93
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:1114
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1871
DeclarationName VAListTagName
VAListTagName - The declaration name corresponding to __va_list_tag.
Definition: Sema.h:427
sema::FunctionScopeInfo * getEnclosingFunction() const
Definition: Sema.cpp:2333
llvm::DenseMap< CanonicalDeclPtr< const FunctionDecl >, FunctionDeclAndLoc > DeviceKnownEmittedFns
An inverse call graph, mapping known-emitted functions to one of their known-emitted callers (plus th...
Definition: Sema.h:13056
sema::CapturedRegionScopeInfo * getCurCapturedRegion()
Retrieve the current captured region, if any.
Definition: Sema.cpp:2700
void warnStackExhausted(SourceLocation Loc)
Warn that the stack is nearly exhausted.
Definition: Sema.cpp:503
void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E)
Warn when implicitly casting 0 to nullptr.
Definition: Sema.cpp:588
SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
Definition: SemaSYCL.cpp:21
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...
Definition: SemaDecl.cpp:13029
IdentifierResolver IdResolver
Definition: Sema.h:1133
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2294
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:541
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:325
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:337
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3572
bool isUnion() const
Definition: Decl.h:3673
Exposes information about the current target.
Definition: TargetInfo.h:206
virtual bool hasLongDoubleType() const
Determine whether the long double type is supported on this target.
Definition: TargetInfo.h:666
virtual bool hasBitIntType() const
Determine whether the _BitInt type is supported on this target.
Definition: TargetInfo.h:621
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1197
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:610
virtual bool hasFloat16Type() const
Determine whether the _Float16 type is supported on this target.
Definition: TargetInfo.h:651
llvm::StringMap< bool > & getSupportedOpenCLOpts()
Get supported OpenCL extensions and optional core features.
Definition: TargetInfo.h:1651
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition: TargetInfo.h:663
virtual bool hasFPReturn() const
Determine whether return of a floating point value is supported on this target.
Definition: TargetInfo.h:670
bool hasBuiltinMSVaList() const
Returns whether or not type __builtin_ms_va_list type is available on this target.
Definition: TargetInfo.h:974
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition: TargetInfo.h:648
bool hasAArch64SVETypes() const
Returns whether or not the AArch64 SVE built-in types are available on this target.
Definition: TargetInfo.h:981
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition: TargetInfo.h:654
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1393
bool hasRISCVVTypes() const
Returns whether or not the RISC-V V built-in types are available on this target.
Definition: TargetInfo.h:985
The type-property cache.
Definition: Type.cpp:4067
A container of type source information.
Definition: Type.h:6635
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1799
bool isRVVType() const
Definition: Type.h:7170
bool isFloat16Type() const
Definition: Type.h:7233
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7256
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2382
bool isFloat128Type() const
Definition: Type.h:7241
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:631
bool isBitIntType() const
Definition: Type.h:7140
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2329
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:2213
bool isIbm128Type() const
Definition: Type.h:7245
bool isBFloat16Type() const
Definition: Type.h:7237
bool isStructureOrClassType() const
Definition: Type.cpp:587
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2183
Linkage getLinkage() const
Determine the linkage of this type.
Definition: Type.cpp:4212
@ STK_FloatingComplex
Definition: Type.h:2311
@ STK_Floating
Definition: Type.h:2309
@ STK_BlockPointer
Definition: Type.h:2304
@ STK_Bool
Definition: Type.h:2307
@ STK_ObjCObjectPointer
Definition: Type.h:2305
@ STK_FixedPoint
Definition: Type.h:2312
@ STK_IntegralComplex
Definition: Type.h:2310
@ STK_CPointer
Definition: Type.h:2303
@ STK_Integral
Definition: Type.h:2308
@ STK_MemberPointer
Definition: Type.h:2306
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7430
bool isNullPtrType() const
Definition: Type.h:7249
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4322
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3319
Simple class containing the result of Sema::CorrectTypo.
A set of unresolved declarations.
Definition: UnresolvedSet.h:61
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:91
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
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:701
void setType(QualType newType)
Definition: Decl.h:713
QualType getType() const
Definition: Decl.h:712
Represents a variable declaration or definition.
Definition: Decl.h:913
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2726
void setEscapingByref()
Definition: Decl.h:1561
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2312
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1299
const Expr * getInit() const
Definition: Decl.h:1325
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2291
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1252
bool isEscapingByref() const
Indicates the capture is a __block variable that is captured by a block that can potentially escape (...
Definition: Decl.cpp:2614
Declaration of a variable template.
void IssueWarnings(Policy P, FunctionScopeInfo *fscope, const Decl *D, QualType BlockType)
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:759
Retains information about a captured region.
Definition: ScopeInfo.h:785
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:102
bool hasUnrecoverableErrorOccurred() const
Determine whether an unrecoverable error has occurred within this function.
Definition: ScopeInfo.h:406
SmallVector< CompoundScopeInfo, 4 > CompoundScopes
The stack of currently active compound stamement scopes in the function.
Definition: ScopeInfo.h:222
llvm::SmallPtrSet< const BlockDecl *, 1 > Blocks
The set of blocks that are introduced in this function.
Definition: ScopeInfo.h:225
llvm::TinyPtrVector< VarDecl * > ByrefBlockVars
The set of __block variables that are introduced in this function.
Definition: ScopeInfo.h:228
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:144
Defines the clang::TargetInfo interface.
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Definition: SourceManager.h:80
void threadSafetyCleanup(BeforeSet *Cache)
@ OpenCL
Definition: LangStandard.h:63
@ CPlusPlus
Definition: LangStandard.h:53
@ CPlusPlus11
Definition: LangStandard.h:54
@ ExpectedVariableOrFunction
Definition: ParsedAttr.h:1052
@ Nullable
Values of this type can be null.
@ NonNull
Values of this type can never be null.
Expected< std::optional< DarwinSDKInfo > > parseDarwinSDKInfo(llvm::vfs::FileSystem &VFS, StringRef SDKRootPath)
Parse the SDK information from the SDKSettings.json file.
CapturedRegionKind
The different kinds of captured statement.
Definition: CapturedStmt.h:16
@ CR_OpenMP
Definition: CapturedStmt.h:19
@ SC_Register
Definition: Specifiers.h:248
@ SC_Static
Definition: Specifiers.h:243
@ C
Languages that the frontend can parse and compile.
@ Result
The result type of a method or function.
@ TTK_Class
The "class" keyword.
Definition: Type.h:5587
ExprResult ExprError()
Definition: Ownership.h:278
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:917
@ TU_Module
The translation unit is a module.
Definition: LangOptions.h:926
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:923
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.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:123
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:126
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:135
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:130
bool isExternalFormalLinkage(Linkage L)
Definition: Linkage.h:101
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
void runWithSufficientStackSpace(llvm::function_ref< void()> Diag, llvm::function_ref< void()> Fn)
Run a given function on a stack with "sufficient" space.
Definition: Stack.h:40
bool isExternallyVisible(Linkage L)
Definition: Linkage.h:86
unsigned long uint64_t
#define false
Definition: stdbool.h:22
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
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:9349