clang 18.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
59 return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
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 OptionalFileEntryRef FE = SM.getFileEntryRefForID(SM.getFileID(Loc));
156 llvm::timeTraceProfilerBegin("Source", FE ? FE->getName()
157 : 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 APINotes(SourceMgr, LangOpts), CollectStats(false),
195 CodeCompleter(CodeCompleter), CurContext(nullptr),
196 OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
197 MSPointerToMemberRepresentationMethod(
198 LangOpts.getMSPointerToMemberRepresentationMethod()),
199 VtorDispStack(LangOpts.getVtorDispMode()),
200 AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack)),
201 DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
202 CodeSegStack(nullptr), StrictGuardStackCheckStack(false),
203 FpPragmaStack(FPOptionsOverride()), CurInitSeg(nullptr),
204 VisContext(nullptr), PragmaAttributeCurrentTargetDecl(nullptr),
205 IsBuildingRecoveryCallExpr(false), LateTemplateParser(nullptr),
206 LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
207 StdInitializerList(nullptr), StdCoroutineTraitsCache(nullptr),
208 CXXTypeInfoDecl(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;
225
226 LoadedExternalKnownNamespaces = false;
227 for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
228 NSNumberLiteralMethods[I] = nullptr;
229
230 if (getLangOpts().ObjC)
231 NSAPIObj.reset(new NSAPI(Context));
232
235
236 // Tell diagnostics how to render things from the AST library.
238
239 // This evaluation context exists to ensure that there's always at least one
240 // valid evaluation context available. It is never removed from the
241 // evaluation stack.
242 ExprEvalContexts.emplace_back(
245
246 // Initialization of data sharing attributes stack for OpenMP
247 InitDataSharingAttributesStack();
248
249 std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
250 std::make_unique<sema::SemaPPCallbacks>();
251 SemaPPCallbackHandler = Callbacks.get();
252 PP.addPPCallbacks(std::move(Callbacks));
253 SemaPPCallbackHandler->set(*this);
254
255 CurFPFeatures.setFPEvalMethod(PP.getCurrentFPEvalMethod());
256}
257
258// Anchor Sema's type info to this TU.
260
261void Sema::addImplicitTypedef(StringRef Name, QualType T) {
262 DeclarationName DN = &Context.Idents.get(Name);
263 if (IdResolver.begin(DN) == IdResolver.end())
265}
266
268 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
269 SC->InitializeSema(*this);
270
271 // Tell the external Sema source about this Sema object.
272 if (ExternalSemaSource *ExternalSema
273 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
274 ExternalSema->InitializeSema(*this);
275
276 // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
277 // will not be able to merge any duplicate __va_list_tag decls correctly.
278 VAListTagName = PP.getIdentifierInfo("__va_list_tag");
279
280 if (!TUScope)
281 return;
282
283 // Initialize predefined 128-bit integer types, if needed.
287 // If either of the 128-bit integer types are unavailable to name lookup,
288 // define them now.
289 DeclarationName Int128 = &Context.Idents.get("__int128_t");
290 if (IdResolver.begin(Int128) == IdResolver.end())
292
293 DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
294 if (IdResolver.begin(UInt128) == IdResolver.end())
296 }
297
298
299 // Initialize predefined Objective-C types:
300 if (getLangOpts().ObjC) {
301 // If 'SEL' does not yet refer to any declarations, make it refer to the
302 // predefined 'SEL'.
303 DeclarationName SEL = &Context.Idents.get("SEL");
304 if (IdResolver.begin(SEL) == IdResolver.end())
306
307 // If 'id' does not yet refer to any declarations, make it refer to the
308 // predefined 'id'.
310 if (IdResolver.begin(Id) == IdResolver.end())
312
313 // Create the built-in typedef for 'Class'.
317
318 // Create the built-in forward declaratino for 'Protocol'.
319 DeclarationName Protocol = &Context.Idents.get("Protocol");
320 if (IdResolver.begin(Protocol) == IdResolver.end())
322 }
323
324 // Create the internal type for the *StringMakeConstantString builtins.
325 DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
326 if (IdResolver.begin(ConstantString) == IdResolver.end())
328
329 // Initialize Microsoft "predefined C++ types".
330 if (getLangOpts().MSVCCompat) {
331 if (getLangOpts().CPlusPlus &&
332 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(SatisfactionCache.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
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;
595
596 const Expr *EStripped = E->IgnoreParenImpCasts();
597 if (EStripped->getType()->isNullPtrType())
598 return;
599 if (isa<GNUNullExpr>(EStripped))
600 return;
601
602 if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
603 E->getBeginLoc()))
604 return;
605
606 // Don't diagnose the conversion from a 0 literal to a null pointer argument
607 // in a synthesized call to operator<=>.
608 if (!CodeSynthesisContexts.empty() &&
609 CodeSynthesisContexts.back().Kind ==
611 return;
612
613 // Ignore null pointers in defaulted comparison operators.
615 if (FD && FD->isDefaulted()) {
616 return;
617 }
618
619 // If it is a macro from system header, and if the macro name is not "NULL",
620 // do not warn.
621 // Note that uses of "NULL" will be ignored above on systems that define it
622 // as __null.
623 SourceLocation MaybeMacroLoc = E->getBeginLoc();
625 SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
626 !findMacroSpelling(MaybeMacroLoc, "NULL"))
627 return;
628
629 Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
631}
632
633/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
634/// If there is already an implicit cast, merge into the existing one.
635/// The result is of the given category.
637 CastKind Kind, ExprValueKind VK,
638 const CXXCastPath *BasePath,
640#ifndef NDEBUG
641 if (VK == VK_PRValue && !E->isPRValue()) {
642 switch (Kind) {
643 default:
644 llvm_unreachable(
645 ("can't implicitly cast glvalue to prvalue with this cast "
646 "kind: " +
647 std::string(CastExpr::getCastKindName(Kind)))
648 .c_str());
649 case CK_Dependent:
650 case CK_LValueToRValue:
651 case CK_ArrayToPointerDecay:
652 case CK_FunctionToPointerDecay:
653 case CK_ToVoid:
654 case CK_NonAtomicToAtomic:
655 break;
656 }
657 }
658 assert((VK == VK_PRValue || Kind == CK_Dependent || !E->isPRValue()) &&
659 "can't cast prvalue to glvalue");
660#endif
661
664
667
668 if (ExprTy == TypeTy)
669 return E;
670
671 if (Kind == CK_ArrayToPointerDecay) {
672 // C++1z [conv.array]: The temporary materialization conversion is applied.
673 // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
674 if (getLangOpts().CPlusPlus && E->isPRValue()) {
675 // The temporary is an lvalue in C++98 and an xvalue otherwise.
677 E->getType(), E, !getLangOpts().CPlusPlus11);
678 if (Materialized.isInvalid())
679 return ExprError();
680 E = Materialized.get();
681 }
682 // C17 6.7.1p6 footnote 124: The implementation can treat any register
683 // declaration simply as an auto declaration. However, whether or not
684 // addressable storage is actually used, the address of any part of an
685 // object declared with storage-class specifier register cannot be
686 // computed, either explicitly(by use of the unary & operator as discussed
687 // in 6.5.3.2) or implicitly(by converting an array name to a pointer as
688 // discussed in 6.3.2.1).Thus, the only operator that can be applied to an
689 // array declared with storage-class specifier register is sizeof.
690 if (VK == VK_PRValue && !getLangOpts().CPlusPlus && !E->isPRValue()) {
691 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
692 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
693 if (VD->getStorageClass() == SC_Register) {
694 Diag(E->getExprLoc(), diag::err_typecheck_address_of)
695 << /*register variable*/ 3 << E->getSourceRange();
696 return ExprError();
697 }
698 }
699 }
700 }
701 }
702
703 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
704 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
705 ImpCast->setType(Ty);
706 ImpCast->setValueKind(VK);
707 return E;
708 }
709 }
710
711 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
713}
714
715/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
716/// to the conversion from scalar type ScalarTy to the Boolean type.
718 switch (ScalarTy->getScalarTypeKind()) {
719 case Type::STK_Bool: return CK_NoOp;
720 case Type::STK_CPointer: return CK_PointerToBoolean;
721 case Type::STK_BlockPointer: return CK_PointerToBoolean;
722 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
723 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
724 case Type::STK_Integral: return CK_IntegralToBoolean;
725 case Type::STK_Floating: return CK_FloatingToBoolean;
726 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
727 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
728 case Type::STK_FixedPoint: return CK_FixedPointToBoolean;
729 }
730 llvm_unreachable("unknown scalar type kind");
731}
732
733/// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
734static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
735 if (D->getMostRecentDecl()->isUsed())
736 return true;
737
738 if (D->isExternallyVisible())
739 return true;
740
741 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
742 // If this is a function template and none of its specializations is used,
743 // we should warn.
744 if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
745 for (const auto *Spec : Template->specializations())
746 if (ShouldRemoveFromUnused(SemaRef, Spec))
747 return true;
748
749 // UnusedFileScopedDecls stores the first declaration.
750 // The declaration may have become definition so check again.
751 const FunctionDecl *DeclToCheck;
752 if (FD->hasBody(DeclToCheck))
753 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
754
755 // Later redecls may add new information resulting in not having to warn,
756 // so check again.
757 DeclToCheck = FD->getMostRecentDecl();
758 if (DeclToCheck != FD)
759 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
760 }
761
762 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
763 // If a variable usable in constant expressions is referenced,
764 // don't warn if it isn't used: if the value of a variable is required
765 // for the computation of a constant expression, it doesn't make sense to
766 // warn even if the variable isn't odr-used. (isReferenced doesn't
767 // precisely reflect that, but it's a decent approximation.)
768 if (VD->isReferenced() &&
769 VD->mightBeUsableInConstantExpressions(SemaRef->Context))
770 return true;
771
772 if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
773 // If this is a variable template and none of its specializations is used,
774 // we should warn.
775 for (const auto *Spec : Template->specializations())
776 if (ShouldRemoveFromUnused(SemaRef, Spec))
777 return true;
778
779 // UnusedFileScopedDecls stores the first declaration.
780 // The declaration may have become definition so check again.
781 const VarDecl *DeclToCheck = VD->getDefinition();
782 if (DeclToCheck)
783 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
784
785 // Later redecls may add new information resulting in not having to warn,
786 // so check again.
787 DeclToCheck = VD->getMostRecentDecl();
788 if (DeclToCheck != VD)
789 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
790 }
791
792 return false;
793}
794
795static bool isFunctionOrVarDeclExternC(const NamedDecl *ND) {
796 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
797 return FD->isExternC();
798 return cast<VarDecl>(ND)->isExternC();
799}
800
801/// Determine whether ND is an external-linkage function or variable whose
802/// type has no linkage.
804 // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
805 // because we also want to catch the case where its type has VisibleNoLinkage,
806 // which does not affect the linkage of VD.
807 return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&
810}
811
812/// Obtains a sorted list of functions and variables that are undefined but
813/// ODR-used.
815 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
816 for (const auto &UndefinedUse : UndefinedButUsed) {
817 NamedDecl *ND = UndefinedUse.first;
818
819 // Ignore attributes that have become invalid.
820 if (ND->isInvalidDecl()) continue;
821
822 // __attribute__((weakref)) is basically a definition.
823 if (ND->hasAttr<WeakRefAttr>()) continue;
824
825 if (isa<CXXDeductionGuideDecl>(ND))
826 continue;
827
828 if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
829 // An exported function will always be emitted when defined, so even if
830 // the function is inline, it doesn't have to be emitted in this TU. An
831 // imported function implies that it has been exported somewhere else.
832 continue;
833 }
834
835 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
836 if (FD->isDefined())
837 continue;
838 if (FD->isExternallyVisible() &&
840 !FD->getMostRecentDecl()->isInlined() &&
841 !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
842 continue;
843 if (FD->getBuiltinID())
844 continue;
845 } else {
846 const auto *VD = cast<VarDecl>(ND);
847 if (VD->hasDefinition() != VarDecl::DeclarationOnly)
848 continue;
849 if (VD->isExternallyVisible() &&
851 !VD->getMostRecentDecl()->isInline() &&
852 !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
853 continue;
854
855 // Skip VarDecls that lack formal definitions but which we know are in
856 // fact defined somewhere.
857 if (VD->isKnownToBeDefined())
858 continue;
859 }
860
861 Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
862 }
863}
864
865/// checkUndefinedButUsed - Check for undefined objects with internal linkage
866/// or that are inline.
868 if (S.UndefinedButUsed.empty()) return;
869
870 // Collect all the still-undefined entities with internal linkage.
872 S.getUndefinedButUsed(Undefined);
873 if (Undefined.empty()) return;
874
875 for (const auto &Undef : Undefined) {
876 ValueDecl *VD = cast<ValueDecl>(Undef.first);
877 SourceLocation UseLoc = Undef.second;
878
879 if (S.isExternalWithNoLinkageType(VD)) {
880 // C++ [basic.link]p8:
881 // A type without linkage shall not be used as the type of a variable
882 // or function with external linkage unless
883 // -- the entity has C language linkage
884 // -- the entity is not odr-used or is defined in the same TU
885 //
886 // As an extension, accept this in cases where the type is externally
887 // visible, since the function or variable actually can be defined in
888 // another translation unit in that case.
890 ? diag::ext_undefined_internal_type
891 : diag::err_undefined_internal_type)
892 << isa<VarDecl>(VD) << VD;
893 } else if (!VD->isExternallyVisible()) {
894 // FIXME: We can promote this to an error. The function or variable can't
895 // be defined anywhere else, so the program must necessarily violate the
896 // one definition rule.
897 bool IsImplicitBase = false;
898 if (const auto *BaseD = dyn_cast<FunctionDecl>(VD)) {
899 auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>();
900 if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive(
901 llvm::omp::TraitProperty::
902 implementation_extension_disable_implicit_base)) {
903 const auto *Func = cast<FunctionDecl>(
904 cast<DeclRefExpr>(DVAttr->getVariantFuncRef())->getDecl());
905 IsImplicitBase = BaseD->isImplicit() &&
906 Func->getIdentifier()->isMangledOpenMPVariantName();
907 }
908 }
909 if (!S.getLangOpts().OpenMP || !IsImplicitBase)
910 S.Diag(VD->getLocation(), diag::warn_undefined_internal)
911 << isa<VarDecl>(VD) << VD;
912 } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
913 (void)FD;
914 assert(FD->getMostRecentDecl()->isInlined() &&
915 "used object requires definition but isn't inline or internal?");
916 // FIXME: This is ill-formed; we should reject.
917 S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
918 } else {
919 assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
920 "used var requires definition but isn't inline or internal?");
921 S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
922 }
923 if (UseLoc.isValid())
924 S.Diag(UseLoc, diag::note_used_here);
925 }
926
927 S.UndefinedButUsed.clear();
928}
929
931 if (!ExternalSource)
932 return;
933
935 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
936 for (auto &WeakID : WeakIDs)
937 (void)WeakUndeclaredIdentifiers[WeakID.first].insert(WeakID.second);
938}
939
940
941typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
942
943/// Returns true, if all methods and nested classes of the given
944/// CXXRecordDecl are defined in this translation unit.
945///
946/// Should only be called from ActOnEndOfTranslationUnit so that all
947/// definitions are actually read.
949 RecordCompleteMap &MNCComplete) {
950 RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
951 if (Cache != MNCComplete.end())
952 return Cache->second;
953 if (!RD->isCompleteDefinition())
954 return false;
955 bool Complete = true;
957 E = RD->decls_end();
958 I != E && Complete; ++I) {
959 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
960 Complete = M->isDefined() || M->isDefaulted() ||
961 (M->isPure() && !isa<CXXDestructorDecl>(M));
962 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
963 // If the template function is marked as late template parsed at this
964 // point, it has not been instantiated and therefore we have not
965 // performed semantic analysis on it yet, so we cannot know if the type
966 // can be considered complete.
967 Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
968 F->getTemplatedDecl()->isDefined();
969 else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
970 if (R->isInjectedClassName())
971 continue;
972 if (R->hasDefinition())
973 Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
974 MNCComplete);
975 else
976 Complete = false;
977 }
978 }
979 MNCComplete[RD] = Complete;
980 return Complete;
981}
982
983/// Returns true, if the given CXXRecordDecl is fully defined in this
984/// translation unit, i.e. all methods are defined or pure virtual and all
985/// friends, friend functions and nested classes are fully defined in this
986/// translation unit.
987///
988/// Should only be called from ActOnEndOfTranslationUnit so that all
989/// definitions are actually read.
991 RecordCompleteMap &RecordsComplete,
992 RecordCompleteMap &MNCComplete) {
993 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
994 if (Cache != RecordsComplete.end())
995 return Cache->second;
996 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
998 E = RD->friend_end();
999 I != E && Complete; ++I) {
1000 // Check if friend classes and methods are complete.
1001 if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
1002 // Friend classes are available as the TypeSourceInfo of the FriendDecl.
1003 if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
1004 Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
1005 else
1006 Complete = false;
1007 } else {
1008 // Friend functions are available through the NamedDecl of FriendDecl.
1009 if (const FunctionDecl *FD =
1010 dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
1011 Complete = FD->isDefined();
1012 else
1013 // This is a template friend, give up.
1014 Complete = false;
1015 }
1016 }
1017 RecordsComplete[RD] = Complete;
1018 return Complete;
1019}
1020
1022 if (ExternalSource)
1023 ExternalSource->ReadUnusedLocalTypedefNameCandidates(
1026 if (TD->isReferenced())
1027 continue;
1028 Diag(TD->getLocation(), diag::warn_unused_local_typedef)
1029 << isa<TypeAliasDecl>(TD) << TD->getDeclName();
1030 }
1032}
1033
1034/// This is called before the very first declaration in the translation unit
1035/// is parsed. Note that the ASTContext may have already injected some
1036/// declarations.
1038 if (getLangOpts().CPlusPlusModules &&
1039 getLangOpts().getCompilingModule() == LangOptions::CMK_HeaderUnit)
1040 HandleStartOfHeaderUnit();
1041}
1042
1044 // No explicit actions are required at the end of the global module fragment.
1045 if (Kind == TUFragmentKind::Global)
1046 return;
1047
1048 // Transfer late parsed template instantiations over to the pending template
1049 // instantiation list. During normal compilation, the late template parser
1050 // will be installed and instantiating these templates will succeed.
1051 //
1052 // If we are building a TU prefix for serialization, it is also safe to
1053 // transfer these over, even though they are not parsed. The end of the TU
1054 // should be outside of any eager template instantiation scope, so when this
1055 // AST is deserialized, these templates will not be parsed until the end of
1056 // the combined TU.
1061
1062 // If DefinedUsedVTables ends up marking any virtual member functions it
1063 // might lead to more pending template instantiations, which we then need
1064 // to instantiate.
1066
1067 // C++: Perform implicit template instantiations.
1068 //
1069 // FIXME: When we perform these implicit instantiations, we do not
1070 // carefully keep track of the point of instantiation (C++ [temp.point]).
1071 // This means that name lookup that occurs within the template
1072 // instantiation will always happen at the end of the translation unit,
1073 // so it will find some names that are not required to be found. This is
1074 // valid, but we could do better by diagnosing if an instantiation uses a
1075 // name that was not visible at its first point of instantiation.
1076 if (ExternalSource) {
1077 // Load pending instantiations from the external source.
1079 ExternalSource->ReadPendingInstantiations(Pending);
1080 for (auto PII : Pending)
1081 if (auto Func = dyn_cast<FunctionDecl>(PII.first))
1082 Func->setInstantiationIsPending(true);
1084 Pending.begin(), Pending.end());
1085 }
1086
1087 {
1088 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1090 }
1091
1093
1094 assert(LateParsedInstantiations.empty() &&
1095 "end of TU template instantiation should not create more "
1096 "late-parsed templates");
1097
1098 // Report diagnostics for uncorrected delayed typos. Ideally all of them
1099 // should have been corrected by that time, but it is very hard to cover all
1100 // cases in practice.
1101 for (const auto &Typo : DelayedTypos) {
1102 // We pass an empty TypoCorrection to indicate no correction was performed.
1103 Typo.second.DiagHandler(TypoCorrection());
1104 }
1105 DelayedTypos.clear();
1106}
1107
1108/// ActOnEndOfTranslationUnit - This is called at the very end of the
1109/// translation unit when EOF is reached and all but the top-level scope is
1110/// popped.
1112 assert(DelayedDiagnostics.getCurrentPool() == nullptr
1113 && "reached end of translation unit with a pool attached?");
1114
1115 // If code completion is enabled, don't perform any end-of-translation-unit
1116 // work.
1118 return;
1119
1120 // Complete translation units and modules define vtables and perform implicit
1121 // instantiations. PCH files do not.
1122 if (TUKind != TU_Prefix) {
1124
1126 !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1130
1133
1135 } else {
1136 // If we are building a TU prefix for serialization, it is safe to transfer
1137 // these over, even though they are not parsed. The end of the TU should be
1138 // outside of any eager template instantiation scope, so when this AST is
1139 // deserialized, these templates will not be parsed until the end of the
1140 // combined TU.
1145
1146 if (LangOpts.PCHInstantiateTemplates) {
1147 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1149 }
1150 }
1151
1155
1156 // All delayed member exception specs should be checked or we end up accepting
1157 // incompatible declarations.
1160
1161 // All dllexport classes should have been processed already.
1162 assert(DelayedDllExportClasses.empty());
1163 assert(DelayedDllExportMemberFunctions.empty());
1164
1165 // Remove file scoped decls that turned out to be used.
1167 std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
1169 [this](const DeclaratorDecl *DD) {
1170 return ShouldRemoveFromUnused(this, DD);
1171 }),
1173
1174 if (TUKind == TU_Prefix) {
1175 // Translation unit prefixes don't need any of the checking below.
1177 TUScope = nullptr;
1178 return;
1179 }
1180
1181 // Check for #pragma weak identifiers that were never declared
1183 for (const auto &WeakIDs : WeakUndeclaredIdentifiers) {
1184 if (WeakIDs.second.empty())
1185 continue;
1186
1187 Decl *PrevDecl = LookupSingleName(TUScope, WeakIDs.first, SourceLocation(),
1189 if (PrevDecl != nullptr &&
1190 !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
1191 for (const auto &WI : WeakIDs.second)
1192 Diag(WI.getLocation(), diag::warn_attribute_wrong_decl_type)
1193 << "'weak'" << /*isRegularKeyword=*/0 << ExpectedVariableOrFunction;
1194 else
1195 for (const auto &WI : WeakIDs.second)
1196 Diag(WI.getLocation(), diag::warn_weak_identifier_undeclared)
1197 << WeakIDs.first;
1198 }
1199
1200 if (LangOpts.CPlusPlus11 &&
1201 !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
1203
1204 if (!Diags.hasErrorOccurred()) {
1205 if (ExternalSource)
1206 ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
1207 checkUndefinedButUsed(*this);
1208 }
1209
1210 // A global-module-fragment is only permitted within a module unit.
1211 bool DiagnosedMissingModuleDeclaration = false;
1212 if (!ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1214 Diag(ModuleScopes.back().BeginLoc,
1215 diag::err_module_declaration_missing_after_global_module_introducer);
1216 DiagnosedMissingModuleDeclaration = true;
1217 }
1218
1219 if (TUKind == TU_Module) {
1220 // If we are building a module interface unit, we need to have seen the
1221 // module declaration by now.
1222 if (getLangOpts().getCompilingModule() ==
1224 !isCurrentModulePurview() && !DiagnosedMissingModuleDeclaration) {
1225 // FIXME: Make a better guess as to where to put the module declaration.
1226 Diag(getSourceManager().getLocForStartOfFile(
1227 getSourceManager().getMainFileID()),
1228 diag::err_module_declaration_missing);
1229 }
1230
1231 // If we are building a module, resolve all of the exported declarations
1232 // now.
1233 if (Module *CurrentModule = PP.getCurrentModule()) {
1235
1237 Stack.push_back(CurrentModule);
1238 while (!Stack.empty()) {
1239 Module *Mod = Stack.pop_back_val();
1240
1241 // Resolve the exported declarations and conflicts.
1242 // FIXME: Actually complain, once we figure out how to teach the
1243 // diagnostic client to deal with complaints in the module map at this
1244 // point.
1245 ModMap.resolveExports(Mod, /*Complain=*/false);
1246 ModMap.resolveUses(Mod, /*Complain=*/false);
1247 ModMap.resolveConflicts(Mod, /*Complain=*/false);
1248
1249 // Queue the submodules, so their exports will also be resolved.
1250 auto SubmodulesRange = Mod->submodules();
1251 Stack.append(SubmodulesRange.begin(), SubmodulesRange.end());
1252 }
1253 }
1254
1255 // Now we can decide whether the modules we're building need an initializer.
1256 if (Module *CurrentModule = getCurrentModule();
1257 CurrentModule && CurrentModule->isInterfaceOrPartition()) {
1258 auto DoesModNeedInit = [this](Module *M) {
1259 if (!getASTContext().getModuleInitializers(M).empty())
1260 return true;
1261 for (auto [Exported, _] : M->Exports)
1262 if (Exported->isNamedModuleInterfaceHasInit())
1263 return true;
1264 for (Module *I : M->Imports)
1266 return true;
1267
1268 return false;
1269 };
1270
1271 CurrentModule->NamedModuleHasInit =
1272 DoesModNeedInit(CurrentModule) ||
1273 llvm::any_of(CurrentModule->submodules(),
1274 [&](auto *SubM) { return DoesModNeedInit(SubM); });
1275 }
1276
1277 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
1278 // modules when they are built, not every time they are used.
1280 }
1281
1282 // C++ standard modules. Diagnose cases where a function is declared inline
1283 // in the module purview but has no definition before the end of the TU or
1284 // the start of a Private Module Fragment (if one is present).
1285 if (!PendingInlineFuncDecls.empty()) {
1286 for (auto *D : PendingInlineFuncDecls) {
1287 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1288 bool DefInPMF = false;
1289 if (auto *FDD = FD->getDefinition()) {
1290 DefInPMF = FDD->getOwningModule()->isPrivateModule();
1291 if (!DefInPMF)
1292 continue;
1293 }
1294 Diag(FD->getLocation(), diag::err_export_inline_not_defined)
1295 << DefInPMF;
1296 // If we have a PMF it should be at the end of the ModuleScopes.
1297 if (DefInPMF &&
1298 ModuleScopes.back().Module->Kind == Module::PrivateModuleFragment) {
1299 Diag(ModuleScopes.back().BeginLoc,
1300 diag::note_private_module_fragment);
1301 }
1302 }
1303 }
1304 PendingInlineFuncDecls.clear();
1305 }
1306
1307 // C99 6.9.2p2:
1308 // A declaration of an identifier for an object that has file
1309 // scope without an initializer, and without a storage-class
1310 // specifier or with the storage-class specifier static,
1311 // constitutes a tentative definition. If a translation unit
1312 // contains one or more tentative definitions for an identifier,
1313 // and the translation unit contains no external definition for
1314 // that identifier, then the behavior is exactly as if the
1315 // translation unit contains a file scope declaration of that
1316 // identifier, with the composite type as of the end of the
1317 // translation unit, with an initializer equal to 0.
1318 llvm::SmallSet<VarDecl *, 32> Seen;
1319 for (TentativeDefinitionsType::iterator
1321 TEnd = TentativeDefinitions.end();
1322 T != TEnd; ++T) {
1323 VarDecl *VD = (*T)->getActingDefinition();
1324
1325 // If the tentative definition was completed, getActingDefinition() returns
1326 // null. If we've already seen this variable before, insert()'s second
1327 // return value is false.
1328 if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
1329 continue;
1330
1331 if (const IncompleteArrayType *ArrayT
1333 // Set the length of the array to 1 (C99 6.9.2p5).
1334 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
1335 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
1337 ArrayT->getElementType(), One, nullptr, ArraySizeModifier::Normal, 0);
1338 VD->setType(T);
1339 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
1340 diag::err_tentative_def_incomplete_type))
1341 VD->setInvalidDecl();
1342
1343 // No initialization is performed for a tentative definition.
1345
1346 // Notify the consumer that we've completed a tentative definition.
1347 if (!VD->isInvalidDecl())
1349 }
1350
1351 for (auto *D : ExternalDeclarations) {
1352 if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed())
1353 continue;
1354
1356 }
1357
1358 // If there were errors, disable 'unused' warnings since they will mostly be
1359 // noise. Don't warn for a use from a module: either we should warn on all
1360 // file-scope declarations in modules or not at all, but whether the
1361 // declaration is used is immaterial.
1362 if (!Diags.hasErrorOccurred() && TUKind != TU_Module) {
1363 // Output warning for unused file scoped decls.
1364 for (UnusedFileScopedDeclsType::iterator
1367 I != E; ++I) {
1368 if (ShouldRemoveFromUnused(this, *I))
1369 continue;
1370
1371 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1372 const FunctionDecl *DiagD;
1373 if (!FD->hasBody(DiagD))
1374 DiagD = FD;
1375 if (DiagD->isDeleted())
1376 continue; // Deleted functions are supposed to be unused.
1377 SourceRange DiagRange = DiagD->getLocation();
1378 if (const ASTTemplateArgumentListInfo *ASTTAL =
1380 DiagRange.setEnd(ASTTAL->RAngleLoc);
1381 if (DiagD->isReferenced()) {
1382 if (isa<CXXMethodDecl>(DiagD))
1383 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
1384 << DiagD << DiagRange;
1385 else {
1386 if (FD->getStorageClass() == SC_Static &&
1387 !FD->isInlineSpecified() &&
1389 SourceMgr.getExpansionLoc(FD->getLocation())))
1390 Diag(DiagD->getLocation(),
1391 diag::warn_unneeded_static_internal_decl)
1392 << DiagD << DiagRange;
1393 else
1394 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1395 << /*function=*/0 << DiagD << DiagRange;
1396 }
1397 } else {
1398 if (FD->getDescribedFunctionTemplate())
1399 Diag(DiagD->getLocation(), diag::warn_unused_template)
1400 << /*function=*/0 << DiagD << DiagRange;
1401 else
1402 Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD)
1403 ? diag::warn_unused_member_function
1404 : diag::warn_unused_function)
1405 << DiagD << DiagRange;
1406 }
1407 } else {
1408 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
1409 if (!DiagD)
1410 DiagD = cast<VarDecl>(*I);
1411 SourceRange DiagRange = DiagD->getLocation();
1412 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(DiagD)) {
1413 if (const ASTTemplateArgumentListInfo *ASTTAL =
1414 VTSD->getTemplateArgsInfo())
1415 DiagRange.setEnd(ASTTAL->RAngleLoc);
1416 }
1417 if (DiagD->isReferenced()) {
1418 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1419 << /*variable=*/1 << DiagD << DiagRange;
1420 } else if (DiagD->getDescribedVarTemplate()) {
1421 Diag(DiagD->getLocation(), diag::warn_unused_template)
1422 << /*variable=*/1 << DiagD << DiagRange;
1423 } else if (DiagD->getType().isConstQualified()) {
1424 const SourceManager &SM = SourceMgr;
1425 if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
1427 Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
1428 << DiagD << DiagRange;
1429 } else {
1430 Diag(DiagD->getLocation(), diag::warn_unused_variable)
1431 << DiagD << DiagRange;
1432 }
1433 }
1434 }
1435
1437 }
1438
1439 if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
1440 // FIXME: Load additional unused private field candidates from the external
1441 // source.
1442 RecordCompleteMap RecordsComplete;
1443 RecordCompleteMap MNCComplete;
1444 for (const NamedDecl *D : UnusedPrivateFields) {
1445 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1446 if (RD && !RD->isUnion() &&
1447 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
1448 Diag(D->getLocation(), diag::warn_unused_private_field)
1449 << D->getDeclName();
1450 }
1451 }
1452 }
1453
1454 if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
1455 if (ExternalSource)
1456 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
1457 for (const auto &DeletedFieldInfo : DeleteExprs) {
1458 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
1459 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
1460 DeleteExprLoc.second);
1461 }
1462 }
1463 }
1464
1466
1467 // Check we've noticed that we're no longer parsing the initializer for every
1468 // variable. If we miss cases, then at best we have a performance issue and
1469 // at worst a rejects-valid bug.
1470 assert(ParsingInitForAutoVars.empty() &&
1471 "Didn't unmark var as having its initializer parsed");
1472
1474 TUScope = nullptr;
1475}
1476
1477
1478//===----------------------------------------------------------------------===//
1479// Helper functions.
1480//===----------------------------------------------------------------------===//
1481
1483 DeclContext *DC = CurContext;
1484
1485 while (true) {
1486 if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC) ||
1487 isa<RequiresExprBodyDecl>(DC)) {
1488 DC = DC->getParent();
1489 } else if (!AllowLambda && isa<CXXMethodDecl>(DC) &&
1490 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
1491 cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
1492 DC = DC->getParent()->getParent();
1493 } else break;
1494 }
1495
1496 return DC;
1497}
1498
1499/// getCurFunctionDecl - If inside of a function body, this returns a pointer
1500/// to the function decl for the function being parsed. If we're currently
1501/// in a 'block', this returns the containing context.
1502FunctionDecl *Sema::getCurFunctionDecl(bool AllowLambda) const {
1503 DeclContext *DC = getFunctionLevelDeclContext(AllowLambda);
1504 return dyn_cast<FunctionDecl>(DC);
1505}
1506
1509 while (isa<RecordDecl>(DC))
1510 DC = DC->getParent();
1511 return dyn_cast<ObjCMethodDecl>(DC);
1512}
1513
1516 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
1517 return cast<NamedDecl>(DC);
1518 return nullptr;
1519}
1520
1522 if (getLangOpts().OpenCL)
1524 return LangAS::Default;
1525}
1526
1527void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
1528 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1529 // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1530 // been made more painfully obvious by the refactor that introduced this
1531 // function, but it is possible that the incoming argument can be
1532 // eliminated. If it truly cannot be (for example, there is some reentrancy
1533 // issue I am not seeing yet), then there should at least be a clarifying
1534 // comment somewhere.
1535 if (std::optional<TemplateDeductionInfo *> Info = isSFINAEContext()) {
1539 // We'll report the diagnostic below.
1540 break;
1541
1543 // Count this failure so that we know that template argument deduction
1544 // has failed.
1546
1547 // Make a copy of this suppressed diagnostic and store it with the
1548 // template-deduction information.
1549 if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1550 Diagnostic DiagInfo(&Diags);
1551 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1553 }
1554
1556 Diags.Clear();
1557 return;
1558
1560 // Per C++ Core Issue 1170, access control is part of SFINAE.
1561 // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
1562 // make access control a part of SFINAE for the purposes of checking
1563 // type traits.
1565 break;
1566
1568
1569 // Suppress this diagnostic.
1571
1572 // Make a copy of this suppressed diagnostic and store it with the
1573 // template-deduction information.
1574 if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1575 Diagnostic DiagInfo(&Diags);
1576 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1578 }
1579
1581 Diags.Clear();
1582
1583 // Now the diagnostic state is clear, produce a C++98 compatibility
1584 // warning.
1585 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1586
1587 // The last diagnostic which Sema produced was ignored. Suppress any
1588 // notes attached to it.
1590 return;
1591 }
1592
1594 // Make a copy of this suppressed diagnostic and store it with the
1595 // template-deduction information;
1596 if (*Info) {
1597 Diagnostic DiagInfo(&Diags);
1598 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1600 }
1601
1602 // Suppress this diagnostic.
1604 Diags.Clear();
1605 return;
1606 }
1607 }
1608
1609 // Copy the diagnostic printing policy over the ASTContext printing policy.
1610 // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292
1612
1613 // Emit the diagnostic.
1615 return;
1616
1617 // If this is not a note, and we're in a template instantiation
1618 // that is different from the last template instantiation where
1619 // we emitted an error, print a template instantiation
1620 // backtrace.
1621 if (!DiagnosticIDs::isBuiltinNote(DiagID))
1623}
1624
1626Sema::Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint) {
1627 return Diag(Loc, PD.getDiagID(), DeferHint) << PD;
1628}
1629
1632 return true;
1633 auto *FD = dyn_cast<FunctionDecl>(CurContext);
1634 if (!FD)
1635 return false;
1636 auto Loc = DeviceDeferredDiags.find(FD);
1637 if (Loc == DeviceDeferredDiags.end())
1638 return false;
1639 for (auto PDAt : Loc->second) {
1640 if (DiagnosticIDs::isDefaultMappingAsError(PDAt.second.getDiagID()))
1641 return true;
1642 }
1643 return false;
1644}
1645
1646// Print notes showing how we can reach FD starting from an a priori
1647// known-callable function.
1648static void emitCallStackNotes(Sema &S, const FunctionDecl *FD) {
1649 auto FnIt = S.DeviceKnownEmittedFns.find(FD);
1650 while (FnIt != S.DeviceKnownEmittedFns.end()) {
1651 // Respect error limit.
1653 return;
1654 DiagnosticBuilder Builder(
1655 S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
1656 Builder << FnIt->second.FD;
1657 FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD);
1658 }
1659}
1660
1661namespace {
1662
1663/// Helper class that emits deferred diagnostic messages if an entity directly
1664/// or indirectly using the function that causes the deferred diagnostic
1665/// messages is known to be emitted.
1666///
1667/// During parsing of AST, certain diagnostic messages are recorded as deferred
1668/// diagnostics since it is unknown whether the functions containing such
1669/// diagnostics will be emitted. A list of potentially emitted functions and
1670/// variables that may potentially trigger emission of functions are also
1671/// recorded. DeferredDiagnosticsEmitter recursively visits used functions
1672/// by each function to emit deferred diagnostics.
1673///
1674/// During the visit, certain OpenMP directives or initializer of variables
1675/// with certain OpenMP attributes will cause subsequent visiting of any
1676/// functions enter a state which is called OpenMP device context in this
1677/// implementation. The state is exited when the directive or initializer is
1678/// exited. This state can change the emission states of subsequent uses
1679/// of functions.
1680///
1681/// Conceptually the functions or variables to be visited form a use graph
1682/// where the parent node uses the child node. At any point of the visit,
1683/// the tree nodes traversed from the tree root to the current node form a use
1684/// stack. The emission state of the current node depends on two factors:
1685/// 1. the emission state of the root node
1686/// 2. whether the current node is in OpenMP device context
1687/// If the function is decided to be emitted, its contained deferred diagnostics
1688/// are emitted, together with the information about the use stack.
1689///
1690class DeferredDiagnosticsEmitter
1691 : public UsedDeclVisitor<DeferredDiagnosticsEmitter> {
1692public:
1694
1695 // Whether the function is already in the current use-path.
1697
1698 // The current use-path.
1700
1701 // Whether the visiting of the function has been done. Done[0] is for the
1702 // case not in OpenMP device context. Done[1] is for the case in OpenMP
1703 // device context. We need two sets because diagnostics emission may be
1704 // different depending on whether it is in OpenMP device context.
1706
1707 // Emission state of the root node of the current use graph.
1708 bool ShouldEmitRootNode;
1709
1710 // Current OpenMP device context level. It is initialized to 0 and each
1711 // entering of device context increases it by 1 and each exit decreases
1712 // it by 1. Non-zero value indicates it is currently in device context.
1713 unsigned InOMPDeviceContext;
1714
1715 DeferredDiagnosticsEmitter(Sema &S)
1716 : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
1717
1718 bool shouldVisitDiscardedStmt() const { return false; }
1719
1720 void VisitOMPTargetDirective(OMPTargetDirective *Node) {
1721 ++InOMPDeviceContext;
1722 Inherited::VisitOMPTargetDirective(Node);
1723 --InOMPDeviceContext;
1724 }
1725
1726 void visitUsedDecl(SourceLocation Loc, Decl *D) {
1727 if (isa<VarDecl>(D))
1728 return;
1729 if (auto *FD = dyn_cast<FunctionDecl>(D))
1730 checkFunc(Loc, FD);
1731 else
1732 Inherited::visitUsedDecl(Loc, D);
1733 }
1734
1735 void checkVar(VarDecl *VD) {
1736 assert(VD->isFileVarDecl() &&
1737 "Should only check file-scope variables");
1738 if (auto *Init = VD->getInit()) {
1739 auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);
1740 bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
1741 *DevTy == OMPDeclareTargetDeclAttr::DT_Any);
1742 if (IsDev)
1743 ++InOMPDeviceContext;
1744 this->Visit(Init);
1745 if (IsDev)
1746 --InOMPDeviceContext;
1747 }
1748 }
1749
1750 void checkFunc(SourceLocation Loc, FunctionDecl *FD) {
1751 auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0];
1752 FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back();
1753 if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) ||
1754 S.shouldIgnoreInHostDeviceCheck(FD) || InUsePath.count(FD))
1755 return;
1756 // Finalize analysis of OpenMP-specific constructs.
1757 if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 &&
1758 (ShouldEmitRootNode || InOMPDeviceContext))
1759 S.finalizeOpenMPDelayedAnalysis(Caller, FD, Loc);
1760 if (Caller)
1761 S.DeviceKnownEmittedFns[FD] = {Caller, Loc};
1762 // Always emit deferred diagnostics for the direct users. This does not
1763 // lead to explosion of diagnostics since each user is visited at most
1764 // twice.
1765 if (ShouldEmitRootNode || InOMPDeviceContext)
1766 emitDeferredDiags(FD, Caller);
1767 // Do not revisit a function if the function body has been completely
1768 // visited before.
1769 if (!Done.insert(FD).second)
1770 return;
1771 InUsePath.insert(FD);
1772 UsePath.push_back(FD);
1773 if (auto *S = FD->getBody()) {
1774 this->Visit(S);
1775 }
1776 UsePath.pop_back();
1777 InUsePath.erase(FD);
1778 }
1779
1780 void checkRecordedDecl(Decl *D) {
1781 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1782 ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) ==
1783 Sema::FunctionEmissionStatus::Emitted;
1784 checkFunc(SourceLocation(), FD);
1785 } else
1786 checkVar(cast<VarDecl>(D));
1787 }
1788
1789 // Emit any deferred diagnostics for FD
1790 void emitDeferredDiags(FunctionDecl *FD, bool ShowCallStack) {
1791 auto It = S.DeviceDeferredDiags.find(FD);
1792 if (It == S.DeviceDeferredDiags.end())
1793 return;
1794 bool HasWarningOrError = false;
1795 bool FirstDiag = true;
1796 for (PartialDiagnosticAt &PDAt : It->second) {
1797 // Respect error limit.
1799 return;
1800 const SourceLocation &Loc = PDAt.first;
1801 const PartialDiagnostic &PD = PDAt.second;
1802 HasWarningOrError |=
1805 {
1806 DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
1807 PD.Emit(Builder);
1808 }
1809 // Emit the note on the first diagnostic in case too many diagnostics
1810 // cause the note not emitted.
1811 if (FirstDiag && HasWarningOrError && ShowCallStack) {
1812 emitCallStackNotes(S, FD);
1813 FirstDiag = false;
1814 }
1815 }
1816 }
1817};
1818} // namespace
1819
1821 if (ExternalSource)
1822 ExternalSource->ReadDeclsToCheckForDeferredDiags(
1823 DeclsToCheckForDeferredDiags);
1824
1825 if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) ||
1826 DeclsToCheckForDeferredDiags.empty())
1827 return;
1828
1829 DeferredDiagnosticsEmitter DDE(*this);
1830 for (auto *D : DeclsToCheckForDeferredDiags)
1831 DDE.checkRecordedDecl(D);
1832}
1833
1834// In CUDA, there are some constructs which may appear in semantically-valid
1835// code, but trigger errors if we ever generate code for the function in which
1836// they appear. Essentially every construct you're not allowed to use on the
1837// device falls into this category, because you are allowed to use these
1838// constructs in a __host__ __device__ function, but only if that function is
1839// never codegen'ed on the device.
1840//
1841// To handle semantic checking for these constructs, we keep track of the set of
1842// functions we know will be emitted, either because we could tell a priori that
1843// they would be emitted, or because they were transitively called by a
1844// known-emitted function.
1845//
1846// We also keep a partial call graph of which not-known-emitted functions call
1847// which other not-known-emitted functions.
1848//
1849// When we see something which is illegal if the current function is emitted
1850// (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
1851// CheckCUDACall), we first check if the current function is known-emitted. If
1852// so, we immediately output the diagnostic.
1853//
1854// Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags
1855// until we discover that the function is known-emitted, at which point we take
1856// it out of this map and emit the diagnostic.
1857
1859 unsigned DiagID,
1860 const FunctionDecl *Fn,
1861 Sema &S)
1862 : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
1863 ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
1864 switch (K) {
1865 case K_Nop:
1866 break;
1867 case K_Immediate:
1869 ImmediateDiag.emplace(
1870 ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID));
1871 break;
1872 case K_Deferred:
1873 assert(Fn && "Must have a function to attach the deferred diag to.");
1874 auto &Diags = S.DeviceDeferredDiags[Fn];
1875 PartialDiagId.emplace(Diags.size());
1876 Diags.emplace_back(Loc, S.PDiag(DiagID));
1877 break;
1878 }
1879}
1880
1882 : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
1883 ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
1884 PartialDiagId(D.PartialDiagId) {
1885 // Clean the previous diagnostics.
1886 D.ShowCallStack = false;
1887 D.ImmediateDiag.reset();
1888 D.PartialDiagId.reset();
1889}
1890
1892 if (ImmediateDiag) {
1893 // Emit our diagnostic and, if it was a warning or error, output a callstack
1894 // if Fn isn't a priori known-emitted.
1895 bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
1896 DiagID, Loc) >= DiagnosticsEngine::Warning;
1897 ImmediateDiag.reset(); // Emit the immediate diag.
1898 if (IsWarningOrError && ShowCallStack)
1899 emitCallStackNotes(S, Fn);
1900 } else {
1901 assert((!PartialDiagId || ShowCallStack) &&
1902 "Must always show call stack for deferred diags.");
1903 }
1904}
1905
1907Sema::targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD) {
1908 FD = FD ? FD : getCurFunctionDecl();
1909 if (LangOpts.OpenMP)
1910 return LangOpts.OpenMPIsTargetDevice
1911 ? diagIfOpenMPDeviceCode(Loc, DiagID, FD)
1912 : diagIfOpenMPHostCode(Loc, DiagID, FD);
1913 if (getLangOpts().CUDA)
1914 return getLangOpts().CUDAIsDevice ? CUDADiagIfDeviceCode(Loc, DiagID)
1915 : CUDADiagIfHostCode(Loc, DiagID);
1916
1917 if (getLangOpts().SYCLIsDevice)
1918 return SYCLDiagIfDeviceCode(Loc, DiagID);
1919
1921 FD, *this);
1922}
1923
1925 bool DeferHint) {
1926 bool IsError = Diags.getDiagnosticIDs()->isDefaultMappingAsError(DiagID);
1927 bool ShouldDefer = getLangOpts().CUDA && LangOpts.GPUDeferDiag &&
1929 (DeferHint || DeferDiags || !IsError);
1930 auto SetIsLastErrorImmediate = [&](bool Flag) {
1931 if (IsError)
1932 IsLastErrorImmediate = Flag;
1933 };
1934 if (!ShouldDefer) {
1935 SetIsLastErrorImmediate(true);
1937 DiagID, getCurFunctionDecl(), *this);
1938 }
1939
1940 SemaDiagnosticBuilder DB = getLangOpts().CUDAIsDevice
1941 ? CUDADiagIfDeviceCode(Loc, DiagID)
1942 : CUDADiagIfHostCode(Loc, DiagID);
1943 SetIsLastErrorImmediate(DB.isImmediate());
1944 return DB;
1945}
1946
1948 if (isUnevaluatedContext() || Ty.isNull())
1949 return;
1950
1951 // The original idea behind checkTypeSupport function is that unused
1952 // declarations can be replaced with an array of bytes of the same size during
1953 // codegen, such replacement doesn't seem to be possible for types without
1954 // constant byte size like zero length arrays. So, do a deep check for SYCL.
1955 if (D && LangOpts.SYCLIsDevice) {
1958 }
1959
1960 Decl *C = cast<Decl>(getCurLexicalContext());
1961
1962 // Memcpy operations for structs containing a member with unsupported type
1963 // are ok, though.
1964 if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) {
1965 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
1966 MD->isTrivial())
1967 return;
1968
1969 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD))
1970 if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial())
1971 return;
1972 }
1973
1974 // Try to associate errors with the lexical context, if that is a function, or
1975 // the value declaration otherwise.
1976 const FunctionDecl *FD = isa<FunctionDecl>(C)
1977 ? cast<FunctionDecl>(C)
1978 : dyn_cast_or_null<FunctionDecl>(D);
1979
1980 auto CheckDeviceType = [&](QualType Ty) {
1981 if (Ty->isDependentType())
1982 return;
1983
1984 if (Ty->isBitIntType()) {
1986 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
1987 if (D)
1988 PD << D;
1989 else
1990 PD << "expression";
1991 targetDiag(Loc, PD, FD)
1992 << false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/
1993 << Ty << Context.getTargetInfo().getTriple().str();
1994 }
1995 return;
1996 }
1997
1998 // Check if we are dealing with two 'long double' but with different
1999 // semantics.
2000 bool LongDoubleMismatched = false;
2001 if (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128) {
2002 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(Ty);
2003 if ((&Sem != &llvm::APFloat::PPCDoubleDouble() &&
2005 (&Sem == &llvm::APFloat::PPCDoubleDouble() &&
2007 LongDoubleMismatched = true;
2008 }
2009
2010 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
2013 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
2016 !LangOpts.CUDAIsDevice) ||
2017 LongDoubleMismatched) {
2018 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2019 if (D)
2020 PD << D;
2021 else
2022 PD << "expression";
2023
2024 if (targetDiag(Loc, PD, FD)
2025 << true /*show bit size*/
2026 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
2027 << false /*return*/ << Context.getTargetInfo().getTriple().str()) {
2028 if (D)
2029 D->setInvalidDecl();
2030 }
2031 if (D)
2032 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2033 }
2034 };
2035
2036 auto CheckType = [&](QualType Ty, bool IsRetTy = false) {
2037 if (LangOpts.SYCLIsDevice ||
2038 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice) ||
2039 LangOpts.CUDAIsDevice)
2040 CheckDeviceType(Ty);
2041
2043 const TargetInfo &TI = Context.getTargetInfo();
2044 if (!TI.hasLongDoubleType() && UnqualTy == Context.LongDoubleTy) {
2045 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2046 if (D)
2047 PD << D;
2048 else
2049 PD << "expression";
2050
2051 if (Diag(Loc, PD, FD)
2052 << false /*show bit size*/ << 0 << Ty << false /*return*/
2053 << TI.getTriple().str()) {
2054 if (D)
2055 D->setInvalidDecl();
2056 }
2057 if (D)
2058 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2059 }
2060
2061 bool IsDouble = UnqualTy == Context.DoubleTy;
2062 bool IsFloat = UnqualTy == Context.FloatTy;
2063 if (IsRetTy && !TI.hasFPReturn() && (IsDouble || IsFloat)) {
2064 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2065 if (D)
2066 PD << D;
2067 else
2068 PD << "expression";
2069
2070 if (Diag(Loc, PD, FD)
2071 << false /*show bit size*/ << 0 << Ty << true /*return*/
2072 << TI.getTriple().str()) {
2073 if (D)
2074 D->setInvalidDecl();
2075 }
2076 if (D)
2077 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2078 }
2079
2080 if (TI.hasRISCVVTypes() && Ty->isRVVType())
2081 checkRVVTypeSupport(Ty, Loc, D);
2082
2083 // Don't allow SVE types in functions without a SVE target.
2084 if (Ty->isSVESizelessBuiltinType() && FD && FD->hasBody()) {
2085 llvm::StringMap<bool> CallerFeatureMap;
2086 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
2088 "sve", CallerFeatureMap))
2089 Diag(D->getLocation(), diag::err_sve_vector_in_non_sve_target) << Ty;
2090 }
2091 };
2092
2093 CheckType(Ty);
2094 if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
2095 for (const auto &ParamTy : FPTy->param_types())
2096 CheckType(ParamTy);
2097 CheckType(FPTy->getReturnType(), /*IsRetTy=*/true);
2098 }
2099 if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Ty))
2100 CheckType(FNPTy->getReturnType(), /*IsRetTy=*/true);
2101}
2102
2103/// Looks through the macro-expansion chain for the given
2104/// location, looking for a macro expansion with the given name.
2105/// If one is found, returns true and sets the location to that
2106/// expansion loc.
2107bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
2108 SourceLocation loc = locref;
2109 if (!loc.isMacroID()) return false;
2110
2111 // There's no good way right now to look at the intermediate
2112 // expansions, so just jump to the expansion location.
2113 loc = getSourceManager().getExpansionLoc(loc);
2114
2115 // If that's written with the name, stop here.
2116 SmallString<16> buffer;
2117 if (getPreprocessor().getSpelling(loc, buffer) == name) {
2118 locref = loc;
2119 return true;
2120 }
2121 return false;
2122}
2123
2124/// Determines the active Scope associated with the given declaration
2125/// context.
2126///
2127/// This routine maps a declaration context to the active Scope object that
2128/// represents that declaration context in the parser. It is typically used
2129/// from "scope-less" code (e.g., template instantiation, lazy creation of
2130/// declarations) that injects a name for name-lookup purposes and, therefore,
2131/// must update the Scope.
2132///
2133/// \returns The scope corresponding to the given declaraion context, or NULL
2134/// if no such scope is open.
2136
2137 if (!Ctx)
2138 return nullptr;
2139
2140 Ctx = Ctx->getPrimaryContext();
2141 for (Scope *S = getCurScope(); S; S = S->getParent()) {
2142 // Ignore scopes that cannot have declarations. This is important for
2143 // out-of-line definitions of static class members.
2144 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
2145 if (DeclContext *Entity = S->getEntity())
2146 if (Ctx == Entity->getPrimaryContext())
2147 return S;
2148 }
2149
2150 return nullptr;
2151}
2152
2153/// Enter a new function scope
2155 if (FunctionScopes.empty() && CachedFunctionScope) {
2156 // Use CachedFunctionScope to avoid allocating memory when possible.
2157 CachedFunctionScope->Clear();
2158 FunctionScopes.push_back(CachedFunctionScope.release());
2159 } else {
2161 }
2162 if (LangOpts.OpenMP)
2163 pushOpenMPFunctionRegion();
2164}
2165
2168 BlockScope, Block));
2170}
2171
2174 FunctionScopes.push_back(LSI);
2176 return LSI;
2177}
2178
2180 if (LambdaScopeInfo *const LSI = getCurLambda()) {
2181 LSI->AutoTemplateParameterDepth = Depth;
2182 return;
2183 }
2184 llvm_unreachable(
2185 "Remove assertion if intentionally called in a non-lambda context.");
2186}
2187
2188// Check that the type of the VarDecl has an accessible copy constructor and
2189// resolve its destructor's exception specification.
2190// This also performs initialization of block variables when they are moved
2191// to the heap. It uses the same rules as applicable for implicit moves
2192// according to the C++ standard in effect ([class.copy.elision]p3).
2193static void checkEscapingByref(VarDecl *VD, Sema &S) {
2194 QualType T = VD->getType();
2197 SourceLocation Loc = VD->getLocation();
2198 Expr *VarRef =
2199 new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
2201 auto IE = InitializedEntity::InitializeBlock(Loc, T);
2202 if (S.getLangOpts().CPlusPlus23) {
2203 auto *E = ImplicitCastExpr::Create(S.Context, T, CK_NoOp, VarRef, nullptr,
2206 } else {
2209 VarRef);
2210 }
2211
2212 if (!Result.isInvalid()) {
2214 Expr *Init = Result.getAs<Expr>();
2216 }
2217
2218 // The destructor's exception specification is needed when IRGen generates
2219 // block copy/destroy functions. Resolve it here.
2220 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2221 if (CXXDestructorDecl *DD = RD->getDestructor()) {
2222 auto *FPT = DD->getType()->getAs<FunctionProtoType>();
2223 S.ResolveExceptionSpec(Loc, FPT);
2224 }
2225}
2226
2227static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
2228 // Set the EscapingByref flag of __block variables captured by
2229 // escaping blocks.
2230 for (const BlockDecl *BD : FSI.Blocks) {
2231 for (const BlockDecl::Capture &BC : BD->captures()) {
2232 VarDecl *VD = BC.getVariable();
2233 if (VD->hasAttr<BlocksAttr>()) {
2234 // Nothing to do if this is a __block variable captured by a
2235 // non-escaping block.
2236 if (BD->doesNotEscape())
2237 continue;
2238 VD->setEscapingByref();
2239 }
2240 // Check whether the captured variable is or contains an object of
2241 // non-trivial C union type.
2242 QualType CapType = BC.getVariable()->getType();
2245 S.checkNonTrivialCUnion(BC.getVariable()->getType(),
2246 BD->getCaretLocation(),
2249 }
2250 }
2251
2252 for (VarDecl *VD : FSI.ByrefBlockVars) {
2253 // __block variables might require us to capture a copy-initializer.
2254 if (!VD->isEscapingByref())
2255 continue;
2256 // It's currently invalid to ever have a __block variable with an
2257 // array type; should we diagnose that here?
2258 // Regardless, we don't want to ignore array nesting when
2259 // constructing this copy.
2260 if (VD->getType()->isStructureOrClassType())
2261 checkEscapingByref(VD, S);
2262 }
2263}
2264
2265/// Pop a function (or block or lambda or captured region) scope from the stack.
2266///
2267/// \param WP The warning policy to use for CFG-based warnings, or null if such
2268/// warnings should not be produced.
2269/// \param D The declaration corresponding to this function scope, if producing
2270/// CFG-based warnings.
2271/// \param BlockType The type of the block expression, if D is a BlockDecl.
2274 const Decl *D, QualType BlockType) {
2275 assert(!FunctionScopes.empty() && "mismatched push/pop!");
2276
2277 markEscapingByrefs(*FunctionScopes.back(), *this);
2278
2281
2282 if (LangOpts.OpenMP)
2283 popOpenMPFunctionRegion(Scope.get());
2284
2285 // Issue any analysis-based warnings.
2286 if (WP && D)
2287 AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
2288 else
2289 for (const auto &PUD : Scope->PossiblyUnreachableDiags)
2290 Diag(PUD.Loc, PUD.PD);
2291
2292 return Scope;
2293}
2294
2297 if (!Scope->isPlainFunction())
2298 Self->CapturingFunctionScopes--;
2299 // Stash the function scope for later reuse if it's for a normal function.
2300 if (Scope->isPlainFunction() && !Self->CachedFunctionScope)
2301 Self->CachedFunctionScope.reset(Scope);
2302 else
2303 delete Scope;
2304}
2305
2306void Sema::PushCompoundScope(bool IsStmtExpr) {
2307 getCurFunction()->CompoundScopes.push_back(
2308 CompoundScopeInfo(IsStmtExpr, getCurFPFeatures()));
2309}
2310
2312 FunctionScopeInfo *CurFunction = getCurFunction();
2313 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
2314
2315 CurFunction->CompoundScopes.pop_back();
2316}
2317
2318/// Determine whether any errors occurred within this function/method/
2319/// block.
2322}
2323
2325 if (!FunctionScopes.empty())
2326 FunctionScopes.back()->setHasBranchIntoScope();
2327}
2328
2330 if (!FunctionScopes.empty())
2331 FunctionScopes.back()->setHasBranchProtectedScope();
2332}
2333
2335 if (!FunctionScopes.empty())
2336 FunctionScopes.back()->setHasIndirectGoto();
2337}
2338
2340 if (!FunctionScopes.empty())
2341 FunctionScopes.back()->setHasMustTail();
2342}
2343
2345 if (FunctionScopes.empty())
2346 return nullptr;
2347
2348 auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
2349 if (CurBSI && CurBSI->TheDecl &&
2350 !CurBSI->TheDecl->Encloses(CurContext)) {
2351 // We have switched contexts due to template instantiation.
2352 assert(!CodeSynthesisContexts.empty());
2353 return nullptr;
2354 }
2355
2356 return CurBSI;
2357}
2358
2360 if (FunctionScopes.empty())
2361 return nullptr;
2362
2363 for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
2364 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
2365 continue;
2366 return FunctionScopes[e];
2367 }
2368 return nullptr;
2369}
2370
2372 for (auto *Scope : llvm::reverse(FunctionScopes)) {
2373 if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope)) {
2374 if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&
2375 LSI->AfterParameterList) {
2376 // We have switched contexts due to template instantiation.
2377 // FIXME: We should swap out the FunctionScopes during code synthesis
2378 // so that we don't need to check for this.
2379 assert(!CodeSynthesisContexts.empty());
2380 return nullptr;
2381 }
2382 return LSI;
2383 }
2384 }
2385 return nullptr;
2386}
2387
2388LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
2389 if (FunctionScopes.empty())
2390 return nullptr;
2391
2392 auto I = FunctionScopes.rbegin();
2393 if (IgnoreNonLambdaCapturingScope) {
2394 auto E = FunctionScopes.rend();
2395 while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
2396 ++I;
2397 if (I == E)
2398 return nullptr;
2399 }
2400 auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
2401 if (CurLSI && CurLSI->Lambda && CurLSI->CallOperator &&
2402 !CurLSI->Lambda->Encloses(CurContext) && CurLSI->AfterParameterList) {
2403 // We have switched contexts due to template instantiation.
2404 assert(!CodeSynthesisContexts.empty());
2405 return nullptr;
2406 }
2407
2408 return CurLSI;
2409}
2410
2411// We have a generic lambda if we parsed auto parameters, or we have
2412// an associated template parameter list.
2414 if (LambdaScopeInfo *LSI = getCurLambda()) {
2415 return (LSI->TemplateParams.size() ||
2416 LSI->GLTemplateParameterList) ? LSI : nullptr;
2417 }
2418 return nullptr;
2419}
2420
2421
2423 if (!LangOpts.RetainCommentsFromSystemHeaders &&
2425 return;
2426 RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
2428 SourceRange MagicMarkerRange(Comment.getBegin(),
2429 Comment.getBegin().getLocWithOffset(3));
2430 StringRef MagicMarkerText;
2431 switch (RC.getKind()) {
2433 MagicMarkerText = "///<";
2434 break;
2436 MagicMarkerText = "/**<";
2437 break;
2439 // FIXME: are there other scenarios that could produce an invalid
2440 // raw comment here?
2441 Diag(Comment.getBegin(), diag::warn_splice_in_doxygen_comment);
2442 return;
2443 default:
2444 llvm_unreachable("if this is an almost Doxygen comment, "
2445 "it should be ordinary");
2446 }
2447 Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
2448 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
2449 }
2450 Context.addComment(RC);
2451}
2452
2453// Pin this vtable to this file.
2455char ExternalSemaSource::ID;
2456
2459
2462}
2463
2465 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
2466
2468 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
2469
2470/// Figure out if an expression could be turned into a call.
2471///
2472/// Use this when trying to recover from an error where the programmer may have
2473/// written just the name of a function instead of actually calling it.
2474///
2475/// \param E - The expression to examine.
2476/// \param ZeroArgCallReturnTy - If the expression can be turned into a call
2477/// with no arguments, this parameter is set to the type returned by such a
2478/// call; otherwise, it is set to an empty QualType.
2479/// \param OverloadSet - If the expression is an overloaded function
2480/// name, this parameter is populated with the decls of the various overloads.
2481bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
2482 UnresolvedSetImpl &OverloadSet) {
2483 ZeroArgCallReturnTy = QualType();
2484 OverloadSet.clear();
2485
2486 const OverloadExpr *Overloads = nullptr;
2487 bool IsMemExpr = false;
2488 if (E.getType() == Context.OverloadTy) {
2489 OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
2490
2491 // Ignore overloads that are pointer-to-member constants.
2493 return false;
2494
2495 Overloads = FR.Expression;
2496 } else if (E.getType() == Context.BoundMemberTy) {
2497 Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
2498 IsMemExpr = true;
2499 }
2500
2501 bool Ambiguous = false;
2502 bool IsMV = false;
2503
2504 if (Overloads) {
2505 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
2506 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
2507 OverloadSet.addDecl(*it);
2508
2509 // Check whether the function is a non-template, non-member which takes no
2510 // arguments.
2511 if (IsMemExpr)
2512 continue;
2513 if (const FunctionDecl *OverloadDecl
2514 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
2515 if (OverloadDecl->getMinRequiredArguments() == 0) {
2516 if (!ZeroArgCallReturnTy.isNull() && !Ambiguous &&
2517 (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||
2518 OverloadDecl->isCPUSpecificMultiVersion()))) {
2519 ZeroArgCallReturnTy = QualType();
2520 Ambiguous = true;
2521 } else {
2522 ZeroArgCallReturnTy = OverloadDecl->getReturnType();
2523 IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
2524 OverloadDecl->isCPUSpecificMultiVersion();
2525 }
2526 }
2527 }
2528 }
2529
2530 // If it's not a member, use better machinery to try to resolve the call
2531 if (!IsMemExpr)
2532 return !ZeroArgCallReturnTy.isNull();
2533 }
2534
2535 // Attempt to call the member with no arguments - this will correctly handle
2536 // member templates with defaults/deduction of template arguments, overloads
2537 // with default arguments, etc.
2538 if (IsMemExpr && !E.isTypeDependent()) {
2539 Sema::TentativeAnalysisScope Trap(*this);
2541 std::nullopt, SourceLocation());
2542 if (R.isUsable()) {
2543 ZeroArgCallReturnTy = R.get()->getType();
2544 return true;
2545 }
2546 return false;
2547 }
2548
2549 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
2550 if (const auto *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
2551 if (Fun->getMinRequiredArguments() == 0)
2552 ZeroArgCallReturnTy = Fun->getReturnType();
2553 return true;
2554 }
2555 }
2556
2557 // We don't have an expression that's convenient to get a FunctionDecl from,
2558 // but we can at least check if the type is "function of 0 arguments".
2559 QualType ExprTy = E.getType();
2560 const FunctionType *FunTy = nullptr;
2561 QualType PointeeTy = ExprTy->getPointeeType();
2562 if (!PointeeTy.isNull())
2563 FunTy = PointeeTy->getAs<FunctionType>();
2564 if (!FunTy)
2565 FunTy = ExprTy->getAs<FunctionType>();
2566
2567 if (const auto *FPT = dyn_cast_if_present<FunctionProtoType>(FunTy)) {
2568 if (FPT->getNumParams() == 0)
2569 ZeroArgCallReturnTy = FunTy->getReturnType();
2570 return true;
2571 }
2572 return false;
2573}
2574
2575/// Give notes for a set of overloads.
2576///
2577/// A companion to tryExprAsCall. In cases when the name that the programmer
2578/// wrote was an overloaded function, we may be able to make some guesses about
2579/// plausible overloads based on their return types; such guesses can be handed
2580/// off to this method to be emitted as notes.
2581///
2582/// \param Overloads - The overloads to note.
2583/// \param FinalNoteLoc - If we've suppressed printing some overloads due to
2584/// -fshow-overloads=best, this is the location to attach to the note about too
2585/// many candidates. Typically this will be the location of the original
2586/// ill-formed expression.
2587static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
2588 const SourceLocation FinalNoteLoc) {
2589 unsigned ShownOverloads = 0;
2590 unsigned SuppressedOverloads = 0;
2591 for (UnresolvedSetImpl::iterator It = Overloads.begin(),
2592 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2593 if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) {
2594 ++SuppressedOverloads;
2595 continue;
2596 }
2597
2598 const NamedDecl *Fn = (*It)->getUnderlyingDecl();
2599 // Don't print overloads for non-default multiversioned functions.
2600 if (const auto *FD = Fn->getAsFunction()) {
2601 if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() &&
2602 !FD->getAttr<TargetAttr>()->isDefaultVersion())
2603 continue;
2604 if (FD->isMultiVersion() && FD->hasAttr<TargetVersionAttr>() &&
2605 !FD->getAttr<TargetVersionAttr>()->isDefaultVersion())
2606 continue;
2607 }
2608 S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
2609 ++ShownOverloads;
2610 }
2611
2612 S.Diags.overloadCandidatesShown(ShownOverloads);
2613
2614 if (SuppressedOverloads)
2615 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
2616 << SuppressedOverloads;
2617}
2618
2620 const UnresolvedSetImpl &Overloads,
2621 bool (*IsPlausibleResult)(QualType)) {
2622 if (!IsPlausibleResult)
2623 return noteOverloads(S, Overloads, Loc);
2624
2625 UnresolvedSet<2> PlausibleOverloads;
2626 for (OverloadExpr::decls_iterator It = Overloads.begin(),
2627 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2628 const auto *OverloadDecl = cast<FunctionDecl>(*It);
2629 QualType OverloadResultTy = OverloadDecl->getReturnType();
2630 if (IsPlausibleResult(OverloadResultTy))
2631 PlausibleOverloads.addDecl(It.getDecl());
2632 }
2633 noteOverloads(S, PlausibleOverloads, Loc);
2634}
2635
2636/// Determine whether the given expression can be called by just
2637/// putting parentheses after it. Notably, expressions with unary
2638/// operators can't be because the unary operator will start parsing
2639/// outside the call.
2640static bool IsCallableWithAppend(const Expr *E) {
2641 E = E->IgnoreImplicit();
2642 return (!isa<CStyleCastExpr>(E) &&
2643 !isa<UnaryOperator>(E) &&
2644 !isa<BinaryOperator>(E) &&
2645 !isa<CXXOperatorCallExpr>(E));
2646}
2647
2649 if (const auto *UO = dyn_cast<UnaryOperator>(E))
2650 E = UO->getSubExpr();
2651
2652 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2653 if (ULE->getNumDecls() == 0)
2654 return false;
2655
2656 const NamedDecl *ND = *ULE->decls_begin();
2657 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2659 }
2660 return false;
2661}
2662
2664 bool ForceComplain,
2665 bool (*IsPlausibleResult)(QualType)) {
2666 SourceLocation Loc = E.get()->getExprLoc();
2667 SourceRange Range = E.get()->getSourceRange();
2668 UnresolvedSet<4> Overloads;
2669
2670 // If this is a SFINAE context, don't try anything that might trigger ADL
2671 // prematurely.
2672 if (!isSFINAEContext()) {
2673 QualType ZeroArgCallTy;
2674 if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
2675 !ZeroArgCallTy.isNull() &&
2676 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
2677 // At this point, we know E is potentially callable with 0
2678 // arguments and that it returns something of a reasonable type,
2679 // so we can emit a fixit and carry on pretending that E was
2680 // actually a CallExpr.
2681 SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
2683 Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
2684 << (IsCallableWithAppend(E.get())
2685 ? FixItHint::CreateInsertion(ParenInsertionLoc,
2686 "()")
2687 : FixItHint());
2688 if (!IsMV)
2689 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2690
2691 // FIXME: Try this before emitting the fixit, and suppress diagnostics
2692 // while doing so.
2693 E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), std::nullopt,
2694 Range.getEnd().getLocWithOffset(1));
2695 return true;
2696 }
2697 }
2698 if (!ForceComplain) return false;
2699
2701 Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
2702 if (!IsMV)
2703 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2704 E = ExprError();
2705 return true;
2706}
2707
2709 if (!Ident_super)
2710 Ident_super = &Context.Idents.get("super");
2711 return Ident_super;
2712}
2713
2716 unsigned OpenMPCaptureLevel) {
2717 auto *CSI = new CapturedRegionScopeInfo(
2718 getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
2719 (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0,
2720 OpenMPCaptureLevel);
2721 CSI->ReturnType = Context.VoidTy;
2722 FunctionScopes.push_back(CSI);
2724}
2725
2727 if (FunctionScopes.empty())
2728 return nullptr;
2729
2730 return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
2731}
2732
2733const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
2735 return DeleteExprs;
2736}
2737
2739 : S(S), OldFPFeaturesState(S.CurFPFeatures),
2740 OldOverrides(S.FpPragmaStack.CurrentValue),
2741 OldEvalMethod(S.PP.getCurrentFPEvalMethod()),
2742 OldFPPragmaLocation(S.PP.getLastFPEvalPragmaLocation()) {}
2743
2745 S.CurFPFeatures = OldFPFeaturesState;
2746 S.FpPragmaStack.CurrentValue = OldOverrides;
2747 S.PP.setCurrentFPEvalMethod(OldFPPragmaLocation, OldEvalMethod);
2748}
2749
2751 assert(D.getCXXScopeSpec().isSet() &&
2752 "can only be called for qualified names");
2753
2754 auto LR = LookupResult(*this, D.getIdentifier(), D.getBeginLoc(),
2758 if (!DC)
2759 return false;
2760
2761 LookupQualifiedName(LR, DC);
2762 bool Result = std::all_of(LR.begin(), LR.end(), [](Decl *Dcl) {
2763 if (NamedDecl *ND = dyn_cast<NamedDecl>(Dcl)) {
2764 ND = ND->getUnderlyingDecl();
2765 return isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
2766 isa<UsingDecl>(ND);
2767 }
2768 return false;
2769 });
2770 return Result;
2771}
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.
llvm::DenseSet< const void * > Visited
Definition: HTMLLogger.cpp:142
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:2193
static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E)
Definition: Sema.cpp:2648
llvm::DenseMap< const CXXRecordDecl *, bool > RecordCompleteMap
Definition: Sema.cpp:941
static bool IsCallableWithAppend(const Expr *E)
Determine whether the given expression can be called by just putting parentheses after it.
Definition: Sema.cpp:2640
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:948
static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, const SourceLocation FinalNoteLoc)
Give notes for a set of overloads.
Definition: Sema.cpp:2587
static bool isFunctionOrVarDeclExternC(const NamedDecl *ND)
Definition: Sema.cpp:795
static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S)
Definition: Sema.cpp:2227
static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D)
Used to prune the decls of Sema's UnusedFileScopedDecls vector.
Definition: Sema.cpp:734
static void emitCallStackNotes(Sema &S, const FunctionDecl *FD)
Definition: Sema.cpp:1648
static void notePlausibleOverloads(Sema &S, SourceLocation Loc, const UnresolvedSetImpl &Overloads, bool(*IsPlausibleResult)(QualType))
Definition: Sema.cpp:2619
static void checkUndefinedButUsed(Sema &S)
checkUndefinedButUsed - Check for undefined objects with internal linkage or that are inline.
Definition: Sema.cpp:867
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:990
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:697
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1065
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
CanQualType LongTy
Definition: ASTContext.h:1092
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:1095
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2535
CanQualType DoubleTy
Definition: ASTContext.h:1095
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
CanQualType LongDoubleTy
Definition: ASTContext.h:1095
void addComment(const RawComment &RC)
Definition: ASTContext.cpp:325
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2734
IdentifierTable & Idents
Definition: ASTContext.h:636
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:767
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:745
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:750
CanQualType UnsignedLongTy
Definition: ASTContext.h:1093
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType BoundMemberTy
Definition: ASTContext.h:1111
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
CanQualType IntTy
Definition: ASTContext.h:1092
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
Definition: ASTContext.h:1397
CanQualType OverloadTy
Definition: ASTContext.h:1111
CanQualType OCLClkEventTy
Definition: ASTContext.h:1119
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:689
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2307
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
CanQualType OCLSamplerTy
Definition: ASTContext.h:1119
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1083
CanQualType UnsignedIntTy
Definition: ASTContext.h:1093
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1120
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:749
CanQualType OCLQueueTy
Definition: ASTContext.h:1120
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:1179
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:1901
CanQualType HalfTy
Definition: ASTContext.h:1107
CanQualType OCLEventTy
Definition: ASTContext.h:1119
void setPrintingPolicy(const clang::PrintingPolicy &Policy)
Definition: ASTContext.h:693
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
A class which contains all the information about a particular captured value.
Definition: Decl.h:4469
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4463
ArrayRef< Capture > captures() const
Definition: Decl.h:4590
SourceLocation getCaretLocation() const
Definition: Decl.h:4536
bool doesNotEscape() const
Definition: Decl.h:4614
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2792
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:2053
An iterator over the friend declarations of a class.
Definition: DeclFriend.h:186
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
friend_iterator friend_begin() const
Definition: DeclFriend.h:238
friend_iterator friend_end() const
Definition: DeclFriend.h:242
bool isSet() const
Deprecated.
Definition: DeclSpec.h:227
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:4655
ImplicitParamDecl * getContextParam() const
Retrieve the parameter containing captured variables.
Definition: Decl.h:4717
const char * getCastKindName() const
Definition: Expr.h:3565
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:2277
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2065
decl_iterator decls_end() const
Definition: DeclBase.h:2322
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1368
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1567
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1248
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:784
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
T * getAttr() const
Definition: DeclBase.h:577
void addAttr(Attr *A)
Definition: DeclBase.cpp:975
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:555
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
bool isInvalidDecl() const
Definition: DeclBase.h:592
SourceLocation getLocation() const
Definition: DeclBase.h:444
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:530
bool hasAttr() const
Definition: DeclBase.h:581
The name of a declaration.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:768
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:1271
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:1571
const SourceLocation & getLocation() const
Definition: Diagnostic.h:1582
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie)
Definition: Diagnostic.h:889
bool hasErrorOccurred() const
Definition: Diagnostic.h:843
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition: Diagnostic.h:746
void setLastDiagnosticIgnored(bool Ignored)
Pretend that the last diagnostic issued was ignored, so any subsequent notes will be suppressed,...
Definition: Diagnostic.h:761
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition: Diagnostic.h:731
SourceLocation getCurrentDiagLoc() const
Definition: Diagnostic.h:1064
void Clear()
Clear out the current diagnostic.
Definition: Diagnostic.h:982
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:850
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:931
bool EmitCurrentDiagnostic(bool Force=false)
Emit the current diagnostic and clear the diagnostic state.
Definition: Diagnostic.cpp:526
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:690
unsigned getCurrentDiagID() const
Definition: Diagnostic.h:1062
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition: Diagnostic.h:557
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:3031
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3019
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3027
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:267
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:2458
virtual void ReadMethodPool(Selector Sel)
Load the contents of the global method pool for a given selector.
Definition: Sema.cpp:2457
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:2464
~ExternalSemaSource() override
Definition: Sema.cpp:2454
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:2460
virtual void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 > > &)
Definition: Sema.cpp:2467
Represents difference between two FPOptions values.
Definition: LangOptions.h:829
Represents a member of a struct/union/class.
Definition: Decl.h:3015
StringRef getName() const
The name of this FileEntry.
Definition: FileEntry.h:61
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
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:1957
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2572
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3187
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3526
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2475
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3522
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2320
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3107
const ASTTemplateArgumentListInfo * getTemplateSpecializationArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
Definition: Decl.cpp:4125
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4160
Declaration of a template function.
Definition: DeclTemplate.h:977
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3794
QualType getReturnType() const
Definition: Type.h:4078
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:808
HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized.
Definition: HeaderSearch.h:368
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:3677
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2049
Represents a C array with an unspecified size.
Definition: Type.h:3244
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:485
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:457
@ CMK_HeaderUnit
Compiling a module header unit.
Definition: LangOptions.h:116
@ CMK_ModuleInterface
Compiling a C++ modules interface unit.
Definition: LangOptions.h:119
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:805
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:1394
bool resolveConflicts(Module *Mod, bool Complain)
Resolve all of the unresolved conflicts in the given module.
Definition: ModuleMap.cpp:1421
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Definition: ModuleMap.cpp:1407
Describes a module or submodule.
Definition: Module.h:105
bool isNamedModuleInterfaceHasInit() const
Definition: Module.h:622
bool isInterfaceOrPartition() const
Definition: Module.h:609
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Definition: Module.h:401
llvm::iterator_range< submodule_iterator > submodules()
Definition: Module.h:777
@ PrivateModuleFragment
This is the private module fragment within some C++ module.
Definition: Module.h:141
@ ExplicitGlobalModuleFragment
This is the explicit Global Module Fragment of a modular TU.
Definition: Module.h:138
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:248
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:460
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition: Decl.h:402
NamedDecl * getMostRecentDecl()
Definition: Decl.h:474
bool isExternallyVisible() const
Definition: Decl.h:406
This represents '#pragma omp target' directive.
Definition: StmtOpenMP.h:3165
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
void addSupport(const llvm::StringMap< bool > &FeaturesMap, const LangOptions &Opts)
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:2979
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3039
decls_iterator decls_begin() const
Definition: ExprCXX.h:3071
decls_iterator decls_end() const
Definition: ExprCXX.h:3074
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:285
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:6927
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:6921
QualType getCanonicalType() const
Definition: Type.h:6833
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6874
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6853
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:4117
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:969
sema::DelayedDiagnosticPool * getCurrentPool() const
Returns the current delayed-diagnostics pool.
Definition: Sema.h:984
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1725
Custom deleter to allow FunctionScopeInfos to be kept alive for a short time after they've been poppe...
Definition: Sema.h:2003
void operator()(sema::FunctionScopeInfo *Scope) const
Definition: Sema.cpp:2296
A generic diagnostic builder for errors which may or may not be deferred.
Definition: Sema.h:1796
SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID, const FunctionDecl *Fn, Sema &S)
Definition: Sema.cpp:1858
@ K_Nop
Emit no diagnostics.
Definition: Sema.h:1800
@ K_Deferred
Create a deferred diagnostic, which is emitted only if the function it's attached to is codegen'ed.
Definition: Sema.h:1810
@ K_ImmediateWithCallStack
Emit the diagnostic immediately, and, if it's a warning or error, also emit a call stack showing how ...
Definition: Sema.h:1806
@ K_Immediate
Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
Definition: Sema.h:1802
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:10042
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:357
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:9608
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:14145
void LoadExternalWeakUndeclaredIdentifiers()
Load weak undeclared identifiers from the external source.
Definition: Sema.cpp:930
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:803
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition: Sema.cpp:2481
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:4363
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:928
@ NTCUC_BlockCapture
Definition: Sema.h:3054
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1924
void addImplicitTypedef(StringRef Name, QualType T)
Definition: Sema.cpp:261
void PrintContextStack()
Definition: Sema.h:9901
void CheckDelegatingCtorCycles()
bool IsLastErrorImmediate
Is the last error level diagnostic immediate.
Definition: Sema.h:1906
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:1492
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:873
void emitAndClearUnusedLocalTypedefWarnings()
Definition: Sema.cpp:1021
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition: Sema.h:864
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:1186
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition: Sema.h:830
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:13310
void Initialize()
Perform initialization that occurs after the parser has been initialized but before it parses anythin...
Definition: Sema.cpp:267
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:893
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:823
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:2273
Preprocessor & getPreprocessor() const
Definition: Sema.h:1687
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2135
llvm::DenseSet< std::pair< Decl *, unsigned > > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition: Sema.h:9611
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition: Sema.h:704
void setFunctionHasBranchIntoScope()
Definition: Sema.cpp:2324
virtual void anchor()
This virtual key function only exists to limit the emission of debug info describing the Sema class.
Definition: Sema.cpp:259
void ActOnComment(SourceRange Comment)
Definition: Sema.cpp:2422
void ActOnEndOfTranslationUnit()
ActOnEndOfTranslationUnit - This is called at the very end of the translation unit when EOF is reache...
Definition: Sema.cpp:1111
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:705
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:2708
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:1502
ASTContext & Context
Definition: Sema.h:408
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:1685
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:2663
void CheckDelayedMemberExceptionSpecs()
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1562
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:914
ASTContext & getASTContext() const
Definition: Sema.h:1688
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.
SmallVector< VarDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition: Sema.h:906
static const unsigned MaxAlignmentExponent
The maximum alignment, same as in llvm::Value.
Definition: Sema.h:396
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
Definition: SemaDecl.cpp:20434
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:3302
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1507
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition: Sema.cpp:2413
unsigned NumSFINAEErrors
The number of SFINAE diagnostics that have been trapped.
Definition: Sema.h:1497
void setFunctionHasIndirectGoto()
Definition: Sema.cpp:2334
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1521
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2154
void EmitCurrentDiagnostic(unsigned DiagID)
Cause the active diagnostic on the DiagosticsEngine to be emitted.
Definition: Sema.cpp:1527
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition: Sema.h:2012
FPOptions & getCurFPFeatures()
Definition: Sema.h:1683
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:58
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:2172
void PopCompoundScope()
Definition: Sema.cpp:2311
const LangOptions & getLangOpts() const
Definition: Sema.h:1681
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:801
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
ASTConsumer & getASTConsumer() const
Definition: Sema.h:1689
void * OpaqueParser
Definition: Sema.h:948
Preprocessor & PP
Definition: Sema.h:407
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:7183
threadSafety::BeforeSet * ThreadSafetyDeclCache
Definition: Sema.h:10079
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:1947
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:636
ObjCMethodDecl * NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]
The Objective-C NSNumber methods used to create NSNumber literals.
Definition: Sema.h:1201
const LangOptions & LangOpts
Definition: Sema.h:406
std::unique_ptr< sema::FunctionScopeInfo > CachedFunctionScope
Definition: Sema.h:819
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2388
static const uint64_t MaximumAlignment
Definition: Sema.h:397
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:936
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:869
void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind)
Definition: Sema.cpp:1043
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1920
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:10097
DeclContext * getCurLexicalContext() const
Definition: Sema.h:14155
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1514
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:717
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:2019
void PushCompoundScope(bool IsStmtExpr)
Definition: Sema.cpp:2306
bool isDeclaratorFunctionLike(Declarator &D)
Determine whether.
Definition: Sema.cpp:2750
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:2107
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:14186
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:20354
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:2365
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2344
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:421
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:8462
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:9952
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1482
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:12567
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:9897
SourceManager & getSourceManager() const
Definition: Sema.h:1686
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:814
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:3528
void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, SourceLocation IncludeLoc)
Definition: SemaAttr.cpp:436
RedeclarationKind forRedeclarationInCurContext() const
Definition: Sema.h:4426
CanThrowResult canThrow(const Stmt *E)
bool AccessCheckingSFINAE
When true, access checking violations are treated as SFINAE failures rather than hard errors.
Definition: Sema.h:8099
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
@ NTCUK_Destruct
Definition: Sema.h:3068
@ NTCUK_Copy
Definition: Sema.h:3069
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:831
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition: Sema.cpp:2166
void * VisContext
VisContext - Manages the stack for #pragma GCC visibility.
Definition: Sema.h:758
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel=0)
Definition: Sema.cpp:2714
void emitDeferredDiags()
Definition: Sema.cpp:1820
void setFunctionHasMustTail()
Definition: Sema.cpp:2339
bool WarnedStackExhausted
Definition: Sema.h:1644
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14274
TUFragmentKind
Definition: Sema.h:1968
@ Global
The global module fragment, between 'module;' and a module-declaration.
Definition: Sema.h:1970
@ Private
The private module fragment, between 'module :private;' and the end of the translation unit.
Definition: Sema.h:1977
@ Normal
A normal translation unit fragment.
Definition: Sema.h:1974
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2329
void ActOnStartOfTranslationUnit()
This is called before the very first declaration in the translation unit is parsed.
Definition: Sema.cpp:1037
ASTConsumer & Consumer
Definition: Sema.h:409
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:10078
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1630
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:10093
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:880
void RecordParsingTemplateParameterDepth(unsigned Depth)
This is used to inform Sema what the current TemplateParameterDepth is during Parsing.
Definition: Sema.cpp:2179
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9088
void DiagnoseUseOfUnimplementedSelectors()
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:1157
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:882
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:903
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
bool DeferDiags
Whether deferrable diagnostics should be deferred.
Definition: Sema.h:1920
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:2734
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:1423
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1369
SourceManager & SourceMgr
Definition: Sema.h:411
DiagnosticsEngine & Diags
Definition: Sema.h:410
void DiagnoseUnterminatedPragmaAlignPack()
Definition: SemaAttr.cpp:475
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:1682
FPOptions CurFPFeatures
Definition: Sema.h:404
LateTemplateParserCleanupCB * LateTemplateParserCleanup
Definition: Sema.h:947
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition: Sema.h:14187
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10487
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:1517
void PrintStats() const
Print out statistics about the semantic analysis.
Definition: Sema.cpp:565
llvm::BumpPtrAllocator BumpAlloc
Definition: Sema.h:1494
sema::LambdaScopeInfo * getEnclosingLambda() const
Get the innermost lambda enclosing the current location, if any.
Definition: Sema.cpp:2371
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:1133
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1907
DeclarationName VAListTagName
VAListTagName - The declaration name corresponding to __va_list_tag.
Definition: Sema.h:429
sema::FunctionScopeInfo * getEnclosingFunction() const
Definition: Sema.cpp:2359
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:13331
sema::CapturedRegionScopeInfo * getCurCapturedRegion()
Retrieve the current captured region, if any.
Definition: Sema.cpp:2726
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:13339
IdentifierResolver IdResolver
Definition: Sema.h:1152
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2320
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
void setEnd(SourceLocation e)
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp: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:3636
bool isUnion() const
Definition: Decl.h:3739
Exposes information about the current target.
Definition: TargetInfo.h:212
virtual bool hasLongDoubleType() const
Determine whether the long double type is supported on this target.
Definition: TargetInfo.h:687
virtual bool hasBitIntType() const
Determine whether the _BitInt type is supported on this target.
Definition: TargetInfo.h:642
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1218
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:631
virtual bool hasFloat16Type() const
Determine whether the _Float16 type is supported on this target.
Definition: TargetInfo.h:672
llvm::StringMap< bool > & getSupportedOpenCLOpts()
Get supported OpenCL extensions and optional core features.
Definition: TargetInfo.h:1675
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition: TargetInfo.h:684
virtual bool hasFPReturn() const
Determine whether return of a floating point value is supported on this target.
Definition: TargetInfo.h:691
bool hasBuiltinMSVaList() const
Returns whether or not type __builtin_ms_va_list type is available on this target.
Definition: TargetInfo.h:995
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition: TargetInfo.h:669
bool hasAArch64SVETypes() const
Returns whether or not the AArch64 SVE built-in types are available on this target.
Definition: TargetInfo.h:1002
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition: TargetInfo.h:675
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1410
bool hasRISCVVTypes() const
Returns whether or not the RISC-V V built-in types are available on this target.
Definition: TargetInfo.h:1006
The type-property cache.
Definition: Type.cpp:4156
A container of type source information.
Definition: Type.h:6752
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1819
bool isFloat16Type() const
Definition: Type.h:7361
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7384
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2409
bool isFloat128Type() const
Definition: Type.h:7369
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:651
bool isBitIntType() const
Definition: Type.h:7257
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2421
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:2233
bool isIbm128Type() const
Definition: Type.h:7373
bool isRVVType(unsigned ElementCount) const
Definition: Type.h:7295
bool isBFloat16Type() const
Definition: Type.h:7365
bool isStructureOrClassType() const
Definition: Type.cpp:607
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2203
Linkage getLinkage() const
Determine the linkage of this type.
Definition: Type.cpp:4301
@ STK_FloatingComplex
Definition: Type.h:2403
@ STK_Floating
Definition: Type.h:2401
@ STK_BlockPointer
Definition: Type.h:2396
@ STK_Bool
Definition: Type.h:2399
@ STK_ObjCObjectPointer
Definition: Type.h:2397
@ STK_FixedPoint
Definition: Type.h:2404
@ STK_IntegralComplex
Definition: Type.h:2402
@ STK_CPointer
Definition: Type.h:2395
@ STK_Integral
Definition: Type.h:2400
@ STK_MemberPointer
Definition: Type.h:2398
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7558
bool isNullPtrType() const
Definition: Type.h:7377
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4411
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3383
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:704
void setType(QualType newType)
Definition: Decl.h:716
QualType getType() const
Definition: Decl.h:715
Represents a variable declaration or definition.
Definition: Decl.h:916
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2773
void setEscapingByref()
Definition: Decl.h:1586
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2359
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1324
const Expr * getInit() const
Definition: Decl.h:1350
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2338
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1277
bool isEscapingByref() const
Indicates the capture is a __block variable that is captured by a block that can potentially escape (...
Definition: Decl.cpp:2661
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:767
Retains information about a captured region.
Definition: ScopeInfo.h:793
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:409
SmallVector< CompoundScopeInfo, 4 > CompoundScopes
The stack of currently active compound stamement scopes in the function.
Definition: ScopeInfo.h:225
llvm::SmallPtrSet< const BlockDecl *, 1 > Blocks
The set of blocks that are introduced in this function.
Definition: ScopeInfo.h:228
llvm::TinyPtrVector< VarDecl * > ByrefBlockVars
The set of __block variables that are introduced in this function.
Definition: ScopeInfo.h:231
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:81
void threadSafetyCleanup(BeforeSet *Cache)
@ OpenCL
Definition: LangStandard.h:64
@ CPlusPlus
Definition: LangStandard.h:54
@ CPlusPlus11
Definition: LangStandard.h:55
@ ExpectedVariableOrFunction
Definition: ParsedAttr.h:1067
@ 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:252
@ SC_Static
Definition: Specifiers.h:247
@ Result
The result type of a method or function.
@ Class
The "class" keyword.
ExprResult ExprError()
Definition: Ownership.h:264
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:941
@ TU_Module
The translation unit is a module.
Definition: LangOptions.h:950
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:947
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:127
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:130
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:139
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:134
bool isExternalFormalLinkage(Linkage L)
Definition: Linkage.h:117
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
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:90
unsigned long uint64_t
#define false
Definition: stdbool.h:22
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:652
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:9521