clang 17.0.0git
Sema.h
Go to the documentation of this file.
1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
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 defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/Attr.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
32#include "clang/AST/NSAPI.h"
34#include "clang/AST/StmtCXX.h"
36#include "clang/AST/TypeLoc.h"
42#include "clang/Basic/Module.h"
51#include "clang/Sema/DeclSpec.h"
56#include "clang/Sema/Scope.h"
59#include "clang/Sema/Weak.h"
60#include "llvm/ADT/ArrayRef.h"
61#include "llvm/ADT/SetVector.h"
62#include "llvm/ADT/SmallBitVector.h"
63#include "llvm/ADT/SmallPtrSet.h"
64#include "llvm/ADT/SmallSet.h"
65#include "llvm/ADT/SmallVector.h"
66#include "llvm/ADT/TinyPtrVector.h"
67#include "llvm/Frontend/OpenMP/OMPConstants.h"
68#include <deque>
69#include <memory>
70#include <optional>
71#include <string>
72#include <tuple>
73#include <vector>
74
75namespace llvm {
76 class APSInt;
77 template <typename ValueT, typename ValueInfoT> class DenseSet;
78 class SmallBitVector;
79 struct InlineAsmIdentifierInfo;
80}
81
82namespace clang {
83 class ADLResult;
84 class ASTConsumer;
85 class ASTContext;
86 class ASTMutationListener;
87 class ASTReader;
88 class ASTWriter;
89 class ArrayType;
90 class ParsedAttr;
91 class BindingDecl;
92 class BlockDecl;
93 class CapturedDecl;
94 class CXXBasePath;
95 class CXXBasePaths;
96 class CXXBindTemporaryExpr;
98 class CXXConstructorDecl;
99 class CXXConversionDecl;
100 class CXXDeleteExpr;
101 class CXXDestructorDecl;
102 class CXXFieldCollector;
103 class CXXMemberCallExpr;
104 class CXXMethodDecl;
105 class CXXScopeSpec;
106 class CXXTemporary;
107 class CXXTryStmt;
108 class CallExpr;
109 class ClassTemplateDecl;
110 class ClassTemplatePartialSpecializationDecl;
111 class ClassTemplateSpecializationDecl;
112 class VarTemplatePartialSpecializationDecl;
113 class CodeCompleteConsumer;
114 class CodeCompletionAllocator;
115 class CodeCompletionTUInfo;
116 class CodeCompletionResult;
117 class CoroutineBodyStmt;
118 class Decl;
119 class DeclAccessPair;
120 class DeclContext;
121 class DeclRefExpr;
122 class DeclaratorDecl;
123 class DeducedTemplateArgument;
124 class DependentDiagnostic;
125 class DesignatedInitExpr;
126 class Designation;
127 class EnableIfAttr;
128 class EnumConstantDecl;
129 class Expr;
130 class ExtVectorType;
131 class FormatAttr;
132 class FriendDecl;
133 class FunctionDecl;
134 class FunctionProtoType;
135 class FunctionTemplateDecl;
136 class ImplicitConversionSequence;
138 class InitListExpr;
139 class InitializationKind;
140 class InitializationSequence;
141 class InitializedEntity;
142 class IntegerLiteral;
143 class LabelStmt;
144 class LambdaExpr;
145 class LangOptions;
146 class LocalInstantiationScope;
147 class LookupResult;
148 class MacroInfo;
150 class ModuleLoader;
151 class MultiLevelTemplateArgumentList;
152 class NamedDecl;
153 class ObjCCategoryDecl;
154 class ObjCCategoryImplDecl;
155 class ObjCCompatibleAliasDecl;
156 class ObjCContainerDecl;
157 class ObjCImplDecl;
158 class ObjCImplementationDecl;
159 class ObjCInterfaceDecl;
160 class ObjCIvarDecl;
161 template <class T> class ObjCList;
162 class ObjCMessageExpr;
163 class ObjCMethodDecl;
164 class ObjCPropertyDecl;
165 class ObjCProtocolDecl;
166 class OMPThreadPrivateDecl;
167 class OMPRequiresDecl;
168 class OMPDeclareReductionDecl;
169 class OMPDeclareSimdDecl;
170 class OMPClause;
171 struct OMPVarListLocTy;
172 struct OverloadCandidate;
173 enum class OverloadCandidateParamOrder : char;
175 class OverloadCandidateSet;
176 class OverloadExpr;
177 class ParenListExpr;
178 class ParmVarDecl;
179 class Preprocessor;
180 class PseudoDestructorTypeStorage;
181 class PseudoObjectExpr;
182 class QualType;
183 class StandardConversionSequence;
184 class Stmt;
185 class StringLiteral;
186 class SwitchStmt;
187 class TemplateArgument;
188 class TemplateArgumentList;
189 class TemplateArgumentLoc;
190 class TemplateDecl;
191 class TemplateInstantiationCallback;
192 class TemplateParameterList;
193 class TemplatePartialOrderingContext;
194 class TemplateTemplateParmDecl;
195 class Token;
196 class TypeAliasDecl;
197 class TypedefDecl;
198 class TypedefNameDecl;
199 class TypeLoc;
200 class TypoCorrectionConsumer;
201 class UnqualifiedId;
202 class UnresolvedLookupExpr;
203 class UnresolvedMemberExpr;
204 class UnresolvedSetImpl;
205 class UnresolvedSetIterator;
206 class UsingDecl;
207 class UsingShadowDecl;
208 class ValueDecl;
209 class VarDecl;
210 class VarTemplateSpecializationDecl;
211 class VisibilityAttr;
212 class VisibleDeclConsumer;
213 class IndirectFieldDecl;
214 struct DeductionFailureInfo;
215 class TemplateSpecCandidateSet;
216
217namespace sema {
218 class AccessedEntity;
219 class BlockScopeInfo;
220 class Capture;
221 class CapturedRegionScopeInfo;
222 class CapturingScopeInfo;
223 class CompoundScopeInfo;
224 class DelayedDiagnostic;
225 class DelayedDiagnosticPool;
226 class FunctionScopeInfo;
227 class LambdaScopeInfo;
228 class PossiblyUnreachableDiag;
229 class RISCVIntrinsicManager;
230 class SemaPPCallbacks;
231 class TemplateDeductionInfo;
232}
233
234namespace threadSafety {
235 class BeforeSet;
236 void threadSafetyCleanup(BeforeSet* Cache);
237}
238
239// FIXME: No way to easily map from TemplateTypeParmTypes to
240// TemplateTypeParmDecls, so we have this horrible PointerUnion.
241typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *>,
242 SourceLocation>
244
245/// Describes whether we've seen any nullability information for the given
246/// file.
248 /// The first pointer declarator (of any pointer kind) in the file that does
249 /// not have a corresponding nullability annotation.
251
252 /// The end location for the first pointer declarator in the file. Used for
253 /// placing fix-its.
255
256 /// Which kind of pointer declarator we saw.
257 uint8_t PointerKind;
258
259 /// Whether we saw any type nullability annotations in the given file.
260 bool SawTypeNullability = false;
261};
262
263/// A mapping from file IDs to a record of whether we've seen nullability
264/// information in that file.
266 /// A mapping from file IDs to the nullability information for each file ID.
267 llvm::DenseMap<FileID, FileNullability> Map;
268
269 /// A single-element cache based on the file ID.
270 struct {
273 } Cache;
274
275public:
277 // Check the single-element cache.
278 if (file == Cache.File)
279 return Cache.Nullability;
280
281 // It's not in the single-element cache; flush the cache if we have one.
282 if (!Cache.File.isInvalid()) {
283 Map[Cache.File] = Cache.Nullability;
284 }
285
286 // Pull this entry into the cache.
287 Cache.File = file;
288 Cache.Nullability = Map[file];
289 return Cache.Nullability;
290 }
291};
292
293/// Tracks expected type during expression parsing, for use in code completion.
294/// The type is tied to a particular token, all functions that update or consume
295/// the type take a start location of the token they are looking at as a
296/// parameter. This avoids updating the type on hot paths in the parser.
298public:
299 PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
300
301 void enterCondition(Sema &S, SourceLocation Tok);
302 void enterReturn(Sema &S, SourceLocation Tok);
304 /// Handles e.g. BaseType{ .D = Tok...
306 const Designation &D);
307 /// Computing a type for the function argument may require running
308 /// overloading, so we postpone its computation until it is actually needed.
309 ///
310 /// Clients should be very careful when using this function, as it stores a
311 /// function_ref, clients should make sure all calls to get() with the same
312 /// location happen while function_ref is alive.
313 ///
314 /// The callback should also emit signature help as a side-effect, but only
315 /// if the completion point has been reached.
317 llvm::function_ref<QualType()> ComputeType);
318
320 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
321 SourceLocation OpLoc);
322 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
324 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
325 /// Handles all type casts, including C-style cast, C++ casts, etc.
327
328 /// Get the expected type associated with this location, if any.
329 ///
330 /// If the location is a function argument, determining the expected type
331 /// involves considering all function overloads and the arguments so far.
332 /// In this case, signature help for these function overloads will be reported
333 /// as a side-effect (only if the completion point has been reached).
335 if (!Enabled || Tok != ExpectedLoc)
336 return QualType();
337 if (!Type.isNull())
338 return Type;
339 if (ComputeType)
340 return ComputeType();
341 return QualType();
342 }
343
344private:
345 bool Enabled;
346 /// Start position of a token for which we store expected type.
347 SourceLocation ExpectedLoc;
348 /// Expected type for a token starting at ExpectedLoc.
350 /// A function to compute expected type at ExpectedLoc. It is only considered
351 /// if Type is null.
352 llvm::function_ref<QualType()> ComputeType;
353};
354
355/// Sema - This implements semantic analysis and AST building for C.
356class Sema final {
357 Sema(const Sema &) = delete;
358 void operator=(const Sema &) = delete;
359
360 ///Source of additional semantic information.
362
363 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
364
365 /// Determine whether two declarations should be linked together, given that
366 /// the old declaration might not be visible and the new declaration might
367 /// not have external linkage.
368 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
369 const NamedDecl *New) {
370 if (isVisible(Old))
371 return true;
372 // See comment in below overload for why it's safe to compute the linkage
373 // of the new declaration here.
374 if (New->isExternallyDeclarable()) {
375 assert(Old->isExternallyDeclarable() &&
376 "should not have found a non-externally-declarable previous decl");
377 return true;
378 }
379 return false;
380 }
381 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
382
383 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
384 QualType ResultTy,
385 ArrayRef<QualType> Args);
386
387public:
388 /// The maximum alignment, same as in llvm::Value. We duplicate them here
389 /// because that allows us not to duplicate the constants in clang code,
390 /// which we must to since we can't directly use the llvm constants.
391 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
392 ///
393 /// This is the greatest alignment value supported by load, store, and alloca
394 /// instructions, and global values.
395 static const unsigned MaxAlignmentExponent = 32;
396 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
397
401
404
411
412 /// Flag indicating whether or not to collect detailed statistics.
414
415 /// Code-completion consumer.
417
418 /// CurContext - This is the current declaration context of parsing.
420
421 /// Generally null except when we temporarily switch decl contexts,
422 /// like in \see ActOnObjCTemporaryExitContainerContext.
424
425 /// VAListTagName - The declaration name corresponding to __va_list_tag.
426 /// This is used as part of a hack to omit that class from ADL results.
428
429 bool MSStructPragmaOn; // True when \#pragma ms_struct on
430
431 /// Controls member pointer representation format under the MS ABI.
434
435 /// Stack of active SEH __finally scopes. Can be empty.
437
438 /// Source location for newly created implicit MSInheritanceAttrs
440
441 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
442 /// `TransformTypos` in order to keep track of any TypoExprs that are created
443 /// recursively during typo correction and wipe them away if the correction
444 /// fails.
446
447 /// pragma clang section kind
454 PCSK_Relro = 5
455 };
456
459 PCSA_Clear = 1
460 };
461
463 std::string SectionName;
464 bool Valid = false;
466 };
467
473
475 PSK_Reset = 0x0, // #pragma ()
476 PSK_Set = 0x1, // #pragma (value)
477 PSK_Push = 0x2, // #pragma (push[, id])
478 PSK_Pop = 0x4, // #pragma (pop[, id])
479 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
480 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
481 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
482 };
483
486 StringRef SlotLabel;
488 };
489
490 // #pragma pack and align.
492 public:
493 // `Native` represents default align mode, which may vary based on the
494 // platform.
495 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
496
497 // #pragma pack info constructor
498 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
499 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
500 assert(Num == PackNumber && "The pack number has been truncated.");
501 }
502
503 // #pragma align info constructor
505 : PackAttr(false), AlignMode(M),
506 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
507
508 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
509
511
512 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
513 // integer encoding for it. This should only be passed to
514 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
515 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
516 std::uint32_t Encoding{};
517 if (Info.IsXLStack())
518 Encoding |= IsXLMask;
519
520 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
521
522 if (Info.IsPackAttr())
523 Encoding |= PackAttrMask;
524
525 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
526
527 return Encoding;
528 }
529
530 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
531 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
533 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
534 int PackNumber = (Encoding & PackNumMask) >> 4;
535
536 if (Encoding & PackAttrMask)
537 return AlignPackInfo(M, PackNumber, IsXL);
538
539 return AlignPackInfo(M, IsXL);
540 }
541
542 bool IsPackAttr() const { return PackAttr; }
543
544 bool IsAlignAttr() const { return !PackAttr; }
545
546 Mode getAlignMode() const { return AlignMode; }
547
548 unsigned getPackNumber() const { return PackNumber; }
549
550 bool IsPackSet() const {
551 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
552 // attriute on a decl.
553 return PackNumber != UninitPackVal && PackNumber != 0;
554 }
555
556 bool IsXLStack() const { return XLStack; }
557
558 bool operator==(const AlignPackInfo &Info) const {
559 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
560 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
561 Info.XLStack);
562 }
563
564 bool operator!=(const AlignPackInfo &Info) const {
565 return !(*this == Info);
566 }
567
568 private:
569 /// \brief True if this is a pragma pack attribute,
570 /// not a pragma align attribute.
571 bool PackAttr;
572
573 /// \brief The alignment mode that is in effect.
574 Mode AlignMode;
575
576 /// \brief The pack number of the stack.
577 unsigned char PackNumber;
578
579 /// \brief True if it is a XL #pragma align/pack stack.
580 bool XLStack;
581
582 /// \brief Uninitialized pack value.
583 static constexpr unsigned char UninitPackVal = -1;
584
585 // Masks to encode and decode an AlignPackInfo.
586 static constexpr uint32_t IsXLMask{0x0000'0001};
587 static constexpr uint32_t AlignModeMask{0x0000'0006};
588 static constexpr uint32_t PackAttrMask{0x00000'0008};
589 static constexpr uint32_t PackNumMask{0x0000'01F0};
590 };
591
592 template<typename ValueType>
593 struct PragmaStack {
594 struct Slot {
595 llvm::StringRef StackSlotLabel;
596 ValueType Value;
599 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
604 };
605
606 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
607 llvm::StringRef StackSlotLabel, ValueType Value) {
608 if (Action == PSK_Reset) {
610 CurrentPragmaLocation = PragmaLocation;
611 return;
612 }
613 if (Action & PSK_Push)
614 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
615 PragmaLocation);
616 else if (Action & PSK_Pop) {
617 if (!StackSlotLabel.empty()) {
618 // If we've got a label, try to find it and jump there.
619 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
620 return x.StackSlotLabel == StackSlotLabel;
621 });
622 // If we found the label so pop from there.
623 if (I != Stack.rend()) {
624 CurrentValue = I->Value;
625 CurrentPragmaLocation = I->PragmaLocation;
626 Stack.erase(std::prev(I.base()), Stack.end());
627 }
628 } else if (!Stack.empty()) {
629 // We do not have a label, just pop the last entry.
630 CurrentValue = Stack.back().Value;
631 CurrentPragmaLocation = Stack.back().PragmaLocation;
632 Stack.pop_back();
633 }
634 }
635 if (Action & PSK_Set) {
637 CurrentPragmaLocation = PragmaLocation;
638 }
639 }
640
641 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
642 // method body to restore the stacks on exit, so it works like this:
643 //
644 // struct S {
645 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
646 // void Method {}
647 // #pragma <name>(pop, InternalPragmaSlot)
648 // };
649 //
650 // It works even with #pragma vtordisp, although MSVC doesn't support
651 // #pragma vtordisp(push [, id], n)
652 // syntax.
653 //
654 // Push / pop a named sentinel slot.
655 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
656 assert((Action == PSK_Push || Action == PSK_Pop) &&
657 "Can only push / pop #pragma stack sentinels!");
659 }
660
661 // Constructors.
662 explicit PragmaStack(const ValueType &Default)
664
665 bool hasValue() const { return CurrentValue != DefaultValue; }
666
668 ValueType DefaultValue; // Value used for PSK_Reset action.
669 ValueType CurrentValue;
671 };
672 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
673 // we shouldn't do so if they're in a module).
674
675 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
676 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
677 ///
678 /// 0: Suppress all vtordisps
679 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
680 /// structors
681 /// 2: Always insert vtordisps to support RTTI on partially constructed
682 /// objects
685 // The current #pragma align/pack values and locations at each #include.
690 };
692 // Segment #pragmas.
697
698 // #pragma strict_gs_check.
700
701 // This stack tracks the current state of Sema.CurFPFeatures.
704 FPOptionsOverride result;
705 if (!FpPragmaStack.hasValue()) {
706 result = FPOptionsOverride();
707 } else {
708 result = FpPragmaStack.CurrentValue;
709 }
710 return result;
711 }
712
713 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
714 // Actions should be performed only if we enter / exit a C++ method body.
716 public:
717 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
719
720 private:
721 Sema &S;
722 StringRef SlotLabel;
723 bool ShouldAct;
724 };
725
726 /// A mapping that describes the nullability we've seen in each header file.
728
729 /// Last section used with #pragma init_seg.
732
733 /// Sections used with #pragma alloc_text.
734 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
735
736 /// VisContext - Manages the stack for \#pragma GCC visibility.
737 void *VisContext; // Really a "PragmaVisStack*"
738
739 /// This an attribute introduced by \#pragma clang attribute.
744 bool IsUsed;
745 };
746
747 /// A push'd group of PragmaAttributeEntries.
749 /// The location of the push attribute.
751 /// The namespace of this push group.
754 };
755
757
758 /// The declaration that is currently receiving an attribute from the
759 /// #pragma attribute stack.
761
762 /// This represents the last location of a "#pragma clang optimize off"
763 /// directive if such a directive has not been closed by an "on" yet. If
764 /// optimizations are currently "on", this is set to an invalid location.
766
767 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
768 /// whether the optimizations in the list passed to the pragma should be
769 /// turned off or on. This boolean is true by default because command line
770 /// options are honored when `#pragma optimize("", on)`.
771 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
773
774 /// Set of no-builtin functions listed by \#pragma function.
776
777 /// Flag indicating if Sema is building a recovery call expression.
778 ///
779 /// This flag is used to avoid building recovery call expressions
780 /// if Sema is already doing so, which would cause infinite recursions.
782
783 /// Used to control the generation of ExprWithCleanups.
785
786 /// ExprCleanupObjects - This is the stack of objects requiring
787 /// cleanup that are created by the current full expression.
789
790 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
791 /// to a variable (constant) that may or may not be odr-used in this Expr, and
792 /// we won't know until all lvalue-to-rvalue and discarded value conversions
793 /// have been applied to all subexpressions of the enclosing full expression.
794 /// This is cleared at the end of each full expression.
795 using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
798
799 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
800
801 /// Stack containing information about each of the nested
802 /// function, block, and method scopes that are currently active.
804
805 /// The index of the first FunctionScope that corresponds to the current
806 /// context.
808
809 /// Track the number of currently active capturing scopes.
811
814 FunctionScopes.end());
815 }
816
817 /// Stack containing information needed when in C++2a an 'auto' is encountered
818 /// in a function declaration parameter type specifier in order to invent a
819 /// corresponding template parameter in the enclosing abbreviated function
820 /// template. This information is also present in LambdaScopeInfo, stored in
821 /// the FunctionScopes stack.
823
824 /// The index of the first InventedParameterInfo that refers to the current
825 /// context.
827
832 }
833
837
838 /// ExtVectorDecls - This is a list all the extended vector types. This allows
839 /// us to associate a raw vector type with one of the ext_vector type names.
840 /// This is only necessary for issuing pretty diagnostics.
842
843 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
844 std::unique_ptr<CXXFieldCollector> FieldCollector;
845
847
848 /// Set containing all declared private fields that are not used.
850
851 /// Set containing all typedefs that are likely unused.
854
855 /// Delete-expressions to be analyzed at the end of translation unit
856 ///
857 /// This list contains class members, and locations of delete-expressions
858 /// that could not be proven as to whether they mismatch with new-expression
859 /// used in initializer of the field.
860 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
862 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
863
865
866 /// PureVirtualClassDiagSet - a set of class declarations which we have
867 /// emitted a list of pure virtual functions. Used to prevent emitting the
868 /// same list more than once.
869 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
870
871 /// ParsingInitForAutoVars - a set of declarations with auto types for which
872 /// we are currently parsing the initializer.
874
875 /// Look for a locally scoped extern "C" declaration by the given name.
877
881
882 /// All the tentative definitions encountered in the TU.
884
885 /// All the external declarations encoutered and used in the TU.
887
891
892 /// The set of file scoped decls seen so far that have not been used
893 /// and must warn if not used. Only contains the first declaration.
895
899
900 /// All the delegating constructors seen so far in the file, used for
901 /// cycle detection at the end of the TU.
903
904 /// All the overriding functions seen during a class definition
905 /// that had their exception spec checks delayed, plus the overridden
906 /// function.
909
910 /// All the function redeclarations seen during a class definition that had
911 /// their exception spec checks delayed, plus the prior declaration they
912 /// should be checked against. Except during error recovery, the new decl
913 /// should always be a friend declaration, as that's the only valid way to
914 /// redeclare a special member before its class is complete.
917
918 typedef llvm::MapVector<const FunctionDecl *,
919 std::unique_ptr<LateParsedTemplate>>
922
923 /// Callback to the parser to parse templated functions when needed.
924 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
925 typedef void LateTemplateParserCleanupCB(void *P);
929
931 LateTemplateParserCleanupCB *LTPCleanup,
932 void *P) {
933 LateTemplateParser = LTP;
934 LateTemplateParserCleanup = LTPCleanup;
935 OpaqueParser = P;
936 }
937
938 class DelayedDiagnostics;
939
943 };
946
947 /// A class which encapsulates the logic for delaying diagnostics
948 /// during parsing and other processing.
950 /// The current pool of diagnostics into which delayed
951 /// diagnostics should go.
952 sema::DelayedDiagnosticPool *CurPool = nullptr;
953
954 public:
956
957 /// Adds a delayed diagnostic.
958 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
959
960 /// Determines whether diagnostics should be delayed.
961 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
962
963 /// Returns the current delayed-diagnostics pool.
965 return CurPool;
966 }
967
968 /// Enter a new scope. Access and deprecation diagnostics will be
969 /// collected in this pool.
972 state.SavedPool = CurPool;
973 CurPool = &pool;
974 return state;
975 }
976
977 /// Leave a delayed-diagnostic state that was previously pushed.
978 /// Do not emit any of the diagnostics. This is performed as part
979 /// of the bookkeeping of popping a pool "properly".
981 CurPool = state.SavedPool;
982 }
983
984 /// Enter a new scope where access and deprecation diagnostics are
985 /// not delayed.
988 state.SavedPool = CurPool;
989 CurPool = nullptr;
990 return state;
991 }
992
993 /// Undo a previous pushUndelayed().
995 assert(CurPool == nullptr);
996 CurPool = state.SavedPool;
997 }
998 } DelayedDiagnostics;
999
1000 /// A RAII object to temporarily push a declaration context.
1002 private:
1003 Sema &S;
1004 DeclContext *SavedContext;
1005 ProcessingContextState SavedContextState;
1006 QualType SavedCXXThisTypeOverride;
1007 unsigned SavedFunctionScopesStart;
1008 unsigned SavedInventedParameterInfosStart;
1009
1010 public:
1011 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
1012 : S(S), SavedContext(S.CurContext),
1013 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
1014 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
1015 SavedFunctionScopesStart(S.FunctionScopesStart),
1016 SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
1017 {
1018 assert(ContextToPush && "pushing null context");
1019 S.CurContext = ContextToPush;
1020 if (NewThisContext)
1021 S.CXXThisTypeOverride = QualType();
1022 // Any saved FunctionScopes do not refer to this context.
1023 S.FunctionScopesStart = S.FunctionScopes.size();
1024 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1025 }
1026
1027 void pop() {
1028 if (!SavedContext) return;
1029 S.CurContext = SavedContext;
1030 S.DelayedDiagnostics.popUndelayed(SavedContextState);
1031 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1032 S.FunctionScopesStart = SavedFunctionScopesStart;
1033 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1034 SavedContext = nullptr;
1035 }
1036
1038 pop();
1039 }
1040 };
1041
1042 /// Whether the AST is currently being rebuilt to correct immediate
1043 /// invocations. Immediate invocation candidates and references to consteval
1044 /// functions aren't tracked when this is set.
1046
1047 /// Used to change context to isConstantEvaluated without pushing a heavy
1048 /// ExpressionEvaluationContextRecord object.
1050
1051 bool isConstantEvaluated() const {
1052 return ExprEvalContexts.back().isConstantEvaluated() ||
1054 }
1055
1056 /// RAII object to handle the state changes required to synthesize
1057 /// a function body.
1059 Sema &S;
1060 Sema::ContextRAII SavedContext;
1061 bool PushedCodeSynthesisContext = false;
1062
1063 public:
1065 : S(S), SavedContext(S, DC) {
1066 S.PushFunctionScope();
1067 S.PushExpressionEvaluationContext(
1069 if (auto *FD = dyn_cast<FunctionDecl>(DC))
1070 FD->setWillHaveBody(true);
1071 else
1072 assert(isa<ObjCMethodDecl>(DC));
1073 }
1074
1076 assert(!PushedCodeSynthesisContext);
1077
1080 Ctx.PointOfInstantiation = UseLoc;
1081 Ctx.Entity = cast<Decl>(S.CurContext);
1082 S.pushCodeSynthesisContext(Ctx);
1083
1084 PushedCodeSynthesisContext = true;
1085 }
1086
1088 if (PushedCodeSynthesisContext)
1089 S.popCodeSynthesisContext();
1090 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1091 FD->setWillHaveBody(false);
1092 S.PopExpressionEvaluationContext();
1093 S.PopFunctionScopeInfo();
1094 }
1095 };
1096
1097 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
1098 /// declared. Rare. May alias another identifier, declared or undeclared.
1099 ///
1100 /// For aliases, the target identifier is used as a key for eventual
1101 /// processing when the target is declared. For the single-identifier form,
1102 /// the sole identifier is used as the key. Each entry is a `SetVector`
1103 /// (ordered by parse order) of aliases (identified by the alias name) in case
1104 /// of multiple aliases to the same undeclared identifier.
1105 llvm::MapVector<
1107 llvm::SetVector<
1109 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
1111
1112 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1113 /// \#pragma redefine_extname before declared. Used in Solaris system headers
1114 /// to define functions that occur in multiple standards to call the version
1115 /// in the currently selected standard.
1116 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1117
1118
1119 /// Load weak undeclared identifiers from the external source.
1121
1122 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1123 /// \#pragma weak during processing of other Decls.
1124 /// I couldn't figure out a clean way to generate these in-line, so
1125 /// we store them here and handle separately -- which is a hack.
1126 /// It would be best to refactor this.
1128
1130
1131 /// Translation Unit Scope - useful to Objective-C actions that need
1132 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1133 /// For example, user-defined classes, built-in "id" type, etc.
1135
1136 /// The C++ "std" namespace, where the standard library resides.
1138
1139 /// The C++ "std::bad_alloc" class, which is defined by the C++
1140 /// standard library.
1142
1143 /// The C++ "std::align_val_t" enum class, which is defined by the C++
1144 /// standard library.
1146
1147 /// The C++ "std::initializer_list" template, which is defined in
1148 /// <initializer_list>.
1150
1151 /// The C++ "std::coroutine_traits" template, which is defined in
1152 /// <coroutine_traits>
1154
1155 /// The C++ "type_info" declaration, which is defined in <typeinfo>.
1157
1158 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1160
1161 /// The C++ "std::source_location::__impl" struct, defined in
1162 /// <source_location>.
1164
1165 /// Caches identifiers/selectors for NSFoundation APIs.
1166 std::unique_ptr<NSAPI> NSAPIObj;
1167
1168 /// The declaration of the Objective-C NSNumber class.
1170
1171 /// The declaration of the Objective-C NSValue class.
1173
1174 /// Pointer to NSNumber type (NSNumber *).
1176
1177 /// Pointer to NSValue type (NSValue *).
1179
1180 /// The Objective-C NSNumber methods used to create NSNumber literals.
1182
1183 /// The declaration of the Objective-C NSString class.
1185
1186 /// Pointer to NSString type (NSString *).
1188
1189 /// The declaration of the stringWithUTF8String: method.
1191
1192 /// The declaration of the valueWithBytes:objCType: method.
1194
1195 /// The declaration of the Objective-C NSArray class.
1197
1198 /// The declaration of the arrayWithObjects:count: method.
1200
1201 /// The declaration of the Objective-C NSDictionary class.
1203
1204 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1206
1207 /// id<NSCopying> type.
1209
1210 /// will hold 'respondsToSelector:'
1212
1213 /// A flag to remember whether the implicit forms of operator new and delete
1214 /// have been declared.
1216
1217 /// Describes how the expressions currently being parsed are
1218 /// evaluated at run-time, if at all.
1220 /// The current expression and its subexpressions occur within an
1221 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1222 /// \c sizeof, where the type of the expression may be significant but
1223 /// no code will be generated to evaluate the value of the expression at
1224 /// run time.
1226
1227 /// The current expression occurs within a braced-init-list within
1228 /// an unevaluated operand. This is mostly like a regular unevaluated
1229 /// context, except that we still instantiate constexpr functions that are
1230 /// referenced here so that we can perform narrowing checks correctly.
1232
1233 /// The current expression occurs within a discarded statement.
1234 /// This behaves largely similarly to an unevaluated operand in preventing
1235 /// definitions from being required, but not in other ways.
1237
1238 /// The current expression occurs within an unevaluated
1239 /// operand that unconditionally permits abstract references to
1240 /// fields, such as a SIZE operator in MS-style inline assembly.
1242
1243 /// The current context is "potentially evaluated" in C++11 terms,
1244 /// but the expression is evaluated at compile-time (like the values of
1245 /// cases in a switch statement).
1247
1248 /// In addition of being constant evaluated, the current expression
1249 /// occurs in an immediate function context - either a consteval function
1250 /// or a consteval if function.
1252
1253 /// The current expression is potentially evaluated at run time,
1254 /// which means that code may be generated to evaluate the value of the
1255 /// expression at run time.
1257
1258 /// The current expression is potentially evaluated, but any
1259 /// declarations referenced inside that expression are only used if
1260 /// in fact the current expression is used.
1261 ///
1262 /// This value is used when parsing default function arguments, for which
1263 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1264 /// through varargs) but do not want to mark declarations as "referenced"
1265 /// until the default argument is used.
1267 };
1268
1269 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1270
1271 /// Data structure used to record current or nested
1272 /// expression evaluation contexts.
1274 /// The expression evaluation context.
1276
1277 /// Whether the enclosing context needed a cleanup.
1279
1280 /// The number of active cleanup objects when we entered
1281 /// this expression evaluation context.
1283
1284 /// The number of typos encountered during this expression evaluation
1285 /// context (i.e. the number of TypoExprs created).
1286 unsigned NumTypos;
1287
1289
1290 /// The lambdas that are present within this context, if it
1291 /// is indeed an unevaluated context.
1293
1294 /// The declaration that provides context for lambda expressions
1295 /// and block literals if the normal declaration context does not
1296 /// suffice, e.g., in a default function argument.
1298
1299 /// If we are processing a decltype type, a set of call expressions
1300 /// for which we have deferred checking the completeness of the return type.
1302
1303 /// If we are processing a decltype type, a set of temporary binding
1304 /// expressions for which we have deferred checking the destructor.
1306
1308
1309 /// Expressions appearing as the LHS of a volatile assignment in this
1310 /// context. We produce a warning for these when popping the context if
1311 /// they are not discarded-value expressions nor unevaluated operands.
1313
1314 /// Set of candidates for starting an immediate invocation.
1316
1317 /// Set of DeclRefExprs referencing a consteval function when used in a
1318 /// context not already known to be immediately invoked.
1320
1321 /// \brief Describes whether we are in an expression constext which we have
1322 /// to handle differently.
1326
1327 // A context can be nested in both a discarded statement context and
1328 // an immediate function context, so they need to be tracked independently.
1331
1333
1334 // When evaluating immediate functions in the initializer of a default
1335 // argument or default member initializer, this is the declaration whose
1336 // default initializer is being evaluated and the location of the call
1337 // or constructor definition.
1341 : Loc(Loc), Decl(Decl), Context(Context) {
1342 assert(Decl && Context && "invalid initialization context");
1343 }
1344
1346 ValueDecl *Decl = nullptr;
1348 };
1349 std::optional<InitializationContext> DelayedDefaultInitializationContext;
1350
1352 unsigned NumCleanupObjects,
1360
1361 bool isUnevaluated() const {
1365 }
1366
1367 bool isConstantEvaluated() const {
1370 }
1371
1376 // C++23 [expr.const]p14:
1377 // An expression or conversion is in an immediate function
1378 // context if it is potentially evaluated and either:
1379 // * its innermost enclosing non-block scope is a function
1380 // parameter scope of an immediate function, or
1381 // * its enclosing statement is enclosed by the compound-
1382 // statement of a consteval if statement.
1385 }
1386
1389 (Context ==
1392 }
1393 };
1394
1395 /// A stack of expression evaluation contexts.
1397
1398 // Set of failed immediate invocations to avoid double diagnosing.
1400
1401 /// Emit a warning for all pending noderef expressions that we recorded.
1403
1404 /// Compute the mangling number context for a lambda expression or
1405 /// block literal. Also return the extra mangling decl if any.
1406 ///
1407 /// \param DC - The DeclContext containing the lambda expression or
1408 /// block literal.
1409 std::tuple<MangleNumberingContext *, Decl *>
1411
1412
1413 /// SpecialMemberOverloadResult - The overloading result for a special member
1414 /// function.
1415 ///
1416 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1417 /// integer are used to determine whether overload resolution succeeded.
1419 public:
1420 enum Kind {
1423 Success
1425
1426 private:
1427 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
1428
1429 public:
1432 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1433
1434 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1435 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1436
1437 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1438 void setKind(Kind K) { Pair.setInt(K); }
1439 };
1440
1442 : public llvm::FastFoldingSetNode,
1444 public:
1445 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1446 : FastFoldingSetNode(ID)
1447 {}
1448 };
1449
1450 /// A cache of special member function overload resolution results
1451 /// for C++ records.
1452 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1453
1454 /// A cache of the flags available in enumerations with the flag_bits
1455 /// attribute.
1456 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1457
1458 /// The kind of translation unit we are processing.
1459 ///
1460 /// When we're processing a complete translation unit, Sema will perform
1461 /// end-of-translation-unit semantic tasks (such as creating
1462 /// initializers for tentative definitions in C) once parsing has
1463 /// completed. Modules and precompiled headers perform different kinds of
1464 /// checks.
1466
1467 llvm::BumpPtrAllocator BumpAlloc;
1468
1469 /// The number of SFINAE diagnostics that have been trapped.
1471
1472 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1474
1475 /// A mapping from parameters with unparsed default arguments to the
1476 /// set of instantiations of each parameter.
1477 ///
1478 /// This mapping is a temporary data structure used when parsing
1479 /// nested class templates or nested classes of class templates,
1480 /// where we might end up instantiating an inner class before the
1481 /// default arguments of its methods have been parsed.
1483
1484 // Contains the locations of the beginning of unparsed default
1485 // argument locations.
1486 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1487
1488 /// UndefinedInternals - all the used, undefined objects which require a
1489 /// definition in this translation unit.
1490 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1491
1492 /// Determine if VD, which must be a variable or function, is an external
1493 /// symbol that nonetheless can't be referenced from outside this translation
1494 /// unit because its type has no linkage and it's not extern "C".
1495 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
1496
1497 /// Obtain a sorted list of functions that are undefined but ODR-used.
1499 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1500
1501 /// Retrieves list of suspicious delete-expressions that will be checked at
1502 /// the end of translation unit.
1503 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1505
1507 public:
1508 using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1509 using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1510 iterator begin() { return Methods.begin(); }
1511 iterator end() { return Methods.end(); }
1512 iterator find(Selector Sel) { return Methods.find(Sel); }
1513 std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1514 return Methods.insert(Val);
1515 }
1516 int count(Selector Sel) const { return Methods.count(Sel); }
1517 bool empty() const { return Methods.empty(); }
1518
1519 private:
1520 llvm::DenseMap<Selector, Lists> Methods;
1521 };
1522
1523 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1524 /// We need to maintain a list, since selectors can have differing signatures
1525 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1526 /// of selectors are "overloaded").
1527 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1528 /// methods inside categories with a particular selector.
1530
1531 /// Method selectors used in a \@selector expression. Used for implementation
1532 /// of -Wselector.
1533 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1534
1535 /// List of SourceLocations where 'self' is implicitly retained inside a
1536 /// block.
1539
1540 /// Kinds of C++ special members.
1550
1551 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1553
1554 /// The C++ special members which we are currently in the process of
1555 /// declaring. If this process recursively triggers the declaration of the
1556 /// same special member, we should act as if it is not yet declared.
1558
1559 /// Kinds of defaulted comparison operator functions.
1560 enum class DefaultedComparisonKind : unsigned char {
1561 /// This is not a defaultable comparison operator.
1562 None,
1563 /// This is an operator== that should be implemented as a series of
1564 /// subobject comparisons.
1565 Equal,
1566 /// This is an operator<=> that should be implemented as a series of
1567 /// subobject comparisons.
1568 ThreeWay,
1569 /// This is an operator!= that should be implemented as a rewrite in terms
1570 /// of a == comparison.
1571 NotEqual,
1572 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1573 /// terms of a <=> comparison.
1574 Relational,
1575 };
1576
1577 /// The function definitions which were renamed as part of typo-correction
1578 /// to match their respective declarations. We want to keep track of them
1579 /// to ensure that we don't emit a "redefinition" error if we encounter a
1580 /// correctly named definition after the renamed definition.
1582
1583 /// Stack of types that correspond to the parameter entities that are
1584 /// currently being copy-initialized. Can be empty.
1586
1587 void ReadMethodPool(Selector Sel);
1589
1590 /// Private Helper predicate to check for 'self'.
1591 bool isSelfExpr(Expr *RExpr);
1592 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1593
1594 /// Cause the active diagnostic on the DiagosticsEngine to be
1595 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1596 /// should not be used elsewhere.
1597 void EmitCurrentDiagnostic(unsigned DiagID);
1598
1599 /// Records and restores the CurFPFeatures state on entry/exit of compound
1600 /// statements.
1602 public:
1605 FPOptionsOverride getOverrides() { return OldOverrides; }
1606
1607 private:
1608 Sema& S;
1609 FPOptions OldFPFeaturesState;
1610 FPOptionsOverride OldOverrides;
1611 LangOptions::FPEvalMethodKind OldEvalMethod;
1612 SourceLocation OldFPPragmaLocation;
1613 };
1614
1615 void addImplicitTypedef(StringRef Name, QualType T);
1616
1618
1619 /// Increment when we find a reference; decrement when we find an ignored
1620 /// assignment. Ultimately the value is 0 if every reference is an ignored
1621 /// assignment.
1622 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1623
1624 /// Indicate RISC-V vector builtin functions enabled or not.
1626
1627 /// Indicate RISC-V SiFive vector builtin functions enabled or not.
1629
1630private:
1631 std::unique_ptr<sema::RISCVIntrinsicManager> RVIntrinsicManager;
1632
1633 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1634
1635 bool WarnedDarwinSDKInfoMissing = false;
1636
1637public:
1638 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1640 CodeCompleteConsumer *CompletionConsumer = nullptr);
1641 ~Sema();
1642
1643 /// Perform initialization that occurs after the parser has been
1644 /// initialized but before it parses anything.
1645 void Initialize();
1646
1647 /// This virtual key function only exists to limit the emission of debug info
1648 /// describing the Sema class. GCC and Clang only emit debug info for a class
1649 /// with a vtable when the vtable is emitted. Sema is final and not
1650 /// polymorphic, but the debug info size savings are so significant that it is
1651 /// worth adding a vtable just to take advantage of this optimization.
1652 virtual void anchor();
1653
1654 const LangOptions &getLangOpts() const { return LangOpts; }
1657
1660 Preprocessor &getPreprocessor() const { return PP; }
1661 ASTContext &getASTContext() const { return Context; }
1664 ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
1665
1667 StringRef Platform);
1669
1670 ///Registers an external source. If an external source already exists,
1671 /// creates a multiplex external source and appends to it.
1672 ///
1673 ///\param[in] E - A non-null external sema source.
1674 ///
1676
1677 void PrintStats() const;
1678
1679 /// Warn that the stack is nearly exhausted.
1681
1682 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1683 /// guaranteed). Produces a warning if we're low on stack space and allocates
1684 /// more in that case. Use this in code that may recurse deeply (for example,
1685 /// in template instantiation) to avoid stack overflow.
1687 llvm::function_ref<void()> Fn);
1688
1689 /// Helper class that creates diagnostics with optional
1690 /// template instantiation stacks.
1691 ///
1692 /// This class provides a wrapper around the basic DiagnosticBuilder
1693 /// class that emits diagnostics. ImmediateDiagBuilder is
1694 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1695 /// does) and, if the diagnostic comes from inside a template
1696 /// instantiation, printing the template instantiation stack as
1697 /// well.
1699 Sema &SemaRef;
1700 unsigned DiagID;
1701
1702 public:
1703 ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1704 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1705 ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1706 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1707
1708 // This is a cunning lie. DiagnosticBuilder actually performs move
1709 // construction in its copy constructor (but due to varied uses, it's not
1710 // possible to conveniently express this as actual move construction). So
1711 // the default copy ctor here is fine, because the base class disables the
1712 // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1713 // in that case anwyay.
1715
1717 // If we aren't active, there is nothing to do.
1718 if (!isActive()) return;
1719
1720 // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1721 // builder itself so it won't emit the diagnostic in its own destructor.
1722 //
1723 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1724 // do its own needless checks to see if the diagnostic needs to be
1725 // emitted. However, because we take care to ensure that the builder
1726 // objects never escape, a sufficiently smart compiler will be able to
1727 // eliminate that code.
1728 Clear();
1729
1730 // Dispatch to Sema to emit the diagnostic.
1731 SemaRef.EmitCurrentDiagnostic(DiagID);
1732 }
1733
1734 /// Teach operator<< to produce an object of the correct type.
1735 template <typename T>
1737 operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1738 const DiagnosticBuilder &BaseDiag = Diag;
1739 BaseDiag << Value;
1740 return Diag;
1741 }
1742
1743 // It is necessary to limit this to rvalue reference to avoid calling this
1744 // function with a bitfield lvalue argument since non-const reference to
1745 // bitfield is not allowed.
1746 template <typename T,
1747 typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1749 const DiagnosticBuilder &BaseDiag = *this;
1750 BaseDiag << std::move(V);
1751 return *this;
1752 }
1753 };
1754
1755 /// A generic diagnostic builder for errors which may or may not be deferred.
1756 ///
1757 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1758 /// which are not allowed to appear inside __device__ functions and are
1759 /// allowed to appear in __host__ __device__ functions only if the host+device
1760 /// function is never codegen'ed.
1761 ///
1762 /// To handle this, we use the notion of "deferred diagnostics", where we
1763 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1764 ///
1765 /// This class lets you emit either a regular diagnostic, a deferred
1766 /// diagnostic, or no diagnostic at all, according to an argument you pass to
1767 /// its constructor, thus simplifying the process of creating these "maybe
1768 /// deferred" diagnostics.
1770 public:
1771 enum Kind {
1772 /// Emit no diagnostics.
1774 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1776 /// Emit the diagnostic immediately, and, if it's a warning or error, also
1777 /// emit a call stack showing how this function can be reached by an a
1778 /// priori known-emitted function.
1780 /// Create a deferred diagnostic, which is emitted only if the function
1781 /// it's attached to is codegen'ed. Also emit a call stack as with
1782 /// K_ImmediateWithCallStack.
1785
1786 SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1787 const FunctionDecl *Fn, Sema &S);
1790
1791 // The copy and move assignment operator is defined as deleted pending
1792 // further motivation.
1795
1797
1798 bool isImmediate() const { return ImmediateDiag.has_value(); }
1799
1800 /// Convertible to bool: True if we immediately emitted an error, false if
1801 /// we didn't emit an error or we created a deferred error.
1802 ///
1803 /// Example usage:
1804 ///
1805 /// if (SemaDiagnosticBuilder(...) << foo << bar)
1806 /// return ExprError();
1807 ///
1808 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1809 /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1810 operator bool() const { return isImmediate(); }
1811
1812 template <typename T>
1814 operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1815 if (Diag.ImmediateDiag)
1816 *Diag.ImmediateDiag << Value;
1817 else if (Diag.PartialDiagId)
1818 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1819 << Value;
1820 return Diag;
1821 }
1822
1823 // It is necessary to limit this to rvalue reference to avoid calling this
1824 // function with a bitfield lvalue argument since non-const reference to
1825 // bitfield is not allowed.
1826 template <typename T,
1827 typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1829 if (ImmediateDiag)
1830 *ImmediateDiag << std::move(V);
1831 else if (PartialDiagId)
1832 S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1833 return *this;
1834 }
1835
1838 if (Diag.ImmediateDiag)
1839 PD.Emit(*Diag.ImmediateDiag);
1840 else if (Diag.PartialDiagId)
1841 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1842 return Diag;
1843 }
1844
1845 void AddFixItHint(const FixItHint &Hint) const {
1846 if (ImmediateDiag)
1847 ImmediateDiag->AddFixItHint(Hint);
1848 else if (PartialDiagId)
1849 S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1850 }
1851
1853 return ExprError();
1854 }
1856 return StmtError();
1857 }
1858 operator ExprResult() const { return ExprError(); }
1859 operator StmtResult() const { return StmtError(); }
1860 operator TypeResult() const { return TypeError(); }
1861 operator DeclResult() const { return DeclResult(true); }
1862 operator MemInitResult() const { return MemInitResult(true); }
1863
1864 private:
1865 Sema &S;
1866 SourceLocation Loc;
1867 unsigned DiagID;
1868 const FunctionDecl *Fn;
1869 bool ShowCallStack;
1870
1871 // Invariant: At most one of these Optionals has a value.
1872 // FIXME: Switch these to a Variant once that exists.
1873 std::optional<ImmediateDiagBuilder> ImmediateDiag;
1874 std::optional<unsigned> PartialDiagId;
1875 };
1876
1877 /// Is the last error level diagnostic immediate. This is used to determined
1878 /// whether the next info diagnostic should be immediate.
1880
1881 /// Emit a diagnostic.
1882 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1883 bool DeferHint = false);
1884
1885 /// Emit a partial diagnostic.
1887 bool DeferHint = false);
1888
1889 /// Build a partial diagnostic.
1890 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1891
1892 /// Whether deferrable diagnostics should be deferred.
1893 bool DeferDiags = false;
1894
1895 /// RAII class to control scope of DeferDiags.
1897 Sema &S;
1898 bool SavedDeferDiags = false;
1899
1900 public:
1902 : S(S), SavedDeferDiags(S.DeferDiags) {
1903 S.DeferDiags = DeferDiags;
1904 }
1905 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1906 };
1907
1908 /// Whether uncompilable error has occurred. This includes error happens
1909 /// in deferred diagnostics.
1910 bool hasUncompilableErrorOccurred() const;
1911
1912 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1913
1914 /// Get a string to suggest for zero-initialization of a type.
1915 std::string
1917 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1918
1919 /// Calls \c Lexer::getLocForEndOfToken()
1921
1922 /// Retrieve the module loader associated with the preprocessor.
1924
1925 /// Invent a new identifier for parameters of abbreviated templates.
1928 unsigned Index);
1929
1931
1932 private:
1933 /// Function or variable declarations to be checked for whether the deferred
1934 /// diagnostics should be emitted.
1935 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1936
1937 public:
1938 // Emit all deferred diagnostics.
1939 void emitDeferredDiags();
1940
1942 /// The global module fragment, between 'module;' and a module-declaration.
1944 /// A normal translation unit fragment. For a non-module unit, this is the
1945 /// entire translation unit. Otherwise, it runs from the module-declaration
1946 /// to the private-module-fragment (if any) or the end of the TU (if not).
1948 /// The private module fragment, between 'module :private;' and the end of
1949 /// the translation unit.
1950 Private
1952
1956
1958
1960
1961 void PushFunctionScope();
1962 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1964
1965 /// This is used to inform Sema what the current TemplateParameterDepth
1966 /// is during Parsing. Currently it is used to pass on the depth
1967 /// when parsing generic lambda 'auto' parameters.
1968 void RecordParsingTemplateParameterDepth(unsigned Depth);
1969
1970 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1972 unsigned OpenMPCaptureLevel = 0);
1973
1974 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1975 /// time after they've been popped.
1977 Sema *Self;
1978
1979 public:
1980 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1982 };
1983
1985 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1986
1989 const Decl *D = nullptr,
1990 QualType BlockType = QualType());
1991
1993 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1994 }
1995
1997
2002
2003 void PushCompoundScope(bool IsStmtExpr);
2004 void PopCompoundScope();
2005
2007
2009
2010 /// Retrieve the current block, if any.
2012
2013 /// Get the innermost lambda enclosing the current location, if any. This
2014 /// looks through intervening non-lambda scopes such as local functions and
2015 /// blocks.
2017
2018 /// Retrieve the current lambda scope info, if any.
2019 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
2020 /// lambda scope info ignoring all inner capturing scopes that are not
2021 /// lambda scopes.
2023 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
2024
2025 /// Retrieve the current generic lambda info, if any.
2027
2028 /// Retrieve the current captured region, if any.
2030
2031 /// Retrieve the current function, if any, that should be analyzed for
2032 /// potential availability violations.
2034
2035 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
2037
2038 /// Called before parsing a function declarator belonging to a function
2039 /// declaration.
2041 unsigned TemplateParameterDepth);
2042
2043 /// Called after parsing a function declarator belonging to a function
2044 /// declaration.
2046
2047 void ActOnComment(SourceRange Comment);
2048
2049 //===--------------------------------------------------------------------===//
2050 // Type Analysis / Processing: SemaType.cpp.
2051 //
2052
2054 const DeclSpec *DS = nullptr);
2055 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
2056 const DeclSpec *DS = nullptr);
2058 SourceLocation Loc, DeclarationName Entity);
2059 QualType BuildReferenceType(QualType T, bool LValueRef,
2060 SourceLocation Loc, DeclarationName Entity);
2062 Expr *ArraySize, unsigned Quals,
2063 SourceRange Brackets, DeclarationName Entity);
2064 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
2066 SourceLocation AttrLoc);
2067 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
2068 SourceLocation AttrLoc);
2069
2070 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
2071 SourceLocation AttrLoc);
2072
2073 /// Same as above, but constructs the AddressSpace index if not provided.
2075 SourceLocation AttrLoc);
2076
2078
2080
2081 /// Build a function type.
2082 ///
2083 /// This routine checks the function type according to C++ rules and
2084 /// under the assumption that the result type and parameter types have
2085 /// just been instantiated from a template. It therefore duplicates
2086 /// some of the behavior of GetTypeForDeclarator, but in a much
2087 /// simpler form that is only suitable for this narrow use case.
2088 ///
2089 /// \param T The return type of the function.
2090 ///
2091 /// \param ParamTypes The parameter types of the function. This array
2092 /// will be modified to account for adjustments to the types of the
2093 /// function parameters.
2094 ///
2095 /// \param Loc The location of the entity whose type involves this
2096 /// function type or, if there is no such entity, the location of the
2097 /// type that will have function type.
2098 ///
2099 /// \param Entity The name of the entity that involves the function
2100 /// type, if known.
2101 ///
2102 /// \param EPI Extra information about the function type. Usually this will
2103 /// be taken from an existing function with the same prototype.
2104 ///
2105 /// \returns A suitable function type, if there are no errors. The
2106 /// unqualified type will always be a FunctionProtoType.
2107 /// Otherwise, returns a NULL type.
2109 MutableArrayRef<QualType> ParamTypes,
2110 SourceLocation Loc, DeclarationName Entity,
2112
2114 SourceLocation Loc,
2115 DeclarationName Entity);
2117 SourceLocation Loc, DeclarationName Entity);
2121 SourceLocation Loc);
2123 SourceLocation Loc);
2124 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2125
2128
2129 /// Package the given type and TSI into a ParsedType.
2134 TypeSourceInfo **TInfo = nullptr);
2135 CanThrowResult canThrow(const Stmt *E);
2136 /// Determine whether the callee of a particular function call can throw.
2137 /// E, D and Loc are all optional.
2138 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2141 const FunctionProtoType *FPT);
2148 const FunctionProtoType *Old, SourceLocation OldLoc,
2149 const FunctionProtoType *New, SourceLocation NewLoc);
2151 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2152 const FunctionProtoType *Old, SourceLocation OldLoc,
2153 const FunctionProtoType *New, SourceLocation NewLoc);
2154 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2156 const PartialDiagnostic &NestedDiagID,
2157 const PartialDiagnostic &NoteID,
2158 const PartialDiagnostic &NoThrowDiagID,
2159 const FunctionProtoType *Superset,
2160 SourceLocation SuperLoc,
2161 const FunctionProtoType *Subset,
2162 SourceLocation SubLoc);
2163 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2164 const PartialDiagnostic &NoteID,
2166 SourceLocation TargetLoc,
2167 const FunctionProtoType *Source,
2168 SourceLocation SourceLoc);
2169
2171
2172 /// The parser has parsed the context-sensitive type 'instancetype'
2173 /// in an Objective-C message declaration. Return the appropriate type.
2175
2176 /// Abstract class used to diagnose incomplete types.
2179
2180 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2181 virtual ~TypeDiagnoser() {}
2182 };
2183
2184 static int getPrintable(int I) { return I; }
2185 static unsigned getPrintable(unsigned I) { return I; }
2186 static bool getPrintable(bool B) { return B; }
2187 static const char * getPrintable(const char *S) { return S; }
2188 static StringRef getPrintable(StringRef S) { return S; }
2189 static const std::string &getPrintable(const std::string &S) { return S; }
2190 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2191 return II;
2192 }
2194 static QualType getPrintable(QualType T) { return T; }
2195 static SourceRange getPrintable(SourceRange R) { return R; }
2197 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2199
2200 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2201 protected:
2202 unsigned DiagID;
2203 std::tuple<const Ts &...> Args;
2204
2205 template <std::size_t... Is>
2207 std::index_sequence<Is...>) const {
2208 // Apply all tuple elements to the builder in order.
2209 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2210 (void)Dummy;
2211 }
2212
2213 public:
2214 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2215 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2216 assert(DiagID != 0 && "no diagnostic for type diagnoser");
2217 }
2218
2219 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2220 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2221 emit(DB, std::index_sequence_for<Ts...>());
2222 DB << T;
2223 }
2224 };
2225
2226 /// Do a check to make sure \p Name looks like a legal argument for the
2227 /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
2228 /// is invalid for the given declaration.
2229 ///
2230 /// \p AL is used to provide caret diagnostics in case of a malformed name.
2231 ///
2232 /// \returns true if the name is a valid swift name for \p D, false otherwise.
2233 bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2234 const ParsedAttr &AL, bool IsAsync);
2235
2236 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2237 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2238 /// For example, a diagnostic with no other parameters would generally have
2239 /// the form "...%select{incomplete|sizeless}0 type %1...".
2240 template <typename... Ts>
2242 public:
2243 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2244 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2245
2246 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2247 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2248 this->emit(DB, std::index_sequence_for<Ts...>());
2249 DB << T->isSizelessType() << T;
2250 }
2251 };
2252
2253 enum class CompleteTypeKind {
2254 /// Apply the normal rules for complete types. In particular,
2255 /// treat all sizeless types as incomplete.
2256 Normal,
2257
2258 /// Relax the normal rules for complete types so that they include
2259 /// sizeless built-in types.
2261
2262 // FIXME: Eventually we should flip the default to Normal and opt in
2263 // to AcceptSizeless rather than opt out of it.
2265 };
2266
2268
2269private:
2270 /// Methods for marking which expressions involve dereferencing a pointer
2271 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2272 /// they are parsed, meaning that a noderef pointer may not be accessed. For
2273 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2274 /// `*p`, but need to check that `address of` is called on it. This requires
2275 /// keeping a container of all pending expressions and checking if the address
2276 /// of them are eventually taken.
2277 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2278 void CheckAddressOfNoDeref(const Expr *E);
2279 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2280
2281 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2282 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2283
2284 struct ModuleScope {
2285 SourceLocation BeginLoc;
2286 clang::Module *Module = nullptr;
2287 bool ModuleInterface = false;
2288 VisibleModuleSet OuterVisibleModules;
2289 };
2290 /// The modules we're currently parsing.
2292
2293 /// For an interface unit, this is the implicitly imported interface unit.
2294 clang::Module *ThePrimaryInterface = nullptr;
2295
2296 /// The explicit global module fragment of the current translation unit.
2297 /// The explicit Global Module Fragment, as specified in C++
2298 /// [module.global.frag].
2299 clang::Module *TheGlobalModuleFragment = nullptr;
2300
2301 /// The implicit global module fragments of the current translation unit.
2302 /// We would only create at most two implicit global module fragments to
2303 /// avoid performance penalties when there are many language linkage
2304 /// exports.
2305 ///
2306 /// The contents in the implicit global module fragment can't be discarded
2307 /// no matter if it is exported or not.
2308 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
2309 clang::Module *TheExportedImplicitGlobalModuleFragment = nullptr;
2310
2311 /// Namespace definitions that we will export when they finish.
2312 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2313
2314 /// In a C++ standard module, inline declarations require a definition to be
2315 /// present at the end of a definition domain. This set holds the decls to
2316 /// be checked at the end of the TU.
2317 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
2318
2319 /// Helper function to judge if we are in module purview.
2320 /// Return false if we are not in a module.
2321 bool isCurrentModulePurview() const {
2322 return getCurrentModule() ? getCurrentModule()->isModulePurview() : false;
2323 }
2324
2325 /// Enter the scope of the explicit global module fragment.
2326 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
2327 /// Leave the scope of the explicit global module fragment.
2328 void PopGlobalModuleFragment();
2329
2330 /// Enter the scope of an implicit global module fragment.
2331 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc,
2332 bool IsExported);
2333 /// Leave the scope of an implicit global module fragment.
2334 void PopImplicitGlobalModuleFragment();
2335
2336 VisibleModuleSet VisibleModules;
2337
2338 /// Cache for module units which is usable for current module.
2339 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
2340
2341 bool isUsableModule(const Module *M);
2342
2343 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
2344
2345public:
2346 /// Get the module unit whose scope we are currently within.
2348 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2349 }
2350
2351 /// Is the module scope we are an interface?
2353 return ModuleScopes.empty() ? false : ModuleScopes.back().ModuleInterface;
2354 }
2355
2356 /// Is the module scope we are in a C++ Header Unit?
2358 return ModuleScopes.empty() ? false
2359 : ModuleScopes.back().Module->isHeaderUnit();
2360 }
2361
2362 /// Get the module owning an entity.
2363 Module *getOwningModule(const Decl *Entity) {
2364 return Entity->getOwningModule();
2365 }
2366
2367 /// Make a merged definition of an existing hidden definition \p ND
2368 /// visible at the specified location.
2370
2371 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2372
2373 // When loading a non-modular PCH files, this is used to restore module
2374 // visibility.
2376 VisibleModules.setVisible(Mod, ImportLoc);
2377 }
2378
2379 /// Determine whether a declaration is visible to name lookup.
2380 bool isVisible(const NamedDecl *D) {
2381 return D->isUnconditionallyVisible() ||
2382 isAcceptableSlow(D, AcceptableKind::Visible);
2383 }
2384
2385 /// Determine whether a declaration is reachable.
2386 bool isReachable(const NamedDecl *D) {
2387 // All visible declarations are reachable.
2388 return D->isUnconditionallyVisible() ||
2389 isAcceptableSlow(D, AcceptableKind::Reachable);
2390 }
2391
2392 /// Determine whether a declaration is acceptable (visible/reachable).
2394 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
2395 }
2396
2397 /// Determine whether any declaration of an entity is visible.
2398 bool
2400 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2401 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2402 }
2403
2406 /// Determine whether any declaration of an entity is reachable.
2407 bool
2409 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2410 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
2411 }
2413 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2414
2415 bool hasVisibleMergedDefinition(const NamedDecl *Def);
2417
2418 /// Determine if \p D and \p Suggested have a structurally compatible
2419 /// layout as described in C11 6.2.7/1.
2420 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2421
2422 /// Determine if \p D has a visible definition. If not, suggest a declaration
2423 /// that should be made visible to expose the definition.
2424 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2425 bool OnlyNeedComplete = false);
2427 NamedDecl *Hidden;
2428 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2429 }
2430
2431 /// Determine if \p D has a reachable definition. If not, suggest a
2432 /// declaration that should be made reachable to expose the definition.
2433 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
2434 bool OnlyNeedComplete = false);
2436 NamedDecl *Hidden;
2437 return hasReachableDefinition(D, &Hidden);
2438 }
2439
2440 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
2441 AcceptableKind Kind,
2442 bool OnlyNeedComplete = false);
2444 NamedDecl *Hidden;
2445 return hasAcceptableDefinition(D, &Hidden, Kind);
2446 }
2447
2448 /// Determine if the template parameter \p D has a visible default argument.
2449 bool
2451 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2452 /// Determine if the template parameter \p D has a reachable default argument.
2454 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2455 /// Determine if the template parameter \p D has a reachable default argument.
2459
2460 /// Determine if there is a visible declaration of \p D that is an explicit
2461 /// specialization declaration for a specialization of a template. (For a
2462 /// member specialization, use hasVisibleMemberSpecialization.)
2464 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2465 /// Determine if there is a reachable declaration of \p D that is an explicit
2466 /// specialization declaration for a specialization of a template. (For a
2467 /// member specialization, use hasReachableMemberSpecialization.)
2469 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2470
2471 /// Determine if there is a visible declaration of \p D that is a member
2472 /// specialization declaration (as opposed to an instantiated declaration).
2474 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2475 /// Determine if there is a reachable declaration of \p D that is a member
2476 /// specialization declaration (as opposed to an instantiated declaration).
2478 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2479
2480 /// Determine if \p A and \p B are equivalent internal linkage declarations
2481 /// from different modules, and thus an ambiguity error can be downgraded to
2482 /// an extension warning.
2484 const NamedDecl *B);
2486 SourceLocation Loc, const NamedDecl *D,
2488
2490
2491 // Check whether the size of array element of type \p EltTy is a multiple of
2492 // its alignment and return false if it isn't.
2494
2497 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2498 }
2500 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2502 CompleteTypeKind Kind, unsigned DiagID);
2503
2505 TypeDiagnoser &Diagnoser) {
2506 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2507 }
2508 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2509 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2510 }
2511
2512 template <typename... Ts>
2513 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2514 const Ts &...Args) {
2515 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2516 return RequireCompleteType(Loc, T, Diagnoser);
2517 }
2518
2519 template <typename... Ts>
2521 const Ts &... Args) {
2522 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2523 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2524 }
2525
2526 /// Get the type of expression E, triggering instantiation to complete the
2527 /// type if necessary -- that is, if the expression refers to a templated
2528 /// static data member of incomplete array type.
2529 ///
2530 /// May still return an incomplete type if instantiation was not possible or
2531 /// if the type is incomplete for a different reason. Use
2532 /// RequireCompleteExprType instead if a diagnostic is expected for an
2533 /// incomplete expression type.
2535
2538 TypeDiagnoser &Diagnoser);
2539 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2540
2541 template <typename... Ts>
2542 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2543 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2545 }
2546
2547 template <typename... Ts>
2548 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2549 const Ts &... Args) {
2550 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2552 }
2553
2555 TypeDiagnoser &Diagnoser);
2556 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2557
2558 template <typename... Ts>
2559 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2560 const Ts &...Args) {
2561 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2562 return RequireLiteralType(Loc, T, Diagnoser);
2563 }
2564
2566 const CXXScopeSpec &SS, QualType T,
2567 TagDecl *OwnedTagDecl = nullptr);
2568
2569 // Returns the underlying type of a decltype with the given expression.
2571
2573 /// If AsUnevaluated is false, E is treated as though it were an evaluated
2574 /// context, such as when building a type for decltype(auto).
2575 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
2576
2579 SourceLocation Loc);
2585 SourceLocation Loc);
2587 SourceLocation Loc);
2589 SourceLocation Loc);
2591 SourceLocation Loc);
2593 SourceLocation Loc);
2594
2595 //===--------------------------------------------------------------------===//
2596 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2597 //
2598
2600 SkipBodyInfo() = default;
2601 bool ShouldSkip = false;
2604 NamedDecl *New = nullptr;
2605 };
2606
2607 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2608
2610
2611 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2612
2614 Scope *S, CXXScopeSpec *SS = nullptr,
2615 bool isClassName = false, bool HasTrailingDot = false,
2616 ParsedType ObjectType = nullptr,
2617 bool IsCtorOrDtorName = false,
2618 bool WantNontrivialTypeSourceInfo = false,
2619 bool IsClassTemplateDeductionContext = true,
2620 ImplicitTypenameContext AllowImplicitTypename =
2622 IdentifierInfo **CorrectedII = nullptr);
2624 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2626 SourceLocation IILoc,
2627 Scope *S,
2628 CXXScopeSpec *SS,
2629 ParsedType &SuggestedType,
2630 bool IsTemplateName = false);
2631
2632 /// Attempt to behave like MSVC in situations where lookup of an unqualified
2633 /// type name has failed in a dependent context. In these situations, we
2634 /// automatically form a DependentTypeName that will retry lookup in a related
2635 /// scope during instantiation.
2637 SourceLocation NameLoc,
2638 bool IsTemplateTypeArg);
2639
2640 /// Describes the result of the name lookup and resolution performed
2641 /// by \c ClassifyName().
2643 /// This name is not a type or template in this context, but might be
2644 /// something else.
2646 /// Classification failed; an error has been produced.
2648 /// The name has been typo-corrected to a keyword.
2650 /// The name was classified as a type.
2652 /// The name was classified as a specific non-type, non-template
2653 /// declaration. ActOnNameClassifiedAsNonType should be called to
2654 /// convert the declaration to an expression.
2656 /// The name was classified as an ADL-only function name.
2657 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2658 /// result to an expression.
2660 /// The name denotes a member of a dependent type that could not be
2661 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2662 /// convert the result to an expression.
2664 /// The name was classified as an overload set, and an expression
2665 /// representing that overload set has been formed.
2666 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2667 /// expression referencing the overload set.
2669 /// The name was classified as a template whose specializations are types.
2671 /// The name was classified as a variable template name.
2673 /// The name was classified as a function template name.
2675 /// The name was classified as an ADL-only function template name.
2677 /// The name was classified as a concept name.
2679 };
2680
2683 union {
2688 };
2689
2690 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2691
2692 public:
2694
2696
2699 }
2700
2703 }
2704
2707 Result.Expr = E;
2708 return Result;
2709 }
2710
2713 Result.NonTypeDecl = D;
2714 return Result;
2715 }
2716
2719 }
2720
2723 }
2724
2727 Result.Template = Name;
2728 return Result;
2729 }
2730
2733 Result.Template = Name;
2734 return Result;
2735 }
2736
2739 Result.Template = Name;
2740 return Result;
2741 }
2742
2745 Result.Template = Name;
2746 return Result;
2747 }
2748
2751 Result.Template = Name;
2752 return Result;
2753 }
2754
2755 NameClassificationKind getKind() const { return Kind; }
2756
2758 assert(Kind == NC_OverloadSet);
2759 return Expr;
2760 }
2761
2763 assert(Kind == NC_Type);
2764 return Type;
2765 }
2766
2768 assert(Kind == NC_NonType);
2769 return NonTypeDecl;
2770 }
2771
2773 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2774 Kind == NC_VarTemplate || Kind == NC_Concept ||
2775 Kind == NC_UndeclaredTemplate);
2776 return Template;
2777 }
2778
2780 switch (Kind) {
2781 case NC_TypeTemplate:
2782 return TNK_Type_template;
2784 return TNK_Function_template;
2785 case NC_VarTemplate:
2786 return TNK_Var_template;
2787 case NC_Concept:
2788 return TNK_Concept_template;
2791 default:
2792 llvm_unreachable("unsupported name classification.");
2793 }
2794 }
2795 };
2796
2797 /// Perform name lookup on the given name, classifying it based on
2798 /// the results of name lookup and the following token.
2799 ///
2800 /// This routine is used by the parser to resolve identifiers and help direct
2801 /// parsing. When the identifier cannot be found, this routine will attempt
2802 /// to correct the typo and classify based on the resulting name.
2803 ///
2804 /// \param S The scope in which we're performing name lookup.
2805 ///
2806 /// \param SS The nested-name-specifier that precedes the name.
2807 ///
2808 /// \param Name The identifier. If typo correction finds an alternative name,
2809 /// this pointer parameter will be updated accordingly.
2810 ///
2811 /// \param NameLoc The location of the identifier.
2812 ///
2813 /// \param NextToken The token following the identifier. Used to help
2814 /// disambiguate the name.
2815 ///
2816 /// \param CCC The correction callback, if typo correction is desired.
2817 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2818 IdentifierInfo *&Name, SourceLocation NameLoc,
2819 const Token &NextToken,
2820 CorrectionCandidateCallback *CCC = nullptr);
2821
2822 /// Act on the result of classifying a name as an undeclared (ADL-only)
2823 /// non-type declaration.
2825 SourceLocation NameLoc);
2826 /// Act on the result of classifying a name as an undeclared member of a
2827 /// dependent base class.
2829 IdentifierInfo *Name,
2830 SourceLocation NameLoc,
2831 bool IsAddressOfOperand);
2832 /// Act on the result of classifying a name as a specific non-type
2833 /// declaration.
2835 NamedDecl *Found,
2836 SourceLocation NameLoc,
2837 const Token &NextToken);
2838 /// Act on the result of classifying a name as an overload set.
2840
2841 /// Describes the detailed kind of a template name. Used in diagnostics.
2848 Concept,
2850 };
2853
2854 /// Determine whether it's plausible that E was intended to be a
2855 /// template-name.
2857 if (!getLangOpts().CPlusPlus || E.isInvalid())
2858 return false;
2859 Dependent = false;
2860 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2861 return !DRE->hasExplicitTemplateArgs();
2862 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2863 return !ME->hasExplicitTemplateArgs();
2864 Dependent = true;
2865 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2866 return !DSDRE->hasExplicitTemplateArgs();
2867 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2868 return !DSME->hasExplicitTemplateArgs();
2869 // Any additional cases recognized here should also be handled by
2870 // diagnoseExprIntendedAsTemplateName.
2871 return false;
2872 }
2876
2877 void warnOnReservedIdentifier(const NamedDecl *D);
2878
2880
2882 MultiTemplateParamsArg TemplateParameterLists);
2884 QualType &T, SourceLocation Loc,
2885 unsigned FailedFoldDiagID);
2890 bool IsTemplateId);
2891 void
2892 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2893 SourceLocation FallbackLoc,
2894 SourceLocation ConstQualLoc = SourceLocation(),
2895 SourceLocation VolatileQualLoc = SourceLocation(),
2896 SourceLocation RestrictQualLoc = SourceLocation(),
2897 SourceLocation AtomicQualLoc = SourceLocation(),
2898 SourceLocation UnalignedQualLoc = SourceLocation());
2899
2901 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2903 const LookupResult &R);
2906 const LookupResult &R);
2907 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2908 const LookupResult &R);
2909 void CheckShadow(Scope *S, VarDecl *D);
2910
2911 /// Warn if 'E', which is an expression that is about to be modified, refers
2912 /// to a shadowing declaration.
2914
2916
2917private:
2918 /// Map of current shadowing declarations to shadowed declarations. Warn if
2919 /// it looks like the user is trying to modify the shadowing declaration.
2920 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2921
2922public:
2923 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2924 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2925 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2926 TypedefNameDecl *NewTD);
2929 TypeSourceInfo *TInfo,
2932 LookupResult &Previous, bool &Redeclaration);
2934 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
2935 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
2936 bool &AddToScope, ArrayRef<BindingDecl *> Bindings = std::nullopt);
2937 NamedDecl *
2939 MultiTemplateParamsArg TemplateParamLists);
2940 // Returns true if the variable declaration is a redeclaration
2944 Expr *Init);
2948
2950 TypeSourceInfo *TInfo,
2952 MultiTemplateParamsArg TemplateParamLists,
2953 bool &AddToScope);
2955
2957 /// Diagnose issues that are non-constant or that are extensions.
2958 Diagnose,
2959 /// Identify whether this function satisfies the formal rules for constexpr
2960 /// functions in the current lanugage mode (with no extensions).
2962 };
2963
2965 CheckConstexprKind Kind);
2966
2969 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2971 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2972 // Returns true if the function declaration is a redeclaration
2975 bool IsMemberSpecialization, bool DeclIsDefn);
2978 QualType NewT, QualType OldT);
2979 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2983 bool IsDefinition);
2987 SourceLocation Loc,
2988 QualType T);
2990 SourceLocation NameLoc, IdentifierInfo *Name,
2991 QualType T, TypeSourceInfo *TSInfo,
2992 StorageClass SC);
2993 void ActOnParamDefaultArgument(Decl *param,
2994 SourceLocation EqualLoc,
2995 Expr *defarg);
2997 SourceLocation ArgLoc);
2998 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
3000 SourceLocation EqualLoc);
3001 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
3002 SourceLocation EqualLoc);
3003
3004 // Contexts where using non-trivial C union types can be disallowed. This is
3005 // passed to err_non_trivial_c_union_in_invalid_context.
3007 // Function parameter.
3009 // Function return.
3011 // Default-initialized object.
3013 // Variable with automatic storage duration.
3015 // Initializer expression that might copy from another object.
3017 // Assignment.
3019 // Compound literal.
3021 // Block capture.
3023 // lvalue-to-rvalue conversion of volatile type.
3025 };
3026
3027 /// Emit diagnostics if the initializer or any of its explicit or
3028 /// implicitly-generated subexpressions require copying or
3029 /// default-initializing a type that is or contains a C union type that is
3030 /// non-trivial to copy or default-initialize.
3032
3033 // These flags are passed to checkNonTrivialCUnion.
3038 };
3039
3040 /// Emit diagnostics if a non-trivial C union type or a struct that contains
3041 /// a non-trivial C union is used in an invalid context.
3043 NonTrivialCUnionContext UseContext,
3044 unsigned NonTrivialKind);
3045
3046 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
3047 void ActOnUninitializedDecl(Decl *dcl);
3048 void ActOnInitializerError(Decl *Dcl);
3049
3050 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
3051 void ActOnCXXForRangeDecl(Decl *D);
3053 IdentifierInfo *Ident,
3054 ParsedAttributes &Attrs);
3055 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
3056 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
3059 void FinalizeDeclaration(Decl *D);
3061 ArrayRef<Decl *> Group);
3063
3064 /// Should be called on all declarations that might have attached
3065 /// documentation comments.
3066 void ActOnDocumentableDecl(Decl *D);
3068
3069 enum class FnBodyKind {
3070 /// C++ [dcl.fct.def.general]p1
3071 /// function-body:
3072 /// ctor-initializer[opt] compound-statement
3073 /// function-try-block
3074 Other,
3075 /// = default ;
3076 Default,
3077 /// = delete ;
3078 Delete
3079 };
3080
3082 SourceLocation LocAfterDecls);
3084 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
3085 SkipBodyInfo *SkipBody = nullptr);
3087 MultiTemplateParamsArg TemplateParamLists,
3088 SkipBodyInfo *SkipBody = nullptr,
3089 FnBodyKind BodyKind = FnBodyKind::Other);
3091 SkipBodyInfo *SkipBody = nullptr,
3092 FnBodyKind BodyKind = FnBodyKind::Other);
3093 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind);
3099 return D && isa<ObjCMethodDecl>(D);
3100 }
3101
3102 /// Determine whether we can delay parsing the body of a function or
3103 /// function template until it is used, assuming we don't care about emitting
3104 /// code for that function.
3105 ///
3106 /// This will be \c false if we may need the body of the function in the
3107 /// middle of parsing an expression (where it's impractical to switch to
3108 /// parsing a different function), for instance, if it's constexpr in C++11
3109 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
3110 bool canDelayFunctionBody(const Declarator &D);
3111
3112 /// Determine whether we can skip parsing the body of a function
3113 /// definition, assuming we don't care about analyzing its body or emitting
3114 /// code for that function.
3115 ///
3116 /// This will be \c false only if we may need the body of the function in
3117 /// order to parse the rest of the program (for instance, if it is
3118 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
3119 bool canSkipFunctionBody(Decl *D);
3120
3121 /// Determine whether \param D is function like (function or function
3122 /// template) for parsing.
3124
3127 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
3130
3131 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
3132 /// attribute for which parsing is delayed.
3134
3135 /// Diagnose any unused parameters in the given sequence of
3136 /// ParmVarDecl pointers.
3138
3139 /// Diagnose whether the size of parameters or return value of a
3140 /// function or obj-c method definition is pass-by-value and larger than a
3141 /// specified threshold.
3142 void
3144 QualType ReturnTy, NamedDecl *D);
3145
3146 void DiagnoseInvalidJumps(Stmt *Body);
3148 SourceLocation AsmLoc,
3149 SourceLocation RParenLoc);
3150
3151 Decl *ActOnTopLevelStmtDecl(Stmt *Statement);
3152
3153 /// Handle a C++11 empty-declaration and attribute-declaration.
3155 SourceLocation SemiLoc);
3156
3157 enum class ModuleDeclKind {
3158 Interface, ///< 'export module X;'
3159 Implementation, ///< 'module X;'
3160 PartitionInterface, ///< 'export module X:Y;'
3161 PartitionImplementation, ///< 'module X:Y;'
3162 };
3163
3164 /// An enumeration to represent the transition of states in parsing module
3165 /// fragments and imports. If we are not parsing a C++20 TU, or we find
3166 /// an error in state transition, the state is set to NotACXX20Module.
3168 FirstDecl, ///< Parsing the first decl in a TU.
3169 GlobalFragment, ///< after 'module;' but before 'module X;'
3170 ImportAllowed, ///< after 'module X;' but before any non-import decl.
3171 ImportFinished, ///< after any non-import decl.
3172 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
3173 ///< non-import decl.
3174 PrivateFragmentImportFinished, ///< after 'module :private;' but a
3175 ///< non-import decl has already been seen.
3176 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
3177 };
3178
3179private:
3180 /// The parser has begun a translation unit to be compiled as a C++20
3181 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
3182 void HandleStartOfHeaderUnit();
3183
3184public:
3185 /// The parser has processed a module-declaration that begins the definition
3186 /// of a module interface or implementation.
3188 SourceLocation ModuleLoc, ModuleDeclKind MDK,
3189 ModuleIdPath Path, ModuleIdPath Partition,
3190 ModuleImportState &ImportState);
3191
3192 /// The parser has processed a global-module-fragment declaration that begins
3193 /// the definition of the global module fragment of the current module unit.
3194 /// \param ModuleLoc The location of the 'module' keyword.
3196
3197 /// The parser has processed a private-module-fragment declaration that begins
3198 /// the definition of the private module fragment of the current module unit.
3199 /// \param ModuleLoc The location of the 'module' keyword.
3200 /// \param PrivateLoc The location of the 'private' keyword.
3202 SourceLocation PrivateLoc);
3203
3204 /// The parser has processed a module import declaration.
3205 ///
3206 /// \param StartLoc The location of the first token in the declaration. This
3207 /// could be the location of an '@', 'export', or 'import'.
3208 /// \param ExportLoc The location of the 'export' keyword, if any.
3209 /// \param ImportLoc The location of the 'import' keyword.
3210 /// \param Path The module toplevel name as an access path.
3211 /// \param IsPartition If the name is for a partition.
3213 SourceLocation ExportLoc,
3214 SourceLocation ImportLoc, ModuleIdPath Path,
3215 bool IsPartition = false);
3217 SourceLocation ExportLoc,
3218 SourceLocation ImportLoc, Module *M,
3219 ModuleIdPath Path = {});
3220
3221 /// The parser has processed a module import translated from a
3222 /// #include or similar preprocessing directive.
3223 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3224 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3225
3226 /// The parsed has entered a submodule.
3227 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
3228 /// The parser has left a submodule.
3229 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
3230
3231 /// Create an implicit import of the given module at the given
3232 /// source location, for error recovery, if possible.
3233 ///
3234 /// This routine is typically used when an entity found by name lookup
3235 /// is actually hidden within a module that we know about but the user
3236 /// has forgotten to import.
3237 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
3238 Module *Mod);
3239
3240 /// Kinds of missing import. Note, the values of these enumerators correspond
3241 /// to %select values in diagnostics.
3244 Definition,
3248 };
3249
3250 /// Diagnose that the specified declaration needs to be visible but
3251 /// isn't, and suggest a module import that would resolve the problem.
3253 MissingImportKind MIK, bool Recover = true);
3255 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
3256 MissingImportKind MIK, bool Recover);
3257
3259 SourceLocation LBraceLoc);
3261 SourceLocation RBraceLoc);
3262
3263 /// We've found a use of a templated declaration that would trigger an
3264 /// implicit instantiation. Check that any relevant explicit specializations
3265 /// and partial specializations are visible/reachable, and diagnose if not.
3268
3269 /// Retrieve a suitable printing policy for diagnostics.
3271 return getPrintingPolicy(Context, PP);
3272 }
3273
3274 /// Retrieve a suitable printing policy for diagnostics.
3276 const Preprocessor &PP);
3277
3278 /// Scope actions.
3279 void ActOnPopScope(SourceLocation Loc, Scope *S);
3281
3283 const ParsedAttributesView &DeclAttrs,
3284 RecordDecl *&AnonRecord);
3286 const ParsedAttributesView &DeclAttrs,
3287 MultiTemplateParamsArg TemplateParams,
3288 bool IsExplicitInstantiation,
3289 RecordDecl *&AnonRecord);
3290
3292 AccessSpecifier AS,
3293 RecordDecl *Record,
3294 const PrintingPolicy &Policy);
3295
3297 RecordDecl *Record);
3298
3299 /// Common ways to introduce type names without a tag for use in diagnostics.
3300 /// Keep in sync with err_tag_reference_non_tag.
3311 };
3312
3313 /// Given a non-tag type declaration, returns an enum useful for indicating
3314 /// what kind of non-tag type this is.
3316
3318 TagTypeKind NewTag, bool isDefinition,
3319 SourceLocation NewTagLoc,
3320 const IdentifierInfo *Name);
3321
3323 TUK_Reference, // Reference to a tag: 'struct foo *X;'
3324 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
3325 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
3326 TUK_Friend // Friend declaration: 'friend struct foo;'
3328
3330 // Not parsing a type within __builtin_offsetof.
3332 // Parsing a type within __builtin_offsetof.
3334 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
3335 // To improve our diagnostic message.
3337 };
3338
3339 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3340 SourceLocation KWLoc, CXXScopeSpec &SS,
3341 IdentifierInfo *Name, SourceLocation NameLoc,
3343 SourceLocation ModulePrivateLoc,
3344 MultiTemplateParamsArg TemplateParameterLists,
3345 bool &OwnedDecl, bool &IsDependent,
3346 SourceLocation ScopedEnumKWLoc,
3347 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3348 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3349 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
3350
3352 unsigned TagSpec, SourceLocation TagLoc,
3353 CXXScopeSpec &SS, IdentifierInfo *Name,
3354 SourceLocation NameLoc,
3356 MultiTemplateParamsArg TempParamLists);
3357
3359 unsigned TagSpec,
3360 TagUseKind TUK,
3361 const CXXScopeSpec &SS,
3362 IdentifierInfo *Name,
3363 SourceLocation TagLoc,
3364 SourceLocation NameLoc);
3365
3366 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3367 IdentifierInfo *ClassName,
3369 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3370 Declarator &D, Expr *BitfieldWidth);
3371
3372 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3373 Declarator &D, Expr *BitfieldWidth,
3374 InClassInitStyle InitStyle,
3375 AccessSpecifier AS);
3377 SourceLocation DeclStart, Declarator &D,
3378 Expr *BitfieldWidth,
3379 InClassInitStyle InitStyle,
3380 AccessSpecifier AS,
3381 const ParsedAttr &MSPropertyAttr);
3382
3384 TypeSourceInfo *TInfo,
3385 RecordDecl *Record, SourceLocation Loc,
3386 bool Mutable, Expr *BitfieldWidth,
3387 InClassInitStyle InitStyle,
3388 SourceLocation TSSL,
3389 AccessSpecifier AS, NamedDecl *PrevDecl,
3390 Declarator *D = nullptr);
3391
3393 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3394
3396 /// The triviality of a method unaffected by "trivial_abi".
3398
3399 /// The triviality of a method affected by "trivial_abi".
3402
3405 bool Diagnose = false);
3406
3407 /// For a defaulted function, the kind of defaulted function that it is.
3409 CXXSpecialMember SpecialMember : 8;
3410 DefaultedComparisonKind Comparison : 8;
3411
3412 public:
3414 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3415 }
3417 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3419 : SpecialMember(CXXInvalid), Comparison(Comp) {}
3420
3421 bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3422 bool isComparison() const {
3423 return Comparison != DefaultedComparisonKind::None;
3424 }
3425
3426 explicit operator bool() const {
3427 return isSpecialMember() || isComparison();
3428 }
3429
3430 CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3431 DefaultedComparisonKind asComparison() const { return Comparison; }
3432
3433 /// Get the index of this function kind for use in diagnostics.
3434 unsigned getDiagnosticIndex() const {
3435 static_assert(CXXInvalid > CXXDestructor,
3436 "invalid should have highest index");
3437 static_assert((unsigned)DefaultedComparisonKind::None == 0,
3438 "none should be equal to zero");
3439 return SpecialMember + (unsigned)Comparison;
3440 }
3441 };
3442
3443 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3444
3447 }
3450 }
3451
3452 void ActOnLastBitfield(SourceLocation DeclStart,
3453 SmallVectorImpl<Decl *> &AllIvarDecls);
3454 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3455 Declarator &D, Expr *BitfieldWidth,
3456 tok::ObjCKeywordKind visibility);
3457
3458 // This is used for both record definitions and ObjC interface declarations.
3459 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3460 ArrayRef<Decl *> Fields, SourceLocation LBrac,
3461 SourceLocation RBrac, const ParsedAttributesView &AttrList);
3462
3463 /// ActOnTagStartDefinition - Invoked when we have entered the
3464 /// scope of a tag's definition (e.g., for an enumeration, class,
3465 /// struct, or union).
3467
3468 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3469 /// Differently from C++, actually parse the body and reject / error out
3470 /// in case of a structural mismatch.
3471 bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3472
3473 /// Check ODR hashes for C/ObjC when merging types from modules.
3474 /// Differently from C++, actually parse the body and reject in case
3475 /// of a mismatch.
3476 template <typename T,
3477 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
3479 if (Duplicate->getODRHash() != Previous->getODRHash())
3480 return false;
3481
3482 // Make the previous decl visible.
3484 return true;
3485 }
3486
3488
3489 /// Invoked when we enter a tag definition that we're skipping.
3491
3493
3494 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3495 /// C++ record definition's base-specifiers clause and are starting its
3496 /// member declarations.
3498 SourceLocation FinalLoc,
3499 bool IsFinalSpelledSealed,
3500 bool IsAbstract,
3501 SourceLocation LBraceLoc);
3502
3503 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3504 /// the definition of a tag (enumeration, class, struct, or union).
3506 SourceRange BraceRange);
3507
3509
3511
3512 /// Invoked when we must temporarily exit the objective-c container
3513 /// scope for parsing/looking-up C constructs.
3514 ///
3515 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3518
3519 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3520 /// error parsing the definition of a tag.
3522
3524 EnumConstantDecl *LastEnumConst,
3525 SourceLocation IdLoc,
3527 Expr *val);
3529 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3530 QualType EnumUnderlyingTy, bool IsFixed,
3531 const EnumDecl *Prev);
3532
3533 /// Determine whether the body of an anonymous enumeration should be skipped.
3534 /// \param II The name of the first enumerator.
3536 SourceLocation IILoc);
3537
3538 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3540 const ParsedAttributesView &Attrs,
3541 SourceLocation EqualLoc, Expr *Val);
3542 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3543 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3544 const ParsedAttributesView &Attr);
3545
3546 /// Set the current declaration context until it gets popped.
3547 void PushDeclContext(Scope *S, DeclContext *DC);
3548 void PopDeclContext();
3549
3550 /// EnterDeclaratorContext - Used when we must lookup names in the context
3551 /// of a declarator's nested name specifier.
3554
3555 /// Enter a template parameter scope, after it's been associated with a particular
3556 /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3557 /// in the correct order.
3559
3560 /// Push the parameters of D, which must be a function, into scope.
3563
3564 /// If \p AllowLambda is true, treat lambda as function.
3565 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
3566
3567 /// Returns a pointer to the innermost enclosing function, or nullptr if the
3568 /// current context is not inside a function. If \p AllowLambda is true,
3569 /// this can return the call operator of an enclosing lambda, otherwise
3570 /// lambdas are skipped when looking for an enclosing function.
3571 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
3572
3573 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3574 /// the method decl for the method being parsed. If we're currently
3575 /// in a 'block', this returns the containing context.
3577
3578 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3579 /// or C function we're in, otherwise return null. If we're currently
3580 /// in a 'block', this returns the containing context.
3582
3583 /// Add this decl to the scope shadowed decl chains.
3584 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3585
3586 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3587 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3588 /// true if 'D' belongs to the given declaration context.
3589 ///
3590 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3591 /// enclosing namespace set of the context, rather than contained
3592 /// directly within it.
3593 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3594 bool AllowInlineNamespace = false) const;
3595
3596 /// Finds the scope corresponding to the given decl context, if it
3597 /// happens to be an enclosing scope. Otherwise return NULL.
3599
3600 /// Subroutines of ActOnDeclarator().
3602 TypeSourceInfo *TInfo);
3604
3605 /// Describes the kind of merge to perform for availability
3606 /// attributes (including "deprecated", "unavailable", and "availability").
3608 /// Don't merge availability attributes at all.
3610 /// Merge availability attributes for a redeclaration, which requires
3611 /// an exact match.
3613 /// Merge availability attributes for an override, which requires
3614 /// an exact match or a weakening of constraints.
3616 /// Merge availability attributes for an implementation of
3617 /// a protocol requirement.
3619 /// Merge availability attributes for an implementation of
3620 /// an optional protocol requirement.
3623
3624 /// Describes the kind of priority given to an availability attribute.
3625 ///
3626 /// The sum of priorities deteremines the final priority of the attribute.
3627 /// The final priority determines how the attribute will be merged.
3628 /// An attribute with a lower priority will always remove higher priority
3629 /// attributes for the specified platform when it is being applied. An
3630 /// attribute with a higher priority will not be applied if the declaration
3631 /// already has an availability attribute with a lower priority for the
3632 /// specified platform. The final prirority values are not expected to match
3633 /// the values in this enumeration, but instead should be treated as a plain
3634 /// integer value. This enumeration just names the priority weights that are
3635 /// used to calculate that final vaue.
3637 /// The availability attribute was specified explicitly next to the
3638 /// declaration.
3640
3641 /// The availability attribute was applied using '#pragma clang attribute'.
3643
3644 /// The availability attribute for a specific platform was inferred from
3645 /// an availability attribute for another platform.
3648
3649 /// Attribute merging methods. Return true if a new attribute was added.
3650 AvailabilityAttr *
3652 IdentifierInfo *Platform, bool Implicit,
3653 VersionTuple Introduced, VersionTuple Deprecated,
3654 VersionTuple Obsoleted, bool IsUnavailable,
3655 StringRef Message, bool IsStrict, StringRef Replacement,
3657 TypeVisibilityAttr *
3659 TypeVisibilityAttr::VisibilityType Vis);
3660 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3661 VisibilityAttr::VisibilityType Vis);
3662 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3663 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3664 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3665 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3666 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3667 const AttributeCommonInfo &CI,
3668 bool BestCase,
3669 MSInheritanceModel Model);
3670 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3671 StringRef NewUserDiagnostic);
3672 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3673 IdentifierInfo *Format, int FormatIdx,
3674 int FirstArg);
3675 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3676 StringRef Name);
3677 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3678 StringRef Name);
3679 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3680 const AttributeCommonInfo &CI,
3681 const IdentifierInfo *Ident);
3682 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3683 SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3684 StringRef Name);
3685 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3686 const AttributeCommonInfo &CI);
3687 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3688 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3689 const InternalLinkageAttr &AL);
3690 WebAssemblyImportNameAttr *mergeImportNameAttr(
3691 Decl *D, const WebAssemblyImportNameAttr &AL);
3692 WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3693 Decl *D, const WebAssemblyImportModuleAttr &AL);
3694 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3695 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3696 const EnforceTCBLeafAttr &AL);
3697 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
3698 HLSLNumThreadsAttr *mergeHLSLNumThreadsAttr(Decl *D,
3699 const AttributeCommonInfo &AL,
3700 int X, int Y, int Z);
3701 HLSLShaderAttr *mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL,
3702 HLSLShaderAttr::ShaderType ShaderType);
3703
3704 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3707 LookupResult &OldDecls);
3708 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3709 bool MergeTypeWithOld, bool NewDeclIsDefn);
3711 Scope *S, bool MergeTypeWithOld);
3714 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3716 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3717 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3719
3720 // AssignmentAction - This is used by all the assignment diagnostic functions
3721 // to represent what is actually causing the operation
3732
3733 /// C++ Overloading.
3735 /// This is a legitimate overload: the existing declarations are
3736 /// functions or function templates with different signatures.
3738
3739 /// This is not an overload because the signature exactly matches
3740 /// an existing declaration.
3742
3743 /// This is not an overload because the lookup results contain a
3744 /// non-function.
3748 FunctionDecl *New,
3749 const LookupResult &OldDecls,
3750 NamedDecl *&OldDecl,
3751 bool UseMemberUsingDeclRules);
3752 bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
3753 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true,
3754 bool ConsiderRequiresClauses = true);
3755
3756 // Calculates whether the expression Constraint depends on an enclosing
3757 // template, for the purposes of [temp.friend] p9.
3758 // TemplateDepth is the 'depth' of the friend function, which is used to
3759 // compare whether a declaration reference is referring to a containing
3760 // template, or just the current friend function. A 'lower' TemplateDepth in
3761 // the AST refers to a 'containing' template. As the constraint is
3762 // uninstantiated, this is relative to the 'top' of the TU.
3763 bool
3765 unsigned TemplateDepth,
3766 const Expr *Constraint);
3767
3768 // Calculates whether the friend function depends on an enclosing template for
3769 // the purposes of [temp.friend] p9.
3771
3772 // Calculates whether two constraint expressions are equal irrespective of a
3773 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
3774 // 'New', which are the "source" of the constraint, since this is necessary
3775 // for figuring out the relative 'depth' of the constraint. The depth of the
3776 // 'primary template' and the 'instantiated from' templates aren't necessarily
3777 // the same, such as a case when one is a 'friend' defined in a class.
3779 const Expr *OldConstr,
3780 const NamedDecl *New,
3781 const Expr *NewConstr);
3782
3783 enum class AllowedExplicit {
3784 /// Allow no explicit functions to be used.
3785 None,
3786 /// Allow explicit conversion functions but not explicit constructors.
3788 /// Allow both explicit conversion functions and explicit constructors.
3789 All
3790 };
3791
3793 TryImplicitConversion(Expr *From, QualType ToType,
3794 bool SuppressUserConversions,
3795 AllowedExplicit AllowExplicit,
3796 bool InOverloadResolution,
3797 bool CStyle,
3798 bool AllowObjCWritebackConversion);
3799
3800 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3801 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3802 bool IsComplexPromotion(QualType FromType, QualType ToType);
3803 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3804 bool InOverloadResolution,
3805 QualType& ConvertedType, bool &IncompatibleObjC);
3806 bool isObjCPointerConversion(QualType FromType, QualType ToType,
3807 QualType& ConvertedType, bool &IncompatibleObjC);
3808 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3809 QualType &ConvertedType);
3810 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3811 QualType& ConvertedType);
3813 const FunctionProtoType *NewType,
3814 unsigned *ArgPos = nullptr,
3815 bool Reversed = false);
3817 QualType FromType, QualType ToType);
3818
3821 bool CheckPointerConversion(Expr *From, QualType ToType,
3822 CastKind &Kind,
3823 CXXCastPath& BasePath,
3824 bool IgnoreBaseAccess,
3825 bool Diagnose = true);
3826 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3827 bool InOverloadResolution,
3828 QualType &ConvertedType);
3829 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3830 CastKind &Kind,
3831 CXXCastPath &BasePath,
3832 bool IgnoreBaseAccess);
3833 bool IsQualificationConversion(QualType FromType, QualType ToType,
3834 bool CStyle, bool &ObjCLifetimeConversion);
3835 bool IsFunctionConversion(QualType FromType, QualType ToType,
3836 QualType &ResultTy);
3839
3841 const InitializedEntity &Entity, InitListExpr *From);
3842
3843 bool IsStringInit(Expr *Init, const ArrayType *AT);
3844
3846 ExprResult Init);
3848 SourceLocation EqualLoc,
3849 ExprResult Init,
3850 bool TopLevelOfInitList = false,
3851 bool AllowExplicit = false);
3853 NestedNameSpecifier *Qualifier,
3854 NamedDecl *FoundDecl,
3855 CXXMethodDecl *Method);
3856
3857 /// Check that the lifetime of the initializer (and its subobjects) is
3858 /// sufficient for initializing the entity, and perform lifetime extension
3859 /// (when permitted) if not.
3860 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3861
3864
3865 /// Contexts in which a converted constant expression is required.
3866 enum CCEKind {
3867 CCEK_CaseValue, ///< Expression in a case label.
3868 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
3869 CCEK_TemplateArg, ///< Value of a non-type template parameter.
3870 CCEK_ArrayBound, ///< Array bound in array declarator or new-expression.
3871 CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier.
3872 CCEK_Noexcept ///< Condition in a noexcept(bool) specifier.
3875 llvm::APSInt &Value, CCEKind CCE);
3877 APValue &Value, CCEKind CCE,
3878 NamedDecl *Dest = nullptr);
3879
3880 /// Abstract base class used to perform a contextual implicit
3881 /// conversion from an expression to any type passing a filter.
3883 public:
3886
3888 bool SuppressConversion = false)
3890
3891 /// Determine whether the specified type is a valid destination type
3892 /// for this conversion.
3893 virtual bool match(QualType T) = 0;
3894
3895 /// Emits a diagnostic complaining that the expression does not have
3896 /// integral or enumeration type.
3897 virtual SemaDiagnosticBuilder
3899
3900 /// Emits a diagnostic when the expression has incomplete class type.
3901 virtual SemaDiagnosticBuilder
3903
3904 /// Emits a diagnostic when the only matching conversion function
3905 /// is explicit.
3907 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3908
3909 /// Emits a note for the explicit conversion function.
3910 virtual SemaDiagnosticBuilder
3912
3913 /// Emits a diagnostic when there are multiple possible conversion
3914 /// functions.
3915 virtual SemaDiagnosticBuilder
3917
3918 /// Emits a note for one of the candidate conversions.
3919 virtual SemaDiagnosticBuilder
3921
3922 /// Emits a diagnostic when we picked a conversion function
3923 /// (for cases when we are not allowed to pick a conversion function).
3925 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3926
3928 };
3929
3931 bool AllowScopedEnumerations;
3932
3933 public:
3934 ICEConvertDiagnoser(bool AllowScopedEnumerations,
3935 bool Suppress, bool SuppressConversion)
3937 AllowScopedEnumerations(AllowScopedEnumerations) {}
3938
3939 /// Match an integral or (possibly scoped) enumeration type.
3940 bool match(QualType T) override;
3941
3944 return diagnoseNotInt(S, Loc, T);
3945 }
3946
3947 /// Emits a diagnostic complaining that the expression does not have
3948 /// integral or enumeration type.
3949 virtual SemaDiagnosticBuilder
3951 };
3952
3953 /// Perform a contextual implicit conversion.
3955 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3956
3957
3961 OS_Error
3964
3965 // Note that LK_String is intentionally after the other literals, as
3966 // this is used for diagnostics logic.
3974 LK_None
3977
3979 NestedNameSpecifier *Qualifier,
3980 NamedDecl *FoundDecl,
3981 NamedDecl *Member);
3982
3983 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3984 // TODO: make this is a typesafe union.
3987
3989
3991 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
3992 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3993 bool PartialOverloading = false, bool AllowExplicit = true,
3994 bool AllowExplicitConversion = false,
3995 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3996 ConversionSequenceList EarlyConversions = std::nullopt,
3998 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3999 ArrayRef<Expr *> Args,
4000 OverloadCandidateSet &CandidateSet,
4001 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4002 bool SuppressUserConversions = false,
4003 bool PartialOverloading = false,
4004 bool FirstArgumentIsBase = false);
4005 void AddMethodCandidate(DeclAccessPair FoundDecl,
4006 QualType ObjectType,
4007 Expr::Classification ObjectClassification,
4008 ArrayRef<Expr *> Args,
4009 OverloadCandidateSet& CandidateSet,
4010 bool SuppressUserConversion = false,
4012 void
4013 AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
4014 CXXRecordDecl *ActingContext, QualType ObjectType,
4015 Expr::Classification ObjectClassification,
4016 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
4017 bool SuppressUserConversions = false,
4018 bool PartialOverloading = false,
4019 ConversionSequenceList EarlyConversions = std::nullopt,
4021 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
4022 DeclAccessPair FoundDecl,
4023 CXXRecordDecl *ActingContext,
4024 TemplateArgumentListInfo *ExplicitTemplateArgs,
4025 QualType ObjectType,
4026 Expr::Classification ObjectClassification,
4027 ArrayRef<Expr *> Args,
4028 OverloadCandidateSet& CandidateSet,
4029 bool SuppressUserConversions = false,
4030 bool PartialOverloading = false,
4033 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
4034 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4035 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
4036 bool PartialOverloading = false, bool AllowExplicit = true,
4037 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
4040 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
4041 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
4042 ConversionSequenceList &Conversions, bool SuppressUserConversions,
4043 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
4044 Expr::Classification ObjectClassification = {},
4047 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
4048 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
4049 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
4050 bool AllowExplicit, bool AllowResultConversion = true);
4052 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
4053 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
4054 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
4055 bool AllowExplicit, bool AllowResultConversion = true);
4056 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
4057 DeclAccessPair FoundDecl,
4058 CXXRecordDecl *ActingContext,
4059 const FunctionProtoType *Proto,
4060 Expr *Object, ArrayRef<Expr *> Args,
4061 OverloadCandidateSet& CandidateSet);
4063 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
4064 OverloadCandidateSet &CandidateSet,
4065 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4067 SourceLocation OpLoc, ArrayRef<Expr *> Args,
4068 OverloadCandidateSet &CandidateSet,
4070 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
4071 OverloadCandidateSet& CandidateSet,
4072 bool IsAssignmentOperator = false,
4073 unsigned NumContextualBoolArguments = 0);
4075 SourceLocation OpLoc, ArrayRef<Expr *> Args,
4076 OverloadCandidateSet& CandidateSet);
4077 void AddArgumentDependentLookupCandidates(DeclarationName Name,
4078 SourceLocation Loc,
4079 ArrayRef<Expr *> Args,
4080 TemplateArgumentListInfo *ExplicitTemplateArgs,
4081 OverloadCandidateSet& CandidateSet,
4082 bool PartialOverloading = false);
4083
4084 // Emit as a 'note' the specific overload candidate
4086 const NamedDecl *Found, const FunctionDecl *Fn,
4088 QualType DestType = QualType(), bool TakingAddress = false);
4089
4090 // Emit as a series of 'note's all template and non-templates identified by
4091 // the expression Expr
4092 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
4093 bool TakingAddress = false);
4094
4095 /// Check the enable_if expressions on the given function. Returns the first
4096 /// failing attribute, or NULL if they were all successful.
4097 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
4098 ArrayRef<Expr *> Args,
4099 bool MissingImplicitThis = false);
4100
4101 /// Find the failed Boolean condition within a given Boolean
4102 /// constant expression, and describe it with a string.
4103 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
4104
4105 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
4106 /// non-ArgDependent DiagnoseIfAttrs.
4107 ///
4108 /// Argument-dependent diagnose_if attributes should be checked each time a
4109 /// function is used as a direct callee of a function call.
4110 ///
4111 /// Returns true if any errors were emitted.
4112 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
4113 const Expr *ThisArg,
4114 ArrayRef<const Expr *> Args,
4115 SourceLocation Loc);
4116
4117 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
4118 /// ArgDependent DiagnoseIfAttrs.
4119 ///
4120 /// Argument-independent diagnose_if attributes should be checked on every use
4121 /// of a function.
4122 ///
4123 /// Returns true if any errors were emitted.
4124 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
4125 SourceLocation Loc);
4126
4127 /// Returns whether the given function's address can be taken or not,
4128 /// optionally emitting a diagnostic if the address can't be taken.
4129 ///
4130 /// Returns false if taking the address of the function is illegal.
4131 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
4132 bool Complain = false,
4133 SourceLocation Loc = SourceLocation());
4134
4135 // [PossiblyAFunctionType] --> [Return]
4136 // NonFunctionType --> NonFunctionType
4137 // R (A) --> R(A)
4138 // R (*)(A) --> R (A)
4139 // R (&)(A) --> R (A)
4140 // R (S::*)(A) --> R (A)
4141 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
4142
4143 FunctionDecl *
4144 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
4145 QualType TargetType,
4146 bool Complain,
4147 DeclAccessPair &Found,
4148 bool *pHadMultipleCandidates = nullptr);
4149
4150 FunctionDecl *
4151 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
4152
4154 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
4155
4157 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
4158 TemplateSpecCandidateSet *FailedTSC = nullptr);
4159
4161 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
4162 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
4163 QualType DestTypeForComplaining = QualType(),
4164 unsigned DiagIDForComplaining = 0);
4165
4166 Expr *FixOverloadedFunctionReference(Expr *E,
4167 DeclAccessPair FoundDecl,
4168 FunctionDecl *Fn);
4170 DeclAccessPair FoundDecl,
4171 FunctionDecl *Fn);
4172
4173 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
4174 ArrayRef<Expr *> Args,
4175 OverloadCandidateSet &CandidateSet,
4176 bool PartialOverloading = false);
4178 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
4179 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
4180
4181 // An enum used to represent the different possible results of building a
4182 // range-based for loop.
4188
4190 SourceLocation RangeLoc,
4191 const DeclarationNameInfo &NameInfo,
4192 LookupResult &MemberLookup,
4193 OverloadCandidateSet *CandidateSet,
4194 Expr *Range, ExprResult *CallExpr);
4195
4198 SourceLocation LParenLoc,
4199 MultiExprArg Args,
4200 SourceLocation RParenLoc,
4201 Expr *ExecConfig,
4202 bool AllowTypoCorrection=true,
4203 bool CalleesAddressIsTaken=false);
4204
4206 MultiExprArg Args, SourceLocation RParenLoc,
4207 OverloadCandidateSet *CandidateSet,
4209
4213 const UnresolvedSetImpl &Fns,
4214 bool PerformADL = true);
4215
4218 const UnresolvedSetImpl &Fns,
4219 Expr *input, bool RequiresADL = true);
4220
4223 const UnresolvedSetImpl &Fns,
4224 ArrayRef<Expr *> Args, bool RequiresADL = true);
4227 const UnresolvedSetImpl &Fns,
4228 Expr *LHS, Expr *RHS,
4229 bool RequiresADL = true,
4230 bool AllowRewrittenCandidates = true,
4231 FunctionDecl *DefaultedFn = nullptr);
4233 const UnresolvedSetImpl &Fns,
4234 Expr *LHS, Expr *RHS,
4235 FunctionDecl *DefaultedFn);
4236
4238 SourceLocation RLoc, Expr *Base,
4239 MultiExprArg Args);
4240
4242 SourceLocation LParenLoc,
4243 MultiExprArg Args,
4244 SourceLocation RParenLoc,
4245 Expr *ExecConfig = nullptr,
4246 bool IsExecConfig = false,
4247 bool AllowRecovery = false);
4250 MultiExprArg Args,
4251 SourceLocation RParenLoc);
4252
4254 SourceLocation OpLoc,
4255 bool *NoArrowOperatorFound = nullptr);
4256
4257 /// CheckCallReturnType - Checks that a call expression's return type is
4258 /// complete. Returns true on failure. The location passed in is the location
4259 /// that best represents the call.
4260 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
4261 CallExpr *CE, FunctionDecl *FD);
4262
4263 /// Helpers for dealing with blocks and functions.
4265 bool CheckParameterNames);
4269
4270 /// \name Name lookup
4271 ///
4272 /// These routines provide name lookup that is used during semantic
4273 /// analysis to resolve the various kinds of names (identifiers,
4274 /// overloaded operator names, constructor names, etc.) into zero or
4275 /// more declarations within a particular scope. The major entry
4276 /// points are LookupName, which performs unqualified name lookup,
4277 /// and LookupQualifiedName, which performs qualified name lookup.
4278 ///
4279 /// All name lookup is performed based on some specific criteria,
4280 /// which specify what names will be visible to name lookup and how
4281 /// far name lookup should work. These criteria are important both
4282 /// for capturing language semantics (certain lookups will ignore
4283 /// certain names, for example) and for performance, since name
4284 /// lookup is often a bottleneck in the compilation of C++. Name
4285 /// lookup criteria is specified via the LookupCriteria enumeration.
4286 ///
4287 /// The results of name lookup can vary based on the kind of name
4288 /// lookup performed, the current language, and the translation
4289 /// unit. In C, for example, name lookup will either return nothing
4290 /// (no entity found) or a single declaration. In C++, name lookup
4291 /// can additionally refer to a set of overloaded functions or
4292 /// result in an ambiguity. All of the possible results of name
4293 /// lookup are captured by the LookupResult class, which provides
4294 /// the ability to distinguish among them.
4295 //@{
4296
4297 /// Describes the kind of name lookup to perform.
4299 /// Ordinary name lookup, which finds ordinary names (functions,
4300 /// variables, typedefs, etc.) in C and most kinds of names
4301 /// (functions, variables, members, types, etc.) in C++.
4303 /// Tag name lookup, which finds the names of enums, classes,
4304 /// structs, and unions.
4306 /// Label name lookup.
4308 /// Member name lookup, which finds the names of
4309 /// class/struct/union members.
4311 /// Look up of an operator name (e.g., operator+) for use with
4312 /// operator overloading. This lookup is similar to ordinary name
4313 /// lookup, but will ignore any declarations that are class members.
4315 /// Look up a name following ~ in a destructor name. This is an ordinary
4316 /// lookup, but prefers tags to typedefs.
4318 /// Look up of a name that precedes the '::' scope resolution
4319 /// operator in C++. This lookup completely ignores operator, object,
4320 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
4322 /// Look up a namespace name within a C++ using directive or
4323 /// namespace alias definition, ignoring non-namespace names (C++
4324 /// [basic.lookup.udir]p1).
4326 /// Look up all declarations in a scope with the given name,
4327 /// including resolved using declarations. This is appropriate
4328 /// for checking redeclarations for a using declaration.
4330 /// Look up an ordinary name that is going to be redeclared as a
4331 /// name with linkage. This lookup ignores any declarations that
4332 /// are outside of the current scope unless they have linkage. See
4333 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
4335 /// Look up a friend of a local class. This lookup does not look
4336 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
4338 /// Look up the name of an Objective-C protocol.
4340 /// Look up implicit 'self' parameter of an objective-c method.
4342 /// Look up the name of an OpenMP user-defined reduction operation.