clang 24.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/ASTLambda.h"
20#include "clang/AST/Attr.h"
22#include "clang/AST/CharUnits.h"
23#include "clang/AST/DeclBase.h"
24#include "clang/AST/DeclCXX.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
33#include "clang/AST/StmtCXX.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
41#include "clang/Basic/Cuda.h"
44#include "clang/Basic/LLVM.h"
45#include "clang/Basic/Lambda.h"
47#include "clang/Basic/Module.h"
58#include "clang/Sema/Attr.h"
60#include "clang/Sema/DeclSpec.h"
66#include "clang/Sema/Scope.h"
67#include "clang/Sema/SemaBase.h"
70#include "clang/Sema/Weak.h"
71#include "llvm/ADT/APInt.h"
72#include "llvm/ADT/ArrayRef.h"
73#include "llvm/ADT/BitmaskEnum.h"
74#include "llvm/ADT/DenseMap.h"
75#include "llvm/ADT/DenseSet.h"
76#include "llvm/ADT/FloatingPointMode.h"
77#include "llvm/ADT/FoldingSet.h"
78#include "llvm/ADT/MapVector.h"
79#include "llvm/ADT/PointerIntPair.h"
80#include "llvm/ADT/PointerUnion.h"
81#include "llvm/ADT/STLExtras.h"
82#include "llvm/ADT/STLForwardCompat.h"
83#include "llvm/ADT/STLFunctionalExtras.h"
84#include "llvm/ADT/SetVector.h"
85#include "llvm/ADT/SmallBitVector.h"
86#include "llvm/ADT/SmallPtrSet.h"
87#include "llvm/ADT/SmallSet.h"
88#include "llvm/ADT/SmallVector.h"
89#include "llvm/ADT/StringExtras.h"
90#include "llvm/ADT/StringMap.h"
91#include "llvm/ADT/TinyPtrVector.h"
92#include "llvm/Support/Allocator.h"
93#include "llvm/Support/Compiler.h"
94#include "llvm/Support/Error.h"
95#include "llvm/Support/ErrorHandling.h"
96#include <cassert>
97#include <climits>
98#include <cstddef>
99#include <cstdint>
100#include <deque>
101#include <functional>
102#include <iterator>
103#include <memory>
104#include <optional>
105#include <string>
106#include <tuple>
107#include <type_traits>
108#include <utility>
109#include <vector>
110
111namespace llvm {
112struct InlineAsmIdentifierInfo;
113} // namespace llvm
114
115namespace clang {
116class ADLResult;
117class APValue;
119class ASTConsumer;
120class ASTContext;
121class ASTDeclReader;
123class ASTReader;
124class ASTWriter;
125class CXXBasePath;
126class CXXBasePaths;
129enum class ComparisonCategoryType : unsigned char;
131class DarwinSDKInfo;
132class DeclGroupRef;
136class Designation;
137class IdentifierInfo;
144enum class LangAS : unsigned int;
146class LookupResult;
149class ModuleLoader;
153class ObjCMethodDecl;
154struct OverloadCandidate;
155enum class OverloadCandidateParamOrder : char;
156enum OverloadCandidateRewriteKind : unsigned;
158class Preprocessor;
160struct ResolvedAllocation;
161class SemaAMDGPU;
162class SemaARM;
163class SemaAVR;
164class SemaBPF;
166class SemaCUDA;
167class SemaDirectX;
168class SemaHLSL;
169class SemaHexagon;
170class SemaLoongArch;
171class SemaM68k;
172class SemaMIPS;
173class SemaMSP430;
174class SemaNVPTX;
175class SemaObjC;
176class SemaOpenACC;
177class SemaOpenCL;
178class SemaOpenMP;
179class SemaPPC;
180class SemaPseudoObject;
181class SemaRISCV;
182class SemaSPIRV;
183class SemaSYCL;
184class SemaSwift;
185class SemaSystemZ;
186class SemaWasm;
187class SemaX86;
189class TemplateArgument;
193class Token;
194class TypeConstraint;
199
200namespace sema {
201class BlockScopeInfo;
202class Capture;
209class LambdaScopeInfo;
210class SemaPPCallbacks;
212} // namespace sema
213
214// AssignmentAction - This is used by all the assignment diagnostic functions
215// to represent what is actually causing the operation
226
227// Inline capacity for type-aware, aligned, and unaligned allocation argument
228// list candidates.
230
231namespace threadSafety {
232class BeforeSet;
233void threadSafetyCleanup(BeforeSet *Cache);
234} // namespace threadSafety
235
236// FIXME: No way to easily map from TemplateTypeParmTypes to
237// TemplateTypeParmDecls, so we have this horrible PointerUnion.
238typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *,
239 const TemplateSpecializationType *,
240 const SubstBuiltinTemplatePackType *>,
241 SourceLocation>
243
244/// Describes whether we've seen any nullability information for the given
245/// file.
247 /// The first pointer declarator (of any pointer kind) in the file that does
248 /// not have a corresponding nullability annotation.
250
251 /// The end location for the first pointer declarator in the file. Used for
252 /// placing fix-its.
254
255 /// Which kind of pointer declarator we saw.
257
258 /// Whether we saw any type nullability annotations in the given file.
259 bool SawTypeNullability = false;
260};
261
262/// A mapping from file IDs to a record of whether we've seen nullability
263/// information in that file.
265 /// A mapping from file IDs to the nullability information for each file ID.
266 llvm::DenseMap<FileID, FileNullability> Map;
267
268 /// A single-element cache based on the file ID.
269 struct {
272 } Cache;
273
274public:
276 // Check the single-element cache.
277 if (file == Cache.File)
278 return Cache.Nullability;
279
280 // It's not in the single-element cache; flush the cache if we have one.
281 if (!Cache.File.isInvalid()) {
282 Map[Cache.File] = Cache.Nullability;
283 }
284
285 // Pull this entry into the cache.
286 Cache.File = file;
287 Cache.Nullability = Map[file];
288 return Cache.Nullability;
289 }
290};
291
292/// Tracks expected type during expression parsing, for use in code completion.
293/// The type is tied to a particular token, all functions that update or consume
294/// the type take a start location of the token they are looking at as a
295/// parameter. This avoids updating the type on hot paths in the parser.
297public:
299 : Ctx(Ctx), Enabled(Enabled) {}
300
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
321 SourceLocation OpLoc);
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 ASTContext *Ctx;
346 bool Enabled;
347 /// Start position of a token for which we store expected type.
348 SourceLocation ExpectedLoc;
349 /// Expected type for a token starting at ExpectedLoc.
351 /// A function to compute expected type at ExpectedLoc. It is only considered
352 /// if Type is null.
353 llvm::function_ref<QualType()> ComputeType;
354};
355
357 SkipBodyInfo() = default;
358 bool ShouldSkip = false;
360 NamedDecl *Previous = nullptr;
361 NamedDecl *New = nullptr;
362};
363
364/// Describes the result of template argument deduction.
365///
366/// The TemplateDeductionResult enumeration describes the result of
367/// template argument deduction, as returned from
368/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
369/// structure provides additional information about the results of
370/// template argument deduction, e.g., the deduced template argument
371/// list (if successful) or the specific template parameters or
372/// deduced arguments that were involved in the failure.
374 /// Template argument deduction was successful.
376 /// The declaration was invalid; do nothing.
378 /// Template argument deduction exceeded the maximum template
379 /// instantiation depth (which has already been diagnosed).
381 /// Template argument deduction did not deduce a value
382 /// for every template parameter.
384 /// Template argument deduction did not deduce a value for every
385 /// expansion of an expanded template parameter pack.
387 /// Template argument deduction produced inconsistent
388 /// deduced values for the given template parameter.
390 /// Template argument deduction failed due to inconsistent
391 /// cv-qualifiers on a template parameter type that would
392 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
393 /// but were given a non-const "X".
395 /// Substitution of the deduced template argument values
396 /// resulted in an error.
398 /// After substituting deduced template arguments, a dependent
399 /// parameter type did not match the corresponding argument.
401 /// After substituting deduced template arguments, an element of
402 /// a dependent parameter type did not match the corresponding element
403 /// of the corresponding argument (when deducing from an initializer list).
405 /// A non-depnedent component of the parameter did not match the
406 /// corresponding component of the argument.
408 /// When performing template argument deduction for a function
409 /// template, there were too many call arguments.
411 /// When performing template argument deduction for a function
412 /// template, there were too few call arguments.
414 /// The explicitly-specified template arguments were not valid
415 /// template arguments for the given template.
417 /// Checking non-dependent argument conversions failed.
419 /// The deduced arguments did not satisfy the constraints associated
420 /// with the template.
422 /// Deduction failed; that's all we know.
424 /// CUDA Target attributes do not match.
426 /// Some error which was already diagnosed.
428};
429
430/// The kind of conversion being performed.
432 /// An implicit conversion.
434 /// A C-style cast.
436 /// A functional-style cast.
438 /// A cast other than a C-style cast.
440 /// A conversion for an operand of a builtin overloaded operator.
442};
443
444enum class TagUseKind {
445 Reference, // Reference to a tag: 'struct foo *X;'
446 Declaration, // Fwd decl of a tag: 'struct foo;'
447 Definition, // Definition of a tag: 'struct foo { int X; } Y;'
448 Friend // Friend declaration: 'friend struct foo;'
449};
450
451/// Used with attributes/effects with a boolean condition, e.g. `nonblocking`.
453 None, // effect is not present.
454 False, // effect(false).
455 True, // effect(true).
456 Dependent // effect(expr) where expr is dependent.
457};
458
459/// pragma clang section kind
462 BSS = 1,
463 Data = 2,
465 Text = 4,
467};
468
469enum class PragmaClangSectionAction { Set = 0, Clear = 1 };
470
472 Native, // #pragma options align=native
473 Natural, // #pragma options align=natural
474 Packed, // #pragma options align=packed
475 Power, // #pragma options align=power
476 Mac68k, // #pragma options align=mac68k
477 Reset // #pragma options align=reset
478};
479
480enum class TUFragmentKind {
481 /// The global module fragment, between 'module;' and a module-declaration.
483 /// A normal translation unit fragment. For a non-module unit, this is the
484 /// entire translation unit. Otherwise, it runs from the module-declaration
485 /// to the private-module-fragment (if any) or the end of the TU (if not).
487 /// The private module fragment, between 'module :private;' and the end of
488 /// the translation unit.
490};
491
504
505// Used for emitting the right warning by DefaultVariadicArgumentPromotion
513
522
523// Contexts where using non-trivial C union types can be disallowed. This is
524// passed to err_non_trivial_c_union_in_invalid_context.
526 // Function parameter.
528 // Function return.
530 // Default-initialized object.
532 // Variable with automatic storage duration.
534 // Initializer expression that might copy from another object.
536 // Assignment.
538 // Compound literal.
540 // Block capture.
542 // lvalue-to-rvalue conversion of volatile type.
544};
545
546/// Describes the result of the name lookup and resolution performed
547/// by \c Sema::ClassifyName().
549 /// This name is not a type or template in this context, but might be
550 /// something else.
552 /// Classification failed; an error has been produced.
554 /// The name has been typo-corrected to a keyword.
556 /// The name was classified as a type.
558 /// The name was classified as a specific non-type, non-template
559 /// declaration. ActOnNameClassifiedAsNonType should be called to
560 /// convert the declaration to an expression.
562 /// The name was classified as an ADL-only function name.
563 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
564 /// result to an expression.
566 /// The name denotes a member of a dependent type that could not be
567 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
568 /// convert the result to an expression.
570 /// The name was classified as an overload set, and an expression
571 /// representing that overload set has been formed.
572 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
573 /// expression referencing the overload set.
575 /// The name was classified as a template whose specializations are types.
577 /// The name was classified as a variable template name.
579 /// The name was classified as a function template name.
581 /// The name was classified as an ADL-only function template name.
583 /// The name was classified as a concept name.
585};
586
588 // Address discrimination argument of __ptrauth.
590
591 // Extra discriminator argument of __ptrauth.
593};
594
595/// Common ways to introduce type names without a tag for use in diagnostics.
596/// Keep in sync with err_tag_reference_non_tag.
608
609enum class OffsetOfKind {
610 // Not parsing a type within __builtin_offsetof.
612 // Parsing a type within __builtin_offsetof.
614 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
615 // To improve our diagnostic message.
617};
618
619/// Describes the kind of merge to perform for availability
620/// attributes (including "deprecated", "unavailable", and "availability").
622 /// Don't merge availability attributes at all.
624 /// Merge availability attributes for a redeclaration, which requires
625 /// an exact match.
627 /// Merge availability attributes for an override, which requires
628 /// an exact match or a weakening of constraints.
630 /// Merge availability attributes for an implementation of
631 /// a protocol requirement.
633 /// Merge availability attributes for an implementation of
634 /// an optional protocol requirement.
636};
637
639 /// The triviality of a method unaffected by "trivial_abi".
641
642 /// The triviality of a method affected by "trivial_abi".
644};
645
647
648enum class AllowFoldKind {
651};
652
653/// Context in which we're performing a usual arithmetic conversion.
654enum class ArithConvKind {
655 /// An arithmetic operation.
657 /// A bitwise operation.
659 /// A comparison.
661 /// A conditional (?:) operator.
663 /// A compound assignment expression.
665};
666
667// Used for determining in which context a type is allowed to be passed to a
668// vararg function.
676
677/// AssignConvertType - All of the 'assignment' semantic checks return this
678/// enum to indicate whether the assignment was allowed. These checks are
679/// done for simple assignments, as well as initialization, return from
680/// function, argument passing, etc. The query is phrased in terms of a
681/// source and destination type.
683 /// Compatible - the types are compatible according to the standard.
685
686 /// CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because
687 /// a void * can implicitly convert to another pointer type, which we
688 /// differentiate for better diagnostic behavior.
690
691 /// PointerToInt - The assignment converts a pointer to an int, which we
692 /// accept as an extension.
694
695 /// IntToPointer - The assignment converts an int to a pointer, which we
696 /// accept as an extension.
698
699 /// FunctionVoidPointer - The assignment is between a function pointer and
700 /// void*, which the standard doesn't allow, but we accept as an extension.
702
703 /// IncompatiblePointer - The assignment is between two pointers types that
704 /// are not compatible, but we accept them as an extension.
706
707 /// IncompatibleFunctionPointer - The assignment is between two function
708 /// pointers types that are not compatible, but we accept them as an
709 /// extension.
711
712 /// IncompatibleFunctionPointerStrict - The assignment is between two
713 /// function pointer types that are not identical, but are compatible,
714 /// unless compiled with -fsanitize=cfi, in which case the type mismatch
715 /// may trip an indirect call runtime check.
717
718 /// IncompatiblePointerSign - The assignment is between two pointers types
719 /// which point to integers which have a different sign, but are otherwise
720 /// identical. This is a subset of the above, but broken out because it's by
721 /// far the most common case of incompatible pointers.
723
724 /// CompatiblePointerDiscardsQualifiers - The assignment discards
725 /// c/v/r qualifiers, which we accept as an extension.
727
728 /// IncompatiblePointerDiscardsQualifiers - The assignment
729 /// discards qualifiers that we don't permit to be discarded,
730 /// like address spaces.
732
733 /// IncompatiblePointerDiscardsOverflowBehavior - The assignment
734 /// discards overflow behavior annotations between otherwise compatible
735 /// pointer types.
737
738 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
739 /// changes address spaces in nested pointer types which is not allowed.
740 /// For instance, converting __private int ** to __generic int ** is
741 /// illegal even though __private could be converted to __generic.
743
744 /// IncompatibleNestedPointerQualifiers - The assignment is between two
745 /// nested pointer types, and the qualifiers other than the first two
746 /// levels differ e.g. char ** -> const char **, but we accept them as an
747 /// extension.
749
750 /// IncompatibleVectors - The assignment is between two vector types that
751 /// have the same size, which we accept as an extension.
753
754 /// IntToBlockPointer - The assignment converts an int to a block
755 /// pointer. We disallow this.
757
758 /// IncompatibleBlockPointer - The assignment is between two block
759 /// pointers types that are not compatible.
761
762 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
763 /// id type and something else (that is incompatible with it). For example,
764 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
766
767 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
768 /// object with __weak qualifier.
770
771 /// IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType
772 /// kinds, e.g., from __ob_trap to __ob_wrap or vice versa.
774
775 /// CompatibleOBTDiscards - Assignment discards overflow behavior
777
778 /// Incompatible - We reject this conversion outright, it is invalid to
779 /// represent it in the AST.
781};
782
783/// The scope in which to find allocation functions.
785 /// Only look for allocation functions in the global scope.
787 /// Only look for allocation functions in the scope of the
788 /// allocated class.
790 /// Look for allocation functions in both the global scope
791 /// and in the scope of the allocated class.
793};
794
795/// Describes the result of an "if-exists" condition check.
796enum class IfExistsResult {
797 /// The symbol exists.
799
800 /// The symbol does not exist.
802
803 /// The name is a dependent name, so the results will differ
804 /// from one instantiation to the next.
806
807 /// An error occurred.
809};
810
811enum class CorrectTypoKind {
812 NonError, // CorrectTypo used in a non error recovery situation.
813 ErrorRecovery // CorrectTypo used in normal error recovery.
814};
815
816enum class OverloadKind {
817 /// This is a legitimate overload: the existing declarations are
818 /// functions or function templates with different signatures.
820
821 /// This is not an overload because the signature exactly matches
822 /// an existing declaration.
824
825 /// This is not an overload because the lookup results contain a
826 /// non-function.
828};
829
830/// Contexts in which a converted constant expression is required.
831enum class CCEKind {
832 CaseValue, ///< Expression in a case label.
833 Enumerator, ///< Enumerator value with fixed underlying type.
834 TemplateArg, ///< Value of a non-type template parameter.
835 TempArgStrict, ///< As above, but applies strict template checking
836 ///< rules.
837 ArrayBound, ///< Array bound in array declarator or new-expression.
838 ExplicitBool, ///< Condition in an explicit(bool) specifier.
839 Noexcept, ///< Condition in a noexcept(bool) specifier.
840 StaticAssertMessageSize, ///< Call to size() in a static assert
841 ///< message.
842 StaticAssertMessageData, ///< Call to data() in a static assert
843 ///< message.
844 PackIndex ///< Index of a pack indexing expression or specifier.
845};
846
847/// Enums for the diagnostics of target, target_version and target_clones.
848namespace DiagAttrParams {
852} // end namespace DiagAttrParams
853
854void inferNoReturnAttr(Sema &S, Decl *D);
855
856#ifdef __GNUC__
857#pragma GCC diagnostic push
858#pragma GCC diagnostic ignored "-Wattributes"
859#endif
860/// Sema - This implements semantic analysis and AST building for C.
861/// \nosubgrouping
862class Sema final : public SemaBase {
863#ifdef __GNUC__
864#pragma GCC diagnostic pop
865#endif
866 // Table of Contents
867 // -----------------
868 // 1. Semantic Analysis (Sema.cpp)
869 // 2. API Notes (SemaAPINotes.cpp)
870 // 3. C++ Access Control (SemaAccess.cpp)
871 // 4. Attributes (SemaAttr.cpp)
872 // 5. Availability Attribute Handling (SemaAvailability.cpp)
873 // 6. Bounds Safety (SemaBoundsSafety.cpp)
874 // 7. Casts (SemaCast.cpp)
875 // 8. Extra Semantic Checking (SemaChecking.cpp)
876 // 9. C++ Coroutines (SemaCoroutine.cpp)
877 // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
878 // 11. Declarations (SemaDecl.cpp)
879 // 12. Declaration Attribute Handling (SemaDeclAttr.cpp)
880 // 13. C++ Declarations (SemaDeclCXX.cpp)
881 // 14. C++ Exception Specifications (SemaExceptionSpec.cpp)
882 // 15. Expressions (SemaExpr.cpp)
883 // 16. C++ Expressions (SemaExprCXX.cpp)
884 // 17. Member Access Expressions (SemaExprMember.cpp)
885 // 18. Initializers (SemaInit.cpp)
886 // 19. C++ Lambda Expressions (SemaLambda.cpp)
887 // 20. Name Lookup (SemaLookup.cpp)
888 // 21. Modules (SemaModule.cpp)
889 // 22. C++ Overloading (SemaOverload.cpp)
890 // 23. Statements (SemaStmt.cpp)
891 // 24. `inline asm` Statement (SemaStmtAsm.cpp)
892 // 25. Statement Attribute Handling (SemaStmtAttr.cpp)
893 // 26. C++ Templates (SemaTemplate.cpp)
894 // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
895 // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp)
896 // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
897 // 30. C++ Template Declaration Instantiation
898 // (SemaTemplateInstantiateDecl.cpp)
899 // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp)
900 // 32. Constraints and Concepts (SemaConcept.cpp)
901 // 33. Types (SemaType.cpp)
902 // 34. FixIt Helpers (SemaFixItUtils.cpp)
903 // 35. Function Effects (SemaFunctionEffects.cpp)
904 // 36. C++ Expansion Statements (SemaExpand.cpp)
905
906 /// \name Semantic Analysis
907 /// Implementations are in Sema.cpp
908 ///@{
909
910public:
911 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
913 CodeCompleteConsumer *CompletionConsumer = nullptr);
914 ~Sema();
915
916 /// Perform initialization that occurs after the parser has been
917 /// initialized but before it parses anything.
918 void Initialize();
919
920 /// This virtual key function only exists to limit the emission of debug info
921 /// describing the Sema class. GCC and Clang only emit debug info for a class
922 /// with a vtable when the vtable is emitted. Sema is final and not
923 /// polymorphic, but the debug info size savings are so significant that it is
924 /// worth adding a vtable just to take advantage of this optimization.
926
927 const LangOptions &getLangOpts() const { return LangOpts; }
930
933 Preprocessor &getPreprocessor() const { return PP; }
934 ASTContext &getASTContext() const { return Context; }
938
940 StringRef Platform);
942
943 /// Registers an external source. If an external source already exists,
944 /// creates a multiplex external source and appends to it.
945 ///
946 ///\param[in] E - A non-null external sema source.
947 ///
949
950 /// Print out statistics about the semantic analysis.
951 void PrintStats() const;
952
953 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
954 /// guaranteed). Produces a warning if we're low on stack space and allocates
955 /// more in that case. Use this in code that may recurse deeply (for example,
956 /// in template instantiation) to avoid stack overflow.
958 llvm::function_ref<void()> Fn);
959
960 /// Returns default addr space for method qualifiers.
962
963 /// Load weak undeclared identifiers from the external source.
965
966 /// Load #pragma redefine_extname'd undeclared identifiers from the external
967 /// source.
969
970 /// Determine if VD, which must be a variable or function, is an external
971 /// symbol that nonetheless can't be referenced from outside this translation
972 /// unit because its type has no linkage and it's not extern "C".
973 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
974
975 /// Determines whether the given source location is in the main file
976 /// and we're in a context where we should warn about unused entities.
977 bool isMainFileLoc(SourceLocation Loc) const;
978
979 /// Obtain a sorted list of functions that are undefined but ODR-used.
981 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined);
982
983 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
985 /// Retrieves list of suspicious delete-expressions that will be checked at
986 /// the end of translation unit.
987 const llvm::MapVector<FieldDecl *, DeleteLocs> &
989
990 /// Cause the built diagnostic to be emitted on the DiagosticsEngine.
991 /// This is closely coupled to the SemaDiagnosticBuilder class and
992 /// should not be used elsewhere.
993 void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB);
994
995 void addImplicitTypedef(StringRef Name, QualType T);
996
997 /// Whether uncompilable error has occurred. This includes error happens
998 /// in deferred diagnostics.
999 bool hasUncompilableErrorOccurred() const;
1000
1001 /// Looks through the macro-expansion chain for the given
1002 /// location, looking for a macro expansion with the given name.
1003 /// If one is found, returns true and sets the location to that
1004 /// expansion loc.
1005 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1006
1007 /// Calls \c Lexer::getLocForEndOfToken()
1008 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1009
1010 /// Calls \c Lexer::findNextToken() to find the next token, and if the
1011 /// locations of both ends of the token can be resolved it return that
1012 /// range; Otherwise it returns an invalid SourceRange.
1014 SourceLocation Loc, bool IncludeMacros, bool IncludeComments,
1015 std::optional<tok::TokenKind> ExpectedToken = std::nullopt);
1016
1017 /// Retrieve the module loader associated with the preprocessor.
1019
1020 /// Invent a new identifier for parameters of abbreviated templates.
1023 unsigned Index);
1024
1026
1027 // Emit all deferred diagnostics.
1028 void emitDeferredDiags();
1029
1030 /// This is called before the very first declaration in the translation unit
1031 /// is parsed. Note that the ASTContext may have already injected some
1032 /// declarations.
1034 /// ActOnEndOfTranslationUnit - This is called at the very end of the
1035 /// translation unit when EOF is reached and all but the top-level scope is
1036 /// popped.
1039
1040 /// Determines the active Scope associated with the given declaration
1041 /// context.
1042 ///
1043 /// This routine maps a declaration context to the active Scope object that
1044 /// represents that declaration context in the parser. It is typically used
1045 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1046 /// declarations) that injects a name for name-lookup purposes and, therefore,
1047 /// must update the Scope.
1048 ///
1049 /// \returns The scope corresponding to the given declaraion context, or NULL
1050 /// if no such scope is open.
1052
1053 void PushFunctionScope();
1054 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1056
1057 /// This is used to inform Sema what the current TemplateParameterDepth
1058 /// is during Parsing. Currently it is used to pass on the depth
1059 /// when parsing generic lambda 'auto' parameters.
1060 void RecordParsingTemplateParameterDepth(unsigned Depth);
1061
1062 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1064 unsigned OpenMPCaptureLevel = 0);
1065
1066 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1067 /// time after they've been popped.
1069 Sema *Self;
1070
1071 public:
1072 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1074 };
1075
1077 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1078
1079 /// Pop a function (or block or lambda or captured region) scope from the
1080 /// stack.
1081 ///
1082 /// \param WP The warning policy to use for CFG-based warnings, or null if
1083 /// such warnings should not be produced.
1084 /// \param D The declaration corresponding to this function scope, if
1085 /// producing CFG-based warnings.
1086 /// \param BlockType The type of the block expression, if D is a BlockDecl.
1089 Decl *D = nullptr, QualType BlockType = QualType());
1090
1092
1097
1098 void PushCompoundScope(bool IsStmtExpr);
1099 void PopCompoundScope();
1100
1101 /// Determine whether any errors occurred within this function/method/
1102 /// block.
1104
1105 /// Retrieve the current block, if any.
1107
1108 /// Get the innermost lambda or block enclosing the current location, if any.
1109 /// This looks through intervening non-lambda, non-block scopes such as local
1110 /// functions.
1112
1113 /// Retrieve the current lambda scope info, if any.
1114 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1115 /// lambda scope info ignoring all inner capturing scopes that are not
1116 /// lambda scopes.
1118 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1119
1120 /// Retrieve the current generic lambda info, if any.
1122
1123 /// Retrieve the current captured region, if any.
1125
1126 void ActOnComment(SourceRange Comment);
1127
1128 /// Returns true if any of the documentation warnings is enabled at \p Loc.
1130
1131 /// Discard the areDocumentationDiagsEnabled() cache, for when a
1132 /// `#pragma clang diagnostic` has changed diagnostic severities.
1134
1135private:
1136 /// The uncached answer for both documentation groups at \p Loc.
1137 bool computeDocumentationDiagsAt(SourceLocation Loc) const;
1138
1139 /// Caches results for areDocumentationDiagsEnabled().
1140 /// Flushed whenever a diagnostic pragma changes severities.
1141 /// Level one is keyed on the diagnostic state alone.
1142 const void *DocDiagsStateKey = nullptr;
1143 bool DocDiagsEnabledIgnoringSystem = false;
1144
1145 /// Level two, for when the location does matter. Bit i of each mask is a
1146 /// DiagStateSystemClass value; bit 0 is unused.
1147 uint8_t DocDiagsExactComputed = 0;
1148 uint8_t DocDiagsExactEnabled = 0;
1149
1150public:
1151 /// Returns true if a comment at \p Loc should be retained in the AST
1152 /// (some consumer such as -Wdocumentation, -fparse-all-comments, code
1153 /// completion, or AST-file serialization may read it back).
1155
1156 /// Retrieve the parser's current scope.
1157 ///
1158 /// This routine must only be used when it is certain that semantic analysis
1159 /// and the parser are in precisely the same context, which is not the case
1160 /// when, e.g., we are performing any kind of template instantiation.
1161 /// Therefore, the only safe places to use this scope are in the parser
1162 /// itself and in routines directly invoked from the parser and *never* from
1163 /// template substitution or instantiation.
1164 Scope *getCurScope() const { return CurScope; }
1165
1167
1171
1172 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
1173 const FunctionDecl *FD = nullptr);
1175 const PartialDiagnostic &PD,
1176 const FunctionDecl *FD = nullptr) {
1177 return targetDiag(Loc, PD.getDiagID(), FD) << PD;
1178 }
1179
1180 /// Check if the type is allowed to be used for the current target.
1182 ValueDecl *D = nullptr);
1183
1184 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
1185 /// cast. If there is already an implicit cast, merge into the existing one.
1186 /// If isLvalue, the result of the cast is an lvalue.
1189 const CXXCastPath *BasePath = nullptr,
1191
1192 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
1193 /// to the conversion from scalar type ScalarTy to the Boolean type.
1195
1196 /// If \p AllowLambda is true, treat lambda as function.
1197 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
1198
1199 /// Returns a pointer to the innermost enclosing function, or nullptr if the
1200 /// current context is not inside a function. If \p AllowLambda is true,
1201 /// this can return the call operator of an enclosing lambda, otherwise
1202 /// lambdas are skipped when looking for an enclosing function.
1203 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
1204
1205 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1206 /// the method decl for the method being parsed. If we're currently
1207 /// in a 'block', this returns the containing context.
1209
1210 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1211 /// or C function we're in, otherwise return null. If we're currently
1212 /// in a 'block', this returns the containing context.
1214
1215 /// Warn if we're implicitly casting from a _Nullable pointer type to a
1216 /// _Nonnull one.
1218 SourceLocation Loc);
1219
1220 /// Warn when implicitly casting 0 to nullptr.
1221 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
1222
1223 /// Warn when implicitly changing function effects.
1225 SourceLocation Loc);
1226
1227 /// makeUnavailableInSystemHeader - There is an error in the current
1228 /// context. If we're still in a system header, and we can plausibly
1229 /// make the relevant declaration unavailable instead of erroring, do
1230 /// so and return true.
1232 UnavailableAttr::ImplicitReason reason);
1233
1234 /// Retrieve a suitable printing policy for diagnostics.
1238
1239 /// Retrieve a suitable printing policy for diagnostics.
1241 const Preprocessor &PP);
1242
1243 /// Scope actions.
1245
1246 /// Determine whether \param D is function like (function or function
1247 /// template) for parsing.
1249
1250 /// The maximum alignment, same as in llvm::Value. We duplicate them here
1251 /// because that allows us not to duplicate the constants in clang code,
1252 /// which we must to since we can't directly use the llvm constants.
1253 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
1254 ///
1255 /// This is the greatest alignment value supported by load, store, and alloca
1256 /// instructions, and global values.
1257 static const unsigned MaxAlignmentExponent = 32;
1258 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
1259
1260 /// Flag indicating whether or not to collect detailed statistics.
1262
1263 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
1264
1265 /// Stack containing information about each of the nested
1266 /// function, block, and method scopes that are currently active.
1268
1269 /// The index of the first FunctionScope that corresponds to the current
1270 /// context.
1272
1273 /// Track the number of currently active capturing scopes.
1275
1276 llvm::BumpPtrAllocator BumpAlloc;
1277
1278 /// The kind of translation unit we are processing.
1279 ///
1280 /// When we're processing a complete translation unit, Sema will perform
1281 /// end-of-translation-unit semantic tasks (such as creating
1282 /// initializers for tentative definitions in C) once parsing has
1283 /// completed. Modules and precompiled headers perform different kinds of
1284 /// checks.
1286
1287 /// Translation Unit Scope - useful to Objective-C actions that need
1288 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1289 /// For example, user-defined classes, built-in "id" type, etc.
1291
1293 return CurScope->incrementMSManglingNumber();
1294 }
1295
1296 /// Try to recover by turning the given expression into a
1297 /// call. Returns true if recovery was attempted or an error was
1298 /// emitted; this may also leave the ExprResult invalid.
1300 bool ForceComplain = false,
1301 bool (*IsPlausibleResult)(QualType) = nullptr);
1302
1303 // Adds implicit lifetime bound attribute for implicit this to its
1304 // TypeSourceInfo.
1306
1307 /// Figure out if an expression could be turned into a call.
1308 ///
1309 /// Use this when trying to recover from an error where the programmer may
1310 /// have written just the name of a function instead of actually calling it.
1311 ///
1312 /// \param E - The expression to examine.
1313 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1314 /// with no arguments, this parameter is set to the type returned by such a
1315 /// call; otherwise, it is set to an empty QualType.
1316 /// \param OverloadSet - If the expression is an overloaded function
1317 /// name, this parameter is populated with the decls of the various
1318 /// overloads.
1319 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1320 UnresolvedSetImpl &NonTemplateOverloads);
1321
1325
1328
1336
1337 std::unique_ptr<APINotesSelectorDiagnosticState> APINotesSelectorDiagnostics;
1338
1339 /// A RAII object to enter scope of a compound statement.
1341 public:
1342 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
1343 S.ActOnStartOfCompoundStmt(IsStmtExpr);
1344 }
1345
1346 ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); }
1349
1350 private:
1351 Sema &S;
1352 };
1353
1354 /// An RAII helper that pops function a function scope on exit.
1360 if (Active)
1361 S.PopFunctionScopeInfo();
1362 }
1363 void disable() { Active = false; }
1364 };
1365
1367 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1368 }
1369
1370 /// Worker object for performing CFG-based warnings.
1373
1374 /// Callback to the parser to parse templated functions when needed.
1375 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
1378
1380 LateTemplateParser = LTP;
1381 OpaqueParser = P;
1382 }
1383
1384 /// Callback to the parser to parse a type expressed as a string.
1385 std::function<TypeResult(StringRef, StringRef, SourceLocation)>
1387
1388 /// VAListTagName - The declaration name corresponding to __va_list_tag.
1389 /// This is used as part of a hack to omit that class from ADL results.
1391
1392 /// Is the last error level diagnostic immediate. This is used to determined
1393 /// whether the next info diagnostic should be immediate.
1395
1396 /// Track if we're currently analyzing overflow behavior types in assignment
1397 /// context.
1399
1400 class DelayedDiagnostics;
1401
1403 sema::DelayedDiagnosticPool *SavedPool = nullptr;
1405 };
1408
1409 /// A class which encapsulates the logic for delaying diagnostics
1410 /// during parsing and other processing.
1412 /// The current pool of diagnostics into which delayed
1413 /// diagnostics should go.
1414 sema::DelayedDiagnosticPool *CurPool = nullptr;
1415
1416 public:
1418
1419 /// Adds a delayed diagnostic.
1420 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
1421
1422 /// Determines whether diagnostics should be delayed.
1423 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
1424
1425 /// Returns the current delayed-diagnostics pool.
1426 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
1427
1428 /// Enter a new scope. Access and deprecation diagnostics will be
1429 /// collected in this pool.
1432 state.SavedPool = CurPool;
1433 CurPool = &pool;
1434 return state;
1435 }
1436
1437 /// Leave a delayed-diagnostic state that was previously pushed.
1438 /// Do not emit any of the diagnostics. This is performed as part
1439 /// of the bookkeeping of popping a pool "properly".
1441 CurPool = state.SavedPool;
1442 }
1443
1444 /// Enter a new scope where access and deprecation diagnostics are
1445 /// not delayed.
1448 state.SavedPool = CurPool;
1449 CurPool = nullptr;
1450 return state;
1451 }
1452
1453 /// Undo a previous pushUndelayed().
1455 assert(CurPool == nullptr);
1456 CurPool = state.SavedPool;
1457 }
1459
1463
1464 /// Diagnostics that are emitted only if we discover that the given function
1465 /// must be codegen'ed. Because handling these correctly adds overhead to
1466 /// compilation, this is currently only used for offload languages like CUDA,
1467 /// OpenMP, and SYCL.
1468 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
1469
1470 /// CurContext - This is the current declaration context of parsing.
1472
1474 assert(AMDGPUPtr);
1475 return *AMDGPUPtr;
1476 }
1477
1479 assert(ARMPtr);
1480 return *ARMPtr;
1481 }
1482
1484 assert(AVRPtr);
1485 return *AVRPtr;
1486 }
1487
1489 assert(BPFPtr);
1490 return *BPFPtr;
1491 }
1492
1494 assert(CodeCompletionPtr);
1495 return *CodeCompletionPtr;
1496 }
1497
1499 assert(CUDAPtr);
1500 return *CUDAPtr;
1501 }
1502
1504 assert(DirectXPtr);
1505 return *DirectXPtr;
1506 }
1507
1509 assert(HLSLPtr);
1510 return *HLSLPtr;
1511 }
1512
1514 assert(HexagonPtr);
1515 return *HexagonPtr;
1516 }
1517
1519 assert(LoongArchPtr);
1520 return *LoongArchPtr;
1521 }
1522
1524 assert(M68kPtr);
1525 return *M68kPtr;
1526 }
1527
1529 assert(MIPSPtr);
1530 return *MIPSPtr;
1531 }
1532
1534 assert(MSP430Ptr);
1535 return *MSP430Ptr;
1536 }
1537
1539 assert(NVPTXPtr);
1540 return *NVPTXPtr;
1541 }
1542
1544 assert(ObjCPtr);
1545 return *ObjCPtr;
1546 }
1547
1549 assert(OpenACCPtr);
1550 return *OpenACCPtr;
1551 }
1552
1554 assert(OpenCLPtr);
1555 return *OpenCLPtr;
1556 }
1557
1559 assert(OpenMPPtr && "SemaOpenMP is dead");
1560 return *OpenMPPtr;
1561 }
1562
1564 assert(PPCPtr);
1565 return *PPCPtr;
1566 }
1567
1569 assert(PseudoObjectPtr);
1570 return *PseudoObjectPtr;
1571 }
1572
1574 assert(RISCVPtr);
1575 return *RISCVPtr;
1576 }
1577
1579 assert(SPIRVPtr);
1580 return *SPIRVPtr;
1581 }
1582
1584 assert(SYCLPtr);
1585 return *SYCLPtr;
1586 }
1587
1589 assert(SwiftPtr);
1590 return *SwiftPtr;
1591 }
1592
1594 assert(SystemZPtr);
1595 return *SystemZPtr;
1596 }
1597
1599 assert(WasmPtr);
1600 return *WasmPtr;
1601 }
1602
1604 assert(X86Ptr);
1605 return *X86Ptr;
1606 }
1607
1608 /// Source of additional semantic information.
1610
1611protected:
1612 friend class Parser;
1614 friend class ASTReader;
1615 friend class ASTDeclReader;
1616 friend class ASTWriter;
1617
1618private:
1619 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1620 bool WarnedDarwinSDKInfoMissing = false;
1621
1622 StackExhaustionHandler StackHandler;
1623
1624 Sema(const Sema &) = delete;
1625 void operator=(const Sema &) = delete;
1626
1627 /// The handler for the FileChanged preprocessor events.
1628 ///
1629 /// Used for diagnostics that implement custom semantic analysis for #include
1630 /// directives, like -Wpragma-pack.
1631 sema::SemaPPCallbacks *SemaPPCallbackHandler;
1632
1633 /// The parser's current scope.
1634 ///
1635 /// The parser maintains this state here.
1636 Scope *CurScope;
1637
1638 mutable IdentifierInfo *Ident_super;
1639
1640 std::unique_ptr<SemaAMDGPU> AMDGPUPtr;
1641 std::unique_ptr<SemaARM> ARMPtr;
1642 std::unique_ptr<SemaAVR> AVRPtr;
1643 std::unique_ptr<SemaBPF> BPFPtr;
1644 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1645 std::unique_ptr<SemaCUDA> CUDAPtr;
1646 std::unique_ptr<SemaDirectX> DirectXPtr;
1647 std::unique_ptr<SemaHLSL> HLSLPtr;
1648 std::unique_ptr<SemaHexagon> HexagonPtr;
1649 std::unique_ptr<SemaLoongArch> LoongArchPtr;
1650 std::unique_ptr<SemaM68k> M68kPtr;
1651 std::unique_ptr<SemaMIPS> MIPSPtr;
1652 std::unique_ptr<SemaMSP430> MSP430Ptr;
1653 std::unique_ptr<SemaNVPTX> NVPTXPtr;
1654 std::unique_ptr<SemaObjC> ObjCPtr;
1655 std::unique_ptr<SemaOpenACC> OpenACCPtr;
1656 std::unique_ptr<SemaOpenCL> OpenCLPtr;
1657 std::unique_ptr<SemaOpenMP> OpenMPPtr;
1658 std::unique_ptr<SemaPPC> PPCPtr;
1659 std::unique_ptr<SemaPseudoObject> PseudoObjectPtr;
1660 std::unique_ptr<SemaRISCV> RISCVPtr;
1661 std::unique_ptr<SemaSPIRV> SPIRVPtr;
1662 std::unique_ptr<SemaSYCL> SYCLPtr;
1663 std::unique_ptr<SemaSwift> SwiftPtr;
1664 std::unique_ptr<SemaSystemZ> SystemZPtr;
1665 std::unique_ptr<SemaWasm> WasmPtr;
1666 std::unique_ptr<SemaX86> X86Ptr;
1667
1668 ///@}
1669
1670 //
1671 //
1672 // -------------------------------------------------------------------------
1673 //
1674 //
1675
1676 /// \name API Notes
1677 /// Implementations are in SemaAPINotes.cpp
1678 ///@{
1679
1680public:
1681 /// Map any API notes provided for this declaration to attributes on the
1682 /// declaration.
1683 ///
1684 /// Triggered by declaration-attribute processing.
1685 void ProcessAPINotes(Decl *D);
1686 /// Apply the 'Nullability:' annotation to the specified declaration
1687 void ApplyNullability(Decl *D, NullabilityKind Nullability);
1688 /// Apply the 'Type:' annotation to the specified declaration
1689 void ApplyAPINotesType(Decl *D, StringRef TypeString);
1690
1691 /// Diagnose exact API notes selectors that were not matched by any
1692 /// declaration processed in this translation unit.
1694
1695 /// Whether APINotes should be gathered for all applicable Swift language
1696 /// versions, without being applied. Leaving clients of the current module
1697 /// to select and apply the correct version.
1699 return APINotes.captureVersionIndependentSwift();
1700 }
1701 ///@}
1702
1703 //
1704 //
1705 // -------------------------------------------------------------------------
1706 //
1707 //
1708
1709 /// \name C++ Access Control
1710 /// Implementations are in SemaAccess.cpp
1711 ///@{
1712
1713public:
1720
1721 /// SetMemberAccessSpecifier - Set the access specifier of a member.
1722 /// Returns true on error (when the previous member decl access specifier
1723 /// is different from the new member decl access specifier).
1724 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1725 NamedDecl *PrevMemberDecl,
1726 AccessSpecifier LexicalAS);
1727
1728 /// Perform access-control checking on a previously-unresolved member
1729 /// access which has now been resolved to a member.
1731 DeclAccessPair FoundDecl);
1733 DeclAccessPair FoundDecl);
1734
1735 /// Checks access to an overloaded operator new or delete.
1737 SourceRange PlacementRange,
1738 CXXRecordDecl *NamingClass,
1739 DeclAccessPair FoundDecl,
1740 bool Diagnose = true);
1741
1742 /// Checks access to a constructor.
1744 DeclAccessPair FoundDecl,
1745 const InitializedEntity &Entity,
1746 bool IsCopyBindingRefToTemp = false);
1747
1748 /// Checks access to a constructor.
1750 DeclAccessPair FoundDecl,
1751 const InitializedEntity &Entity,
1752 const PartialDiagnostic &PDiag);
1754 CXXDestructorDecl *Dtor,
1755 const PartialDiagnostic &PDiag,
1756 QualType objectType = QualType());
1757
1758 /// Checks access to the target of a friend declaration.
1760
1761 /// Checks access to a member.
1763 CXXRecordDecl *NamingClass,
1765
1766 /// Checks implicit access to a member in a structured binding.
1769 CXXRecordDecl *DecomposedClass,
1770 DeclAccessPair Field);
1772 const SourceRange &,
1773 DeclAccessPair FoundDecl);
1774
1775 /// Checks access to an overloaded member operator, including
1776 /// conversion operators.
1778 Expr *ArgExpr,
1779 DeclAccessPair FoundDecl);
1781 ArrayRef<Expr *> ArgExprs,
1782 DeclAccessPair FoundDecl);
1784 DeclAccessPair FoundDecl);
1785
1786 /// Checks access for a hierarchy conversion.
1787 ///
1788 /// \param ForceCheck true if this check should be performed even if access
1789 /// control is disabled; some things rely on this for semantics
1790 /// \param ForceUnprivileged true if this check should proceed as if the
1791 /// context had no special privileges
1793 QualType Derived, const CXXBasePath &Path,
1794 unsigned DiagID, bool ForceCheck = false,
1795 bool ForceUnprivileged = false);
1796
1798 SourceLocation AccessLoc, CXXRecordDecl *Base, CXXRecordDecl *Derived,
1799 const CXXBasePath &Path, unsigned DiagID,
1800 llvm::function_ref<void(PartialDiagnostic &PD)> SetupPDiag,
1801 bool ForceCheck = false, bool ForceUnprivileged = false);
1802
1803 /// Checks access to all the declarations in the given result set.
1804 void CheckLookupAccess(const LookupResult &R);
1805
1806 /// Checks access to Target from the given class. The check will take access
1807 /// specifiers into account, but no member access expressions and such.
1808 ///
1809 /// \param Target the declaration to check if it can be accessed
1810 /// \param NamingClass the class in which the lookup was started.
1811 /// \param BaseType type of the left side of member access expression.
1812 /// \p BaseType and \p NamingClass are used for C++ access control.
1813 /// Depending on the lookup case, they should be set to the following:
1814 /// - lhs.target (member access without a qualifier):
1815 /// \p BaseType and \p NamingClass are both the type of 'lhs'.
1816 /// - lhs.X::target (member access with a qualifier):
1817 /// BaseType is the type of 'lhs', NamingClass is 'X'
1818 /// - X::target (qualified lookup without member access):
1819 /// BaseType is null, NamingClass is 'X'.
1820 /// - target (unqualified lookup).
1821 /// BaseType is null, NamingClass is the parent class of 'target'.
1822 /// \return true if the Target is accessible from the Class, false otherwise.
1823 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1824 QualType BaseType);
1825
1826 /// Is the given member accessible for the purposes of deciding whether to
1827 /// define a special member function as deleted?
1829 DeclAccessPair Found, QualType ObjectType,
1830 SourceLocation Loc,
1831 const PartialDiagnostic &Diag);
1834 QualType ObjectType) {
1835 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1836 SourceLocation(), PDiag());
1837 }
1838
1840 const DependentDiagnostic &DD,
1841 const MultiLevelTemplateArgumentList &TemplateArgs);
1843
1844 ///@}
1845
1846 //
1847 //
1848 // -------------------------------------------------------------------------
1849 //
1850 //
1851
1852 /// \name Attributes
1853 /// Implementations are in SemaAttr.cpp
1854 ///@{
1855
1856public:
1857 /// Controls member pointer representation format under the MS ABI.
1860
1861 bool MSStructPragmaOn; // True when \#pragma ms_struct on
1862
1863 /// Source location for newly created implicit MSInheritanceAttrs
1865
1871
1877
1879 PSK_Reset = 0x0, // #pragma ()
1880 PSK_Set = 0x1, // #pragma (value)
1881 PSK_Push = 0x2, // #pragma (push[, id])
1882 PSK_Pop = 0x4, // #pragma (pop[, id])
1883 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
1884 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1885 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
1886 };
1887
1893
1894 // #pragma pack and align.
1896 public:
1897 // `Native` represents default align mode, which may vary based on the
1898 // platform.
1899 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1900
1901 // #pragma pack info constructor
1902 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1903 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1904 assert(Num == PackNumber && "The pack number has been truncated.");
1905 }
1906
1907 // #pragma align info constructor
1909 : PackAttr(false), AlignMode(M),
1910 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1911
1912 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1913
1915
1916 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1917 // integer encoding for it. This should only be passed to
1918 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
1920 std::uint32_t Encoding{};
1921 if (Info.IsXLStack())
1922 Encoding |= IsXLMask;
1923
1924 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1925
1926 if (Info.IsPackAttr())
1927 Encoding |= PackAttrMask;
1928
1929 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1930
1931 return Encoding;
1932 }
1933
1934 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1935 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1937 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1938 int PackNumber = (Encoding & PackNumMask) >> 4;
1939
1940 if (Encoding & PackAttrMask)
1941 return AlignPackInfo(M, PackNumber, IsXL);
1942
1943 return AlignPackInfo(M, IsXL);
1944 }
1945
1946 bool IsPackAttr() const { return PackAttr; }
1947
1948 bool IsAlignAttr() const { return !PackAttr; }
1949
1950 Mode getAlignMode() const { return AlignMode; }
1951
1952 unsigned getPackNumber() const { return PackNumber; }
1953
1954 bool IsPackSet() const {
1955 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1956 // attriute on a decl.
1957 return PackNumber != UninitPackVal && PackNumber != 0;
1958 }
1959
1960 bool IsXLStack() const { return XLStack; }
1961
1962 bool operator==(const AlignPackInfo &Info) const {
1963 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
1964 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
1965 Info.XLStack);
1966 }
1967
1968 bool operator!=(const AlignPackInfo &Info) const {
1969 return !(*this == Info);
1970 }
1971
1972 private:
1973 /// \brief True if this is a pragma pack attribute,
1974 /// not a pragma align attribute.
1975 bool PackAttr;
1976
1977 /// \brief The alignment mode that is in effect.
1978 Mode AlignMode;
1979
1980 /// \brief The pack number of the stack.
1981 unsigned char PackNumber;
1982
1983 /// \brief True if it is a XL #pragma align/pack stack.
1984 bool XLStack;
1985
1986 /// \brief Uninitialized pack value.
1987 static constexpr unsigned char UninitPackVal = -1;
1988
1989 // Masks to encode and decode an AlignPackInfo.
1990 static constexpr uint32_t IsXLMask{0x0000'0001};
1991 static constexpr uint32_t AlignModeMask{0x0000'0006};
1992 static constexpr uint32_t PackAttrMask{0x00000'0008};
1993 static constexpr uint32_t PackNumMask{0x0000'01F0};
1994 };
1995
1996 template <typename ValueType> struct PragmaStack {
2008
2009 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
2010 llvm::StringRef StackSlotLabel, ValueType Value) {
2011 if (Action == PSK_Reset) {
2013 CurrentPragmaLocation = PragmaLocation;
2014 return;
2015 }
2016 if (Action & PSK_Push)
2017 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
2018 PragmaLocation);
2019 else if (Action & PSK_Pop) {
2020 if (!StackSlotLabel.empty()) {
2021 // If we've got a label, try to find it and jump there.
2022 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
2023 return x.StackSlotLabel == StackSlotLabel;
2024 });
2025 // If we found the label so pop from there.
2026 if (I != Stack.rend()) {
2027 CurrentValue = I->Value;
2028 CurrentPragmaLocation = I->PragmaLocation;
2029 Stack.erase(std::prev(I.base()), Stack.end());
2030 }
2031 } else if (!Stack.empty()) {
2032 // We do not have a label, just pop the last entry.
2033 CurrentValue = Stack.back().Value;
2034 CurrentPragmaLocation = Stack.back().PragmaLocation;
2035 Stack.pop_back();
2036 }
2037 }
2038 if (Action & PSK_Set) {
2040 CurrentPragmaLocation = PragmaLocation;
2041 }
2042 }
2043
2044 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
2045 // method body to restore the stacks on exit, so it works like this:
2046 //
2047 // struct S {
2048 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
2049 // void Method {}
2050 // #pragma <name>(pop, InternalPragmaSlot)
2051 // };
2052 //
2053 // It works even with #pragma vtordisp, although MSVC doesn't support
2054 // #pragma vtordisp(push [, id], n)
2055 // syntax.
2056 //
2057 // Push / pop a named sentinel slot.
2058 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
2059 assert((Action == PSK_Push || Action == PSK_Pop) &&
2060 "Can only push / pop #pragma stack sentinels!");
2061 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
2062 }
2063
2064 // Constructors.
2065 explicit PragmaStack(const ValueType &Default)
2067
2068 bool hasValue() const { return CurrentValue != DefaultValue; }
2069
2071 ValueType DefaultValue; // Value used for PSK_Reset action.
2072 ValueType CurrentValue;
2074 };
2075 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
2076 // we shouldn't do so if they're in a module).
2077
2078 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
2079 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
2080 ///
2081 /// 0: Suppress all vtordisps
2082 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
2083 /// structors
2084 /// 2: Always insert vtordisps to support RTTI on partially constructed
2085 /// objects
2088 // The current #pragma align/pack values and locations at each #include.
2095 // Segment #pragmas.
2100
2101 // #pragma strict_gs_check.
2103
2104 // This stack tracks the current state of Sema.CurFPFeatures.
2107 FPOptionsOverride result;
2108 if (!FpPragmaStack.hasValue()) {
2109 result = FPOptionsOverride();
2110 } else {
2111 result = FpPragmaStack.CurrentValue;
2112 }
2113 return result;
2114 }
2115
2122
2123 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
2124 // Actions should be performed only if we enter / exit a C++ method body.
2126 public:
2127 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
2132
2133 private:
2134 Sema &S;
2135 StringRef SlotLabel;
2136 bool ShouldAct;
2137 };
2138
2139 /// Used for #pragma init_seg.
2146
2147 /// Sections used with #pragma alloc_text.
2148 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
2149
2150 /// VisContext - Manages the stack for \#pragma GCC visibility.
2151 void *VisContext; // Really a "PragmaVisStack*"
2152
2153 /// This an attribute introduced by \#pragma clang attribute.
2160
2161 /// A push'd group of PragmaAttributeEntries.
2163 /// The location of the push attribute.
2165 /// The namespace of this push group.
2168 };
2169
2171
2172 /// The declaration that is currently receiving an attribute from the
2173 /// #pragma attribute stack.
2175
2176 /// This represents the last location of a "#pragma clang optimize off"
2177 /// directive if such a directive has not been closed by an "on" yet. If
2178 /// optimizations are currently "on", this is set to an invalid location.
2180
2181 /// Get the location for the currently active "\#pragma clang optimize
2182 /// off". If this location is invalid, then the state of the pragma is "on".
2186
2187 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
2188 /// whether the optimizations in the list passed to the pragma should be
2189 /// turned off or on. This boolean is true by default because command line
2190 /// options are honored when `#pragma optimize("", on)`.
2191 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
2193
2194 /// Set of no-builtin functions listed by \#pragma function.
2196
2197 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
2198 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
2200
2201 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
2203
2204 /// Add gsl::Pointer attribute to std::container::iterator
2205 /// \param ND The declaration that introduces the name
2206 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
2207 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
2208
2209 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
2211
2212 /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
2214
2215 /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
2217
2218 /// Add [[gsl::Pointer]] attributes for std:: types.
2220
2221 LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
2222 StringRef ParamName);
2223 // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
2224 // can be the name of a function parameter, we need to parse the function
2225 // declaration and rest of the parameters before processesing 'X'. Therefore
2226 // do this lazily instead of processing while parsing the annotation itself.
2228
2229 /// Add _Nullable attributes for std:: types.
2231
2232 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
2235 PragmaClangSectionKind SecKind,
2236 StringRef SecName);
2237
2238 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
2240 SourceLocation PragmaLoc);
2241
2242 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
2243 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
2244 StringRef SlotLabel, Expr *Alignment);
2245
2246 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
2247 /// (unless they are value dependent or type dependent). Returns false
2248 /// and emits a diagnostic if one or more of the arguments could not be
2249 /// folded into a constant.
2252
2257
2259 SourceLocation IncludeLoc);
2261
2262 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
2264
2265 /// ActOnPragmaMSComment - Called on well formed
2266 /// \#pragma comment(kind, "arg").
2268 StringRef Arg);
2269
2270 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
2271 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
2272 StringRef Value);
2273
2274 /// Are precise floating point semantics currently enabled?
2276 return !CurFPFeatures.getAllowFPReassociate() &&
2277 !CurFPFeatures.getNoSignedZero() &&
2278 !CurFPFeatures.getAllowReciprocal() &&
2279 !CurFPFeatures.getAllowApproxFunc();
2280 }
2281
2284
2285 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
2286 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
2288
2289 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
2290 /// pointers_to_members(representation method[, general purpose
2291 /// representation]).
2294 SourceLocation PragmaLoc);
2295
2296 /// Called on well formed \#pragma vtordisp().
2297 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
2299
2300 bool UnifySection(StringRef SectionName, int SectionFlags,
2301 NamedDecl *TheDecl);
2302 bool UnifySection(StringRef SectionName, int SectionFlags,
2303 SourceLocation PragmaSectionLocation);
2304
2305 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
2306 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
2307 PragmaMsStackAction Action,
2308 llvm::StringRef StackSlotLabel,
2309 StringLiteral *SegmentName, llvm::StringRef PragmaName);
2310
2311 /// Called on well formed \#pragma section().
2312 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
2313 StringLiteral *SegmentName);
2314
2315 /// Called on well-formed \#pragma init_seg().
2316 /// If a function name is provided (", func-name"), it is passed via Func.
2317 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
2318 StringLiteral *SegmentName,
2319 IdentifierLoc *Func = nullptr);
2320
2321 /// Called on well-formed \#pragma alloc_text().
2323 SourceLocation PragmaLocation, StringRef Section,
2324 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
2325 &Functions);
2326
2327 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
2328 /// strict_gs_check.
2330 PragmaMsStackAction Action,
2331 bool Value);
2332
2333 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
2334 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
2335 SourceLocation PragmaLoc);
2336
2338 SourceLocation PragmaLoc,
2341 const IdentifierInfo *Namespace);
2342
2343 /// Called on well-formed '\#pragma clang attribute pop'.
2345 const IdentifierInfo *Namespace);
2346
2347 /// Adds the attributes that have been specified using the
2348 /// '\#pragma clang attribute push' directives to the given declaration.
2349 void AddPragmaAttributes(Scope *S, Decl *D);
2350
2352 llvm::function_ref<void(SourceLocation, PartialDiagnostic)>;
2354 return [this](SourceLocation Loc, PartialDiagnostic PD) {
2355 // This bypasses a lot of the filters in the diag engine, as it's
2356 // to be used to attach notes to diagnostics which have already
2357 // been filtered through.
2358 DiagnosticBuilder Builder(Diags.Report(Loc, PD.getDiagID()));
2359 PD.Emit(Builder);
2360 };
2361 }
2362
2368
2370
2371 /// Called on well formed \#pragma clang optimize.
2372 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
2373
2374 /// #pragma optimize("[optimization-list]", on | off).
2375 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
2376
2377 /// Call on well formed \#pragma function.
2378 void
2380 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
2381
2383 SourceLocation NameLoc,
2384 Scope *curScope);
2385
2386 /// Information from a C++ #pragma export, for a symbol that we
2387 /// haven't seen the declaration for yet.
2392
2393 llvm::DenseMap<IdentifierInfo *, PendingPragmaInfo> PendingExportedNames;
2394
2395 /// ActonPragmaExport - called on well-formed '\#pragma export'.
2396 void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc,
2397 Scope *curScope);
2398
2399 /// Only called on function definitions; if there is a pragma in scope
2400 /// with the effect of a range-based optnone, consider marking the function
2401 /// with attribute optnone.
2403
2404 /// Only called on function definitions; if there is a `#pragma alloc_text`
2405 /// that decides which code section the function should be in, add
2406 /// attribute section to the function.
2408
2409 /// Adds the 'optnone' attribute to the function declaration if there
2410 /// are no conflicts; Loc represents the location causing the 'optnone'
2411 /// attribute to be added (usually because of a pragma).
2413
2414 /// Only called on function definitions; if there is a MSVC #pragma optimize
2415 /// in scope, consider changing the function's attributes based on the
2416 /// optimization list passed to the pragma.
2418
2419 /// Only called on function definitions; if there is a pragma in scope
2420 /// with the effect of a range-based no_builtin, consider marking the function
2421 /// with attribute no_builtin.
2423
2424 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
2425 /// add an appropriate visibility attribute.
2427
2428 /// FreeVisContext - Deallocate and null out VisContext.
2429 void FreeVisContext();
2430
2431 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
2432 void ActOnPragmaVisibility(const IdentifierInfo *VisType,
2433 SourceLocation PragmaLoc);
2434
2435 /// ActOnPragmaFPContract - Called on well formed
2436 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
2437 /// \#pragma clang fp contract
2439
2440 /// Called on well formed
2441 /// \#pragma clang fp reassociate
2442 /// or
2443 /// \#pragma clang fp reciprocal
2445 bool IsEnabled);
2446
2447 /// ActOnPragmaFenvAccess - Called on well formed
2448 /// \#pragma STDC FENV_ACCESS
2449 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
2450
2451 /// ActOnPragmaCXLimitedRange - Called on well formed
2452 /// \#pragma STDC CX_LIMITED_RANGE
2455
2456 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
2459
2460 /// Called to set constant rounding mode for floating point operations.
2461 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
2462
2463 /// Called to set exception behavior for floating point operations.
2465
2466 /// PushNamespaceVisibilityAttr - Note that we've entered a
2467 /// namespace with a visibility attribute.
2468 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
2469 SourceLocation Loc);
2470
2471 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
2472 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
2473 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
2474
2475 /// Handles semantic checking for features that are common to all attributes,
2476 /// such as checking whether a parameter was properly specified, or the
2477 /// correct number of arguments were passed, etc. Returns true if the
2478 /// attribute has been diagnosed.
2479 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
2480 bool SkipArgCountCheck = false);
2481 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
2482 bool SkipArgCountCheck = false);
2484 bool SkipArgCountCheck = false);
2485
2486 ///@}
2487
2488 //
2489 //
2490 // -------------------------------------------------------------------------
2491 //
2492 //
2493
2494 /// \name Availability Attribute Handling
2495 /// Implementations are in SemaAvailability.cpp
2496 ///@{
2497
2498public:
2499 /// Issue any -Wunguarded-availability warnings in \c FD
2501
2503
2504 /// Retrieve the current function, if any, that should be analyzed for
2505 /// potential availability violations.
2507
2509 const ObjCInterfaceDecl *UnknownObjCClass,
2510 bool ObjCPropertyAccess,
2511 bool AvoidPartialAvailabilityChecks,
2512 ObjCInterfaceDecl *ClassReceiver);
2513
2515
2516 std::pair<AvailabilityResult, const NamedDecl *>
2517 ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
2518 ObjCInterfaceDecl *ClassReceiver);
2519 ///@}
2520
2521 //
2522 //
2523 // -------------------------------------------------------------------------
2524 //
2525 //
2526
2527 /// \name Bounds Safety
2528 /// Implementations are in SemaBoundsSafety.cpp
2529 ///@{
2530public:
2532 bool CountInBytes = false;
2533 bool OrNull = false;
2534 bool IsEndedBy = false;
2535
2536 /// Return the flags for a bounds attribute of kind \p K.
2538 };
2541
2542 /// Check the type shape for counted_by, sized_by and their _or_null variants.
2543 /// The caller checks declaration context, count expressions, flexible array
2544 /// member eligibility and nesting.
2545 ///
2546 /// \p Flags selects the attribute variant. For void pointers, counted_by is
2547 /// treated as a byte count outside the -fbounds-safety attribute model. Set
2548 /// \c Flags.CountInBytes in this case if \p UpdateFlags is true.
2549 /// \p AttrSpelling, \p AllowRedecl and \p AttrArg are reserved for that model
2550 /// (see LangOptions::hasBoundsSafetyAttributes).
2551 ///
2552 /// \returns false after diagnosing an attribute that must be dropped. Returns
2553 /// true if the shape is valid, after the warning for an array of structs with
2554 /// flexible array members, and, under the -fbounds-safety attribute model,
2555 /// after an error on a pointer, with \c Flags.CountInBytes set so that type
2556 /// construction can recover.
2558 SourceRange AttrRange,
2559 BoundsAttrFlags &Flags,
2560 StringRef AttrSpelling = {},
2561 bool AllowRedecl = false,
2562 Expr *AttrArg = nullptr,
2563 bool UpdateFlags = true);
2564
2565 /// Check a counted_by-family attribute in type position and initialize
2566 /// \p Flags from \p AttrKind. \p PointerNestLevel counts the pointer, array
2567 /// and function declarator chunks enclosing the attribute.
2568 ///
2569 /// \returns false after diagnosing an attribute that must be dropped (see
2570 /// ValidateBoundsAttrTypeShape).
2573 SourceRange AttrRange, unsigned PointerNestLevel, BoundsAttrFlags &Flags);
2574
2575 /// Check if applying the specified attribute variant from the "counted by"
2576 /// family of attributes to FieldDecl \p FD is semantically valid. If
2577 /// semantically invalid diagnostics will be emitted explaining the problems.
2578 ///
2579 /// \param FD The FieldDecl to apply the attribute to
2580 /// \param E The count expression on the attribute
2581 /// \param CountInBytes If true the attribute is from the "sized_by" family of
2582 /// attributes. If the false the attribute is from
2583 /// "counted_by" family of attributes.
2584 /// \param OrNull If true the attribute is from the "_or_null" suffixed family
2585 /// of attributes. If false the attribute does not have the
2586 /// suffix.
2587 ///
2588 /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g.
2589 /// \p CountInBytes and \p OrNull both being true indicates the
2590 /// `counted_by_or_null` attribute.
2591 ///
2592 /// \returns false iff semantically valid.
2593 bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
2594 bool OrNull);
2595
2596 /// Late-parsed bounds types dropped while their declarator was built. The
2597 /// attribute has already been diagnosed and its node is no longer part of
2598 /// any type, so the completion pass must skip it rather than parse its
2599 /// argument and complete it.
2602
2606
2608 return RejectedLateParsedBoundsTypes.contains(BATy);
2609 }
2610
2611 /// Validate the late-parsed type attribute \p LA and wrap \p QT in a
2612 /// CountAttributedType with no count yet, recorded on \p LA for later
2613 /// completion. Returns false if \p LA is invalid.
2615
2616 /// Supply the parsed argument of a late-parsed bounds attribute to the type
2617 /// built for it by ProcessLateParsedTypeAttr, and run the checks that need
2618 /// the owning declaration. \p FD is the field the type belongs to. Returns
2619 /// false if the attribute was rejected.
2621 FieldDecl *FD, Expr *Arg);
2622
2623 /// Perform Bounds Safety Semantic checks for assigning to a `__counted_by` or
2624 /// `__counted_by_or_null` pointer type \param LHSTy.
2625 ///
2626 /// \param LHSTy The type being assigned to. Checks will only be performed if
2627 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2628 /// \param RHSExpr The expression being assigned from.
2629 /// \param Action The type assignment being performed
2630 /// \param Loc The SourceLocation to use for error diagnostics
2631 /// \param Assignee The ValueDecl being assigned. This is used to compute
2632 /// the name of the assignee. If the assignee isn't known this can
2633 /// be set to nullptr.
2634 /// \param ShowFullyQualifiedAssigneeName If set to true when using \p
2635 /// Assignee to compute the name of the assignee use the fully
2636 /// qualified name, otherwise use the unqualified name.
2637 ///
2638 /// \returns True iff no diagnostic where emitted, false otherwise.
2640 QualType LHSTy, Expr *RHSExpr, AssignmentAction Action,
2641 SourceLocation Loc, const ValueDecl *Assignee,
2642 bool ShowFullyQualifiedAssigneeName);
2643
2644 /// Perform Bounds Safety Semantic checks for initializing a Bounds Safety
2645 /// pointer.
2646 ///
2647 /// \param Entity The entity being initialized
2648 /// \param Kind The kind of initialization being performed
2649 /// \param Action The type assignment being performed
2650 /// \param LHSTy The type being assigned to. Checks will only be performed if
2651 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2652 /// \param RHSExpr The expression being used for initialization.
2653 ///
2654 /// \returns True iff no diagnostic where emitted, false otherwise.
2656 const InitializationKind &Kind,
2657 AssignmentAction Action,
2658 QualType LHSType, Expr *RHSExpr);
2659
2660 /// Perform Bounds Safety semantic checks for uses of invalid uses counted_by
2661 /// or counted_by_or_null pointers in \param E.
2662 ///
2663 /// \param E the expression to check
2664 ///
2665 /// \returns True iff no diagnostic where emitted, false otherwise.
2667 ///@}
2668
2669 //
2670 //
2671 // -------------------------------------------------------------------------
2672 //
2673 //
2674
2675 /// \name Casts
2676 /// Implementations are in SemaCast.cpp
2677 ///@{
2678
2679public:
2685
2686 /// ActOnCXXNamedCast - Parse
2687 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
2689 SourceLocation LAngleBracketLoc, Declarator &D,
2690 SourceLocation RAngleBracketLoc,
2691 SourceLocation LParenLoc, Expr *E,
2692 SourceLocation RParenLoc);
2693
2695 TypeSourceInfo *Ty, Expr *E,
2696 SourceRange AngleBrackets, SourceRange Parens);
2697
2699 ExprResult Operand,
2700 SourceLocation RParenLoc);
2701
2703 Expr *Operand, SourceLocation RParenLoc);
2704
2705 // Checks that reinterpret casts don't have undefined behavior.
2706 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2707 bool IsDereference, SourceRange Range);
2708
2709 // Checks that the vector type should be initialized from a scalar
2710 // by splatting the value rather than populating a single element.
2711 // This is the case for AltiVecVector types as well as with
2712 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
2713 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
2714
2715 // Checks if the -faltivec-src-compat=gcc option is specified.
2716 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
2717 // treated the same way as they are when trying to initialize
2718 // these vectors on gcc (an error is emitted).
2720 QualType SrcTy);
2721
2723 SourceLocation RParenLoc, Expr *Op);
2724
2726 SourceLocation LParenLoc,
2727 Expr *CastExpr,
2728 SourceLocation RParenLoc);
2729
2730 ///@}
2731
2732 //
2733 //
2734 // -------------------------------------------------------------------------
2735 //
2736 //
2737
2738 /// \name Extra Semantic Checking
2739 /// Implementations are in SemaChecking.cpp
2740 ///@{
2741
2742public:
2743 /// Used to change context to isConstantEvaluated without pushing a heavy
2744 /// ExpressionEvaluationContextRecord object.
2746
2751
2753 unsigned ByteNo) const;
2754
2756 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
2757 FAPK_Variadic, // values to format are passed as variadic arguments
2758 FAPK_VAList, // values to format are passed in a va_list
2759 FAPK_Elsewhere, // values to format are not passed to this function
2760 };
2761
2762 // Used to grab the relevant information from a FormatAttr and a
2763 // FunctionDeclaration.
2769
2770 /// Given a function and its FormatAttr or FormatMatchesAttr info, attempts to
2771 /// populate the FormatStringInfo parameter with the attribute's correct
2772 /// format_idx and firstDataArg. Returns true when the format fits the
2773 /// function and the FormatStringInfo has been populated.
2774 static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx,
2775 unsigned FirstArg, FormatStringInfo *FSI);
2776 static bool getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
2777 bool HasImplicitThisParam, bool IsVariadic,
2778 FormatStringInfo *FSI);
2779
2780 // Used by C++ template instantiation.
2782
2783 /// ConvertVectorExpr - Handle __builtin_convertvector
2785 SourceLocation BuiltinLoc,
2786 SourceLocation RParenLoc);
2787
2788 static StringRef GetFormatStringTypeName(FormatStringType FST);
2789 static FormatStringType GetFormatStringType(StringRef FormatFlavor);
2790 static FormatStringType GetFormatStringType(const FormatAttr *Format);
2791 static FormatStringType GetFormatStringType(const FormatMatchesAttr *Format);
2792
2793 bool FormatStringHasSArg(const StringLiteral *FExpr);
2794
2795 /// Check for comparisons of floating-point values using == and !=. Issue a
2796 /// warning if the comparison is not likely to do what the programmer
2797 /// intended.
2798 void CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
2799 const Expr *RHS, BinaryOperatorKind Opcode);
2800
2801 /// Register a magic integral constant to be used as a type tag.
2802 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
2803 uint64_t MagicValue, QualType Type,
2804 bool LayoutCompatible, bool MustBeNull);
2805
2808
2812
2814
2815 /// If true, \c Type should be compared with other expression's types for
2816 /// layout-compatibility.
2817 LLVM_PREFERRED_TYPE(bool)
2819 LLVM_PREFERRED_TYPE(bool)
2820 unsigned MustBeNull : 1;
2821 };
2822
2823 /// A pair of ArgumentKind identifier and magic value. This uniquely
2824 /// identifies the magic value.
2825 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
2826
2827 /// Diagnoses the current set of gathered accesses. This happens at the end of
2828 /// each expression evaluation context. Diagnostics are emitted only for
2829 /// accesses gathered in the current evaluation context.
2831
2832 /// This function checks if the expression is in the sef of potentially
2833 /// misaligned members and it is converted to some pointer type T with lower
2834 /// or equal alignment requirements. If so it removes it. This is used when
2835 /// we do not want to diagnose such misaligned access (e.g. in conversions to
2836 /// void*).
2837 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
2838
2839 /// Returns true if `From` is a function or pointer to a function with the
2840 /// `cfi_unchecked_callee` attribute but `To` is a function or pointer to
2841 /// function without this attribute.
2842 bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const;
2843
2844 /// This function calls Action when it determines that E designates a
2845 /// misaligned member due to the packed attribute. This is used to emit
2846 /// local diagnostics like in reference binding.
2848 Expr *E,
2849 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
2850 Action);
2851
2852 enum class AtomicArgumentOrder { API, AST };
2854 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
2855 SourceLocation RParenLoc, MultiExprArg Args,
2858
2859 /// Check to see if a given expression could have '.c_str()' called on it.
2860 bool hasCStrMethod(const Expr *E);
2861
2862 /// Diagnose pointers that are always non-null.
2863 /// \param E the expression containing the pointer
2864 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
2865 /// compared to a null pointer
2866 /// \param IsEqual True when the comparison is equal to a null pointer
2867 /// \param Range Extra SourceRange to highlight in the diagnostic
2870 bool IsEqual, SourceRange Range);
2871
2872 /// CheckParmsForFunctionDef - Check that the parameters of the given
2873 /// function are appropriate for the definition of a function. This
2874 /// takes care of any checks that cannot be performed on the
2875 /// declaration itself, e.g., that the types of each of the function
2876 /// parameters are complete.
2878 bool CheckParameterNames);
2879
2880 /// CheckCastAlign - Implements -Wcast-align, which warns when a
2881 /// pointer cast increases the alignment requirements.
2882 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2883
2884 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
2885 /// to weak/__unsafe_unretained type.
2886 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
2887
2888 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
2889 /// to weak/__unsafe_unretained expression.
2890 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
2891
2892 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2893 /// statement as a \p Body, and it is located on the same line.
2894 ///
2895 /// This helps prevent bugs due to typos, such as:
2896 /// if (condition);
2897 /// do_stuff();
2898 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
2899 unsigned DiagID);
2900
2901 /// Warn if a for/while loop statement \p S, which is followed by
2902 /// \p PossibleBody, has a suspicious null statement as a body.
2903 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
2904
2905 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
2906 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2907 SourceLocation OpLoc);
2908
2909 bool IsLayoutCompatible(QualType T1, QualType T2) const;
2911 const TypeSourceInfo *Derived);
2912
2913 /// CheckFunctionCall - Check a direct function call for various correctness
2914 /// and safety properties not strictly enforced by the C type system.
2915 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2916 const FunctionProtoType *Proto);
2917
2924
2925 /// \param FPOnly restricts the arguments to floating-point types.
2926 std::optional<QualType>
2927 BuiltinVectorMath(CallExpr *TheCall,
2930 bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2931
2932 void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction,
2933 const Expr *ThisArg, ArrayRef<const Expr *> Args);
2934
2935 /// Handles the checks for format strings, non-POD arguments to vararg
2936 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
2937 /// attributes and AArch64 SME attributes.
2938 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2939 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2940 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2941 VariadicCallType CallType);
2942
2943 /// Verify that two format strings (as understood by attribute(format) and
2944 /// attribute(format_matches) are compatible. If they are incompatible,
2945 /// diagnostics are emitted with the assumption that \c
2946 /// AuthoritativeFormatString is correct and
2947 /// \c TestedFormatString is wrong. If \c FunctionCallArg is provided,
2948 /// diagnostics will point to it and a note will refer to \c
2949 /// TestedFormatString or \c AuthoritativeFormatString as appropriate.
2950 bool
2952 const StringLiteral *AuthoritativeFormatString,
2953 const StringLiteral *TestedFormatString,
2954 const Expr *FunctionCallArg = nullptr);
2955
2956 /// Verify that one format string (as understood by attribute(format)) is
2957 /// self-consistent; for instance, that it doesn't have multiple positional
2958 /// arguments referring to the same argument in incompatible ways. Diagnose
2959 /// if it isn't.
2961
2962 /// \brief Enforce the bounds of a TCB
2963 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
2964 /// directly calls other functions in the same TCB as marked by the
2965 /// enforce_tcb and enforce_tcb_leaf attributes.
2966 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2967 const NamedDecl *Callee);
2968
2969 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2970
2971 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2972 /// TheCall is a constant expression.
2973 bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
2974 llvm::APSInt &Result);
2975
2976 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2977 /// TheCall is a constant expression in the range [Low, High].
2978 bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
2979 int High, bool RangeIsError = true);
2980
2981 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
2982 /// TheCall is a constant expression is a multiple of Num..
2983 bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
2984 unsigned Multiple);
2985
2986 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
2987 /// constant expression representing a power of 2.
2988 bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum);
2989
2990 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
2991 /// a constant expression representing an arbitrary byte value shifted left by
2992 /// a multiple of 8 bits.
2993 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
2994 unsigned ArgBits);
2995
2996 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
2997 /// TheCall is a constant expression representing either a shifted byte value,
2998 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
2999 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
3000 /// Arm MVE intrinsics.
3001 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum,
3002 unsigned ArgBits);
3003
3004 /// Checks that a call expression's argument count is at least the desired
3005 /// number. This is useful when doing custom type-checking on a variadic
3006 /// function. Returns true on error.
3007 bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount);
3008
3009 /// Checks that a call expression's argument count is at most the desired
3010 /// number. This is useful when doing custom type-checking on a variadic
3011 /// function. Returns true on error.
3012 bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount);
3013
3014 /// Checks that a call expression's argument count is in the desired range.
3015 /// This is useful when doing custom type-checking on a variadic function.
3016 /// Returns true on error.
3017 bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
3018 unsigned MaxArgCount);
3019
3020 /// Checks that a call expression's argument count is the desired number.
3021 /// This is useful when doing custom type-checking. Returns true on error.
3022 bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount);
3023
3025
3026 /// Returns true if the argument consists of one contiguous run of 1s with any
3027 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
3028 /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3029 /// since all 1s are not contiguous.
3030 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
3031
3033 bool *ICContext = nullptr,
3034 bool IsListInit = false);
3035
3036 /// Check for overflow behavior type related implicit conversion diagnostics.
3037 /// Returns true if OBT-related diagnostic was issued, false otherwise.
3039 SourceLocation CC);
3040
3041 bool
3046 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr =
3048
3049private:
3050 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
3051 const ArraySubscriptExpr *ASE = nullptr,
3052 bool AllowOnePastEnd = true, bool IndexNegated = false);
3053 void CheckArrayAccess(const Expr *E);
3054
3055 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3056 const FunctionProtoType *Proto);
3057
3058 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3059 /// such as function pointers returned from functions.
3060 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
3061
3062 /// CheckConstructorCall - Check a constructor call for correctness and safety
3063 /// properties not enforced by the C type system.
3064 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
3066 const FunctionProtoType *Proto, SourceLocation Loc);
3067
3068 /// Warn if a pointer or reference argument passed to a function points to an
3069 /// object that is less aligned than the parameter. This can happen when
3070 /// creating a typedef with a lower alignment than the original type and then
3071 /// calling functions defined in terms of the original type.
3072 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3073 StringRef ParamName, QualType ArgTy, QualType ParamTy);
3074
3075 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
3076
3077 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
3078 CallExpr *TheCall);
3079
3080 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3081 CallExpr *TheCall);
3082
3083 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
3084
3085 /// Argument-value fortify checks for libc functions that are not builtins,
3086 /// dispatched by name (e.g. umask). Diagnostics belong to -Wfortify-source.
3087 void checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall);
3088
3089 /// Check the arguments to '__builtin_va_start', '__builtin_ms_va_start',
3090 /// or '__builtin_c23_va_start' for validity. Emit an error and return true
3091 /// on failure; return false on success.
3092 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
3093 bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
3094
3095 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3096 /// friends. This is declared to take (...), so we have to check everything.
3097 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
3098
3099 /// BuiltinSemaBuiltinFPClassification - Handle functions like
3100 /// __builtin_isnan and friends. This is declared to take (...), so we have
3101 /// to check everything.
3102 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
3103 unsigned BuiltinID);
3104
3105 /// Perform semantic analysis for a call to __builtin_complex.
3106 bool BuiltinComplex(CallExpr *TheCall);
3107 bool BuiltinOSLogFormat(CallExpr *TheCall);
3108
3109 /// BuiltinPrefetch - Handle __builtin_prefetch.
3110 /// This is declared to take (const void*, ...) and can take two
3111 /// optional constant int args.
3112 bool BuiltinPrefetch(CallExpr *TheCall);
3113
3114 /// Handle __builtin_alloca_with_align. This is declared
3115 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3116 /// than 8.
3117 bool BuiltinAllocaWithAlign(CallExpr *TheCall);
3118
3119 /// BuiltinArithmeticFence - Handle __arithmetic_fence.
3120 bool BuiltinArithmeticFence(CallExpr *TheCall);
3121
3122 /// BuiltinAssume - Handle __assume (MS Extension).
3123 /// __assume does not evaluate its arguments, and should warn if its argument
3124 /// has side effects.
3125 bool BuiltinAssume(CallExpr *TheCall);
3126
3127 /// Handle __builtin_assume_aligned. This is declared
3128 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3129 bool BuiltinAssumeAligned(CallExpr *TheCall);
3130
3131 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3132 /// This checks that the target supports __builtin_longjmp and
3133 /// that val is a constant 1.
3134 bool BuiltinLongjmp(CallExpr *TheCall);
3135
3136 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3137 /// This checks that the target supports __builtin_setjmp.
3138 bool BuiltinSetjmp(CallExpr *TheCall);
3139
3140 /// We have a call to a function like __sync_fetch_and_add, which is an
3141 /// overloaded function based on the pointer type of its first argument.
3142 /// The main BuildCallExpr routines have already promoted the types of
3143 /// arguments because all of these calls are prototyped as void(...).
3144 ///
3145 /// This function goes through and does final semantic checking for these
3146 /// builtins, as well as generating any warnings.
3147 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
3148
3149 /// BuiltinNontemporalOverloaded - We have a call to
3150 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3151 /// overloaded function based on the pointer type of its last argument.
3152 ///
3153 /// This function goes through and does final semantic checking for these
3154 /// builtins.
3155 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
3156 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
3158
3159 /// \param FPOnly restricts the arguments to floating-point types.
3160 bool BuiltinElementwiseMath(CallExpr *TheCall,
3163 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
3164
3165 bool BuiltinNonDeterministicValue(CallExpr *TheCall);
3166
3167 bool CheckInvalidBuiltinCountedByRef(const Expr *E,
3169 bool BuiltinCountedByRef(CallExpr *TheCall);
3170
3171 // Matrix builtin handling.
3172 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
3173 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
3174 ExprResult CallResult);
3175 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
3176 ExprResult CallResult);
3177
3178 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3179 /// functions) for correct use of format strings.
3180 /// Returns true if a format string has been fully checked.
3181 bool CheckFormatArguments(const FormatAttr *Format,
3182 ArrayRef<const Expr *> Args, bool IsCXXMember,
3183 VariadicCallType CallType, SourceLocation Loc,
3184 SourceRange Range,
3185 llvm::SmallBitVector &CheckedVarArgs);
3186 bool CheckFormatString(const FormatMatchesAttr *Format,
3187 ArrayRef<const Expr *> Args, bool IsCXXMember,
3188 VariadicCallType CallType, SourceLocation Loc,
3189 SourceRange Range,
3190 llvm::SmallBitVector &CheckedVarArgs);
3191 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
3192 FormatArgumentPassingKind FAPK,
3193 StringLiteral *ReferenceFormatString,
3194 unsigned format_idx, unsigned firstDataArg,
3196 SourceLocation Loc, SourceRange range,
3197 llvm::SmallBitVector &CheckedVarArgs);
3198
3199 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
3200
3201 /// Warn when using the wrong abs() function.
3202 void CheckAbsoluteValueFunction(const CallExpr *Call,
3203 const FunctionDecl *FDecl);
3204
3205 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
3206
3207 /// Check for dangerous or invalid arguments to memset().
3208 ///
3209 /// This issues warnings on known problematic, dangerous or unspecified
3210 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3211 /// function calls.
3212 ///
3213 /// \param Call The call expression to diagnose.
3214 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
3215 IdentifierInfo *FnName);
3216
3217 bool CheckSizeofMemaccessArgument(const Expr *SizeOfArg, const Expr *Dest,
3218 IdentifierInfo *FnName);
3219 // Warn if the user has made the 'size' argument to strlcpy or strlcat
3220 // be the size of the source, instead of the destination.
3221 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
3222
3223 // Warn on anti-patterns as the 'size' argument to strncat.
3224 // The correct size argument should look like following:
3225 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3226 void CheckStrncatArguments(const CallExpr *Call,
3227 const IdentifierInfo *FnName);
3228
3229 /// Alerts the user that they are attempting to free a non-malloc'd object.
3230 void CheckFreeArguments(const CallExpr *E);
3231
3232 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
3233 SourceLocation ReturnLoc, bool isObjCMethod = false,
3234 const AttrVec *Attrs = nullptr,
3235 const FunctionDecl *FD = nullptr);
3236
3237 /// Diagnoses "dangerous" implicit conversions within the given
3238 /// expression (which is a full expression). Implements -Wconversion
3239 /// and -Wsign-compare.
3240 ///
3241 /// \param CC the "context" location of the implicit conversion, i.e.
3242 /// the most location of the syntactic entity requiring the implicit
3243 /// conversion
3244 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
3245
3246 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
3247 /// Input argument E is a logical expression.
3249
3250 /// Diagnose when expression is an integer constant expression and its
3251 /// evaluation results in integer overflow
3252 void CheckForIntOverflow(const Expr *E);
3253 void CheckUnsequencedOperations(const Expr *E);
3254
3255 /// Perform semantic checks on a completed expression. This will either
3256 /// be a full-expression or a default argument expression.
3257 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
3258 bool IsConstexpr = false);
3259
3260 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
3261 Expr *Init);
3262
3263 /// A map from magic value to type information.
3264 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
3265 TypeTagForDatatypeMagicValues;
3266
3267 /// Peform checks on a call of a function with argument_with_type_tag
3268 /// or pointer_with_type_tag attributes.
3269 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
3270 const ArrayRef<const Expr *> ExprArgs,
3271 SourceLocation CallSiteLoc);
3272
3273 /// Check if we are taking the address of a packed field
3274 /// as this may be a problem if the pointer value is dereferenced.
3275 void CheckAddressOfPackedMember(Expr *rhs);
3276
3277 /// Helper class that collects misaligned member designations and
3278 /// their location info for delayed diagnostics.
3279 struct MisalignedMember {
3280 Expr *E;
3281 RecordDecl *RD;
3282 ValueDecl *MD;
3283 CharUnits Alignment;
3284
3285 MisalignedMember() : E(), RD(), MD() {}
3286 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
3287 CharUnits Alignment)
3288 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
3289 explicit MisalignedMember(Expr *E)
3290 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
3291
3292 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
3293 };
3294
3295 /// Adds an expression to the set of gathered misaligned members.
3296 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
3297 CharUnits Alignment);
3298 ///@}
3299
3300 //
3301 //
3302 // -------------------------------------------------------------------------
3303 //
3304 //
3305
3306 /// \name C++ Coroutines
3307 /// Implementations are in SemaCoroutine.cpp
3308 ///@{
3309
3310public:
3311 /// The C++ "std::coroutine_traits" template, which is defined in
3312 /// <coroutine_traits>
3314
3316 StringRef Keyword);
3320
3323 UnresolvedLookupExpr *Lookup);
3325 Expr *Awaiter, bool IsImplicit = false);
3327 UnresolvedLookupExpr *Lookup);
3330 bool IsImplicit = false);
3335
3336 // As a clang extension, enforces that a non-coroutine function must be marked
3337 // with [[clang::coro_wrapper]] if it returns a type marked with
3338 // [[clang::coro_return_type]].
3339 // Expects that FD is not a coroutine.
3341 /// Lookup 'coroutine_traits' in std namespace and std::experimental
3342 /// namespace. The namespace found is recorded in Namespace.
3344 SourceLocation FuncLoc);
3345 /// Check that the expression co_await promise.final_suspend() shall not be
3346 /// potentially-throwing.
3347 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
3348
3349 ///@}
3350
3351 //
3352 //
3353 // -------------------------------------------------------------------------
3354 //
3355 //
3356
3357 /// \name C++ Scope Specifiers
3358 /// Implementations are in SemaCXXScopeSpec.cpp
3359 ///@{
3360
3361public:
3362 // Marks SS invalid if it represents an incomplete type.
3364 // Complete an enum decl, maybe without a scope spec.
3366 CXXScopeSpec *SS = nullptr);
3367
3368 /// Compute the DeclContext that is associated with the given type.
3369 ///
3370 /// \param T the type for which we are attempting to find a DeclContext.
3371 ///
3372 /// \returns the declaration context represented by the type T,
3373 /// or NULL if the declaration context cannot be computed (e.g., because it is
3374 /// dependent and not the current instantiation).
3376
3377 /// Compute the DeclContext that is associated with the given
3378 /// scope specifier.
3379 ///
3380 /// \param SS the C++ scope specifier as it appears in the source
3381 ///
3382 /// \param EnteringContext when true, we will be entering the context of
3383 /// this scope specifier, so we can retrieve the declaration context of a
3384 /// class template or class template partial specialization even if it is
3385 /// not the current instantiation.
3386 ///
3387 /// \returns the declaration context represented by the scope specifier @p SS,
3388 /// or NULL if the declaration context cannot be computed (e.g., because it is
3389 /// dependent and not the current instantiation).
3391 bool EnteringContext = false);
3393
3394 /// If the given nested name specifier refers to the current
3395 /// instantiation, return the declaration that corresponds to that
3396 /// current instantiation (C++0x [temp.dep.type]p1).
3397 ///
3398 /// \param NNS a dependent nested name specifier.
3400
3401 /// The parser has parsed a global nested-name-specifier '::'.
3402 ///
3403 /// \param CCLoc The location of the '::'.
3404 ///
3405 /// \param SS The nested-name-specifier, which will be updated in-place
3406 /// to reflect the parsed nested-name-specifier.
3407 ///
3408 /// \returns true if an error occurred, false otherwise.
3410
3411 /// The parser has parsed a '__super' nested-name-specifier.
3412 ///
3413 /// \param SuperLoc The location of the '__super' keyword.
3414 ///
3415 /// \param ColonColonLoc The location of the '::'.
3416 ///
3417 /// \param SS The nested-name-specifier, which will be updated in-place
3418 /// to reflect the parsed nested-name-specifier.
3419 ///
3420 /// \returns true if an error occurred, false otherwise.
3422 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
3423
3424 /// Determines whether the given declaration is an valid acceptable
3425 /// result for name lookup of a nested-name-specifier.
3426 /// \param SD Declaration checked for nested-name-specifier.
3427 /// \param IsExtension If not null and the declaration is accepted as an
3428 /// extension, the pointed variable is assigned true.
3430 bool *CanCorrect = nullptr);
3431
3432 /// If the given nested-name-specifier begins with a bare identifier
3433 /// (e.g., Base::), perform name lookup for that identifier as a
3434 /// nested-name-specifier within the given scope, and return the result of
3435 /// that name lookup.
3437
3438 /// Keeps information about an identifier in a nested-name-spec.
3439 ///
3441 /// The type of the object, if we're parsing nested-name-specifier in
3442 /// a member access expression.
3444
3445 /// The identifier preceding the '::'.
3447
3448 /// The location of the identifier.
3450
3451 /// The location of the '::'.
3453
3454 /// Creates info object for the most typical case.
3456 SourceLocation ColonColonLoc,
3459 CCLoc(ColonColonLoc) {}
3460
3462 SourceLocation ColonColonLoc, QualType ObjectType)
3464 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
3465 };
3466
3467 /// Build a new nested-name-specifier for "identifier::", as described
3468 /// by ActOnCXXNestedNameSpecifier.
3469 ///
3470 /// \param S Scope in which the nested-name-specifier occurs.
3471 /// \param IdInfo Parser information about an identifier in the
3472 /// nested-name-spec.
3473 /// \param EnteringContext If true, enter the context specified by the
3474 /// nested-name-specifier.
3475 /// \param SS Optional nested name specifier preceding the identifier.
3476 /// \param ScopeLookupResult Provides the result of name lookup within the
3477 /// scope of the nested-name-specifier that was computed at template
3478 /// definition time.
3479 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
3480 /// error recovery and what kind of recovery is performed.
3481 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
3482 /// are allowed. The bool value pointed by this parameter is set to
3483 /// 'true' if the identifier is treated as if it was followed by ':',
3484 /// not '::'.
3485 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3486 ///
3487 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
3488 /// that it contains an extra parameter \p ScopeLookupResult, which provides
3489 /// the result of name lookup within the scope of the nested-name-specifier
3490 /// that was computed at template definition time.
3491 ///
3492 /// If ErrorRecoveryLookup is true, then this call is used to improve error
3493 /// recovery. This means that it should not emit diagnostics, it should
3494 /// just return true on failure. It also means it should only return a valid
3495 /// scope if it *knows* that the result is correct. It should not return in a
3496 /// dependent context, for example. Nor will it extend \p SS with the scope
3497 /// specifier.
3498 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3499 bool EnteringContext, CXXScopeSpec &SS,
3500 NamedDecl *ScopeLookupResult,
3501 bool ErrorRecoveryLookup,
3502 bool *IsCorrectedToColon = nullptr,
3503 bool OnlyNamespace = false);
3504
3505 /// The parser has parsed a nested-name-specifier 'identifier::'.
3506 ///
3507 /// \param S The scope in which this nested-name-specifier occurs.
3508 ///
3509 /// \param IdInfo Parser information about an identifier in the
3510 /// nested-name-spec.
3511 ///
3512 /// \param EnteringContext Whether we're entering the context nominated by
3513 /// this nested-name-specifier.
3514 ///
3515 /// \param SS The nested-name-specifier, which is both an input
3516 /// parameter (the nested-name-specifier before this type) and an
3517 /// output parameter (containing the full nested-name-specifier,
3518 /// including this new type).
3519 ///
3520 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
3521 /// are allowed. The bool value pointed by this parameter is set to 'true'
3522 /// if the identifier is treated as if it was followed by ':', not '::'.
3523 ///
3524 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3525 ///
3526 /// \returns true if an error occurred, false otherwise.
3527 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3528 bool EnteringContext, CXXScopeSpec &SS,
3529 bool *IsCorrectedToColon = nullptr,
3530 bool OnlyNamespace = false);
3531
3532 /// The parser has parsed a nested-name-specifier
3533 /// 'template[opt] template-name < template-args >::'.
3534 ///
3535 /// \param S The scope in which this nested-name-specifier occurs.
3536 ///
3537 /// \param SS The nested-name-specifier, which is both an input
3538 /// parameter (the nested-name-specifier before this type) and an
3539 /// output parameter (containing the full nested-name-specifier,
3540 /// including this new type).
3541 ///
3542 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
3543 /// \param TemplateName the template name.
3544 /// \param TemplateNameLoc The location of the template name.
3545 /// \param LAngleLoc The location of the opening angle bracket ('<').
3546 /// \param TemplateArgs The template arguments.
3547 /// \param RAngleLoc The location of the closing angle bracket ('>').
3548 /// \param CCLoc The location of the '::'.
3549 ///
3550 /// \param EnteringContext Whether we're entering the context of the
3551 /// nested-name-specifier.
3552 ///
3553 ///
3554 /// \returns true if an error occurred, false otherwise.
3556 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3557 TemplateTy TemplateName, SourceLocation TemplateNameLoc,
3558 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
3559 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
3560
3562 SourceLocation ColonColonLoc);
3563
3565 CXXScopeSpec &SS, const DeclSpec &DS, TypeSourceInfo *PatternLoc,
3566 SourceLocation ColonColonLoc, QualType Type);
3567
3568 /// IsInvalidUnlessNestedName - This method is used for error recovery
3569 /// purposes to determine whether the specified identifier is only valid as
3570 /// a nested name specifier, for example a namespace name. It is
3571 /// conservatively correct to always return false from this method.
3572 ///
3573 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
3575 NestedNameSpecInfo &IdInfo,
3576 bool EnteringContext);
3577
3578 /// Given a C++ nested-name-specifier, produce an annotation value
3579 /// that the parser can use later to reconstruct the given
3580 /// nested-name-specifier.
3581 ///
3582 /// \param SS A nested-name-specifier.
3583 ///
3584 /// \returns A pointer containing all of the information in the
3585 /// nested-name-specifier \p SS.
3587
3588 /// Given an annotation pointer for a nested-name-specifier, restore
3589 /// the nested-name-specifier structure.
3590 ///
3591 /// \param Annotation The annotation pointer, produced by
3592 /// \c SaveNestedNameSpecifierAnnotation().
3593 ///
3594 /// \param AnnotationRange The source range corresponding to the annotation.
3595 ///
3596 /// \param SS The nested-name-specifier that will be updated with the contents
3597 /// of the annotation pointer.
3598 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3599 SourceRange AnnotationRange,
3600 CXXScopeSpec &SS);
3601
3602 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3603
3604 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3605 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3606 /// After this method is called, according to [C++ 3.4.3p3], names should be
3607 /// looked up in the declarator-id's scope, until the declarator is parsed and
3608 /// ActOnCXXExitDeclaratorScope is called.
3609 /// The 'SS' should be a non-empty valid CXXScopeSpec.
3611
3612 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3613 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3614 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3615 /// Used to indicate that names should revert to being looked up in the
3616 /// defining scope.
3618
3619 ///@}
3620
3621 //
3622 //
3623 // -------------------------------------------------------------------------
3624 //
3625 //
3626
3627 /// \name Declarations
3628 /// Implementations are in SemaDecl.cpp
3629 ///@{
3630
3631public:
3633
3634 /// The index of the first InventedParameterInfo that refers to the current
3635 /// context.
3637
3638 /// A RAII object to temporarily push a declaration context.
3640 private:
3641 Sema &S;
3642 DeclContext *SavedContext;
3643 ProcessingContextState SavedContextState;
3644 QualType SavedCXXThisTypeOverride;
3645 unsigned SavedFunctionScopesStart;
3646 unsigned SavedInventedParameterInfosStart;
3647
3648 public:
3649 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
3650 : S(S), SavedContext(S.CurContext),
3651 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
3652 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
3653 SavedFunctionScopesStart(S.FunctionScopesStart),
3654 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
3655 assert(ContextToPush && "pushing null context");
3656 S.CurContext = ContextToPush;
3657 if (NewThisContext)
3658 S.CXXThisTypeOverride = QualType();
3659 // Any saved FunctionScopes do not refer to this context.
3660 S.FunctionScopesStart = S.FunctionScopes.size();
3661 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
3662 }
3663
3664 void pop() {
3665 if (!SavedContext)
3666 return;
3667 S.CurContext = SavedContext;
3668 S.DelayedDiagnostics.popUndelayed(SavedContextState);
3669 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
3670 S.FunctionScopesStart = SavedFunctionScopesStart;
3671 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
3672 SavedContext = nullptr;
3673 }
3674
3676 ContextRAII(const ContextRAII &) = delete;
3678 };
3679
3680 void DiagnoseInvalidJumps(Stmt *Body);
3681
3682 /// The function definitions which were renamed as part of typo-correction
3683 /// to match their respective declarations. We want to keep track of them
3684 /// to ensure that we don't emit a "redefinition" error if we encounter a
3685 /// correctly named definition after the renamed definition.
3687
3688 /// A cache of the flags available in enumerations with the flag_enum
3689 /// attribute.
3690 mutable llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
3691
3692 /// A cache of enumerator values for enums checked by -Wassign-enum.
3693 llvm::DenseMap<const EnumDecl *, llvm::SmallVector<llvm::APSInt>>
3695
3696 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
3697 /// declared. Rare. May alias another identifier, declared or undeclared.
3698 ///
3699 /// For aliases, the target identifier is used as a key for eventual
3700 /// processing when the target is declared. For the single-identifier form,
3701 /// the sole identifier is used as the key. Each entry is a `SetVector`
3702 /// (ordered by parse order) of aliases (identified by the alias name) in case
3703 /// of multiple aliases to the same undeclared identifier.
3704 llvm::MapVector<
3706 llvm::SetVector<
3708 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
3710
3711 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
3712 /// \#pragma redefine_extname before declared. Used in Solaris system headers
3713 /// to define functions that occur in multiple standards to call the version
3714 /// in the currently selected standard.
3715 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>
3717
3718 /// Set containing all typedefs that are likely unused.
3721
3722 /// Store UnusedLocalTypedefNameCandidates in \p Sorted in a deterministic
3723 /// order.
3726
3727 typedef LazyVector<const DeclaratorDecl *,
3730
3731 /// The set of file scoped decls seen so far that have not been used
3732 /// and must warn if not used. Only contains the first declaration.
3734
3736 2, 2>
3738
3739 /// All the tentative definitions encountered in the TU.
3741
3742 /// All the external declarations encoutered and used in the TU.
3744
3745 /// Generally null except when we temporarily switch decl contexts,
3746 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
3748
3749 /// Is the module scope we are in a C++ Header Unit?
3751 return ModuleScopes.empty() ? false
3752 : ModuleScopes.back().Module->isHeaderUnit();
3753 }
3754
3755 /// Get the module owning an entity.
3756 Module *getOwningModule(const Decl *Entity) {
3757 return Entity->getOwningModule();
3758 }
3759
3760 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
3761
3763 /// Returns the TypeDeclType for the given type declaration,
3764 /// as ASTContext::getTypeDeclType would, but
3765 /// performs the required semantic checks for name lookup of said entity.
3766 void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD,
3767 SourceLocation NameLoc);
3768
3769 /// If the identifier refers to a type name within this scope,
3770 /// return the declaration of that type.
3771 ///
3772 /// This routine performs ordinary name lookup of the identifier II
3773 /// within the given scope, with optional C++ scope specifier SS, to
3774 /// determine whether the name refers to a type. If so, returns an
3775 /// opaque pointer (actually a QualType) corresponding to that
3776 /// type. Otherwise, returns NULL.
3778 Scope *S, CXXScopeSpec *SS = nullptr,
3779 bool isClassName = false, bool HasTrailingDot = false,
3780 ParsedType ObjectType = nullptr,
3781 bool IsCtorOrDtorName = false,
3782 bool WantNontrivialTypeSourceInfo = false,
3783 bool IsClassTemplateDeductionContext = true,
3784 ImplicitTypenameContext AllowImplicitTypename =
3786 IdentifierInfo **CorrectedII = nullptr);
3787
3788 /// isTagName() - This method is called *for error recovery purposes only*
3789 /// to determine if the specified name is a valid tag name ("struct foo"). If
3790 /// so, this returns the TST for the tag corresponding to it (TST_enum,
3791 /// TST_union, TST_struct, TST_interface, TST_class). This is used to
3792 /// diagnose cases in C where the user forgot to specify the tag.
3794
3795 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
3796 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
3797 /// then downgrade the missing typename error to a warning.
3798 /// This is needed for MSVC compatibility; Example:
3799 /// @code
3800 /// template<class T> class A {
3801 /// public:
3802 /// typedef int TYPE;
3803 /// };
3804 /// template<class T> class B : public A<T> {
3805 /// public:
3806 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
3807 /// };
3808 /// @endcode
3809 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
3811 Scope *S, CXXScopeSpec *SS,
3812 ParsedType &SuggestedType,
3813 bool IsTemplateName = false);
3814
3815 /// Attempt to behave like MSVC in situations where lookup of an unqualified
3816 /// type name has failed in a dependent context. In these situations, we
3817 /// automatically form a DependentTypeName that will retry lookup in a related
3818 /// scope during instantiation.
3820 SourceLocation NameLoc,
3821 bool IsTemplateTypeArg);
3822
3823 class NameClassification {
3825 union {
3830 };
3831
3832 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
3833
3834 public:
3837
3840
3841 static NameClassification Error() {
3842 return NameClassification(NameClassificationKind::Error);
3843 }
3844
3845 static NameClassification Unknown() {
3846 return NameClassification(NameClassificationKind::Unknown);
3847 }
3848
3849 static NameClassification OverloadSet(ExprResult E) {
3850 NameClassification Result(NameClassificationKind::OverloadSet);
3851 Result.Expr = E;
3852 return Result;
3853 }
3854
3855 static NameClassification NonType(NamedDecl *D) {
3856 NameClassification Result(NameClassificationKind::NonType);
3857 Result.NonTypeDecl = D;
3858 return Result;
3859 }
3860
3861 static NameClassification UndeclaredNonType() {
3862 return NameClassification(NameClassificationKind::UndeclaredNonType);
3863 }
3864
3865 static NameClassification DependentNonType() {
3866 return NameClassification(NameClassificationKind::DependentNonType);
3867 }
3868
3869 static NameClassification TypeTemplate(TemplateName Name) {
3870 NameClassification Result(NameClassificationKind::TypeTemplate);
3871 Result.Template = Name;
3872 return Result;
3873 }
3874
3875 static NameClassification VarTemplate(TemplateName Name) {
3876 NameClassification Result(NameClassificationKind::VarTemplate);
3877 Result.Template = Name;
3878 return Result;
3879 }
3880
3881 static NameClassification FunctionTemplate(TemplateName Name) {
3883 Result.Template = Name;
3884 return Result;
3885 }
3886
3887 static NameClassification Concept(TemplateName Name) {
3888 NameClassification Result(NameClassificationKind::Concept);
3889 Result.Template = Name;
3890 return Result;
3891 }
3892
3893 static NameClassification UndeclaredTemplate(TemplateName Name) {
3895 Result.Template = Name;
3896 return Result;
3897 }
3898
3899 NameClassificationKind getKind() const { return Kind; }
3900
3903 return Expr;
3904 }
3905
3907 assert(Kind == NameClassificationKind::Type);
3908 return Type;
3909 }
3910
3912 assert(Kind == NameClassificationKind::NonType);
3913 return NonTypeDecl;
3914 }
3915
3924
3926 switch (Kind) {
3928 return TNK_Type_template;
3930 return TNK_Function_template;
3932 return TNK_Var_template;
3934 return TNK_Concept_template;
3937 default:
3938 llvm_unreachable("unsupported name classification.");
3939 }
3940 }
3941 };
3942
3943 /// Perform name lookup on the given name, classifying it based on
3944 /// the results of name lookup and the following token.
3945 ///
3946 /// This routine is used by the parser to resolve identifiers and help direct
3947 /// parsing. When the identifier cannot be found, this routine will attempt
3948 /// to correct the typo and classify based on the resulting name.
3949 ///
3950 /// \param S The scope in which we're performing name lookup.
3951 ///
3952 /// \param SS The nested-name-specifier that precedes the name.
3953 ///
3954 /// \param Name The identifier. If typo correction finds an alternative name,
3955 /// this pointer parameter will be updated accordingly.
3956 ///
3957 /// \param NameLoc The location of the identifier.
3958 ///
3959 /// \param NextToken The token following the identifier. Used to help
3960 /// disambiguate the name.
3961 ///
3962 /// \param CCC The correction callback, if typo correction is desired.
3963 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
3964 IdentifierInfo *&Name, SourceLocation NameLoc,
3965 const Token &NextToken,
3966 CorrectionCandidateCallback *CCC = nullptr);
3967
3968 /// Act on the result of classifying a name as an undeclared (ADL-only)
3969 /// non-type declaration.
3971 SourceLocation NameLoc);
3972 /// Act on the result of classifying a name as an undeclared member of a
3973 /// dependent base class.
3975 IdentifierInfo *Name,
3976 SourceLocation NameLoc,
3977 bool IsAddressOfOperand);
3978 /// Act on the result of classifying a name as a specific non-type
3979 /// declaration.
3982 SourceLocation NameLoc,
3983 const Token &NextToken);
3984 /// Act on the result of classifying a name as an overload set.
3986
3987 /// Describes the detailed kind of a template name. Used in diagnostics.
3999
4000 /// Determine whether it's plausible that E was intended to be a
4001 /// template-name.
4003 if (!getLangOpts().CPlusPlus || E.isInvalid())
4004 return false;
4005 Dependent = false;
4006 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
4007 return !DRE->hasExplicitTemplateArgs();
4008 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
4009 return !ME->hasExplicitTemplateArgs();
4010 Dependent = true;
4011 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
4012 return !DSDRE->hasExplicitTemplateArgs();
4013 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
4014 return !DSME->hasExplicitTemplateArgs();
4015 // Any additional cases recognized here should also be handled by
4016 // diagnoseExprIntendedAsTemplateName.
4017 return false;
4018 }
4019
4020 void warnOnReservedIdentifier(const NamedDecl *D);
4022
4023 void ProcessPragmaExport(DeclaratorDecl *newDecl);
4024
4026
4028 MultiTemplateParamsArg TemplateParameterLists);
4029
4030 /// Attempt to fold a variable-sized type to a constant-sized type, returning
4031 /// true if we were successful.
4033 SourceLocation Loc,
4034 unsigned FailedFoldDiagID);
4035
4036 /// Register the given locally-scoped extern "C" declaration so
4037 /// that it can be found later for redeclarations. We include any extern "C"
4038 /// declaration that is not visible in the translation unit here, not just
4039 /// function-scope declarations.
4041
4042 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4043 /// If T is the name of a class, then each of the following shall have a
4044 /// name different from T:
4045 /// - every static data member of class T;
4046 /// - every member function of class T
4047 /// - every member of class T that is itself a type;
4048 /// \returns true if the declaration name violates these rules.
4050
4051 /// Diagnose a declaration whose declarator-id has the given
4052 /// nested-name-specifier.
4053 ///
4054 /// \param SS The nested-name-specifier of the declarator-id.
4055 ///
4056 /// \param DC The declaration context to which the nested-name-specifier
4057 /// resolves.
4058 ///
4059 /// \param Name The name of the entity being declared.
4060 ///
4061 /// \param Loc The location of the name of the entity being declared.
4062 ///
4063 /// \param IsMemberSpecialization Whether we are declaring a member
4064 /// specialization.
4065 ///
4066 /// \param TemplateId The template-id, if any.
4067 ///
4068 /// \returns true if we cannot safely recover from this error, false
4069 /// otherwise.
4072 TemplateIdAnnotation *TemplateId,
4073 bool IsMemberSpecialization);
4074
4076
4077 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
4078
4080 unsigned &IntVal);
4081
4082 /// Diagnose function specifiers on a declaration of an identifier that
4083 /// does not identify a function.
4084 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
4085
4086 /// Return the declaration shadowed by the given typedef \p D, or null
4087 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
4089 const LookupResult &R);
4090
4091 /// Return the declaration shadowed by the given variable \p D, or null
4092 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
4094
4095 /// Return the declaration shadowed by the given variable \p D, or null
4096 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
4098 const LookupResult &R);
4099 /// Diagnose variable or built-in function shadowing. Implements
4100 /// -Wshadow.
4101 ///
4102 /// This method is called whenever a VarDecl is added to a "useful"
4103 /// scope.
4104 ///
4105 /// \param ShadowedDecl the declaration that is shadowed by the given variable
4106 /// \param R the lookup of the name
4107 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
4108 const LookupResult &R);
4109
4110 /// Check -Wshadow without the advantage of a previous lookup.
4111 void CheckShadow(Scope *S, VarDecl *D);
4112
4113 /// Warn if 'E', which is an expression that is about to be modified, refers
4114 /// to a shadowing declaration.
4116
4117 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
4118 /// when these variables are captured by the lambda.
4120
4121 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
4122 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4123 TypedefNameDecl *NewTD);
4126 TypeSourceInfo *TInfo,
4128
4129 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4130 /// declares a typedef-name, either using the 'typedef' type specifier or via
4131 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4135 TypeSourceInfo *TInfo,
4137 MultiTemplateParamsArg TemplateParamLists,
4138 bool &AddToScope,
4140
4141private:
4142 // Perform a check on an AsmLabel to verify its consistency and emit
4143 // diagnostics in case of an error.
4144 void CheckAsmLabel(Scope *S, Expr *AsmLabelExpr, StorageClass SC,
4145 TypeSourceInfo *TInfo, VarDecl *);
4146
4147public:
4148 /// Perform semantic checking on a newly-created variable
4149 /// declaration.
4150 ///
4151 /// This routine performs all of the type-checking required for a
4152 /// variable declaration once it has been built. It is used both to
4153 /// check variables after they have been parsed and their declarators
4154 /// have been translated into a declaration, and to check variables
4155 /// that have been instantiated from a template.
4156 ///
4157 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4158 ///
4159 /// Returns true if the variable declaration is a redeclaration.
4160 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
4161 void CheckVariableDeclarationType(VarDecl *NewVD);
4162 void CheckCompleteVariableDeclaration(VarDecl *VD);
4163
4164 NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4165 TypeSourceInfo *TInfo,
4166 LookupResult &Previous,
4167 MultiTemplateParamsArg TemplateParamLists,
4168 bool &AddToScope);
4169
4170 /// Attach the ABI tag a standard calling convention variant requires, as an
4171 /// implicit abi_tag attribute. Call this once the function type is final.
4172 void addImplicitCallingConvAbiTag(FunctionDecl *FD);
4173
4174 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4175 /// and if so, check that it's a valid override and remember it.
4176 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
4177
4178 /// Perform semantic checking of a new function declaration.
4179 ///
4180 /// Performs semantic analysis of the new function declaration
4181 /// NewFD. This routine performs all semantic checking that does not
4182 /// require the actual declarator involved in the declaration, and is
4183 /// used both for the declaration of functions as they are parsed
4184 /// (called via ActOnDeclarator) and for the declaration of functions
4185 /// that have been instantiated via C++ template instantiation (called
4186 /// via InstantiateDecl).
4187 ///
4188 /// \param IsMemberSpecialization whether this new function declaration is
4189 /// a member specialization (that replaces any definition provided by the
4190 /// previous declaration).
4191 ///
4192 /// This sets NewFD->isInvalidDecl() to true if there was an error.
4193 ///
4194 /// \returns true if the function declaration is a redeclaration.
4195 bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
4196 LookupResult &Previous,
4197 bool IsMemberSpecialization, bool DeclIsDefn);
4198
4199 /// Checks if the new declaration declared in dependent context must be
4200 /// put in the same redeclaration chain as the specified declaration.
4201 ///
4202 /// \param D Declaration that is checked.
4203 /// \param PrevDecl Previous declaration found with proper lookup method for
4204 /// the same declaration name.
4205 /// \returns True if D must be added to the redeclaration chain which PrevDecl
4206 /// belongs to.
4207 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
4208
4209 /// Determines if we can perform a correct type check for \p D as a
4210 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
4211 /// best-effort check.
4212 ///
4213 /// \param NewD The new declaration.
4214 /// \param OldD The old declaration.
4215 /// \param NewT The portion of the type of the new declaration to check.
4216 /// \param OldT The portion of the type of the old declaration to check.
4217 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
4218 QualType NewT, QualType OldT);
4219 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
4220 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
4221
4222 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
4223 /// containing class. Otherwise it will return implicit SectionAttr if the
4224 /// function is a definition and there is an active value on CodeSegStack
4225 /// (from the current #pragma code-seg value).
4226 ///
4227 /// \param FD Function being declared.
4228 /// \param IsDefinition Whether it is a definition or just a declaration.
4229 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
4230 /// nullptr if no attribute should be added.
4231 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
4232 bool IsDefinition);
4233
4234 /// Common checks for a parameter-declaration that should apply to both
4235 /// function parameters and non-type template parameters.
4236 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
4237
4238 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4239 /// to introduce parameters into function prototype scope.
4240 Decl *ActOnParamDeclarator(Scope *S, Declarator &D,
4241 SourceLocation ExplicitThisLoc = {});
4242
4243 /// Synthesizes a variable for a parameter arising from a
4244 /// typedef.
4245 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
4246 QualType T);
4247 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
4248 SourceLocation NameLoc,
4249 const IdentifierInfo *Name, QualType T,
4250 TypeSourceInfo *TSInfo, StorageClass SC);
4251
4252 /// Emit diagnostics if the initializer or any of its explicit or
4253 /// implicitly-generated subexpressions require copying or
4254 /// default-initializing a type that is or contains a C union type that is
4255 /// non-trivial to copy or default-initialize.
4256 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
4257
4258 // These flags are passed to checkNonTrivialCUnion.
4264
4265 /// Emit diagnostics if a non-trivial C union type or a struct that contains
4266 /// a non-trivial C union is used in an invalid context.
4268 NonTrivialCUnionContext UseContext,
4269 unsigned NonTrivialKind);
4270
4271 /// Certain globally-unique variables might be accidentally duplicated if
4272 /// built into multiple shared libraries with hidden visibility. This can
4273 /// cause problems if the variable is mutable, its initialization is
4274 /// effectful, or its address is taken.
4277
4278 /// AddInitializerToDecl - Adds the initializer Init to the
4279 /// declaration dcl. If DirectInit is true, this is C++ direct
4280 /// initialization rather than copy initialization.
4281 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
4282 void ActOnUninitializedDecl(Decl *dcl);
4283
4284 /// ActOnInitializerError - Given that there was an error parsing an
4285 /// initializer for the given declaration, try to at least re-establish
4286 /// invariants such as whether a variable's type is either dependent or
4287 /// complete.
4288 void ActOnInitializerError(Decl *Dcl);
4289
4290 void ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt);
4292 IdentifierInfo *Ident,
4293 ParsedAttributes &Attrs);
4294
4295 /// Check if VD needs to be dllexport/dllimport due to being in a
4296 /// dllexport/import function.
4299
4300 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
4301 /// any semantic actions necessary after any initializer has been attached.
4302 void FinalizeDeclaration(Decl *D);
4304 ArrayRef<Decl *> Group);
4305
4306 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
4307 /// group, performing any necessary semantic checking.
4309
4310 /// Should be called on all declarations that might have attached
4311 /// documentation comments.
4312 void ActOnDocumentableDecl(Decl *D);
4314
4315 enum class FnBodyKind {
4316 /// C++26 [dcl.fct.def.general]p1
4317 /// function-body:
4318 /// ctor-initializer[opt] compound-statement
4319 /// function-try-block
4321 /// = default ;
4323 /// deleted-function-body
4324 ///
4325 /// deleted-function-body:
4326 /// = delete ;
4327 /// = delete ( unevaluated-string ) ;
4329 };
4330
4332 SourceLocation LocAfterDecls);
4334 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
4335 SkipBodyInfo *SkipBody = nullptr);
4337 MultiTemplateParamsArg TemplateParamLists,
4338 SkipBodyInfo *SkipBody = nullptr,
4339 FnBodyKind BodyKind = FnBodyKind::Other);
4341 SkipBodyInfo *SkipBody = nullptr,
4342 FnBodyKind BodyKind = FnBodyKind::Other);
4344
4345 /// Determine whether we can delay parsing the body of a function or
4346 /// function template until it is used, assuming we don't care about emitting
4347 /// code for that function.
4348 ///
4349 /// This will be \c false if we may need the body of the function in the
4350 /// middle of parsing an expression (where it's impractical to switch to
4351 /// parsing a different function), for instance, if it's constexpr in C++11
4352 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
4353 bool canDelayFunctionBody(const Declarator &D);
4354
4355 /// Determine whether we can skip parsing the body of a function
4356 /// definition, assuming we don't care about analyzing its body or emitting
4357 /// code for that function.
4358 ///
4359 /// This will be \c false only if we may need the body of the function in
4360 /// order to parse the rest of the program (for instance, if it is
4361 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
4362 bool canSkipFunctionBody(Decl *D);
4363
4364 /// Given the set of return statements within a function body,
4365 /// compute the variables that are subject to the named return value
4366 /// optimization.
4367 ///
4368 /// Each of the variables that is subject to the named return value
4369 /// optimization will be marked as NRVO variables in the AST, and any
4370 /// return statement that has a marked NRVO variable as its NRVO candidate can
4371 /// use the named return value optimization.
4372 ///
4373 /// This function applies a very simplistic algorithm for NRVO: if every
4374 /// return statement in the scope of a variable has the same NRVO candidate,
4375 /// that candidate is an NRVO variable.
4377
4378 /// Performs semantic analysis at the end of a function body.
4379 ///
4380 /// \param RetainFunctionScopeInfo If \c true, the client is responsible for
4381 /// releasing the associated \p FunctionScopeInfo. This is useful when
4382 /// building e.g. LambdaExprs.
4384 bool IsInstantiation = false,
4385 bool RetainFunctionScopeInfo = false);
4388
4389 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
4390 /// attribute for which parsing is delayed.
4392
4393 /// Diagnose any unused parameters in the given sequence of
4394 /// ParmVarDecl pointers.
4396
4397 /// Diagnose whether the size of parameters or return value of a
4398 /// function or obj-c method definition is pass-by-value and larger than a
4399 /// specified threshold.
4400 void
4402 QualType ReturnTy, NamedDecl *D);
4403
4405 SourceLocation RParenLoc);
4406
4409
4410 void ActOnPopScope(SourceLocation Loc, Scope *S);
4411
4412 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4413 /// no declarator (e.g. "struct foo;") is parsed.
4415 const ParsedAttributesView &DeclAttrs,
4416 RecordDecl *&AnonRecord);
4417
4418 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4419 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4420 /// parameters to cope with template friend declarations.
4422 const ParsedAttributesView &DeclAttrs,
4423 MultiTemplateParamsArg TemplateParams,
4424 bool IsExplicitInstantiation,
4425 RecordDecl *&AnonRecord,
4426 SourceLocation EllipsisLoc = {});
4427
4428 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4429 /// anonymous structure or union. Anonymous unions are a C++ feature
4430 /// (C++ [class.union]) and a C11 feature; anonymous structures
4431 /// are a C11 feature and GNU C++ extension.
4432 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS,
4433 RecordDecl *Record,
4434 const PrintingPolicy &Policy);
4435
4436 /// Called once it is known whether
4437 /// a tag declaration is an anonymous union or struct.
4439
4440 /// Emit diagnostic warnings for placeholder members.
4441 /// We can only do that after the class is fully constructed,
4442 /// as anonymous union/structs can insert placeholders
4443 /// in their parent scope (which might be a Record).
4445
4446 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4447 /// Microsoft C anonymous structure.
4448 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4449 /// Example:
4450 ///
4451 /// struct A { int a; };
4452 /// struct B { struct A; int b; };
4453 ///
4454 /// void foo() {
4455 /// B var;
4456 /// var.a = 3;
4457 /// }
4458 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4459 RecordDecl *Record);
4460
4461 /// Given a non-tag type declaration, returns an enum useful for indicating
4462 /// what kind of non-tag type this is.
4463 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
4464
4465 /// Determine whether a tag with a given kind is acceptable
4466 /// as a redeclaration of the given tag declaration.
4467 ///
4468 /// \returns true if the new tag kind is acceptable, false otherwise.
4470 bool isDefinition, SourceLocation NewTagLoc,
4471 const IdentifierInfo *Name);
4472
4473 /// This is invoked when we see 'struct foo' or 'struct {'. In the
4474 /// former case, Name will be non-null. In the later case, Name will be null.
4475 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is
4476 /// a reference/declaration/definition of a tag.
4477 ///
4478 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
4479 /// trailing-type-specifier) other than one in an alias-declaration.
4480 ///
4481 /// \param SkipBody If non-null, will be set to indicate if the caller should
4482 /// skip the definition of this tag and treat it as if it were a declaration.
4483 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4484 SourceLocation KWLoc, CXXScopeSpec &SS,
4485 IdentifierInfo *Name, SourceLocation NameLoc,
4486 const ParsedAttributesView &Attr, AccessSpecifier AS,
4487 SourceLocation ModulePrivateLoc,
4488 MultiTemplateParamsArg TemplateParameterLists,
4489 bool &OwnedDecl, bool &IsDependent,
4490 SourceLocation ScopedEnumKWLoc,
4491 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
4492 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
4493 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
4494
4495 /// ActOnField - Each field of a C struct/union is passed into this in order
4496 /// to create a FieldDecl object for it.
4497 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
4498 Declarator &D, Expr *BitfieldWidth);
4499
4500 /// HandleField - Analyze a field of a C struct or a C++ data member.
4501 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
4502 Declarator &D, Expr *BitfieldWidth,
4503 InClassInitStyle InitStyle, AccessSpecifier AS);
4504
4505 /// Build a new FieldDecl and check its well-formedness.
4506 ///
4507 /// This routine builds a new FieldDecl given the fields name, type,
4508 /// record, etc. \p PrevDecl should refer to any previous declaration
4509 /// with the same name and in the same scope as the field to be
4510 /// created.
4511 ///
4512 /// \returns a new FieldDecl.
4513 ///
4514 /// \todo The Declarator argument is a hack. It will be removed once
4515 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
4516 TypeSourceInfo *TInfo, RecordDecl *Record,
4517 SourceLocation Loc, bool Mutable,
4518 Expr *BitfieldWidth, InClassInitStyle InitStyle,
4519 SourceLocation TSSL, AccessSpecifier AS,
4520 NamedDecl *PrevDecl, Declarator *D = nullptr);
4521
4523
4524 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
4525 /// class and class extensions. For every class \@interface and class
4526 /// extension \@interface, if the last ivar is a bitfield of any type,
4527 /// then add an implicit `char :0` ivar to the end of that interface.
4528 void ActOnLastBitfield(SourceLocation DeclStart,
4529 SmallVectorImpl<Decl *> &AllIvarDecls);
4530
4531 // This is used for both record definitions and ObjC interface declarations.
4532 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
4533 ArrayRef<Decl *> Fields, SourceLocation LBrac,
4534 SourceLocation RBrac, const ParsedAttributesView &AttrList);
4535
4536 /// ActOnTagStartDefinition - Invoked when we have entered the
4537 /// scope of a tag's definition (e.g., for an enumeration, class,
4538 /// struct, or union).
4539 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
4540
4541 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
4542 /// Differently from C++, actually parse the body and reject / error out
4543 /// in case of a structural mismatch.
4544 bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody);
4545
4547
4548 /// Invoked when we enter a tag definition that we're skipping.
4550
4551 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
4552 /// C++ record definition's base-specifiers clause and are starting its
4553 /// member declarations.
4555 SourceLocation FinalLoc,
4556 bool IsFinalSpelledSealed,
4557 bool IsAbstract,
4558 SourceLocation LBraceLoc);
4559
4560 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
4561 /// the definition of a tag (enumeration, class, struct, or union).
4563 SourceRange BraceRange);
4564
4567
4569
4570 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
4571 /// error parsing the definition of a tag.
4573
4575 EnumConstantDecl *LastEnumConst,
4576 SourceLocation IdLoc, IdentifierInfo *Id,
4577 Expr *val);
4578
4579 /// Check that this is a valid underlying type for an enum declaration.
4581
4582 /// Check whether this is a valid redeclaration of a previous enumeration.
4583 /// \return true if the redeclaration was invalid.
4584 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
4585 QualType EnumUnderlyingTy, bool IsFixed,
4586 const EnumDecl *Prev);
4587
4588 /// Determine whether the body of an anonymous enumeration should be skipped.
4589 /// \param II The name of the first enumerator.
4591 SourceLocation IILoc);
4592
4593 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
4594 SourceLocation IdLoc, IdentifierInfo *Id,
4595 const ParsedAttributesView &Attrs,
4596 SourceLocation EqualLoc, Expr *Val,
4597 SkipBodyInfo *SkipBody = nullptr);
4598 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
4599 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
4600 const ParsedAttributesView &Attr);
4601
4602 /// Set the current declaration context until it gets popped.
4603 void PushDeclContext(Scope *S, DeclContext *DC);
4604 void PopDeclContext();
4605
4606 /// EnterDeclaratorContext - Used when we must lookup names in the context
4607 /// of a declarator's nested name specifier.
4610
4611 /// Enter a template parameter scope, after it's been associated with a
4612 /// particular DeclContext. Causes lookup within the scope to chain through
4613 /// enclosing contexts in the correct order.
4615
4616 /// Push the parameters of D, which must be a function, into scope.
4618
4619 /// Add \p Params to scope, so a late-parsed attribute can name them.
4622 /// Undo the above, for when \p S outlives the attribute so no scope pop
4623 /// removes them.
4627
4628 /// Add this decl to the scope shadowed decl chains.
4629 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
4630
4631 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
4632 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
4633 /// true if 'D' belongs to the given declaration context.
4634 ///
4635 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
4636 /// enclosing namespace set of the context, rather than contained
4637 /// directly within it.
4638 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
4639 bool AllowInlineNamespace = false) const;
4640
4641 /// Determine whether a tag-like declaration found by lookup can be
4642 /// redeclared in the given scope. If lookup found a using-shadow, also
4643 /// consider the scope of the declaration named by the using-shadow.
4645 Scope *S = nullptr,
4646 bool AllowInlineNamespace = false) const;
4647
4648 /// Finds the scope corresponding to the given decl context, if it
4649 /// happens to be an enclosing scope. Otherwise return NULL.
4651
4652 /// Subroutines of ActOnDeclarator().
4654 TypeSourceInfo *TInfo);
4656
4657 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
4659 NamedDecl *New, Decl *Old,
4661
4662 /// CheckAttributesOnDeducedType - Calls Sema functions for attributes that
4663 /// requires the type to be deduced.
4665
4666 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
4667 /// same name and scope as a previous declaration 'Old'. Figure out
4668 /// how to resolve this situation, merging decls or emitting
4669 /// diagnostics as appropriate. If there was an error, set New to be invalid.
4671 LookupResult &OldDecls);
4672
4673 /// CleanupMergedEnum - We have just merged the decl 'New' by making another
4674 /// definition visible.
4675 /// This method performs any necessary cleanup on the parser state to discard
4676 /// child nodes from newly parsed decl we are retiring.
4677 void CleanupMergedEnum(Scope *S, Decl *New);
4678
4679 /// MergeFunctionDecl - We just parsed a function 'New' from
4680 /// declarator D which has the same name and scope as a previous
4681 /// declaration 'Old'. Figure out how to resolve this situation,
4682 /// merging decls or emitting diagnostics as appropriate.
4683 ///
4684 /// In C++, New and Old must be declarations that are not
4685 /// overloaded. Use IsOverload to determine whether New and Old are
4686 /// overloaded, and to select the Old declaration that New should be
4687 /// merged with.
4688 ///
4689 /// Returns true if there was an error, false otherwise.
4691 bool MergeTypeWithOld, bool NewDeclIsDefn);
4692
4693 /// Completes the merge of two function declarations that are
4694 /// known to be compatible.
4695 ///
4696 /// This routine handles the merging of attributes and other
4697 /// properties of function declarations from the old declaration to
4698 /// the new declaration, once we know that New is in fact a
4699 /// redeclaration of Old.
4700 ///
4701 /// \returns false
4703 Scope *S, bool MergeTypeWithOld);
4705
4706 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4707 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4708 /// situation, merging decls or emitting diagnostics as appropriate.
4709 ///
4710 /// Tentative definition rules (C99 6.9.2p2) are checked by
4711 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4712 /// definitions here, since the initializer hasn't been attached.
4714
4715 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4716 /// scope as a previous declaration 'Old'. Figure out how to merge their
4717 /// types, emitting diagnostics as appropriate.
4718 ///
4719 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call
4720 /// back to here in AddInitializerToDecl. We can't check them before the
4721 /// initializer is attached.
4722 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
4723
4724 /// We've just determined that \p Old and \p New both appear to be definitions
4725 /// of the same variable. Either diagnose or fix the problem.
4726 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
4728
4729 /// Filters out lookup results that don't fall within the given scope
4730 /// as determined by isDeclInScope.
4732 bool ConsiderLinkage, bool AllowInlineNamespace);
4733
4734 /// We've determined that \p New is a redeclaration of \p Old. Check that they
4735 /// have compatible owning modules.
4737
4738 /// [module.interface]p6:
4739 /// A redeclaration of an entity X is implicitly exported if X was introduced
4740 /// by an exported declaration; otherwise it shall not be exported.
4742
4743 /// A wrapper function for checking the semantic restrictions of
4744 /// a redeclaration within a module.
4746
4747 /// Check the redefinition in C++20 Modules.
4748 ///
4749 /// [basic.def.odr]p14:
4750 /// For any definable item D with definitions in multiple translation units,
4751 /// - if D is a non-inline non-templated function or variable, or
4752 /// - if the definitions in different translation units do not satisfy the
4753 /// following requirements,
4754 /// the program is ill-formed; a diagnostic is required only if the
4755 /// definable item is attached to a named module and a prior definition is
4756 /// reachable at the point where a later definition occurs.
4757 /// - Each such definition shall not be attached to a named module
4758 /// ([module.unit]).
4759 /// - Each such definition shall consist of the same sequence of tokens, ...
4760 /// ...
4761 ///
4762 /// Return true if the redefinition is not allowed. Return false otherwise.
4763 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
4764
4766
4767 /// If it's a file scoped decl that must warn if not used, keep track
4768 /// of it.
4770
4771 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
4773
4776 DiagReceiverTy DiagReceiver);
4777 void DiagnoseUnusedDecl(const NamedDecl *ND);
4778
4779 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
4780 /// unless they are marked attr(unused).
4781 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
4782
4783 /// If VD is set but not otherwise used, diagnose, for a parameter or a
4784 /// variable.
4785 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
4786
4787 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
4788 /// from S, where a non-field would be declared. This routine copes
4789 /// with the difference between C and C++ scoping rules in structs and
4790 /// unions. For example, the following code is well-formed in C but
4791 /// ill-formed in C++:
4792 /// @code
4793 /// struct S6 {
4794 /// enum { BAR } e;
4795 /// };
4796 ///
4797 /// void test_S6() {
4798 /// struct S6 a;
4799 /// a.e = BAR;
4800 /// }
4801 /// @endcode
4802 /// For the declaration of BAR, this routine will return a different
4803 /// scope. The scope S will be the scope of the unnamed enumeration
4804 /// within S6. In C++, this routine will return the scope associated
4805 /// with S6, because the enumeration's scope is a transparent
4806 /// context but structures can contain non-field names. In C, this
4807 /// routine will return the translation unit scope, since the
4808 /// enumeration's scope is a transparent context and structures cannot
4809 /// contain non-field names.
4811
4813 SourceLocation Loc);
4814
4815 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
4816 /// file scope. lazily create a decl for it. ForRedeclaration is true
4817 /// if we're creating this built-in in anticipation of redeclaring the
4818 /// built-in.
4819 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S,
4820 bool ForRedeclaration, SourceLocation Loc);
4821
4822 /// Get the outermost AttributedType node that sets a calling convention.
4823 /// Valid types should not have multiple attributes with different CCs.
4824 const AttributedType *getCallingConvAttributedType(QualType T) const;
4825
4826 /// GetNameForDeclarator - Determine the full declaration name for the
4827 /// given Declarator.
4829
4830 /// Retrieves the declaration name from a parsed unqualified-id.
4832
4833 /// ParsingInitForAutoVars - a set of declarations with auto types for which
4834 /// we are currently parsing the initializer.
4836
4837 /// Look for a locally scoped extern "C" declaration by the given name.
4839
4841
4842 /// Adjust the \c DeclContext for a function or variable that might be a
4843 /// function-local external declaration.
4845
4847
4848 /// Checks if the variant/multiversion functions are compatible.
4850 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
4851 const PartialDiagnostic &NoProtoDiagID,
4852 const PartialDiagnosticAt &NoteCausedDiagIDAt,
4853 const PartialDiagnosticAt &NoSupportDiagIDAt,
4854 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
4855 bool ConstexprSupported, bool CLinkageMayDiffer);
4856
4857 /// type checking declaration initializers (C99 6.7.8)
4859 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
4860
4863 SourceRange Range, bool DirectInit,
4864 Expr *Init);
4865
4867 Expr *Init);
4868
4870
4871 // Heuristically tells if the function is `get_return_object` member of a
4872 // coroutine promise_type by matching the function name.
4873 static bool CanBeGetReturnObject(const FunctionDecl *FD);
4874 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
4875
4876 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4877 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4879 Scope *S);
4880
4881 /// If this function is a C++ replaceable global allocation function
4882 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
4883 /// adds any function attributes that we know a priori based on the standard.
4884 ///
4885 /// We need to check for duplicate attributes both here and where user-written
4886 /// attributes are applied to declarations.
4888 FunctionDecl *FD);
4889
4890 /// Adds any function attributes that we know a priori based on
4891 /// the declaration of this function.
4892 ///
4893 /// These attributes can apply both to implicitly-declared builtins
4894 /// (like __builtin___printf_chk) or to library-declared functions
4895 /// like NSLog or printf.
4896 ///
4897 /// We need to check for duplicate attributes both here and where user-written
4898 /// attributes are applied to declarations.
4900
4901 /// VerifyBitField - verifies that a bit field expression is an ICE and has
4902 /// the correct width, and that the field type is valid.
4903 /// Returns false on success.
4905 const IdentifierInfo *FieldName, QualType FieldTy,
4906 bool IsMsStruct, Expr *BitWidth);
4907
4908 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
4909 /// enum. If AllowMask is true, then we also allow the complement of a valid
4910 /// value, to be used as a mask.
4911 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
4912 bool AllowMask) const;
4913
4914 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
4915 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
4916 SourceLocation WeakNameLoc);
4917
4918 /// ActOnPragmaRedefineExtname - Called on well formed
4919 /// \#pragma redefine_extname oldname newname.
4921 IdentifierInfo *AliasName,
4922 SourceLocation PragmaLoc,
4923 SourceLocation WeakNameLoc,
4924 SourceLocation AliasNameLoc);
4925
4926 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
4927 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
4928 SourceLocation PragmaLoc,
4929 SourceLocation WeakNameLoc,
4930 SourceLocation AliasNameLoc);
4931
4932 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4935 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4936 OMPDiscarded, // Discarded due to OpenMP hostness
4937 TemplateDiscarded, // Discarded due to uninstantiated templates
4939 };
4940 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4941 bool Final = false);
4942
4943 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4945
4946 /// Function or variable declarations to be checked for whether the deferred
4947 /// diagnostics should be emitted.
4949
4950private:
4951 /// Map of current shadowing declarations to shadowed declarations. Warn if
4952 /// it looks like the user is trying to modify the shadowing declaration.
4953 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
4954
4955 // We need this to handle
4956 //
4957 // typedef struct {
4958 // void *foo() { return 0; }
4959 // } A;
4960 //
4961 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
4962 // for example. If 'A', foo will have external linkage. If we have '*A',
4963 // foo will have no linkage. Since we can't know until we get to the end
4964 // of the typedef, this function finds out if D might have non-external
4965 // linkage. Callers should verify at the end of the TU if it D has external
4966 // linkage or not.
4967 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
4968
4969#include "clang/Sema/AttrIsTypeDependent.inc"
4970
4971 ///@}
4972
4973 //
4974 //
4975 // -------------------------------------------------------------------------
4976 //
4977 //
4978
4979 /// \name Declaration Attribute Handling
4980 /// Implementations are in SemaDeclAttr.cpp
4981 ///@{
4982
4983public:
4984 /// Describes the kind of priority given to an availability attribute.
4985 ///
4986 /// The sum of priorities deteremines the final priority of the attribute.
4987 /// The final priority determines how the attribute will be merged.
4988 /// An attribute with a lower priority will always remove higher priority
4989 /// attributes for the specified platform when it is being applied. An
4990 /// attribute with a higher priority will not be applied if the declaration
4991 /// already has an availability attribute with a lower priority for the
4992 /// specified platform. The final prirority values are not expected to match
4993 /// the values in this enumeration, but instead should be treated as a plain
4994 /// integer value. This enumeration just names the priority weights that are
4995 /// used to calculate that final vaue.
4997 /// The availability attribute was specified explicitly next to the
4998 /// declaration.
5000
5001 /// The availability attribute was applied using '#pragma clang attribute'.
5003
5004 /// The availability attribute for a specific platform was inferred from
5005 /// an availability attribute for another platform.
5007
5008 /// The availability attribute was inferred from an 'anyAppleOS'
5009 /// availability attribute.
5011
5012 /// The availability attribute was inferred from an 'anyAppleOS'
5013 /// availability attribute that was applied using '#pragma clang attribute'.
5014 /// This has the lowest priority.
5016 };
5017
5018 /// Describes the reason a calling convention specification was ignored, used
5019 /// for diagnostics.
5026
5027 /// A helper function to provide Attribute Location for the Attr types
5028 /// AND the ParsedAttr.
5029 template <typename AttrInfo>
5030 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
5031 getAttrLoc(const AttrInfo &AL) {
5032 return AL.getLocation();
5033 }
5035
5036 /// If Expr is a valid integer constant, get the value of the integer
5037 /// expression and return success or failure. May output an error.
5038 ///
5039 /// Negative argument is implicitly converted to unsigned, unless
5040 /// \p StrictlyUnsigned is true.
5041 template <typename AttrInfo>
5042 bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val,
5043 unsigned Idx = UINT_MAX,
5044 bool StrictlyUnsigned = false) {
5045 std::optional<llvm::APSInt> I = llvm::APSInt(32);
5046 if (Expr->isTypeDependent() ||
5048 if (Idx != UINT_MAX)
5049 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5050 << &AI << Idx << AANT_ArgumentIntegerConstant
5051 << Expr->getSourceRange();
5052 else
5053 Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
5055 return false;
5056 }
5057
5058 if (!I->isIntN(32)) {
5059 Diag(Expr->getExprLoc(), diag::err_ice_too_large)
5060 << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
5061 return false;
5062 }
5063
5064 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
5065 Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
5066 << &AI << /*non-negative*/ 1;
5067 return false;
5068 }
5069
5070 Val = (uint32_t)I->getZExtValue();
5071 return true;
5072 }
5073
5074 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
5075 /// \#pragma weak during processing of other Decls.
5076 /// I couldn't figure out a clean way to generate these in-line, so
5077 /// we store them here and handle separately -- which is a hack.
5078 /// It would be best to refactor this.
5080
5081 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
5083
5085 2, 2>
5087
5088 /// ExtVectorDecls - This is a list all the extended vector types. This allows
5089 /// us to associate a raw vector type with one of the ext_vector type names.
5090 /// This is only necessary for issuing pretty diagnostics.
5092
5093 /// Check if the argument \p E is a ASCII string literal. If not emit an error
5094 /// and return false, otherwise set \p Str to the value of the string literal
5095 /// and return true.
5097 const Expr *E, StringRef &Str,
5098 SourceLocation *ArgLocation = nullptr);
5099
5100 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
5101 /// If not emit an error and return false. If the argument is an identifier it
5102 /// will emit an error with a fixit hint and treat it as if it was a string
5103 /// literal.
5104 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
5105 StringRef &Str,
5106 SourceLocation *ArgLocation = nullptr);
5107
5108 /// Determine if type T is a valid subject for a nonnull and similar
5109 /// attributes. Dependent types are considered valid so they can be checked
5110 /// during instantiation time. By default, we look through references (the
5111 /// behavior used by nonnull), but if the second parameter is true, then we
5112 /// treat a reference type as valid.
5113 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
5114
5115 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
5116 /// declaration.
5117 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5118 Expr *OE);
5119
5120 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
5121 /// declaration.
5122 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
5123 Expr *ParamExpr);
5124
5125 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
5126 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
5127
5128 AvailabilityAttr *
5130 const IdentifierInfo *Platform, bool Implicit,
5131 VersionTuple Introduced, VersionTuple Deprecated,
5132 VersionTuple Obsoleted, bool IsUnavailable,
5133 StringRef Message, bool IsStrict, StringRef Replacement,
5134 AvailabilityMergeKind AMK, int Priority,
5135 const IdentifierInfo *IIEnvironment,
5136 const IdentifierInfo *InferredPlatformII = nullptr);
5137
5138 AvailabilityAttr *mergeAndInferAvailabilityAttr(
5139 NamedDecl *D, const AttributeCommonInfo &CI,
5140 const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced,
5141 VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable,
5142 StringRef Message, bool IsStrict, StringRef Replacement,
5143 AvailabilityMergeKind AMK, int Priority,
5144 const IdentifierInfo *IIEnvironment,
5145 const IdentifierInfo *InferredPlatformII);
5146
5147 TypeVisibilityAttr *
5149 TypeVisibilityAttr::VisibilityType Vis);
5150 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5151 VisibilityAttr::VisibilityType Vis);
5153 VisibilityAttr::VisibilityType Type);
5154 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
5155 StringRef Name);
5156
5157 /// Used to implement to perform semantic checking on
5158 /// attribute((section("foo"))) specifiers.
5159 ///
5160 /// In this case, "foo" is passed in to be checked. If the section
5161 /// specifier is invalid, return an Error that indicates the problem.
5162 ///
5163 /// This is a simple quality of implementation feature to catch errors
5164 /// and give good diagnostics in cases when the assembler or code generator
5165 /// would otherwise reject the section specifier.
5166 llvm::Error isValidSectionSpecifier(StringRef Str);
5167 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
5168 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
5169 StringRef Name);
5170
5171 // Check for things we'd like to warn about. Multiversioning issues are
5172 // handled later in the process, once we know how many exist.
5173 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
5174
5175 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
5176 StringRef NewUserDiagnostic);
5177 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
5178 const IdentifierInfo *Format, int FormatIdx,
5179 int FirstArg);
5180 FormatMatchesAttr *mergeFormatMatchesAttr(Decl *D,
5181 const AttributeCommonInfo &CI,
5182 const IdentifierInfo *Format,
5183 int FormatIdx,
5184 StringLiteral *FormatStr);
5185 ModularFormatAttr *mergeModularFormatAttr(Decl *D,
5186 const AttributeCommonInfo &CI,
5187 const IdentifierInfo *ModularImplFn,
5188 StringRef ImplName,
5190
5191 PersonalityAttr *mergePersonalityAttr(Decl *D, FunctionDecl *Routine,
5192 const AttributeCommonInfo &CI);
5193
5194 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
5195 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5196 bool IsPackExpansion);
5198 bool IsPackExpansion);
5199
5200 /// AddAlignValueAttr - Adds an align_value attribute to a particular
5201 /// declaration.
5202 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
5203
5204 /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
5205 Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
5208
5210 bool BestCase,
5211 MSInheritanceModel SemanticSpelling);
5212
5214
5215 /// AddModeAttr - Adds a mode attribute to a particular declaration.
5216 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
5217 const IdentifierInfo *Name, bool InInstantiation = false);
5218 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
5219 const AttributeCommonInfo &CI,
5220 const IdentifierInfo *Ident);
5221 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
5222 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
5223 const AttributeCommonInfo &CI);
5224 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
5225 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
5226 const InternalLinkageAttr &AL);
5227
5228 /// Check validaty of calling convention attribute \p attr. If \p FD
5229 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
5230 /// target. Otherwise, it is specified by \p CFT.
5232 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
5234
5235 /// Checks a regparm attribute, returning true if it is ill-formed and
5236 /// otherwise setting numParams to the appropriate value.
5237 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
5238
5239 /// Create a CUDALaunchBoundsAttr attribute. By default, the function only
5240 /// supports nvptx target architectures and skips MaxBlocks if it is previous
5241 /// to sm_90. Use \p IgnoreArch to skip the architecture check.
5242 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
5243 Expr *MaxThreads,
5244 Expr *MinBlocks, Expr *MaxBlocks,
5245 bool IgnoreArch = false);
5246
5247 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
5248 /// declaration.
5249 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5250 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
5251
5252 /// Add a cluster_dims attribute to a particular declaration.
5253 CUDAClusterDimsAttr *createClusterDimsAttr(const AttributeCommonInfo &CI,
5254 Expr *X, Expr *Y, Expr *Z);
5255 void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X,
5256 Expr *Y, Expr *Z);
5257 /// Add a no_cluster attribute to a particular declaration.
5258 void addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI);
5259
5260 enum class RetainOwnershipKind { NS, CF, OS };
5261
5262 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5263 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
5264
5265 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
5266
5267 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
5268 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
5269 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
5270 const AttributeCommonInfo &CI,
5271 bool BestCase,
5272 MSInheritanceModel Model);
5273
5274 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
5275 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
5276 const EnforceTCBLeafAttr &AL);
5277
5278 /// Helper for delayed processing TransparentUnion or
5279 /// BPFPreserveAccessIndexAttr attribute.
5281 const ParsedAttributesView &AttrList);
5282
5283 // Options for ProcessDeclAttributeList().
5287
5290 Result.IncludeCXX11Attributes = Val;
5291 return Result;
5292 }
5293
5296 Result.IgnoreTypeAttributes = Val;
5297 return Result;
5298 }
5299
5300 // Should C++11 attributes be processed?
5302
5303 // Should any type attributes encountered be ignored?
5304 // If this option is false, a diagnostic will be emitted for any type
5305 // attributes of a kind that does not "slide" from the declaration to
5306 // the decl-specifier-seq.
5308 };
5309
5310 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5311 /// attribute list to the specified decl, ignoring any type attributes.
5313 const ParsedAttributesView &AttrList,
5314 const ProcessDeclAttributeOptions &Options =
5316
5317 /// Annotation attributes are the only attributes allowed after an access
5318 /// specifier.
5320 const ParsedAttributesView &AttrList);
5321
5322 /// checkUnusedDeclAttributes - Given a declarator which is not being
5323 /// used to build a declaration, complain about any decl attributes
5324 /// which might be lying around on it.
5326
5327 void DiagnoseUnknownAttribute(const ParsedAttr &AL);
5328
5329 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5330 /// \#pragma weak needs a non-definition decl and source may not have one.
5332 SourceLocation Loc);
5333
5334 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5335 /// applied to it, possibly with an alias.
5336 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
5337
5338 void ProcessPragmaWeak(Scope *S, Decl *D);
5339 // Decl attributes - this routine is the top level dispatcher.
5340 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
5341
5343
5344 /// Given a set of delayed diagnostics, re-emit them as if they had
5345 /// been delayed in the current context instead of in the given pool.
5346 /// Essentially, this just moves them to the current pool.
5348
5349 /// Check that the type is a plain record with one field being a pointer
5350 /// type and the other field being an integer. This matches the common
5351 /// implementation of std::span or sized_allocation_t in P0901R11.
5352 bool CheckSpanLikeType(const AttributeCommonInfo &CI, const QualType &Ty);
5353
5354 /// Check if IdxExpr is a valid parameter index for a function or
5355 /// instance method D. May output an error.
5356 ///
5357 /// \returns true if IdxExpr is a valid index.
5358 template <typename AttrInfo>
5360 const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
5361 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false,
5362 bool CanIndexVariadicArguments = false) {
5364
5365 // In C++ the implicit 'this' function parameter also counts.
5366 // Parameters are counted from one.
5367 bool HP = hasFunctionProto(D);
5368 bool IV = HP && isFunctionOrMethodVariadic(D);
5369 unsigned NumParams =
5370 HP ? getFunctionOrMethodNumParams(D, /*IncludeThis=*/true) : 0;
5371
5372 std::optional<llvm::APSInt> IdxInt;
5373 if (IdxExpr->isTypeDependent() ||
5374 !(IdxInt = IdxExpr->getIntegerConstantExpr(Context))) {
5375 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5376 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
5377 << IdxExpr->getSourceRange();
5378 return false;
5379 }
5380
5381 constexpr unsigned Limit = 1 << ParamIdx::IdxBitWidth;
5382 unsigned IdxSource = IdxInt->getLimitedValue(Limit);
5383 if (IdxSource < 1 || IdxSource == Limit ||
5384 ((!IV || !CanIndexVariadicArguments) && IdxSource > NumParams)) {
5385 Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
5386 << &AI << AttrArgNum << IdxExpr->getSourceRange();
5387 return false;
5388 }
5389 if (hasImplicitObjectParameter(D) && !CanIndexImplicitThis) {
5390 if (IdxSource == 1) {
5391 Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
5392 << &AI << IdxExpr->getSourceRange();
5393 return false;
5394 }
5395 }
5396
5397 Idx = ParamIdx(IdxSource, D);
5398 return true;
5399 }
5400
5401 ///@}
5402
5403 //
5404 //
5405 // -------------------------------------------------------------------------
5406 //
5407 //
5408
5409 /// \name C++ Declarations
5410 /// Implementations are in SemaDeclCXX.cpp
5411 ///@{
5412
5413public:
5415
5416 /// Called before parsing a function declarator belonging to a function
5417 /// declaration.
5419 unsigned TemplateParameterDepth);
5420
5421 /// Called after parsing a function declarator belonging to a function
5422 /// declaration.
5424
5425 // Act on C++ namespaces
5427 SourceLocation NamespaceLoc,
5428 SourceLocation IdentLoc, IdentifierInfo *Ident,
5429 SourceLocation LBrace,
5430 const ParsedAttributesView &AttrList,
5431 UsingDirectiveDecl *&UsingDecl, bool IsNested);
5432
5433 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5434 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5435 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5436
5438
5439 /// Retrieve the special "std" namespace, which may require us to
5440 /// implicitly define the namespace.
5442
5444 EnumDecl *getStdAlignValT() const;
5445
5448 QualType AllocType, SourceLocation);
5449
5451 const IdentifierInfo *MemberOrBase);
5452
5454 /// The '<=>' operator was used in an expression and a builtin operator
5455 /// was selected.
5457 /// A defaulted 'operator<=>' needed the comparison category. This
5458 /// typically only applies to 'std::strong_ordering', due to the implicit
5459 /// fallback return value.
5461 /// A builtin needed 'std::strong_ordering' (eg. '__builtin_type_order').
5463 };
5464
5465 /// Lookup the specified comparison category types in the standard
5466 /// library, an check the VarDecls possibly returned by the operator<=>
5467 /// builtins for that type.
5468 ///
5469 /// \return The type of the comparison category type corresponding to the
5470 /// specified Kind, or a null type if an error occurs
5472 SourceLocation Loc,
5474
5475 /// Tests whether Ty is an instance of std::initializer_list and, if
5476 /// it is and Element is not NULL, assigns the element type to Element.
5477 bool isStdInitializerList(QualType Ty, QualType *Element);
5478
5479 /// Tests whether Ty is an instance of std::type_identity and, if
5480 /// it is and TypeArgument is not NULL, assigns the element type to Element.
5481 /// If MalformedDecl is not null, and type_identity was ruled out due to being
5482 /// incorrectly structured despite having the correct name, the faulty Decl
5483 /// will be assigned to MalformedDecl.
5484 bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument,
5485 const Decl **MalformedDecl = nullptr);
5486
5487 /// Looks for the std::initializer_list template and instantiates it
5488 /// with Element, or emits an error if it's not found.
5489 ///
5490 /// \returns The instantiated template, or null on error.
5492
5493 /// Looks for the std::type_identity template and instantiates it
5494 /// with Type, or returns a null type if type_identity has not been declared
5495 ///
5496 /// \returns The instantiated template, or null if std::type_identity is not
5497 /// declared
5499
5500 /// Determine whether Ctor is an initializer-list constructor, as
5501 /// defined in [dcl.init.list]p2.
5502 bool isInitListConstructor(const FunctionDecl *Ctor);
5503
5504 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5505 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5506 SourceLocation IdentLoc,
5507 IdentifierInfo *NamespcName,
5508 const ParsedAttributesView &AttrList);
5509
5511
5512 Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc,
5513 SourceLocation AliasLoc, IdentifierInfo *Alias,
5514 CXXScopeSpec &SS, SourceLocation IdentLoc,
5515 IdentifierInfo *Ident);
5516
5517 /// Remove decls we can't actually see from a lookup being used to declare
5518 /// shadow using decls.
5519 ///
5520 /// \param S - The scope of the potential shadow decl
5521 /// \param Previous - The lookup of a potential shadow decl's name.
5522 void FilterUsingLookup(Scope *S, LookupResult &lookup);
5523
5524 /// Hides a using shadow declaration. This is required by the current
5525 /// using-decl implementation when a resolvable using declaration in a
5526 /// class is followed by a declaration which would hide or override
5527 /// one or more of the using decl's targets; for example:
5528 ///
5529 /// struct Base { void foo(int); };
5530 /// struct Derived : Base {
5531 /// using Base::foo;
5532 /// void foo(int);
5533 /// };
5534 ///
5535 /// The governing language is C++03 [namespace.udecl]p12:
5536 ///
5537 /// When a using-declaration brings names from a base class into a
5538 /// derived class scope, member functions in the derived class
5539 /// override and/or hide member functions with the same name and
5540 /// parameter types in a base class (rather than conflicting).
5541 ///
5542 /// There are two ways to implement this:
5543 /// (1) optimistically create shadow decls when they're not hidden
5544 /// by existing declarations, or
5545 /// (2) don't create any shadow decls (or at least don't make them
5546 /// visible) until we've fully parsed/instantiated the class.
5547 /// The problem with (1) is that we might have to retroactively remove
5548 /// a shadow decl, which requires several O(n) operations because the
5549 /// decl structures are (very reasonably) not designed for removal.
5550 /// (2) avoids this but is very fiddly and phase-dependent.
5551 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5552
5553 /// Determines whether to create a using shadow decl for a particular
5554 /// decl, given the set of decls existing prior to this using lookup.
5556 const LookupResult &PreviousDecls,
5557 UsingShadowDecl *&PrevShadow);
5558
5559 /// Builds a shadow declaration corresponding to a 'using' declaration.
5562 UsingShadowDecl *PrevDecl);
5563
5564 /// Checks that the given using declaration is not an invalid
5565 /// redeclaration. Note that this is checking only for the using decl
5566 /// itself, not for any ill-formedness among the UsingShadowDecls.
5568 bool HasTypenameKeyword,
5569 const CXXScopeSpec &SS,
5570 SourceLocation NameLoc,
5571 const LookupResult &Previous);
5572
5573 /// Checks that the given nested-name qualifier used in a using decl
5574 /// in the current context is appropriately related to the current
5575 /// scope. If an error is found, diagnoses it and returns true.
5576 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's
5577 /// the result of that lookup. UD is likewise nullptr, except when we have an
5578 /// already-populated UsingDecl whose shadow decls contain the same
5579 /// information (i.e. we're instantiating a UsingDecl with non-dependent
5580 /// scope).
5581 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5582 const CXXScopeSpec &SS,
5583 const DeclarationNameInfo &NameInfo,
5584 SourceLocation NameLoc,
5585 const LookupResult *R = nullptr,
5586 const UsingDecl *UD = nullptr);
5587
5588 /// Builds a using declaration.
5589 ///
5590 /// \param IsInstantiation - Whether this call arises from an
5591 /// instantiation of an unresolved using declaration. We treat
5592 /// the lookup differently for these declarations.
5594 SourceLocation UsingLoc,
5595 bool HasTypenameKeyword,
5596 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5597 DeclarationNameInfo NameInfo,
5598 SourceLocation EllipsisLoc,
5599 const ParsedAttributesView &AttrList,
5600 bool IsInstantiation, bool IsUsingIfExists);
5602 SourceLocation UsingLoc,
5603 SourceLocation EnumLoc,
5604 SourceLocation NameLoc,
5605 TypeSourceInfo *EnumType, EnumDecl *ED);
5606 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5607 ArrayRef<NamedDecl *> Expansions);
5608
5609 /// Additional checks for a using declaration referring to a constructor name.
5611
5612 /// Given a derived-class using shadow declaration for a constructor and the
5613 /// correspnding base class constructor, find or create the implicit
5614 /// synthesized derived class constructor to use for this initialization.
5617 ConstructorUsingShadowDecl *DerivedShadow);
5618
5620 SourceLocation UsingLoc,
5621 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5622 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5623 const ParsedAttributesView &AttrList);
5625 SourceLocation UsingLoc,
5626 SourceLocation EnumLoc, SourceRange TyLoc,
5627 const IdentifierInfo &II, ParsedType Ty,
5628 const CXXScopeSpec &SS);
5630 MultiTemplateParamsArg TemplateParams,
5631 SourceLocation UsingLoc, UnqualifiedId &Name,
5632 const ParsedAttributesView &AttrList,
5633 TypeResult Type, Decl *DeclFromDeclSpec);
5634
5635 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5636 /// including handling of its default argument expressions.
5637 ///
5638 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5640 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5642 bool HadMultipleCandidates, bool IsListInitialization,
5643 bool IsStdInitListInitialization, bool RequiresZeroInit,
5644 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5645
5646 /// Build a CXXConstructExpr whose constructor has already been resolved if
5647 /// it denotes an inherited constructor.
5649 SourceLocation ConstructLoc, QualType DeclInitType,
5650 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5651 bool HadMultipleCandidates, bool IsListInitialization,
5652 bool IsStdInitListInitialization, bool RequiresZeroInit,
5653 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5654
5655 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5656 // the constructor can be elidable?
5658 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5659 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5660 bool HadMultipleCandidates, bool IsListInitialization,
5661 bool IsStdInitListInitialization, bool RequiresZeroInit,
5662 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5663
5665 SourceLocation InitLoc);
5667 const InitializedEntity &Entity,
5668 Expr *InitExpr,
5669 SourceLocation InitLoc);
5670
5671 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5672 /// constructed variable.
5673 void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit);
5674
5675 /// Helper class that collects exception specifications for
5676 /// implicitly-declared special member functions.
5678 // Pointer to allow copying
5679 Sema *Self;
5680 // We order exception specifications thus:
5681 // noexcept is the most restrictive, but is only used in C++11.
5682 // throw() comes next.
5683 // Then a throw(collected exceptions)
5684 // Finally no specification, which is expressed as noexcept(false).
5685 // throw(...) is used instead if any called function uses it.
5686 ExceptionSpecificationType ComputedEST;
5687 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5688 SmallVector<QualType, 4> Exceptions;
5689
5690 void ClearExceptions() {
5691 ExceptionsSeen.clear();
5692 Exceptions.clear();
5693 }
5694
5695 public:
5697 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5698 if (!Self.getLangOpts().CPlusPlus11)
5699 ComputedEST = EST_DynamicNone;
5700 }
5701
5702 /// Get the computed exception specification type.
5704 assert(!isComputedNoexcept(ComputedEST) &&
5705 "noexcept(expr) should not be a possible result");
5706 return ComputedEST;
5707 }
5708
5709 /// The number of exceptions in the exception specification.
5710 unsigned size() const { return Exceptions.size(); }
5711
5712 /// The set of exceptions in the exception specification.
5713 const QualType *data() const { return Exceptions.data(); }
5714
5715 /// Integrate another called method into the collected data.
5716 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5717
5718 /// Integrate an invoked expression into the collected data.
5719 void CalledExpr(Expr *E) { CalledStmt(E); }
5720
5721 /// Integrate an invoked statement into the collected data.
5722 void CalledStmt(Stmt *S);
5723
5724 /// Overwrite an EPI's exception specification with this
5725 /// computed exception specification.
5728 ESI.Type = getExceptionSpecType();
5729 if (ESI.Type == EST_Dynamic) {
5730 ESI.Exceptions = Exceptions;
5731 } else if (ESI.Type == EST_None) {
5732 /// C++11 [except.spec]p14:
5733 /// The exception-specification is noexcept(false) if the set of
5734 /// potential exceptions of the special member function contains "any"
5735 ESI.Type = EST_NoexceptFalse;
5736 ESI.NoexceptExpr =
5737 Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get();
5738 }
5739 return ESI;
5740 }
5741 };
5742
5743 /// Evaluate the implicit exception specification for a defaulted
5744 /// special member function.
5746
5747 /// Check the given exception-specification and update the
5748 /// exception specification information with the results.
5749 void checkExceptionSpecification(bool IsTopLevel,
5751 ArrayRef<ParsedType> DynamicExceptions,
5752 ArrayRef<SourceRange> DynamicExceptionRanges,
5753 Expr *NoexceptExpr,
5754 SmallVectorImpl<QualType> &Exceptions,
5756
5757 /// Add an exception-specification to the given member or friend function
5758 /// (or function template). The exception-specification was parsed
5759 /// after the function itself was declared.
5761 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
5762 ArrayRef<ParsedType> DynamicExceptions,
5763 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr);
5764
5765 class InheritedConstructorInfo;
5766
5767 /// Determine if a special member function should have a deleted
5768 /// definition when it is defaulted.
5770 InheritedConstructorInfo *ICI = nullptr,
5771 bool Diagnose = false);
5772
5773 /// Produce notes explaining why a defaulted function was defined as deleted.
5775
5776 /// Declare the implicit default constructor for the given class.
5777 ///
5778 /// \param ClassDecl The class declaration into which the implicit
5779 /// default constructor will be added.
5780 ///
5781 /// \returns The implicitly-declared default constructor.
5784
5785 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5786 /// defining this constructor as the default constructor.
5789
5790 /// Declare the implicit destructor for the given class.
5791 ///
5792 /// \param ClassDecl The class declaration into which the implicit
5793 /// destructor will be added.
5794 ///
5795 /// \returns The implicitly-declared destructor.
5797
5798 /// DefineImplicitDestructor - Checks for feasibility of
5799 /// defining this destructor as the default destructor.
5800 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5802
5803 /// Build an exception spec for destructors that don't have one.
5804 ///
5805 /// C++11 says that user-defined destructors with no exception spec get one
5806 /// that looks as if the destructor was implicitly declared.
5808
5809 /// Define the specified inheriting constructor.
5812
5813 /// Declare the implicit copy constructor for the given class.
5814 ///
5815 /// \param ClassDecl The class declaration into which the implicit
5816 /// copy constructor will be added.
5817 ///
5818 /// \returns The implicitly-declared copy constructor.
5820
5821 /// DefineImplicitCopyConstructor - Checks for feasibility of
5822 /// defining this constructor as the copy constructor.
5823 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5825
5826 /// Declare the implicit move constructor for the given class.
5827 ///
5828 /// \param ClassDecl The Class declaration into which the implicit
5829 /// move constructor will be added.
5830 ///
5831 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5832 /// declared.
5834
5835 /// DefineImplicitMoveConstructor - Checks for feasibility of
5836 /// defining this constructor as the move constructor.
5837 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5839
5840 /// Declare the implicit copy assignment operator for the given class.
5841 ///
5842 /// \param ClassDecl The class declaration into which the implicit
5843 /// copy assignment operator will be added.
5844 ///
5845 /// \returns The implicitly-declared copy assignment operator.
5847
5848 /// Defines an implicitly-declared copy assignment operator.
5849 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5850 CXXMethodDecl *MethodDecl);
5851
5852 /// Declare the implicit move assignment operator for the given class.
5853 ///
5854 /// \param ClassDecl The Class declaration into which the implicit
5855 /// move assignment operator will be added.
5856 ///
5857 /// \returns The implicitly-declared move assignment operator, or NULL if it
5858 /// wasn't declared.
5860
5861 /// Defines an implicitly-declared move assignment operator.
5862 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5863 CXXMethodDecl *MethodDecl);
5864
5865 /// Check a completed declaration of an implicit special member.
5867
5868 /// Determine whether the given function is an implicitly-deleted
5869 /// special member function.
5871
5872 /// Check whether 'this' shows up in the type of a static member
5873 /// function after the (naturally empty) cv-qualifier-seq would be.
5874 ///
5875 /// \returns true if an error occurred.
5877
5878 /// Whether this' shows up in the exception specification of a static
5879 /// member function.
5881
5882 /// Check whether 'this' shows up in the attributes of the given
5883 /// static member function.
5884 ///
5885 /// \returns true if an error occurred.
5887
5889 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI);
5890
5892
5893 /// Given a constructor and the set of arguments provided for the
5894 /// constructor, convert the arguments and add any required default arguments
5895 /// to form a proper call to this constructor.
5896 ///
5897 /// \returns true if an error occurred, false otherwise.
5899 QualType DeclInitType, MultiExprArg ArgsPtr,
5900 SourceLocation Loc,
5901 SmallVectorImpl<Expr *> &ConvertedArgs,
5902 bool AllowExplicit = false,
5903 bool IsListInitialization = false);
5904
5905 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5906 /// initializer for the declaration 'Dcl'.
5907 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5908 /// static data member of class X, names should be looked up in the scope of
5909 /// class X.
5911
5912 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5913 /// initializer for the declaration 'Dcl'.
5914 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5915
5916 /// Define the "body" of the conversion from a lambda object to a
5917 /// function pointer.
5918 ///
5919 /// This routine doesn't actually define a sensible body; rather, it fills
5920 /// in the initialization expression needed to copy the lambda object into
5921 /// the block, and IR generation actually generates the real body of the
5922 /// block pointer conversion.
5923 void
5925 CXXConversionDecl *Conv);
5926
5927 /// Define the "body" of the conversion from a lambda object to a
5928 /// block pointer.
5929 ///
5930 /// This routine doesn't actually define a sensible body; rather, it fills
5931 /// in the initialization expression needed to copy the lambda object into
5932 /// the block, and IR generation actually generates the real body of the
5933 /// block pointer conversion.
5935 CXXConversionDecl *Conv);
5936
5937 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5938 /// linkage specification, including the language and (if present)
5939 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
5940 /// language string literal. LBraceLoc, if valid, provides the location of
5941 /// the '{' brace. Otherwise, this linkage specification does not
5942 /// have any braces.
5944 Expr *LangStr, SourceLocation LBraceLoc);
5945
5946 /// ActOnFinishLinkageSpecification - Complete the definition of
5947 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
5948 /// valid, it's the position of the closing '}' brace in a linkage
5949 /// specification that uses braces.
5951 SourceLocation RBraceLoc);
5952
5953 //===--------------------------------------------------------------------===//
5954 // C++ Classes
5955 //
5956
5957 /// Get the class that is directly named by the current context. This is the
5958 /// class for which an unqualified-id in this scope could name a constructor
5959 /// or destructor.
5960 ///
5961 /// If the scope specifier denotes a class, this will be that class.
5962 /// If the scope specifier is empty, this will be the class whose
5963 /// member-specification we are currently within. Otherwise, there
5964 /// is no such class.
5966
5967 /// isCurrentClassName - Determine whether the identifier II is the
5968 /// name of the class type currently being defined. In the case of
5969 /// nested classes, this will only return true if II is the name of
5970 /// the innermost class.
5971 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5972 const CXXScopeSpec *SS = nullptr);
5973
5974 /// Determine whether the identifier II is a typo for the name of
5975 /// the class type currently being defined. If so, update it to the identifier
5976 /// that should have been used.
5978
5979 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
5981 SourceLocation ColonLoc,
5982 const ParsedAttributesView &Attrs);
5983
5984 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
5985 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
5986 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
5987 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
5988 /// present (but parsing it has been deferred).
5989 NamedDecl *
5991 MultiTemplateParamsArg TemplateParameterLists,
5992 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5993 InClassInitStyle InitStyle);
5994
5995 /// Enter a new C++ default initializer scope. After calling this, the
5996 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
5997 /// parsing or instantiating the initializer failed.
5999
6000 /// This is invoked after parsing an in-class initializer for a
6001 /// non-static C++ class member, and after instantiating an in-class
6002 /// initializer in a class template. Such actions are deferred until the class
6003 /// is complete.
6005 SourceLocation EqualLoc,
6007
6008 /// Handle a C++ member initializer using parentheses syntax.
6010 ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS,
6011 IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy,
6012 const DeclSpec &DS, SourceLocation IdLoc,
6013 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
6014 SourceLocation RParenLoc, SourceLocation EllipsisLoc);
6015
6016 /// Handle a C++ member initializer using braced-init-list syntax.
6017 MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S,
6018 CXXScopeSpec &SS,
6019 IdentifierInfo *MemberOrBase,
6020 ParsedType TemplateTypeTy,
6021 const DeclSpec &DS, SourceLocation IdLoc,
6022 Expr *InitList, SourceLocation EllipsisLoc);
6023
6024 /// Handle a C++ member initializer.
6025 MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S,
6026 CXXScopeSpec &SS,
6027 IdentifierInfo *MemberOrBase,
6028 ParsedType TemplateTypeTy,
6029 const DeclSpec &DS, SourceLocation IdLoc,
6030 Expr *Init, SourceLocation EllipsisLoc);
6031
6033 SourceLocation IdLoc);
6034
6036 TypeSourceInfo *BaseTInfo, Expr *Init,
6037 CXXRecordDecl *ClassDecl,
6038 SourceLocation EllipsisLoc);
6039
6041 CXXRecordDecl *ClassDecl);
6042
6045
6047 ArrayRef<CXXCtorInitializer *> Initializers = {});
6048
6049 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
6050 /// mark all the non-trivial destructors of its members and bases as
6051 /// referenced.
6052 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
6053 CXXRecordDecl *Record);
6054
6055 /// Mark destructors of virtual bases of this class referenced. In the Itanium
6056 /// C++ ABI, this is done when emitting a destructor for any non-abstract
6057 /// class. In the Microsoft C++ ABI, this is done any time a class's
6058 /// destructor is referenced.
6060 SourceLocation Location, CXXRecordDecl *ClassDecl,
6061 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases =
6062 nullptr);
6063
6064 /// Do semantic checks to allow the complete destructor variant to be emitted
6065 /// when the destructor is defined in another translation unit. In the Itanium
6066 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
6067 /// can be emitted in separate TUs. To emit the complete variant, run a subset
6068 /// of the checks performed when emitting a regular destructor.
6069 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
6070 CXXDestructorDecl *Dtor);
6071
6072 /// The list of classes whose vtables have been used within
6073 /// this translation unit, and the source locations at which the
6074 /// first use occurred.
6075 typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse;
6076
6077 /// The list of vtables that are required but have not yet been
6078 /// materialized.
6080
6081 /// The set of classes whose vtables have been used within
6082 /// this translation unit, and a bit that will be true if the vtable is
6083 /// required to be emitted (otherwise, it should be emitted only if needed
6084 /// by code generation).
6085 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
6086
6087 /// Load any externally-stored vtable uses.
6089
6090 /// Note that the vtable for the given class was used at the
6091 /// given location.
6093 bool DefinitionRequired = false);
6094
6095 /// Mark the exception specifications of all virtual member functions
6096 /// in the given class as needed.
6098 const CXXRecordDecl *RD);
6099
6100 /// MarkVirtualMembersReferenced - Will mark all members of the given
6101 /// CXXRecordDecl referenced.
6103 bool ConstexprOnly = false);
6104
6105 /// Define all of the vtables that have been used in this
6106 /// translation unit and reference any virtual members used by those
6107 /// vtables.
6108 ///
6109 /// \returns true if any work was done, false otherwise.
6110 bool DefineUsedVTables();
6111
6112 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6113 /// special functions, such as the default constructor, copy
6114 /// constructor, or destructor, to the given C++ class (C++
6115 /// [special]p1). This routine can only be executed just before the
6116 /// definition of the class is complete.
6118
6119 /// ActOnMemInitializers - Handle the member initializers for a constructor.
6120 void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc,
6122 bool AnyErrors);
6123
6124 /// Check class-level dllimport/dllexport attribute. The caller must
6125 /// ensure that referenceDLLExportedClassMethods is called some point later
6126 /// when all outer classes of Class are complete.
6129
6131
6132 /// Perform propagation of DLL attributes from a derived class to a
6133 /// templated base class for MS compatibility.
6135 CXXRecordDecl *Class, Attr *ClassAttr,
6136 ClassTemplateSpecializationDecl *BaseTemplateSpec,
6137 SourceLocation BaseLoc);
6138
6139 /// Perform semantic checks on a class definition that has been
6140 /// completing, introducing implicitly-declared members, checking for
6141 /// abstract types, etc.
6142 ///
6143 /// \param S The scope in which the class was parsed. Null if we didn't just
6144 /// parse a class definition.
6145 /// \param Record The completed class.
6147
6148 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6149 /// conditions that are needed for the attribute to have an effect.
6151
6152 /// Check that VTable Pointer authentication is only being set on the first
6153 /// first instantiation of the vtable
6155
6157 Decl *TagDecl, SourceLocation LBrac,
6158 SourceLocation RBrac,
6159 const ParsedAttributesView &AttrList);
6160
6161 /// Perform any semantic analysis which needs to be delayed until all
6162 /// pending class member declarations have been parsed.
6165
6166 /// This is used to implement the constant expression evaluation part of the
6167 /// attribute enable_if extension. There is nothing in standard C++ which
6168 /// would require reentering parameters.
6171 llvm::function_ref<Scope *()> EnterScope);
6173
6174 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6175 /// parsing a top-level (non-nested) C++ class, and we are now
6176 /// parsing those parts of the given Method declaration that could
6177 /// not be parsed earlier (C++ [class.mem]p2), such as default
6178 /// arguments. This action should enter the scope of the given
6179 /// Method declaration as if we had just parsed the qualified method
6180 /// name. However, it should not bring the parameters into scope;
6181 /// that will be performed by ActOnDelayedCXXMethodParameter.
6183 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6185
6186 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6187 /// processing the delayed method declaration for Method. The method
6188 /// declaration is now considered finished. There may be a separate
6189 /// ActOnStartOfFunctionDef action later (not necessarily
6190 /// immediately!) for this method, if it was also defined inside the
6191 /// class body.
6194
6196
6197 bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
6198 StringEvaluationContext EvalContext,
6199 bool ErrorOnInvalidMessage);
6200 bool EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
6201 StringEvaluationContext EvalContext,
6202 bool ErrorOnInvalidMessage);
6203
6205 Expr *AssertExpr, Expr *AssertMessageExpr,
6206 SourceLocation RParenLoc);
6208 Expr *AssertExpr, Expr *AssertMessageExpr,
6209 SourceLocation RParenLoc, bool Failed);
6210
6211 /// Try to print more useful information about a failed static_assert
6212 /// with expression \E
6213 void DiagnoseStaticAssertDetails(const Expr *E);
6214
6215 /// If E represents a built-in type trait, or a known standard type trait,
6216 /// try to print more information about why the type type-trait failed.
6217 /// This assumes we already evaluated the expression to a false boolean value.
6218 void DiagnoseTypeTraitDetails(const Expr *E);
6219
6220 /// Handle a friend type declaration. This works in tandem with
6221 /// ActOnTag.
6222 ///
6223 /// Notes on friend class templates:
6224 ///
6225 /// We generally treat friend class declarations as if they were
6226 /// declaring a class. So, for example, the elaborated type specifier
6227 /// in a friend declaration is required to obey the restrictions of a
6228 /// class-head (i.e. no typedefs in the scope chain), template
6229 /// parameters are required to match up with simple template-ids, &c.
6230 /// However, unlike when declaring a template specialization, it's
6231 /// okay to refer to a template specialization without an empty
6232 /// template parameter declaration, e.g.
6233 /// friend class A<T>::B<unsigned>;
6234 /// We permit this as a special case; if there are any template
6235 /// parameters present at all, require proper matching, i.e.
6236 /// template <> template <class T> friend class A<int>::B;
6237 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6238 MultiTemplateParamsArg TemplateParams,
6239 SourceLocation EllipsisLoc);
6241 MultiTemplateParamsArg TemplateParams);
6242
6243 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6244 /// the well-formedness of the constructor declarator @p D with type @p
6245 /// R. If there are any errors in the declarator, this routine will
6246 /// emit diagnostics and set the invalid bit to true. In any case, the type
6247 /// will be updated to reflect a well-formed type for the constructor and
6248 /// returned.
6250 StorageClass &SC);
6251
6252 /// CheckConstructor - Checks a fully-formed constructor for
6253 /// well-formedness, issuing any diagnostics required. Returns true if
6254 /// the constructor declarator is invalid.
6256
6257 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6258 /// the well-formednes of the destructor declarator @p D with type @p
6259 /// R. If there are any errors in the declarator, this routine will
6260 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6261 /// will be updated to reflect a well-formed type for the destructor and
6262 /// returned.
6264 StorageClass &SC);
6265
6266 /// CheckDestructor - Checks a fully-formed destructor definition for
6267 /// well-formedness, issuing any diagnostics required. Returns true
6268 /// on error.
6270
6271 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6272 /// well-formednes of the conversion function declarator @p D with
6273 /// type @p R. If there are any errors in the declarator, this routine
6274 /// will emit diagnostics and return true. Otherwise, it will return
6275 /// false. Either way, the type @p R will be updated to reflect a
6276 /// well-formed type for the conversion operator.
6278
6279 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6280 /// the declaration of the given C++ conversion function. This routine
6281 /// is responsible for recording the conversion function in the C++
6282 /// class, if possible.
6284
6285 /// Check the validity of a declarator that we parsed for a deduction-guide.
6286 /// These aren't actually declarators in the grammar, so we need to check that
6287 /// the user didn't specify any pieces that are not part of the
6288 /// deduction-guide grammar. Return true on invalid deduction-guide.
6290 StorageClass &SC);
6291
6293
6296 SourceLocation DefaultLoc);
6298
6302 FunctionDecl *Spaceship);
6305
6306 /// Check a defaulted postfix increment or decrement operator function
6307 /// (C++2d [over.inc.default]), defining it as deleted if necessary.
6308 ///
6309 /// \param S The scope in which the function is defaulted, used to perform
6310 /// the unqualified name lookups needed by the implicit definition, or
6311 /// \c nullptr if those lookups have already been performed.
6312 ///
6313 /// \returns \c true if the function is ill-formed.
6315 PostfixOperatorKind Kind);
6316 /// Synthesize the body of a defaulted postfix increment or decrement
6317 /// operator function (C++2d [over.inc.default]p3).
6319 PostfixOperatorKind Kind);
6320
6322 QualType R, bool IsLambda,
6323 DeclContext *DC = nullptr);
6325 DeclarationName Name, QualType R);
6327
6328 //===--------------------------------------------------------------------===//
6329 // C++ Derived Classes
6330 //
6331
6332 /// Check the validity of a C++ base class specifier.
6333 ///
6334 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
6335 /// and returns NULL otherwise.
6337 SourceRange SpecifierRange, bool Virtual,
6338 AccessSpecifier Access,
6339 TypeSourceInfo *TInfo,
6340 SourceLocation EllipsisLoc);
6341
6342 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
6343 /// one entry in the base class list of a class specifier, for
6344 /// example:
6345 /// class foo : public bar, virtual private baz {
6346 /// 'public bar' and 'virtual private baz' are each base-specifiers.
6347 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
6348 const ParsedAttributesView &Attrs, bool Virtual,
6349 AccessSpecifier Access, ParsedType basetype,
6350 SourceLocation BaseLoc,
6351 SourceLocation EllipsisLoc);
6352
6353 /// Performs the actual work of attaching the given base class
6354 /// specifiers to a C++ class.
6357
6358 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
6359 /// class, after checking whether there are any duplicate base
6360 /// classes.
6361 void ActOnBaseSpecifiers(Decl *ClassDecl,
6363
6364 /// Determine whether the type \p Derived is a C++ class that is
6365 /// derived from the type \p Base.
6366 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6368 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6372 CXXBasePaths &Paths);
6373
6374 // FIXME: I don't like this name.
6375 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6376
6378 SourceLocation Loc, SourceRange Range,
6379 CXXCastPath *BasePath = nullptr,
6380 bool IgnoreAccess = false);
6381
6382 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
6383 /// conversion (where Derived and Base are class types) is
6384 /// well-formed, meaning that the conversion is unambiguous (and
6385 /// that all of the base classes are accessible). Returns true
6386 /// and emits a diagnostic if the code is ill-formed, returns false
6387 /// otherwise. Loc is the location where this routine should point to
6388 /// if there is an error, and Range is the source range to highlight
6389 /// if there is an error.
6390 ///
6391 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
6392 /// diagnostic for the respective type of error will be suppressed, but the
6393 /// check for ill-formed code will still be performed.
6395 unsigned InaccessibleBaseID,
6396 unsigned AmbiguousBaseConvID,
6397 SourceLocation Loc, SourceRange Range,
6398 DeclarationName Name, CXXCastPath *BasePath,
6399 bool IgnoreAccess = false);
6400
6401 /// Builds a string representing ambiguous paths from a
6402 /// specific derived class to different subobjects of the same base
6403 /// class.
6404 ///
6405 /// This function builds a string that can be used in error messages
6406 /// to show the different paths that one can take through the
6407 /// inheritance hierarchy to go from the derived class to different
6408 /// subobjects of a base class. The result looks something like this:
6409 /// @code
6410 /// struct D -> struct B -> struct A
6411 /// struct D -> struct C -> struct A
6412 /// @endcode
6413 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6414
6416 const CXXMethodDecl *Old);
6417
6418 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6419 /// covariant, according to C++ [class.virtual]p5.
6421 const CXXMethodDecl *Old);
6422
6423 // Check that the overriding method has no explicit object parameter.
6425 const CXXMethodDecl *Old);
6426
6427 /// Mark the given method pure.
6428 ///
6429 /// \param Method the method to be marked pure.
6430 ///
6431 /// \param InitRange the source range that covers the "0" initializer.
6433
6434 /// CheckOverrideControl - Check C++11 override control semantics.
6436
6437 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6438 /// not used in the declaration of an overriding method.
6440
6441 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
6442 /// function overrides a virtual member function marked 'final', according to
6443 /// C++11 [class.virtual]p4.
6445 const CXXMethodDecl *Old);
6446
6457
6458 struct TypeDiagnoser;
6459
6462 TypeDiagnoser &Diagnoser);
6463 template <typename... Ts>
6465 const Ts &...Args) {
6466 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6467 return RequireNonAbstractType(Loc, T, Diagnoser);
6468 }
6469
6470 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6471
6472 //===--------------------------------------------------------------------===//
6473 // C++ Overloaded Operators [C++ 13.5]
6474 //
6475
6476 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
6477 /// of this overloaded operator is well-formed. If so, returns false;
6478 /// otherwise, emits appropriate diagnostics and returns true.
6480
6481 /// CheckLiteralOperatorDeclaration - Check whether the declaration
6482 /// of this literal operator function is well-formed. If so, returns
6483 /// false; otherwise, emits appropriate diagnostics and returns true.
6485
6486 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
6487 /// found in an explicit(bool) specifier.
6489
6490 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
6491 /// Returns true if the explicit specifier is now resolved.
6493
6494 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6495 /// C++ if/switch/while/for statement.
6496 /// e.g: "if (int x = f()) {...}"
6498
6499 // Emitting members of dllexported classes is delayed until the class
6500 // (including field initializers) is fully parsed.
6503
6504 /// Merge the exception specifications of two variable declarations.
6505 ///
6506 /// This is called when there's a redeclaration of a VarDecl. The function
6507 /// checks if the redeclaration might have an exception specification and
6508 /// validates compatibility and merges the specs if necessary.
6510
6511 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
6512 /// function, once we already know that they have the same
6513 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
6514 /// error, false otherwise.
6516
6517 /// Helpers for dealing with blocks and functions.
6519
6520 /// CheckExtraCXXDefaultArguments - Check for any extra default
6521 /// arguments in the declarator, which is not a function declaration
6522 /// or definition and therefore is not permitted to have default
6523 /// arguments. This routine should be invoked for every declarator
6524 /// that is not a function declaration or definition.
6526
6527 /// Perform semantic analysis for the variable declaration that
6528 /// occurs within a C++ catch clause, returning the newly-created
6529 /// variable.
6531 SourceLocation StartLoc,
6532 SourceLocation IdLoc,
6533 const IdentifierInfo *Id);
6534
6535 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6536 /// handler.
6538
6540
6541 /// Handle a friend tag declaration where the scope specifier was
6542 /// templated.
6544 unsigned TagSpec, SourceLocation TagLoc,
6545 CXXScopeSpec &SS, IdentifierInfo *Name,
6546 SourceLocation NameLoc,
6547 SourceLocation EllipsisLoc,
6549 MultiTemplateParamsArg TempParamLists,
6550 TemplateIdAnnotation *TemplateId);
6551
6554 bool IsInstantiation);
6555
6557 NestedNameSpecifierLoc NNSLoc);
6558
6560 SourceLocation DeclStart, Declarator &D,
6561 Expr *BitfieldWidth,
6562 InClassInitStyle InitStyle,
6563 AccessSpecifier AS,
6564 const ParsedAttr &MSPropertyAttr);
6565
6566 /// Diagnose why the specified class does not have a trivial special member of
6567 /// the given kind.
6570
6571 /// Determine whether a defaulted or deleted special member function is
6572 /// trivial, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6573 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6577 bool Diagnose = false);
6578
6579 /// Handle a C++11 empty-declaration and attribute-declaration.
6581 SourceLocation SemiLoc);
6582
6584 /// Diagnose issues that are non-constant or that are extensions.
6586 /// Identify whether this function satisfies the formal rules for constexpr
6587 /// functions in the current lanugage mode (with no extensions).
6589 };
6590
6591 // Check whether a function declaration satisfies the requirements of a
6592 // constexpr function definition or a constexpr constructor definition. If so,
6593 // return true. If not, produce appropriate diagnostics (unless asked not to
6594 // by Kind) and return false.
6595 //
6596 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
6598 CheckConstexprKind Kind);
6599
6600 /// Diagnose methods which overload virtual methods in a base class
6601 /// without overriding any.
6603
6604 /// Check if a method overloads virtual methods in a base class without
6605 /// overriding any.
6606 void
6608 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6609 void
6611 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6612
6613 /// ActOnParamDefaultArgument - Check whether the default argument
6614 /// provided for a function parameter is well-formed. If so, attach it
6615 /// to the parameter declaration.
6616 void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
6617 Expr *defarg);
6618
6619 /// ActOnParamUnparsedDefaultArgument - We've seen a default
6620 /// argument for a function parameter, but we can't parse it yet
6621 /// because we're inside a class definition. Note that this default
6622 /// argument will be parsed later.
6624 SourceLocation ArgLoc);
6625
6626 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
6627 /// the default argument for the parameter param failed.
6629 Expr *DefaultArg);
6631 SourceLocation EqualLoc);
6632 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6633 SourceLocation EqualLoc);
6634
6635 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
6636 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc,
6637 StringLiteral *Message = nullptr);
6638 /// Mark the given declaration as explicitly defaulted.
6639 ///
6640 /// \param S The scope in which the function is defaulted, if it is
6641 /// available. It is used to perform the unqualified name lookups needed by
6642 /// the implicit definition of an out-of-class defaulted function.
6643 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc,
6644 Scope *S = nullptr);
6645
6646 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
6647 StringLiteral *DeletedMessage = nullptr,
6648 Scope *S = nullptr);
6652
6653 NamedDecl *
6655 MultiTemplateParamsArg TemplateParamLists);
6658 RecordDecl *ClassDecl,
6659 const IdentifierInfo *Name);
6660
6662 SourceLocation Loc);
6664
6665 /// Stack containing information needed when in C++2a an 'auto' is encountered
6666 /// in a function declaration parameter type specifier in order to invent a
6667 /// corresponding template parameter in the enclosing abbreviated function
6668 /// template. This information is also present in LambdaScopeInfo, stored in
6669 /// the FunctionScopes stack.
6671
6672 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
6673 std::unique_ptr<CXXFieldCollector> FieldCollector;
6674
6676 /// Set containing all declared private fields that are not used.
6678
6680
6681 /// PureVirtualClassDiagSet - a set of class declarations which we have
6682 /// emitted a list of pure virtual functions. Used to prevent emitting the
6683 /// same list more than once.
6684 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
6685
6689
6690 /// All the delegating constructors seen so far in the file, used for
6691 /// cycle detection at the end of the TU.
6693
6694 /// The C++ "std" namespace, where the standard library resides.
6696
6697 /// The C++ "std::initializer_list" template, which is defined in
6698 /// <initializer_list>.
6700
6701 /// The C++ "std::type_identity" template, which is defined in
6702 /// <type_traits>.
6704
6705 // Contains the locations of the beginning of unparsed default
6706 // argument locations.
6707 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
6708
6709 /// UndefinedInternals - all the used, undefined objects which require a
6710 /// definition in this translation unit.
6711 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
6712
6713 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMemberKind>
6715
6716 /// The C++ special members which we are currently in the process of
6717 /// declaring. If this process recursively triggers the declaration of the
6718 /// same special member, we should act as if it is not yet declared.
6720
6722
6723 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
6724
6727 ParsingClassDepth++;
6729 }
6731 ParsingClassDepth--;
6733 }
6734
6736 CXXScopeSpec &SS,
6737 ParsedType TemplateTypeTy,
6738 IdentifierInfo *MemberOrBase);
6739
6740private:
6741 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
6742 QualType ResultTy,
6743 ArrayRef<QualType> Args);
6744 // Helper for ActOnFields to check for all function pointer members.
6745 bool EntirelyFunctionPointers(const RecordDecl *Record);
6746
6747 // A cache representing if we've fully checked the various comparison category
6748 // types stored in ASTContext. The bit-index corresponds to the integer value
6749 // of a ComparisonCategoryType enumerator.
6750 llvm::SmallBitVector FullyCheckedComparisonCategories;
6751
6752 /// Check if there is a field shadowing.
6753 void CheckShadowInheritedFields(const SourceLocation &Loc,
6754 DeclarationName FieldName,
6755 const CXXRecordDecl *RD,
6756 bool DeclIsField = true);
6757
6758 ///@}
6759
6760 //
6761 //
6762 // -------------------------------------------------------------------------
6763 //
6764 //
6765
6766 /// \name C++ Exception Specifications
6767 /// Implementations are in SemaExceptionSpec.cpp
6768 ///@{
6769
6770public:
6771 /// All the overriding functions seen during a class definition
6772 /// that had their exception spec checks delayed, plus the overridden
6773 /// function.
6776
6777 /// All the function redeclarations seen during a class definition that had
6778 /// their exception spec checks delayed, plus the prior declaration they
6779 /// should be checked against. Except during error recovery, the new decl
6780 /// should always be a friend declaration, as that's the only valid way to
6781 /// redeclare a special member before its class is complete.
6784
6785 /// Determine if we're in a case where we need to (incorrectly) eagerly
6786 /// parse an exception specification to work around a libstdc++ bug.
6788
6789 /// Check the given noexcept-specifier, convert its expression, and compute
6790 /// the appropriate ExceptionSpecificationType.
6791 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6793
6794 CanThrowResult canThrow(const Stmt *E);
6795 /// Determine whether the callee of a particular function call can throw.
6796 /// E, D and Loc are all optional.
6797 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
6800 const FunctionProtoType *FPT);
6803
6804 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
6805 /// exception specification. Incomplete types, or pointers to incomplete types
6806 /// other than void are not allowed.
6807 ///
6808 /// \param[in,out] T The exception type. This will be decayed to a pointer
6809 /// type
6810 /// when the input is an array or a function type.
6812
6813 /// CheckDistantExceptionSpec - Check if the given type is a pointer or
6814 /// pointer to member to a function with an exception specification. This
6815 /// means that it is invalid to add another level of indirection.
6818
6819 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
6820 /// exception specifications. Exception specifications are equivalent if
6821 /// they allow exactly the same set of exception types. It does not matter how
6822 /// that is achieved. See C++ [except.spec]p2.
6824 SourceLocation OldLoc,
6825 const FunctionProtoType *New,
6826 SourceLocation NewLoc);
6828 const PartialDiagnostic &NoteID,
6829 const FunctionProtoType *Old,
6830 SourceLocation OldLoc,
6831 const FunctionProtoType *New,
6832 SourceLocation NewLoc);
6833 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
6834
6835 /// CheckExceptionSpecSubset - Check whether the second function type's
6836 /// exception specification is a subset (or equivalent) of the first function
6837 /// type. This is used by override and pointer assignment checks.
6839 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
6840 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
6841 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
6842 SourceLocation SuperLoc, const FunctionProtoType *Subset,
6843 bool SkipSubsetFirstParameter, SourceLocation SubLoc);
6844
6845 /// CheckParamExceptionSpec - Check if the parameter and return types of the
6846 /// two functions have equivalent exception specs. This is part of the
6847 /// assignment and override compatibility check. We do not check the
6848 /// parameters of parameter function pointers recursively, as no sane
6849 /// programmer would even be able to write such a function type.
6851 const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID,
6852 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
6853 SourceLocation TargetLoc, const FunctionProtoType *Source,
6854 bool SkipSourceFirstParameter, SourceLocation SourceLoc);
6855
6856 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6857
6858 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6859 /// spec is a subset of base spec.
6861 const CXXMethodDecl *Old);
6862
6863 ///@}
6864
6865 //
6866 //
6867 // -------------------------------------------------------------------------
6868 //
6869 //
6870
6871 /// \name Expressions
6872 /// Implementations are in SemaExpr.cpp
6873 ///@{
6874
6875public:
6876 /// Describes how the expressions currently being parsed are
6877 /// evaluated at run-time, if at all.
6879 /// The current expression and its subexpressions occur within an
6880 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
6881 /// \c sizeof, where the type of the expression may be significant but
6882 /// no code will be generated to evaluate the value of the expression at
6883 /// run time.
6885
6886 /// The current expression occurs within a braced-init-list within
6887 /// an unevaluated operand. This is mostly like a regular unevaluated
6888 /// context, except that we still instantiate constexpr functions that are
6889 /// referenced here so that we can perform narrowing checks correctly.
6891
6892 /// The current expression occurs within a discarded statement.
6893 /// This behaves largely similarly to an unevaluated operand in preventing
6894 /// definitions from being required, but not in other ways.
6896
6897 /// The current expression occurs within an unevaluated
6898 /// operand that unconditionally permits abstract references to
6899 /// fields, such as a SIZE operator in MS-style inline assembly.
6901
6902 /// The current context is "potentially evaluated" in C++11 terms,
6903 /// but the expression is evaluated at compile-time (like the values of
6904 /// cases in a switch statement).
6906
6907 /// In addition of being constant evaluated, the current expression
6908 /// occurs in an immediate function context - either a consteval function
6909 /// or a consteval if statement.
6911
6912 /// The current expression is potentially evaluated at run time,
6913 /// which means that code may be generated to evaluate the value of the
6914 /// expression at run time.
6916
6917 /// The current expression is potentially evaluated, but any
6918 /// declarations referenced inside that expression are only used if
6919 /// in fact the current expression is used.
6920 ///
6921 /// This value is used when parsing default function arguments, for which
6922 /// we would like to provide diagnostics (e.g., passing non-POD arguments
6923 /// through varargs) but do not want to mark declarations as "referenced"
6924 /// until the default argument is used.
6926 };
6927
6928 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
6929 /// to a variable (constant) that may or may not be odr-used in this Expr, and
6930 /// we won't know until all lvalue-to-rvalue and discarded value conversions
6931 /// have been applied to all subexpressions of the enclosing full expression.
6932 /// This is cleared at the end of each full expression.
6935
6936 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
6937
6938 /// Data structure used to record current or nested
6939 /// expression evaluation contexts.
6941 /// The expression evaluation context.
6943
6944 /// Whether the enclosing context needed a cleanup.
6946
6947 /// The number of active cleanup objects when we entered
6948 /// this expression evaluation context.
6950
6952
6953 /// The lambdas that are present within this context, if it
6954 /// is indeed an unevaluated context.
6956
6957 /// The declaration that provides context for lambda expressions
6958 /// and block literals if the normal declaration context does not
6959 /// suffice, e.g., in a default function argument.
6961
6962 /// Declaration for initializer if one is currently being
6963 /// parsed. Used when an expression has a possibly unreachable
6964 /// diagnostic to reference the declaration as a whole.
6966
6967 /// If we are processing a decltype type, a set of call expressions
6968 /// for which we have deferred checking the completeness of the return type.
6970
6971 /// If we are processing a decltype type, a set of temporary binding
6972 /// expressions for which we have deferred checking the destructor.
6974
6976
6977 /// Expressions appearing as the LHS of a volatile assignment in this
6978 /// context. We produce a warning for these when popping the context if
6979 /// they are not discarded-value expressions nor unevaluated operands.
6981
6982 /// Set of candidates for starting an immediate invocation.
6985
6986 /// Set of DeclRefExprs referencing a consteval function when used in a
6987 /// context not already known to be immediately invoked.
6989
6990 /// P2718R0 - Lifetime extension in range-based for loops.
6991 /// MaterializeTemporaryExprs in for-range-init expressions which need to
6992 /// extend lifetime. Add MaterializeTemporaryExpr* if the value of
6993 /// InLifetimeExtendingContext is true.
6995
6996 /// Small set of gathered accesses to potentially misaligned members
6997 /// due to the packed attribute.
6999
7000 /// \brief Describes whether we are in an expression constext which we have
7001 /// to handle differently.
7009
7010 // A context can be nested in both a discarded statement context and
7011 // an immediate function context, so they need to be tracked independently.
7015
7017
7018 // We are in a constant context, but we also allow
7019 // non constant expressions, for example for array bounds (which may be
7020 // VLAs).
7022
7023 /// Whether we are currently in a context in which all temporaries must be
7024 /// lifetime-extended, even if they're not bound to a reference (for
7025 /// example, in a for-range initializer).
7027
7028 /// Whether evaluating an expression for a switch case label.
7029 bool IsCaseExpr = false;
7030
7031 /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
7033
7034 // When evaluating immediate functions in the initializer of a default
7035 // argument or default member initializer, this is the declaration whose
7036 // default initializer is being evaluated and the location of the call
7037 // or constructor definition.
7041 : Loc(Loc), Decl(Decl), Context(Context) {
7042 assert(Decl && Context && "invalid initialization context");
7043 }
7044
7046 ValueDecl *Decl = nullptr;
7048 };
7049 std::optional<InitializationContext> DelayedDefaultInitializationContext;
7050
7061
7067
7074
7079
7084 // C++23 [expr.const]p14:
7085 // An expression or conversion is in an immediate function
7086 // context if it is potentially evaluated and either:
7087 // * its innermost enclosing non-block scope is a function
7088 // parameter scope of an immediate function, or
7089 // * its enclosing statement is enclosed by the compound-
7090 // statement of a consteval if statement.
7093 }
7094
7102 };
7103
7105 assert(!ExprEvalContexts.empty() &&
7106 "Must be in an expression evaluation context");
7107 return ExprEvalContexts.back();
7108 }
7109
7111 assert(!ExprEvalContexts.empty() &&
7112 "Must be in an expression evaluation context");
7113 return ExprEvalContexts.back();
7114 }
7115
7117 assert(ExprEvalContexts.size() >= 2 &&
7118 "Must be in an expression evaluation context");
7119 return ExprEvalContexts[ExprEvalContexts.size() - 2];
7120 }
7121
7123 return const_cast<Sema *>(this)->parentEvaluationContext();
7124 }
7125
7130
7131 /// Increment when we find a reference; decrement when we find an ignored
7132 /// assignment. Ultimately the value is 0 if every reference is an ignored
7133 /// assignment.
7134 ///
7135 /// Uses canonical VarDecl as key so in-class decls and out-of-class defs of
7136 /// static data members get tracked as a single entry.
7137 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
7138
7139 /// Used to control the generation of ExprWithCleanups.
7141
7142 /// ExprCleanupObjects - This is the stack of objects requiring
7143 /// cleanup that are created by the current full expression.
7145
7146 /// Determine whether the use of this declaration is valid, without
7147 /// emitting diagnostics.
7148 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
7149 // A version of DiagnoseUseOfDecl that should be used if overload resolution
7150 // has been used to find this declaration, which means we don't have to bother
7151 // checking the trailing requires clause.
7153 return DiagnoseUseOfDecl(
7154 D, Loc, /*UnknownObjCClass=*/nullptr, /*ObjCPropertyAccess=*/false,
7155 /*AvoidPartialAvailabilityChecks=*/false, /*ClassReceiver=*/nullptr,
7156 /*SkipTrailingRequiresClause=*/true);
7157 }
7158
7159 /// Determine whether the use of this declaration is valid, and
7160 /// emit any corresponding diagnostics.
7161 ///
7162 /// This routine diagnoses various problems with referencing
7163 /// declarations that can occur when using a declaration. For example,
7164 /// it might warn if a deprecated or unavailable declaration is being
7165 /// used, or produce an error (and return true) if a C++0x deleted
7166 /// function is being used.
7167 ///
7168 /// \returns true if there was an error (this declaration cannot be
7169 /// referenced), false otherwise.
7171 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
7172 bool ObjCPropertyAccess = false,
7173 bool AvoidPartialAvailabilityChecks = false,
7174 ObjCInterfaceDecl *ClassReceiver = nullptr,
7175 bool SkipTrailingRequiresClause = false);
7176
7177 /// Emit a note explaining that this function is deleted.
7179
7180 /// DiagnoseSentinelCalls - This routine checks whether a call or
7181 /// message-send is to a declaration with the sentinel attribute, and
7182 /// if so, it checks that the requirements of the sentinel are
7183 /// satisfied.
7185 ArrayRef<Expr *> Args);
7186
7188 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
7191
7193 ExpressionEvaluationContext NewContext, FunctionDecl *FD);
7194
7197 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
7201
7203
7207
7208 /// Check whether E, which is either a discarded-value expression or an
7209 /// unevaluated operand, is a simple-assignment to a volatlie-qualified
7210 /// lvalue, and if so, remove it from the list of volatile-qualified
7211 /// assignments that we are going to warn are deprecated.
7213
7215
7216 // Functions for marking a declaration referenced. These functions also
7217 // contain the relevant logic for marking if a reference to a function or
7218 // variable is an odr-use (in the C++11 sense). There are separate variants
7219 // for expressions referring to a decl; these exist because odr-use marking
7220 // needs to be delayed for some constant variables when we build one of the
7221 // named expressions.
7222 //
7223 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
7224 // should usually be true. This only needs to be set to false if the lack of
7225 // odr-use cannot be determined from the current context (for instance,
7226 // because the name denotes a virtual function and was written without an
7227 // explicit nested-name-specifier).
7228 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
7229
7230 /// Mark a function referenced, and check whether it is odr-used
7231 /// (C++ [basic.def.odr]p2, C99 6.9p3)
7233 bool MightBeOdrUse = true);
7234
7235 /// Mark a variable referenced, and check whether it is odr-used
7236 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
7237 /// used directly for normal expressions referring to VarDecl.
7239
7240 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
7241 ///
7242 /// Note, this may change the dependence of the DeclRefExpr, and so needs to
7243 /// be handled with care if the DeclRefExpr is not newly-created.
7244 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
7245
7246 /// Perform reference-marking and odr-use handling for a MemberExpr.
7248
7249 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
7252 unsigned CapturingScopeIndex);
7253
7255 void CleanupVarDeclMarking();
7256
7257 /// Try to capture the given variable.
7258 ///
7259 /// \param Var The variable to capture.
7260 ///
7261 /// \param Loc The location at which the capture occurs.
7262 ///
7263 /// \param Kind The kind of capture, which may be implicit (for either a
7264 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
7265 ///
7266 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
7267 /// an explicit lambda capture.
7268 ///
7269 /// \param BuildAndDiagnose Whether we are actually supposed to add the
7270 /// captures or diagnose errors. If false, this routine merely check whether
7271 /// the capture can occur without performing the capture itself or complaining
7272 /// if the variable cannot be captured.
7273 ///
7274 /// \param CaptureType Will be set to the type of the field used to capture
7275 /// this variable in the innermost block or lambda. Only valid when the
7276 /// variable can be captured.
7277 ///
7278 /// \param DeclRefType Will be set to the type of a reference to the capture
7279 /// from within the current scope. Only valid when the variable can be
7280 /// captured.
7281 ///
7282 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
7283 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
7284 /// This is useful when enclosing lambdas must speculatively capture
7285 /// variables that may or may not be used in certain specializations of
7286 /// a nested generic lambda.
7287 ///
7288 /// \returns true if an error occurred (i.e., the variable cannot be
7289 /// captured) and false if the capture succeeded.
7291 TryCaptureKind Kind, SourceLocation EllipsisLoc,
7292 bool BuildAndDiagnose, QualType &CaptureType,
7293 QualType &DeclRefType,
7294 const unsigned *const FunctionScopeIndexToStopAt);
7295
7296 /// Try to capture the given variable.
7299 SourceLocation EllipsisLoc = SourceLocation());
7300
7301 /// Checks if the variable must be captured.
7303
7304 /// Given a variable, determine the type that a reference to that
7305 /// variable will have in the given scope.
7307
7308 /// Mark all of the declarations referenced within a particular AST node as
7309 /// referenced. Used when template instantiation instantiates a non-dependent
7310 /// type -- entities referenced by the type are now referenced.
7312
7313 /// Mark any declarations that appear within this expression or any
7314 /// potentially-evaluated subexpressions as "referenced".
7315 ///
7316 /// \param SkipLocalVariables If true, don't mark local variables as
7317 /// 'referenced'.
7318 /// \param StopAt Subexpressions that we shouldn't recurse into.
7320 bool SkipLocalVariables = false,
7321 ArrayRef<const Expr *> StopAt = {});
7322
7323 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
7324 /// conversion.
7325 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
7326
7327 /// Conditionally issue a diagnostic based on the statements's reachability
7328 /// analysis.
7329 ///
7330 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
7331 /// the function body is parsed, and then do a basic reachability analysis to
7332 /// determine if the statement is reachable. If it is unreachable, the
7333 /// diagnostic will not be emitted.
7334 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7335 const PartialDiagnostic &PD);
7336
7337 /// Conditionally issue a diagnostic based on the current
7338 /// evaluation context.
7339 ///
7340 /// \param Statement If Statement is non-null, delay reporting the
7341 /// diagnostic until the function body is parsed, and then do a basic
7342 /// reachability analysis to determine if the statement is reachable.
7343 /// If it is unreachable, the diagnostic will not be emitted.
7344 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
7345 const PartialDiagnostic &PD);
7346 /// Similar, but diagnostic is only produced if all the specified statements
7347 /// are reachable.
7348 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7349 const PartialDiagnostic &PD);
7350
7351 // Primary Expressions.
7352 SourceRange getExprRange(Expr *E) const;
7353
7354 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
7355 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
7356 bool HasTrailingLParen, bool IsAddressOfOperand,
7357 CorrectionCandidateCallback *CCC = nullptr,
7358 bool IsInlineAsmIdentifier = false);
7359
7360 /// Decomposes the given name into a DeclarationNameInfo, its location, and
7361 /// possibly a list of template arguments.
7362 ///
7363 /// If this produces template arguments, it is permitted to call
7364 /// DecomposeTemplateName.
7365 ///
7366 /// This actually loses a lot of source location information for
7367 /// non-standard name kinds; we should consider preserving that in
7368 /// some way.
7369 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
7370 TemplateArgumentListInfo &Buffer,
7371 DeclarationNameInfo &NameInfo,
7372 const TemplateArgumentListInfo *&TemplateArgs);
7373
7374 /// Diagnose a lookup that found results in an enclosing class during error
7375 /// recovery. This usually indicates that the results were found in a
7376 /// dependent base class that could not be searched as part of a template
7377 /// definition. Always issues a diagnostic (though this may be only a warning
7378 /// in MS compatibility mode).
7379 ///
7380 /// Return \c true if the error is unrecoverable, or \c false if the caller
7381 /// should attempt to recover using these lookup results.
7382 bool DiagnoseDependentMemberLookup(const LookupResult &R);
7383
7384 /// Diagnose an empty lookup.
7385 ///
7386 /// \return false if new lookup candidates were found
7387 bool
7388 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
7389 CorrectionCandidateCallback &CCC,
7390 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
7391 ArrayRef<Expr *> Args = {},
7392 DeclContext *LookupCtx = nullptr);
7393
7394 /// If \p D cannot be odr-used in the current expression evaluation context,
7395 /// return a reason explaining why. Otherwise, return NOUR_None.
7397
7398 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7399 SourceLocation Loc,
7400 const CXXScopeSpec *SS = nullptr);
7401 DeclRefExpr *
7402 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7403 const DeclarationNameInfo &NameInfo,
7404 const CXXScopeSpec *SS = nullptr,
7405 NamedDecl *FoundD = nullptr,
7406 SourceLocation TemplateKWLoc = SourceLocation(),
7407 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7408
7409 /// BuildDeclRefExpr - Build an expression that references a
7410 /// declaration that does not require a closure capture.
7411 DeclRefExpr *
7412 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7413 const DeclarationNameInfo &NameInfo,
7414 NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr,
7415 SourceLocation TemplateKWLoc = SourceLocation(),
7416 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7417
7418 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R,
7419 bool HasTrailingLParen);
7420
7421 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
7422 /// declaration name, generally during template instantiation.
7423 /// There's a large number of things which don't need to be done along
7424 /// this path.
7426 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
7427 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
7428
7429 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R,
7430 bool NeedsADL,
7431 bool AcceptInvalidDecl = false);
7432
7433 /// Complete semantic analysis for a reference to the given declaration.
7435 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
7436 NamedDecl *FoundD = nullptr,
7437 const TemplateArgumentListInfo *TemplateArgs = nullptr,
7438 bool AcceptInvalidDecl = false);
7439
7440 // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens,
7441 // where Tokens representing function local predefined macros (such as
7442 // __FUNCTION__) are replaced (expanded) with string-literal Tokens.
7443 std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks);
7444
7445 ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK);
7446 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
7447 ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val);
7448
7449 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero);
7450
7451 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
7453 Scope *UDLScope = nullptr);
7454 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
7455 ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R,
7456 MultiExprArg Val);
7457 ExprResult ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
7458 unsigned NumUserSpecifiedExprs,
7459 SourceLocation InitLoc,
7460 SourceLocation LParenLoc,
7461 SourceLocation RParenLoc);
7462
7463 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
7464 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle
7465 /// string concatenation ([C99 5.1.1.2, translation phase #6]), so it may come
7466 /// from multiple tokens. However, the common case is that StringToks points
7467 /// to one string.
7468 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
7469 Scope *UDLScope = nullptr);
7470
7471 ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks);
7472
7473 /// ControllingExprOrType is either an opaque pointer coming out of a
7474 /// ParsedType or an Expr *. FIXME: it'd be better to split this interface
7475 /// into two so we don't take a void *, but that's awkward because one of
7476 /// the operands is either a ParsedType or an Expr *, which doesn't lend
7477 /// itself to generic code very well.
7478 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
7479 SourceLocation DefaultLoc,
7480 SourceLocation RParenLoc,
7481 bool PredicateIsExpr,
7482 void *ControllingExprOrType,
7483 ArrayRef<ParsedType> ArgTypes,
7484 ArrayRef<Expr *> ArgExprs);
7485 /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME:
7486 /// it'd be better to split this interface into two so we don't take a
7487 /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that
7488 /// isn't a trivial change.
7489 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
7490 SourceLocation DefaultLoc,
7491 SourceLocation RParenLoc,
7492 bool PredicateIsExpr,
7493 void *ControllingExprOrType,
7494 ArrayRef<TypeSourceInfo *> Types,
7495 ArrayRef<Expr *> Exprs);
7496
7497 // Binary/Unary Operators. 'Tok' is the token for the operator.
7498 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
7499 Expr *InputExpr, bool IsAfterAmp = false);
7500 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
7501 Expr *Input, bool IsAfterAmp = false);
7502
7503 /// Unary Operators. 'Tok' is the token for the operator.
7504 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
7505 Expr *Input, bool IsAfterAmp = false);
7506
7507 /// Determine whether the given expression is a qualified member
7508 /// access expression, of a form that could be turned into a pointer to member
7509 /// with the address-of operator.
7510 bool isQualifiedMemberAccess(Expr *E);
7511 bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
7512 const Expr *Op,
7513 const CXXMethodDecl *MD);
7514
7515 /// CheckAddressOfOperand - The operand of & must be either a function
7516 /// designator or an lvalue designating an object. If it is an lvalue, the
7517 /// object cannot be declared with storage class register or be a bit field.
7518 /// Note: The usual conversions are *not* applied to the operand of the &
7519 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7520 /// In C++, the operand might be an overloaded function name, in which case
7521 /// we allow the '&' but retain the overloaded-function type.
7522 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
7523
7524 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
7525 /// _Alignas(type-name) .
7526 /// [dcl.align] An alignment-specifier of the form
7527 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
7528 ///
7529 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
7530 /// _Alignas(_Alignof(type-name)).
7531 bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
7532 SourceLocation OpLoc, SourceRange R);
7533 bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
7534 SourceLocation OpLoc, SourceRange R);
7535
7536 /// Build a sizeof or alignof expression given a type operand.
7537 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
7538 SourceLocation OpLoc,
7539 UnaryExprOrTypeTrait ExprKind,
7540 SourceRange R);
7541
7542 /// Build a sizeof or alignof expression given an expression
7543 /// operand.
7544 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
7545 UnaryExprOrTypeTrait ExprKind);
7546
7547 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
7548 /// expr and the same for @c alignof and @c __alignof
7549 /// Note that the ArgRange is invalid if isType is false.
7550 ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
7551 UnaryExprOrTypeTrait ExprKind,
7552 bool IsType, void *TyOrEx,
7553 SourceRange ArgRange);
7554
7555 /// Check for operands with placeholder types and complain if found.
7556 /// Returns ExprError() if there was an error and no recovery was possible.
7558 bool CheckVecStepExpr(Expr *E);
7559
7560 /// Check the constraints on expression operands to unary type expression
7561 /// and type traits.
7562 ///
7563 /// Completes any types necessary and validates the constraints on the operand
7564 /// expression. The logic mostly mirrors the type-based overload, but may
7565 /// modify the expression as it completes the type for that expression through
7566 /// template instantiation, etc.
7567 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
7568
7569 /// Check the constraints on operands to unary expression and type
7570 /// traits.
7571 ///
7572 /// This will complete any types necessary, and validate the various
7573 /// constraints on those operands.
7574 ///
7575 /// The UsualUnaryConversions() function is *not* called by this routine.
7576 /// C99 6.3.2.1p[2-4] all state:
7577 /// Except when it is the operand of the sizeof operator ...
7578 ///
7579 /// C++ [expr.sizeof]p4
7580 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
7581 /// standard conversions are not applied to the operand of sizeof.
7582 ///
7583 /// This policy is followed for all of the unary trait expressions.
7584 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
7585 SourceRange ExprRange,
7586 UnaryExprOrTypeTrait ExprKind,
7587 StringRef KWName);
7588
7589 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
7590 tok::TokenKind Kind, Expr *Input);
7591
7592 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
7593 MultiExprArg ArgExprs,
7594 SourceLocation RLoc);
7595 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
7596 Expr *Idx, SourceLocation RLoc);
7597
7598 ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx,
7599 SourceLocation RBLoc);
7600
7601 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
7602 Expr *ColumnIdx,
7603 SourceLocation RBLoc);
7604
7605 /// ConvertArgumentsForCall - Converts the arguments specified in
7606 /// Args/NumArgs to the parameter types of the function FDecl with
7607 /// function prototype Proto. Call is the call expression itself, and
7608 /// Fn is the function expression. For a C++ member function, this
7609 /// routine does not attempt to convert the object argument. Returns
7610 /// true if the call is ill-formed.
7611 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl,
7612 const FunctionProtoType *Proto,
7613 ArrayRef<Expr *> Args, SourceLocation RParenLoc,
7614 bool ExecConfig = false);
7615
7616 /// CheckStaticArrayArgument - If the given argument corresponds to a static
7617 /// array parameter, check that it is non-null, and that if it is formed by
7618 /// array-to-pointer decay, the underlying array is sufficiently large.
7619 ///
7620 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of
7621 /// the array type derivation, then for each call to the function, the value
7622 /// of the corresponding actual argument shall provide access to the first
7623 /// element of an array with at least as many elements as specified by the
7624 /// size expression.
7625 void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param,
7626 const Expr *ArgExpr);
7627
7628 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
7629 /// This provides the location of the left/right parens and a list of comma
7630 /// locations.
7631 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7632 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7633 Expr *ExecConfig = nullptr);
7634
7635 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7636 /// This provides the location of the left/right parens and a list of comma
7637 /// locations.
7638 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7639 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7640 Expr *ExecConfig = nullptr,
7641 bool IsExecConfig = false,
7642 bool AllowRecovery = false);
7643
7644 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7645 // with the specified CallArgs
7646 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7647 MultiExprArg CallArgs);
7648
7650
7651 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7652 /// i.e. an expression not of \p OverloadTy. The expression should
7653 /// unary-convert to an expression of function-pointer or
7654 /// block-pointer type.
7655 ///
7656 /// \param NDecl the declaration being called, if available
7658 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
7659 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
7660 Expr *Config = nullptr, bool IsExecConfig = false,
7661 ADLCallKind UsesADL = ADLCallKind::NotADL);
7662
7664 ParsedType &Ty, SourceLocation RParenLoc,
7665 Expr *CastExpr);
7666
7667 /// Prepares for a scalar cast, performing all the necessary stages
7668 /// except the final cast and returning the kind required.
7670
7671 /// Build an altivec or OpenCL literal.
7673 SourceLocation RParenLoc, Expr *E,
7674 TypeSourceInfo *TInfo);
7675
7676 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7677 /// the ParenListExpr into a sequence of comma binary operators.
7679
7681 SourceLocation RParenLoc, Expr *InitExpr);
7682
7684 TypeSourceInfo *TInfo,
7685 SourceLocation RParenLoc,
7686 Expr *LiteralExpr);
7687
7688 ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7689 SourceLocation RBraceLoc);
7690
7691 ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7692 SourceLocation RBraceLoc, bool IsExplicit);
7693
7694 /// Binary Operators. 'Tok' is the token for the operator.
7696 Expr *LHSExpr, Expr *RHSExpr);
7698 Expr *LHSExpr, Expr *RHSExpr,
7699 bool ForFoldExpression = false);
7700
7701 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7702 /// operator @p Opc at location @c TokLoc. This routine only supports
7703 /// built-in operations; ActOnBinOp handles overloaded operators.
7705 Expr *LHSExpr, Expr *RHSExpr,
7706 bool ForFoldExpression = false);
7708 UnresolvedSetImpl &Functions);
7709
7710 /// Look for instances where it is likely the comma operator is confused with
7711 /// another operator. There is an explicit list of acceptable expressions for
7712 /// the left hand side of the comma operator, otherwise emit a warning.
7713 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
7714
7715 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7716 /// in the case of a the GNU conditional expr extension.
7718 SourceLocation ColonLoc, Expr *CondExpr,
7719 Expr *LHSExpr, Expr *RHSExpr);
7720
7721 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
7723 LabelDecl *TheDecl);
7724
7725 void ActOnStartStmtExpr();
7726 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
7727 SourceLocation RPLoc);
7729 SourceLocation RPLoc, unsigned TemplateDepth);
7730 // Handle the final expression in a statement expression.
7732 void ActOnStmtExprError();
7733
7734 /// __builtin_offsetof(type, a.b[123][456].c)
7736 TypeSourceInfo *TInfo,
7737 const Designation &Desig,
7738 SourceLocation RParenLoc);
7741 ParsedType ParsedArgTy,
7742 const Designation &Desig,
7743 SourceLocation RParenLoc);
7744
7745 // __builtin_choose_expr(constExpr, expr1, expr2)
7746 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr,
7747 Expr *LHSExpr, Expr *RHSExpr,
7748 SourceLocation RPLoc);
7749
7750 // __builtin_va_arg(expr, type)
7752 SourceLocation RPLoc);
7754 TypeSourceInfo *TInfo, SourceLocation RPLoc);
7755
7756 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(),
7757 // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location()
7759 SourceLocation BuiltinLoc,
7760 SourceLocation RPLoc);
7761
7762 // #embed
7764 StringLiteral *BinaryData, StringRef FileName);
7765
7766 // Build a potentially resolved SourceLocExpr.
7768 SourceLocation BuiltinLoc, SourceLocation RPLoc,
7769 DeclContext *ParentContext);
7770
7771 // __null
7773
7774 bool CheckCaseExpression(Expr *E);
7775
7776 //===------------------------- "Block" Extension ------------------------===//
7777
7778 /// ActOnBlockStart - This callback is invoked when a block literal is
7779 /// started.
7780 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
7781
7782 /// ActOnBlockArguments - This callback allows processing of block arguments.
7783 /// If there are no arguments, this is still invoked.
7784 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
7785 Scope *CurScope);
7786
7787 /// ActOnBlockError - If there is an error parsing a block, this callback
7788 /// is invoked to pop the information about the block from the action impl.
7789 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
7790
7791 /// ActOnBlockStmtExpr - This is called when the body of a block statement
7792 /// literal was successfully completed. ^(int x){...}
7794 Scope *CurScope);
7795
7796 //===---------------------------- Clang Extensions ----------------------===//
7797
7798 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7799 /// provided arguments.
7800 ///
7801 /// __builtin_convertvector( value, dst type )
7802 ///
7804 SourceLocation BuiltinLoc,
7805 SourceLocation RParenLoc);
7806
7807 //===---------------------------- OpenCL Features -----------------------===//
7808
7809 /// Parse a __builtin_astype expression.
7810 ///
7811 /// __builtin_astype( value, dst type )
7812 ///
7813 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7814 SourceLocation BuiltinLoc,
7815 SourceLocation RParenLoc);
7816
7817 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7819 SourceLocation BuiltinLoc,
7820 SourceLocation RParenLoc);
7821
7822 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
7824 ArrayRef<Expr *> SubExprs,
7825 QualType T = QualType());
7826
7827 /// Cast a base object to a member's actual type.
7828 ///
7829 /// There are two relevant checks:
7830 ///
7831 /// C++ [class.access.base]p7:
7832 ///
7833 /// If a class member access operator [...] is used to access a non-static
7834 /// data member or non-static member function, the reference is ill-formed
7835 /// if the left operand [...] cannot be implicitly converted to a pointer to
7836 /// the naming class of the right operand.
7837 ///
7838 /// C++ [expr.ref]p7:
7839 ///
7840 /// If E2 is a non-static data member or a non-static member function, the
7841 /// program is ill-formed if the class of which E2 is directly a member is
7842 /// an ambiguous base (11.8) of the naming class (11.9.3) of E2.
7843 ///
7844 /// Note that the latter check does not consider access; the access of the
7845 /// "real" base class is checked as appropriate when checking the access of
7846 /// the member name.
7848 NestedNameSpecifier Qualifier,
7849 NamedDecl *FoundDecl,
7850 NamedDecl *Member);
7851
7852 /// CheckCallReturnType - Checks that a call expression's return type is
7853 /// complete. Returns true on failure. The location passed in is the location
7854 /// that best represents the call.
7855 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7856 CallExpr *CE, FunctionDecl *FD);
7857
7858 /// Emit a warning for all pending noderef expressions that we recorded.
7860
7861private:
7862 /// Shared logic for building default member initializer which used in a
7863 /// constructor or an aggregate initialization.
7864 ///
7865 ///
7866 /// The caller enters that evaluation context and decides whether the result
7867 /// is finished as a full-expression. \p NestedDefaultChecking and
7868 /// \p NeedRebuild have to be sampled before entering it.
7869 ExprResult BuildCXXDefaultInitInternal(SourceLocation Loc, FieldDecl *Field,
7870 const InitializedEntity &Entity,
7871 bool NestedDefaultChecking,
7872 bool NeedRebuild);
7873
7874public:
7878 const InitializedEntity &MemberEntity);
7879
7880 /// Instantiate or parse a C++ default argument expression as necessary.
7881 /// Return true on error.
7883 ParmVarDecl *Param, Expr *Init = nullptr,
7884 bool SkipImmediateInvocations = true);
7885
7886 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
7887 /// the default expr if needed.
7889 ParmVarDecl *Param, Expr *Init = nullptr);
7890
7891 /// Wrap the expression in a ConstantExpr if it is a potential immediate
7892 /// invocation.
7894
7896
7897 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
7898 bool IsInvalidSMECallConversion(QualType FromType, QualType ToType);
7899
7900 /// Abstract base class used for diagnosing integer constant
7901 /// expression violations.
7903 public:
7905
7907
7908 virtual SemaDiagnosticBuilder
7909 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
7911 SourceLocation Loc) = 0;
7914 };
7915
7916 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7917 /// and reports the appropriate diagnostics. Returns false on success.
7918 /// Can optionally return the value of the expression.
7921 VerifyICEDiagnoser &Diagnoser,
7925 unsigned DiagID,
7928 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr,
7932 AllowFoldKind CanFold = AllowFoldKind::No) {
7933 return VerifyIntegerConstantExpression(E, nullptr, CanFold);
7934 }
7935
7936 /// DiagnoseAssignmentAsCondition - Given that an expression is
7937 /// being used as a boolean condition, warn if it's an assignment.
7939
7940 /// Redundant parentheses over an equality comparison can indicate
7941 /// that the user intended an assignment used as condition.
7943
7945 public:
7947 FullExprArg(Sema &actions) : E(nullptr) {}
7948
7949 ExprResult release() { return E; }
7950
7951 Expr *get() const { return E; }
7952
7953 Expr *operator->() { return E; }
7954
7955 private:
7956 // FIXME: No need to make the entire Sema class a friend when it's just
7957 // Sema::MakeFullExpr that needs access to the constructor below.
7958 friend class Sema;
7959
7960 explicit FullExprArg(Expr *expr) : E(expr) {}
7961
7962 Expr *E;
7963 };
7964
7966 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
7967 }
7969 return FullExprArg(
7970 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
7971 }
7973 ExprResult FE =
7974 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
7975 /*DiscardedValue*/ true);
7976 return FullExprArg(FE.get());
7977 }
7978
7979 class ConditionResult {
7980 Decl *ConditionVar;
7981 ExprResult Condition;
7982 bool Invalid;
7983 std::optional<bool> KnownValue;
7984
7985 friend class Sema;
7986 ConditionResult(Sema &S, Decl *ConditionVar, ExprResult Condition,
7987 bool IsConstexpr)
7988 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
7989 if (IsConstexpr && Condition.get()) {
7990 if (std::optional<llvm::APSInt> Val =
7991 Condition.get()->getIntegerConstantExpr(S.Context)) {
7992 KnownValue = !!(*Val);
7993 }
7994 }
7995 }
7996 explicit ConditionResult(bool Invalid)
7997 : ConditionVar(nullptr), Condition(Invalid), Invalid(Invalid),
7998 KnownValue(std::nullopt) {}
7999
8000 public:
8001 ConditionResult() : ConditionResult(false) {}
8002 bool isInvalid() const { return Invalid; }
8003 std::pair<VarDecl *, Expr *> get() const {
8004 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
8005 Condition.get());
8006 }
8007 std::optional<bool> getKnownValue() const { return KnownValue; }
8008 };
8010
8011 /// CheckBooleanCondition - Diagnose problems involving the use of
8012 /// the given expression as a boolean condition (e.g. in an if
8013 /// statement). Also performs the standard function and array
8014 /// decays, possibly changing the input variable.
8015 ///
8016 /// \param Loc - A location associated with the condition, e.g. the
8017 /// 'if' keyword.
8018 /// \return true iff there were any errors
8020 bool IsConstexpr = false);
8021
8022 enum class ConditionKind {
8023 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
8024 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
8025 Switch ///< An integral condition for a 'switch' statement.
8026 };
8027
8028 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
8029 ConditionKind CK, bool MissingOK = false);
8030
8031 QualType CheckConditionalOperands( // C99 6.5.15
8032 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
8033 ExprObjectKind &OK, SourceLocation QuestionLoc);
8034
8035 /// Emit a specialized diagnostic when one expression is a null pointer
8036 /// constant and the other is not a pointer. Returns true if a diagnostic is
8037 /// emitted.
8038 bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8039 SourceLocation QuestionLoc);
8040
8041 /// type checking for vector binary operators.
8043 SourceLocation Loc, bool IsCompAssign,
8044 bool AllowBothBool, bool AllowBoolConversion,
8045 bool AllowBoolOperation);
8046
8047 /// Return a signed ext_vector_type that is of identical size and number of
8048 /// elements. For floating point vectors, return an integer type of identical
8049 /// size and number of elements. In the non ext_vector_type case, search from
8050 /// the largest type to the smallest type to avoid cases where long long ==
8051 /// long, where long gets picked over long long.
8054
8055 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8056 /// operates on extended vector types. Instead of producing an IntTy result,
8057 /// like a scalar comparison, a vector comparison produces a vector of integer
8058 /// types.
8060 SourceLocation Loc,
8061 BinaryOperatorKind Opc);
8063 SourceLocation Loc,
8064 BinaryOperatorKind Opc);
8066 SourceLocation Loc,
8067 BinaryOperatorKind Opc);
8069 SourceLocation Loc,
8070 BinaryOperatorKind Opc);
8072 SourceLocation Loc,
8073 BinaryOperatorKind Opc);
8074 // type checking for sizeless vector binary operators.
8076 SourceLocation Loc, bool IsCompAssign,
8077 ArithConvKind OperationKind);
8078
8079 /// Type checking for matrix binary operators.
8081 SourceLocation Loc,
8082 bool IsCompAssign);
8084 SourceLocation Loc, bool IsCompAssign);
8085
8086 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from
8087 /// the first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE
8088 /// VLST) allowed?
8089 ///
8090 /// This will also return false if the two given types do not make sense from
8091 /// the perspective of SVE bitcasts.
8092 bool isValidSveBitcast(QualType srcType, QualType destType);
8093
8094 /// Are the two types matrix types and do they have the same dimensions i.e.
8095 /// do they have the same number of rows and the same number of columns?
8097
8098 bool areVectorTypesSameSize(QualType srcType, QualType destType);
8099
8100 /// Are the two types lax-compatible vector types? That is, given
8101 /// that one of them is a vector, do they have equal storage sizes,
8102 /// where the storage size is the number of elements times the element
8103 /// size?
8104 ///
8105 /// This will also return false if either of the types is neither a
8106 /// vector nor a real type.
8107 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
8108
8109 /// Is this a legal conversion between two types, one of which is
8110 /// known to be a vector type?
8111 bool isLaxVectorConversion(QualType srcType, QualType destType);
8112
8113 // This returns true if at least one of the types is an altivec vector.
8114 bool anyAltivecTypes(QualType srcType, QualType destType);
8115
8116 // type checking C++ declaration initializers (C++ [dcl.init]).
8117
8118 /// Check a cast of an unknown-any type. We intentionally only
8119 /// trigger this for C-style casts.
8122 ExprValueKind &VK, CXXCastPath &Path);
8123
8124 /// Force an expression with unknown-type to an expression of the
8125 /// given type.
8127
8128 /// Type-check an expression that's being passed to an
8129 /// __unknown_anytype parameter.
8131 QualType &paramType);
8132
8133 // CheckMatrixCast - Check type constraints for matrix casts.
8134 // We allow casting between matrixes of the same dimensions i.e. when they
8135 // have the same number of rows and column. Returns true if the cast is
8136 // invalid.
8137 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8138 CastKind &Kind);
8139
8140 // CheckVectorCast - check type constraints for vectors.
8141 // Since vectors are an extension, there are no C standard reference for this.
8142 // We allow casting between vectors and integer datatypes of the same size.
8143 // returns true if the cast is invalid
8144 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8145 CastKind &Kind);
8146
8147 /// Prepare `SplattedExpr` for a vector splat operation, adding
8148 /// implicit casts if necessary.
8149 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
8150
8151 /// Prepare `SplattedExpr` for a matrix splat operation, adding
8152 /// implicit casts if necessary.
8153 ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr);
8154
8155 // CheckExtVectorCast - check type constraints for extended vectors.
8156 // Since vectors are an extension, there are no C standard reference for this.
8157 // We allow casting between vectors and integer datatypes of the same size,
8158 // or vectors and the element type of that vector.
8159 // returns the cast expr
8161 CastKind &Kind);
8162
8164 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
8165 }
8166
8167 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2), converts
8168 // functions and arrays to their respective pointers (C99 6.3.2.1), and
8169 // promotes floating-piont types according to the language semantics.
8171
8172 // UsualUnaryFPConversions - promotes floating-point types according to the
8173 // current language semantics.
8175
8176 /// CallExprUnaryConversions - a special case of an unary conversion
8177 /// performed on a function designator of a call expression.
8179
8180 // DefaultFunctionArrayConversion - converts functions and arrays
8181 // to their respective pointers (C99 6.3.2.1).
8183
8184 // DefaultFunctionArrayLvalueConversion - converts functions and
8185 // arrays to their respective pointers and performs the
8186 // lvalue-to-rvalue conversion.
8188 bool Diagnose = true);
8189
8190 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8191 // the operand. This function is a no-op if the operand has a function type
8192 // or an array type.
8194
8195 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8196 // do not have a prototype. Integer promotions are performed on each
8197 // argument, and arguments that have type float are promoted to double.
8199
8201 const FunctionProtoType *Proto,
8202 Expr *Fn);
8203
8204 /// Determine the degree of POD-ness for an expression.
8205 /// Incomplete types are considered POD, since this check can be performed
8206 /// when we're in an unevaluated context.
8208
8209 /// Check to see if the given expression is a valid argument to a variadic
8210 /// function, issuing a diagnostic if not.
8211 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8212
8213 /// GatherArgumentsForCall - Collector argument expressions for various
8214 /// form of call prototypes.
8216 SourceLocation CallLoc, FunctionDecl *FDecl,
8217 const FunctionProtoType *Proto, unsigned FirstParam,
8220 bool AllowExplicit = false, bool IsListInitialization = false);
8221
8222 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8223 // will create a runtime trap if the resulting type is not a POD type.
8225 FunctionDecl *FDecl);
8226
8227 // Check that the usual arithmetic conversions can be performed on this pair
8228 // of expressions that might be of enumeration type.
8230 ArithConvKind ACK);
8231
8232 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8233 // operands and then handles various conversions that are common to binary
8234 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8235 // routine returns the first non-arithmetic type found. The client is
8236 // responsible for emitting appropriate error diagnostics.
8238 SourceLocation Loc, ArithConvKind ACK);
8239
8241 switch (ConvTy) {
8242 default:
8243 return false;
8247 return true;
8248 }
8249 llvm_unreachable("impossible");
8250 }
8251
8252 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8253 /// assignment conversion type specified by ConvTy. This returns true if the
8254 /// conversion was invalid or false if the conversion was accepted.
8256 QualType DstType, QualType SrcType,
8257 Expr *SrcExpr, AssignmentAction Action,
8258 bool *Complained = nullptr);
8259
8260 /// CheckAssignmentConstraints - Perform type checking for assignment,
8261 /// argument passing, variable initialization, and function return values.
8262 /// C99 6.5.16.
8264 QualType LHSType,
8265 QualType RHSType);
8266
8267 /// Check assignment constraints and optionally prepare for a conversion of
8268 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8269 /// is true.
8271 ExprResult &RHS, CastKind &Kind,
8272 bool ConvertRHS = true);
8273
8274 /// Check assignment constraints for an assignment of RHS to LHSType.
8275 ///
8276 /// \param LHSType The destination type for the assignment.
8277 /// \param RHS The source expression for the assignment.
8278 /// \param Diagnose If \c true, diagnostics may be produced when checking
8279 /// for assignability. If a diagnostic is produced, \p RHS will be
8280 /// set to ExprError(). Note that this function may still return
8281 /// without producing a diagnostic, even for an invalid assignment.
8282 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
8283 /// in an audited Core Foundation API and does not need to be checked
8284 /// for ARC retain issues.
8285 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
8286 /// conversions necessary to perform the assignment. If \c false,
8287 /// \p Diagnose must also be \c false.
8289 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
8290 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
8291
8292 // If the lhs type is a transparent union, check whether we
8293 // can initialize the transparent union with the given expression.
8295 ExprResult &RHS);
8296
8297 /// the following "Check" methods will return a valid/converted QualType
8298 /// or a null QualType (indicating an error diagnostic was issued).
8299
8300 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8302 ExprResult &RHS);
8303
8304 /// Diagnose cases where a scalar was implicitly converted to a vector and
8305 /// diagnose the underlying types. Otherwise, diagnose the error
8306 /// as invalid vector logical operands for non-C++ cases.
8308 ExprResult &RHS);
8309
8311 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8312 BinaryOperatorKind Opc);
8313 QualType CheckRemainderOperands( // C99 6.5.5
8314 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8315 bool IsCompAssign = false);
8316 QualType CheckAdditionOperands( // C99 6.5.6
8317 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8318 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8320 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8321 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8322 QualType CheckShiftOperands( // C99 6.5.7
8323 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8324 BinaryOperatorKind Opc, bool IsCompAssign = false);
8326 QualType CheckCompareOperands( // C99 6.5.8/9
8327 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8328 BinaryOperatorKind Opc);
8329 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8330 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8331 BinaryOperatorKind Opc);
8332 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8333 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8334 BinaryOperatorKind Opc);
8335 // CheckAssignmentOperands is used for both simple and compound assignment.
8336 // For simple assignment, pass both expressions and a null converted type.
8337 // For compound assignment, pass both expressions and the converted type.
8338 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8339 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
8340 BinaryOperatorKind Opc);
8341
8342 /// To be used for checking whether the arguments being passed to
8343 /// function exceeds the number of parameters expected for it.
8344 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
8345 bool PartialOverloading = false) {
8346 // We check whether we're just after a comma in code-completion.
8347 if (NumArgs > 0 && PartialOverloading)
8348 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
8349 return NumArgs > NumParams;
8350 }
8351
8352 /// Whether the AST is currently being rebuilt to correct immediate
8353 /// invocations. Immediate invocation candidates and references to consteval
8354 /// functions aren't tracked when this is set.
8356
8362
8363 /// Determines whether we are currently in a context that
8364 /// is not evaluated as per C++ [expr] p5.
8367 }
8368
8372
8376
8380
8387
8388 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8390 assert(!ExprEvalContexts.empty() &&
8391 "Must be in an expression evaluation context");
8392 for (const auto &Ctx : llvm::reverse(ExprEvalContexts)) {
8394 Ctx.DelayedDefaultInitializationContext)
8395 return Ctx.DelayedDefaultInitializationContext;
8396 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8397 Ctx.isUnevaluated())
8398 break;
8399 }
8400 return std::nullopt;
8401 }
8402
8403 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8405 assert(!ExprEvalContexts.empty() &&
8406 "Must be in an expression evaluation context");
8407 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
8408 for (auto &Ctx : llvm::reverse(ExprEvalContexts)) {
8410 !Ctx.DelayedDefaultInitializationContext && Res)
8411 break;
8412 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8413 Ctx.isUnevaluated())
8414 break;
8415 Res = Ctx.DelayedDefaultInitializationContext;
8416 }
8417 return Res;
8418 }
8419
8420 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
8421 /// SelfAssigned when inside a CXXMethodDecl.
8422 const FieldDecl *
8424
8426
8427 template <typename... Ts>
8429 const Ts &...Args) {
8430 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8431 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
8432 }
8433
8434 template <typename... Ts>
8435 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
8436 const Ts &...Args) {
8437 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8439 }
8440
8441 /// Abstract class used to diagnose incomplete types.
8444
8445 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
8446 virtual ~TypeDiagnoser() {}
8447 };
8448
8449 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
8450 protected:
8451 unsigned DiagID;
8452 std::tuple<const Ts &...> Args;
8453
8454 template <std::size_t... Is>
8456 std::index_sequence<Is...>) const {
8457 // Apply all tuple elements to the builder in order.
8458 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
8459 (void)Dummy;
8460 }
8461
8462 public:
8463 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8464 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
8465 assert(DiagID != 0 && "no diagnostic for type diagnoser");
8466 }
8467
8468 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8469 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
8470 emit(DB, std::index_sequence_for<Ts...>());
8471 DB << T;
8472 }
8473 };
8474
8475 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
8476 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
8477 /// For example, a diagnostic with no other parameters would generally have
8478 /// the form "...%select{incomplete|sizeless}0 type %1...".
8479 template <typename... Ts>
8481 public:
8482 SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8483 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
8484
8485 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8486 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
8487 this->emit(DB, std::index_sequence_for<Ts...>());
8488 DB << T->isSizelessType() << T;
8489 }
8490 };
8491
8492 /// Check an argument list for placeholders that we won't try to
8493 /// handle later.
8495
8496 /// The C++ "std::source_location::__impl" struct, defined in
8497 /// <source_location>.
8499
8500 /// A stack of expression evaluation contexts.
8502
8503 // Set of failed immediate invocations to avoid double diagnosing.
8505
8506 /// List of SourceLocations where 'self' is implicitly retained inside a
8507 /// block.
8510
8511 /// Do an explicit extend of the given block pointer if we're in ARC.
8513
8514 std::vector<std::pair<QualType, unsigned>> ExcessPrecisionNotSatisfied;
8517
8518private:
8519 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
8520
8521 /// Methods for marking which expressions involve dereferencing a pointer
8522 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
8523 /// they are parsed, meaning that a noderef pointer may not be accessed. For
8524 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
8525 /// `*p`, but need to check that `address of` is called on it. This requires
8526 /// keeping a container of all pending expressions and checking if the address
8527 /// of them are eventually taken.
8528 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
8529 void CheckAddressOfNoDeref(const Expr *E);
8530
8531 ///@}
8532
8533 //
8534 //
8535 // -------------------------------------------------------------------------
8536 //
8537 //
8538
8539 /// \name C++ Expressions
8540 /// Implementations are in SemaExprCXX.cpp
8541 ///@{
8542
8543public:
8544 /// The C++ "std::bad_alloc" class, which is defined by the C++
8545 /// standard library.
8547
8548 /// The C++ "std::align_val_t" enum class, which is defined by the C++
8549 /// standard library.
8551
8552 /// The C++ "type_info" declaration, which is defined in <typeinfo>.
8554
8555 /// A flag to remember whether the implicit forms of operator new and delete
8556 /// have been declared.
8558
8559 /// Delete-expressions to be analyzed at the end of translation unit
8560 ///
8561 /// This list contains class members, and locations of delete-expressions
8562 /// that could not be proven as to whether they mismatch with new-expression
8563 /// used in initializer of the field.
8564 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
8565
8566 /// Handle the result of the special case name lookup for inheriting
8567 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
8568 /// constructor names in member using declarations, even if 'X' is not the
8569 /// name of the corresponding type.
8571 SourceLocation NameLoc,
8572 const IdentifierInfo &Name);
8573
8575 SourceLocation NameLoc, Scope *S,
8576 CXXScopeSpec &SS, bool EnteringContext);
8578 Scope *S, CXXScopeSpec &SS,
8579 ParsedType ObjectType, bool EnteringContext);
8580
8582 ParsedType ObjectType);
8583
8584 /// Build a C++ typeid expression with a type operand.
8585 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8586 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8587
8588 /// Build a C++ typeid expression with an expression operand.
8589 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8590 Expr *Operand, SourceLocation RParenLoc);
8591
8592 /// ActOnCXXTypeid - Parse typeid( something ).
8594 bool isType, void *TyOrExpr,
8595 SourceLocation RParenLoc);
8596
8597 /// Build a Microsoft __uuidof expression with a type operand.
8598 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8599 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8600
8601 /// Build a Microsoft __uuidof expression with an expression operand.
8602 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8603 Expr *Operand, SourceLocation RParenLoc);
8604
8605 /// ActOnCXXUuidof - Parse __uuidof( something ).
8607 bool isType, void *TyOrExpr,
8608 SourceLocation RParenLoc);
8609
8610 //// ActOnCXXThis - Parse 'this' pointer.
8612
8613 /// Check whether the type of 'this' is valid in the current context.
8615
8616 /// Build a CXXThisExpr and mark it referenced in the current context.
8617 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
8619
8620 /// Try to retrieve the type of the 'this' pointer.
8621 ///
8622 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
8624
8625 /// When non-NULL, the C++ 'this' expression is allowed despite the
8626 /// current context not being a non-static member function. In such cases,
8627 /// this provides the type used for 'this'.
8629
8630 /// RAII object used to temporarily allow the C++ 'this' expression
8631 /// to be used, with the given qualifiers on the current class type.
8633 Sema &S;
8634 QualType OldCXXThisTypeOverride;
8635 bool Enabled;
8636
8637 public:
8638 /// Introduce a new scope where 'this' may be allowed (when enabled),
8639 /// using the given declaration (which is either a class template or a
8640 /// class) along with the given qualifiers.
8641 /// along with the qualifiers placed on '*this'.
8642 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
8643 bool Enabled = true);
8644
8648 };
8649
8650 /// Make sure the value of 'this' is actually available in the current
8651 /// context, if it is a potentially evaluated context.
8652 ///
8653 /// \param Loc The location at which the capture of 'this' occurs.
8654 ///
8655 /// \param Explicit Whether 'this' is explicitly captured in a lambda
8656 /// capture list.
8657 ///
8658 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
8659 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
8660 /// This is useful when enclosing lambdas must speculatively capture
8661 /// 'this' that may or may not be used in certain specializations of
8662 /// a nested generic lambda (depending on whether the name resolves to
8663 /// a non-static member function or a static function).
8664 /// \return returns 'true' if failed, 'false' if success.
8666 SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true,
8667 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
8668 bool ByCopy = false);
8669
8670 /// Determine whether the given type is the type of *this that is used
8671 /// outside of the body of a member function for a type that is currently
8672 /// being defined.
8674
8675 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
8677
8678 /// Build a boolean-typed literal expression.
8680
8681 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
8683
8684 //// ActOnCXXThrow - Parse throw expressions.
8687 bool IsThrownVarInScope);
8688
8689 /// CheckCXXThrowOperand - Validate the operand of a throw.
8690 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
8691
8692 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
8693 /// Can be interpreted either as function-style casting ("int(x)")
8694 /// or class type construction ("ClassType(x,y,z)")
8695 /// or creation of a value-initialized type ("int()").
8697 SourceLocation LParenOrBraceLoc,
8698 MultiExprArg Exprs,
8699 SourceLocation RParenOrBraceLoc,
8700 bool ListInitialization);
8701
8703 SourceLocation LParenLoc,
8704 MultiExprArg Exprs,
8705 SourceLocation RParenLoc,
8706 bool ListInitialization);
8707
8708 /// Parsed a C++ 'new' expression (C++ 5.3.4).
8709 ///
8710 /// E.g.:
8711 /// @code new (memory) int[size][4] @endcode
8712 /// or
8713 /// @code ::new Foo(23, "hello") @endcode
8714 ///
8715 /// \param StartLoc The first location of the expression.
8716 /// \param UseGlobal True if 'new' was prefixed with '::'.
8717 /// \param PlacementLParen Opening paren of the placement arguments.
8718 /// \param PlacementArgs Placement new arguments.
8719 /// \param PlacementRParen Closing paren of the placement arguments.
8720 /// \param TypeIdParens If the type is in parens, the source range.
8721 /// \param D The type to be allocated, as well as array dimensions.
8722 /// \param Initializer The initializing expression or initializer-list, or
8723 /// null if there is none.
8724 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
8725 SourceLocation PlacementLParen,
8726 MultiExprArg PlacementArgs,
8727 SourceLocation PlacementRParen,
8728 SourceRange TypeIdParens, Declarator &D,
8729 Expr *Initializer);
8731 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
8732 MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
8733 SourceRange TypeIdParens, QualType AllocType,
8734 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
8735 SourceRange DirectInitRange, Expr *Initializer);
8736
8737 /// Determine whether \p FD is an aligned allocation or deallocation
8738 /// function that is unavailable.
8740
8741 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
8742 /// function that is unavailable.
8744 SourceLocation Loc);
8745
8746 /// Checks that a type is suitable as the allocated type
8747 /// in a new-expression.
8748 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
8749 SourceRange R);
8750
8751 /// Finds the overloads of operator new and delete that are appropriate
8752 /// for the allocation.
8753 std::optional<ResolvedAllocation> FindAllocationFunctions(
8754 SourceLocation StartLoc, SourceRange Range,
8756 QualType AllocType, bool IsArray, const ImplicitAllocationParameters &IAP,
8757 MultiExprArg PlaceArgs, bool Diagnose = true);
8758
8759 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
8760 /// delete. These are:
8761 /// @code
8762 /// // C++03:
8763 /// void* operator new(std::size_t) throw(std::bad_alloc);
8764 /// void* operator new[](std::size_t) throw(std::bad_alloc);
8765 /// void operator delete(void *) throw();
8766 /// void operator delete[](void *) throw();
8767 /// // C++11:
8768 /// void* operator new(std::size_t);
8769 /// void* operator new[](std::size_t);
8770 /// void operator delete(void *) noexcept;
8771 /// void operator delete[](void *) noexcept;
8772 /// // C++1y:
8773 /// void* operator new(std::size_t);
8774 /// void* operator new[](std::size_t);
8775 /// void operator delete(void *) noexcept;
8776 /// void operator delete[](void *) noexcept;
8777 /// void operator delete(void *, std::size_t) noexcept;
8778 /// void operator delete[](void *, std::size_t) noexcept;
8779 /// @endcode
8780 /// Note that the placement and nothrow forms of new are *not* implicitly
8781 /// declared. Their use requires including <new>.
8784 ArrayRef<QualType> Params);
8785
8787 DeclarationName Name, FunctionDecl *&Operator,
8789 bool Diagnose = true);
8792 DeclarationName Name,
8793 bool Diagnose = true);
8795 CXXRecordDecl *RD,
8796 bool Diagnose,
8797 bool LookForGlobal,
8798 DeclarationName Name);
8799
8800 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
8801 /// @code ::delete ptr; @endcode
8802 /// or
8803 /// @code delete [] ptr; @endcode
8804 ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
8805 bool ArrayForm, Expr *Operand);
8807 bool IsDelete, bool CallCanBeVirtual,
8808 bool WarnOnNonAbstractTypes,
8809 SourceLocation DtorLoc);
8810
8812 Expr *Operand, SourceLocation RParen);
8814 SourceLocation RParen);
8815
8817 SourceLocation OpLoc,
8818 tok::TokenKind OpKind,
8819 ParsedType &ObjectType,
8820 bool &MayBePseudoDestructor);
8821
8823 Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8824 const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc,
8825 SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType);
8826
8828 Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8829 CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc,
8830 SourceLocation TildeLoc, UnqualifiedId &SecondTypeName);
8831
8833 SourceLocation OpLoc,
8834 tok::TokenKind OpKind,
8835 SourceLocation TildeLoc,
8836 const DeclSpec &DS);
8837
8838 /// MaybeCreateExprWithCleanups - If the current full-expression
8839 /// requires any cleanups, surround it with a ExprWithCleanups node.
8840 /// Otherwise, just returns the passed-in expression.
8844
8845 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
8846 return ActOnFinishFullExpr(
8847 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
8848 }
8850 bool DiscardedValue, bool IsConstexpr = false,
8851 bool IsTemplateArgument = false);
8853
8854 /// Process the expression contained within a decltype. For such expressions,
8855 /// certain semantic checks on temporaries are delayed until this point, and
8856 /// are omitted for the 'topmost' call in the decltype expression. If the
8857 /// topmost call bound a temporary, strip that temporary off the expression.
8859
8860 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
8861 bool IsUDSuffix);
8862
8864
8865 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
8866 SourceLocation StmtLoc,
8867 ConditionKind CK);
8868
8869 /// Check the use of the given variable as a C++ condition in an if,
8870 /// while, do-while, or switch statement.
8872 SourceLocation StmtLoc, ConditionKind CK);
8873
8874 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8875 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
8876
8877 /// Helper function to determine whether this is the (deprecated) C++
8878 /// conversion from a string literal to a pointer to non-const char or
8879 /// non-const wchar_t (for narrow and wide string literals,
8880 /// respectively).
8882
8883 /// PerformImplicitConversion - Perform an implicit conversion of the
8884 /// expression From to the type ToType using the pre-computed implicit
8885 /// conversion sequence ICS. Returns the converted
8886 /// expression. Action is the kind of conversion we're performing,
8887 /// used in the error message.
8889 Expr *From, QualType ToType, const ImplicitConversionSequence &ICS,
8890 AssignmentAction Action,
8892
8893 /// PerformImplicitConversion - Perform an implicit conversion of the
8894 /// expression From to the type ToType by following the standard
8895 /// conversion sequence SCS. Returns the converted
8896 /// expression. Flavor is the context in which we're performing this
8897 /// conversion, for use in error messages.
8899 const StandardConversionSequence &SCS,
8900 AssignmentAction Action,
8902
8903 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
8904
8905 /// Parsed one of the type trait support pseudo-functions.
8906 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8908 SourceLocation RParenLoc);
8909 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8911 SourceLocation RParenLoc);
8912
8913 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
8914 /// pseudo-functions.
8915 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8916 ParsedType LhsTy, Expr *DimExpr,
8917 SourceLocation RParen);
8918
8919 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8920 TypeSourceInfo *TSInfo, Expr *DimExpr,
8921 SourceLocation RParen);
8922
8923 /// ActOnExpressionTrait - Parsed one of the unary type trait support
8924 /// pseudo-functions.
8925 ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8926 Expr *Queried, SourceLocation RParen);
8927
8928 ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8929 Expr *Queried, SourceLocation RParen);
8930
8933 bool isIndirect);
8935 ExprResult &RHS,
8936 SourceLocation QuestionLoc);
8937
8938 //// Determines if a type is trivially relocatable
8939 /// according to the C++26 rules.
8940 // FIXME: This is in Sema because it requires
8941 // overload resolution, can we move to ASTContext?
8944
8945 /// Check the operands of ?: under C++ semantics.
8946 ///
8947 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
8948 /// extension. In this case, LHS == Cond. (But they're not aliases.)
8949 ///
8950 /// This function also implements GCC's vector extension and the
8951 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
8952 /// permit the use of a?b:c where the type of a is that of a integer vector
8953 /// with the same number of elements and size as the vectors of b and c. If
8954 /// one of either b or c is a scalar it is implicitly converted to match the
8955 /// type of the vector. Otherwise the expression is ill-formed. If both b and
8956 /// c are scalars, then b and c are checked and converted to the type of a if
8957 /// possible.
8958 ///
8959 /// The expressions are evaluated differently for GCC's and OpenCL's
8960 /// extensions. For the GCC extension, the ?: operator is evaluated as
8961 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
8962 /// For the OpenCL extensions, the ?: operator is evaluated as
8963 /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
8964 /// most-significant-bit-set(a[n]) ? b[n] : c[n]).
8966 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK,
8967 ExprObjectKind &OK, SourceLocation questionLoc);
8968
8969 /// Find a merged pointer type and convert the two expressions to it.
8970 ///
8971 /// This finds the composite pointer type for \p E1 and \p E2 according to
8972 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
8973 /// it. It does not emit diagnostics (FIXME: that's not true if \p
8974 /// ConvertArgs is \c true).
8975 ///
8976 /// \param Loc The location of the operator requiring these two expressions to
8977 /// be converted to the composite pointer type.
8978 ///
8979 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target
8980 /// type.
8982 bool ConvertArgs = true);
8984 ExprResult &E2, bool ConvertArgs = true) {
8985 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8986 QualType Composite =
8987 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
8988 E1 = E1Tmp;
8989 E2 = E2Tmp;
8990 return Composite;
8991 }
8992
8993 /// MaybeBindToTemporary - If the passed in expression has a record type with
8994 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
8995 /// it simply returns the passed in expression.
8997
8998 /// IgnoredValueConversions - Given that an expression's result is
8999 /// syntactically ignored, perform any conversions that are
9000 /// required.
9002
9004
9007 const DeclarationNameInfo &TargetNameInfo);
9008
9010 SourceLocation KeywordLoc,
9011 bool IsIfExists, CXXScopeSpec &SS,
9012 UnqualifiedId &Name);
9013
9016 ArrayRef<ParmVarDecl *> LocalParameters,
9017 Scope *BodyScope);
9021 CXXScopeSpec &SS,
9022 SourceLocation NameLoc,
9023 const IdentifierInfo *TypeName,
9024 TemplateIdAnnotation *TemplateId);
9026 SourceLocation NoexceptLoc);
9028 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
9029 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
9032 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
9036 bool IsSatisfied, SourceLocation NoexceptLoc,
9044 SourceLocation LParenLoc,
9045 ArrayRef<ParmVarDecl *> LocalParameters,
9046 SourceLocation RParenLoc,
9048 SourceLocation ClosingBraceLoc);
9049
9050private:
9051 ExprResult BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
9052 bool IsDelete);
9053
9054 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
9055 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
9056 bool DeleteWasArrayForm);
9057
9058 std::optional<AllocationArgumentSet>
9059 resolveAllocationArguments(LookupResult &R,
9061 ArrayRef<Expr *> PlacementArguments);
9062
9063 // Attempts to construct the type identity argument for the call to a
9064 // type aware operator new. Returns null on failure.
9065 Expr *tryGetTypeIdentityArgument(QualType Type, SourceLocation);
9066
9067 Expr *AllocationSizeExpr = nullptr;
9068 Expr *AllocationAlignmentExpr = nullptr;
9069 llvm::DenseMap<QualType, Expr *> AllocationTypeIdentityArguments;
9070
9071 ///@}
9072
9073 //
9074 //
9075 // -------------------------------------------------------------------------
9076 //
9077 //
9078
9079 /// \name Member Access Expressions
9080 /// Implementations are in SemaExprMember.cpp
9081 ///@{
9082
9083public:
9084 /// Check whether an expression might be an implicit class member access.
9086 bool IsAddressOfOperand);
9087
9088 /// Builds an expression which might be an implicit member expression.
9090 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
9091 const TemplateArgumentListInfo *TemplateArgs, const Scope *S);
9092
9093 /// Builds an implicit member access expression. The current context
9094 /// is known to be an instance method, and the given unqualified lookup
9095 /// set is known to contain only instance members, at least one of which
9096 /// is from an appropriate type.
9098 BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9099 LookupResult &R,
9100 const TemplateArgumentListInfo *TemplateArgs,
9101 bool IsDefiniteInstance, const Scope *S);
9102
9104 Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc,
9105 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9106 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9107 const TemplateArgumentListInfo *TemplateArgs);
9108
9109 /// The main callback when the parser finds something like
9110 /// expression . [nested-name-specifier] identifier
9111 /// expression -> [nested-name-specifier] identifier
9112 /// where 'identifier' encompasses a fairly broad spectrum of
9113 /// possibilities, including destructor and operator references.
9114 ///
9115 /// \param OpKind either tok::arrow or tok::period
9116 /// \param ObjCImpDecl the current Objective-C \@implementation
9117 /// decl; this is an ugly hack around the fact that Objective-C
9118 /// \@implementations aren't properly put in the context chain
9120 tok::TokenKind OpKind, CXXScopeSpec &SS,
9121 SourceLocation TemplateKWLoc,
9122 UnqualifiedId &Member, Decl *ObjCImpDecl);
9123
9124 MemberExpr *
9125 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
9126 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
9127 ValueDecl *Member, DeclAccessPair FoundDecl,
9128 bool HadMultipleCandidates,
9129 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
9131 const TemplateArgumentListInfo *TemplateArgs = nullptr);
9132
9133 // Check whether the declarations we found through a nested-name
9134 // specifier in a member expression are actually members of the base
9135 // type. The restriction here is:
9136 //
9137 // C++ [expr.ref]p2:
9138 // ... In these cases, the id-expression shall name a
9139 // member of the class or of one of its base classes.
9140 //
9141 // So it's perfectly legitimate for the nested-name specifier to name
9142 // an unrelated class, and for us to find an overload set including
9143 // decls from classes which are not superclasses, as long as the decl
9144 // we actually pick through overload resolution is from a superclass.
9145 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
9146 const CXXScopeSpec &SS,
9147 const LookupResult &R);
9148
9149 // This struct is for use by ActOnMemberAccess to allow
9150 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
9151 // changing the access operator from a '.' to a '->' (to see if that is the
9152 // change needed to fix an error about an unknown member, e.g. when the class
9153 // defines a custom operator->).
9159
9161 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
9162 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9163 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9164 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
9165 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9166
9169 bool IsArrow, const CXXScopeSpec &SS,
9170 SourceLocation TemplateKWLoc,
9171 NamedDecl *FirstQualifierInScope, LookupResult &R,
9172 const TemplateArgumentListInfo *TemplateArgs,
9173 const Scope *S, bool SuppressQualifierCheck = false,
9174 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9175
9176 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
9177 SourceLocation OpLoc,
9178 const CXXScopeSpec &SS, FieldDecl *Field,
9179 DeclAccessPair FoundDecl,
9180 const DeclarationNameInfo &MemberNameInfo);
9181
9182 /// Perform conversions on the LHS of a member access expression.
9184
9186 const CXXScopeSpec &SS, SourceLocation nameLoc,
9187 IndirectFieldDecl *indirectField,
9188 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
9189 Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation());
9190
9191private:
9192 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
9193
9194 ///@}
9195
9196 //
9197 //
9198 // -------------------------------------------------------------------------
9199 //
9200 //
9201
9202 /// \name Initializers
9203 /// Implementations are in SemaInit.cpp
9204 ///@{
9205
9206public:
9207 /// Stack of types that correspond to the parameter entities that are
9208 /// currently being copy-initialized. Can be empty.
9210
9211 llvm::DenseMap<unsigned, CXXDeductionGuideDecl *>
9213
9214 bool IsStringInit(Expr *Init, const ArrayType *AT);
9215
9216 /// The initializers of \p ILE with each multi-element EmbedExpr split into
9217 /// one EmbedExpr per embedded element; \p Storage is used only if needed.
9219 SmallVectorImpl<Expr *> &Storage);
9220
9221 /// Determine whether we can perform aggregate initialization for the purposes
9222 /// of overload resolution.
9224 const InitializedEntity &Entity, InitListExpr *From);
9225
9227 SourceLocation EqualOrColonLoc,
9228 bool GNUSyntax, ExprResult Init);
9229
9230 /// Check that the lifetime of the initializer (and its subobjects) is
9231 /// sufficient for initializing the entity, and perform lifetime extension
9232 /// (when permitted) if not.
9234
9237 bool BoundToLvalueReference);
9238
9239 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9240 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9241 /// we don't have xvalues there.
9243
9247
9251 SourceLocation EqualLoc, ExprResult Init,
9252 bool TopLevelOfInitList = false,
9253 bool AllowExplicit = false);
9254
9256 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
9257 const InitializationKind &Kind, MultiExprArg Init);
9258
9259 ///@}
9260
9261 //
9262 //
9263 // -------------------------------------------------------------------------
9264 //
9265 //
9266
9267 /// \name C++ Lambda Expressions
9268 /// Implementations are in SemaLambda.cpp
9269 ///@{
9270
9271public:
9272 /// Create a new lambda closure type.
9274 TypeSourceInfo *Info,
9275 unsigned LambdaDependencyKind,
9276 LambdaCaptureDefault CaptureDefault);
9277
9278 /// Number lambda for linkage purposes if necessary.
9280 std::optional<CXXRecordDecl::LambdaNumbering>
9281 NumberingOverride = std::nullopt);
9282
9283 /// Endow the lambda scope info with the relevant properties.
9284 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
9285 SourceRange IntroducerRange,
9286 LambdaCaptureDefault CaptureDefault,
9287 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
9288 bool Mutable);
9289
9292
9294 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
9295 TemplateParameterList *TemplateParams);
9296
9297 void
9299 SourceLocation CallOperatorLoc,
9300 const AssociatedConstraint &TrailingRequiresClause,
9301 TypeSourceInfo *MethodTyInfo,
9302 ConstexprSpecKind ConstexprKind, StorageClass SC,
9304 bool HasExplicitResultType);
9305
9306 /// Returns true if the explicit object parameter was invalid.
9308 SourceLocation CallLoc);
9309
9310 /// Perform initialization analysis of the init-capture and perform
9311 /// any implicit conversions such as an lvalue-to-rvalue conversion if
9312 /// not being used to initialize a reference.
9314 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
9315 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
9317 Loc, ByRef, EllipsisLoc, std::nullopt, Id,
9319 }
9321 SourceLocation EllipsisLoc,
9322 UnsignedOrNone NumExpansions,
9323 IdentifierInfo *Id,
9324 bool DirectInit, Expr *&Init);
9325
9326 /// Create a dummy variable within the declcontext of the lambda's
9327 /// call operator, for name lookup purposes for a lambda init capture.
9328 ///
9329 /// CodeGen handles emission of lambda captures, ignoring these dummy
9330 /// variables appropriately.
9332 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
9333 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
9334
9335 /// Add an init-capture to a lambda scope.
9336 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef);
9337
9338 /// Note that we have finished the explicit captures for the
9339 /// given lambda.
9341
9342 /// Deduce a block or lambda's return type based on the return
9343 /// statements present in the body.
9345
9346 /// Once the Lambdas capture are known, we can start to create the closure,
9347 /// call operator method, and keep track of the captures.
9348 /// We do the capture lookup here, but they are not actually captured until
9349 /// after we know what the qualifiers of the call operator are.
9351 Scope *CurContext);
9352
9353 /// This is called after parsing the explicit template parameter list
9354 /// on a lambda (if it exists) in C++2a.
9356 SourceLocation LAngleLoc,
9357 ArrayRef<NamedDecl *> TParams,
9358 SourceLocation RAngleLoc,
9359 ExprResult RequiresClause);
9360
9362 SourceLocation MutableLoc);
9363
9365 Scope *LambdaScope,
9367
9368 /// ActOnStartOfLambdaDefinition - This is called just before we start
9369 /// parsing the body of a lambda; it analyzes the explicit captures and
9370 /// arguments, and sets up various data-structures for the body of the
9371 /// lambda.
9373 Declarator &ParamInfo, const DeclSpec &DS);
9374
9375 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
9376 /// is invoked to pop the information about the lambda.
9377 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
9378 bool IsInstantiation = false);
9379
9380 /// ActOnLambdaExpr - This is called when the body of a lambda expression
9381 /// was successfully completed.
9383
9384 /// Does copying/destroying the captured variable have side effects?
9385 bool CaptureHasSideEffects(const sema::Capture &From);
9386
9387 /// Diagnose if an explicit lambda capture is unused. Returns true if a
9388 /// diagnostic is emitted.
9389 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
9390 SourceRange FixItRange,
9391 const sema::Capture &From);
9392
9393 /// Build a FieldDecl suitable to hold the given capture.
9395 bool IsOpenMP = false);
9396
9397 /// Initialize the given capture with a suitable expression.
9399 SourceLocation ImplicitCaptureLoc,
9400 bool IsOpenMPMapping = false);
9401
9402 /// Complete a lambda-expression having processed and attached the
9403 /// lambda body.
9405
9406 /// Get the return type to use for a lambda's conversion function(s) to
9407 /// function pointer type, given the type of the call operator.
9408 QualType
9410 CallingConv CC);
9411
9413 SourceLocation ConvLocation,
9414 CXXConversionDecl *Conv, Expr *Src);
9415
9417 : private FunctionScopeRAII {
9418 public:
9420 Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
9422 bool ShouldAddDeclsFromParentScope = true);
9423 };
9424
9425 /// Compute the mangling number context for a lambda expression or
9426 /// block literal. Also return the extra mangling decl if any.
9427 ///
9428 /// \param DC - The DeclContext containing the lambda expression or
9429 /// block literal.
9430 std::tuple<MangleNumberingContext *, Decl *>
9432
9433 ///@}
9434
9435 //
9436 //
9437 // -------------------------------------------------------------------------
9438 //
9439 //
9440
9441 /// \name Name Lookup
9442 ///
9443 /// These routines provide name lookup that is used during semantic
9444 /// analysis to resolve the various kinds of names (identifiers,
9445 /// overloaded operator names, constructor names, etc.) into zero or
9446 /// more declarations within a particular scope. The major entry
9447 /// points are LookupName, which performs unqualified name lookup,
9448 /// and LookupQualifiedName, which performs qualified name lookup.
9449 ///
9450 /// All name lookup is performed based on some specific criteria,
9451 /// which specify what names will be visible to name lookup and how
9452 /// far name lookup should work. These criteria are important both
9453 /// for capturing language semantics (certain lookups will ignore
9454 /// certain names, for example) and for performance, since name
9455 /// lookup is often a bottleneck in the compilation of C++. Name
9456 /// lookup criteria is specified via the LookupCriteria enumeration.
9457 ///
9458 /// The results of name lookup can vary based on the kind of name
9459 /// lookup performed, the current language, and the translation
9460 /// unit. In C, for example, name lookup will either return nothing
9461 /// (no entity found) or a single declaration. In C++, name lookup
9462 /// can additionally refer to a set of overloaded functions or
9463 /// result in an ambiguity. All of the possible results of name
9464 /// lookup are captured by the LookupResult class, which provides
9465 /// the ability to distinguish among them.
9466 ///
9467 /// Implementations are in SemaLookup.cpp
9468 ///@{
9469
9470public:
9471 /// Tracks whether we are in a context where typo correction is
9472 /// disabled.
9474
9475 /// The number of typos corrected by CorrectTypo.
9477
9478 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9479 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9480
9481 /// A cache containing identifiers for which typo correction failed and
9482 /// their locations, so that repeated attempts to correct an identifier in a
9483 /// given location are ignored if typo correction already failed for it.
9485
9486 /// SpecialMemberOverloadResult - The overloading result for a special member
9487 /// function.
9488 ///
9489 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
9490 /// integer are used to determine whether overload resolution succeeded.
9492 public:
9494
9495 private:
9496 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
9497
9498 public:
9501 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
9502
9503 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
9504 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
9505
9506 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
9507 void setKind(Kind K) { Pair.setInt(K); }
9508 };
9509
9510 using SpecialMemberCacheKey = std::pair<const CXXRecordDecl *, unsigned>;
9511
9512 /// A cache of special member function overload resolution results
9513 /// for C++ records.
9514 llvm::DenseMap<SpecialMemberCacheKey, SpecialMemberOverloadResult>
9516
9518
9519 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
9520 // TODO: make this is a typesafe union.
9523
9524 /// Describes the kind of name lookup to perform.
9526 /// Ordinary name lookup, which finds ordinary names (functions,
9527 /// variables, typedefs, etc.) in C and most kinds of names
9528 /// (functions, variables, members, types, etc.) in C++.
9530 /// Tag name lookup, which finds the names of enums, classes,
9531 /// structs, and unions.
9533 /// Label name lookup.
9535 /// Member name lookup, which finds the names of
9536 /// class/struct/union members.
9538 /// Look up of an operator name (e.g., operator+) for use with
9539 /// operator overloading. This lookup is similar to ordinary name
9540 /// lookup, but will ignore any declarations that are class members.
9542 /// Look up a name following ~ in a destructor name. This is an ordinary
9543 /// lookup, but prefers tags to typedefs.
9545 /// Look up of a name that precedes the '::' scope resolution
9546 /// operator in C++. This lookup completely ignores operator, object,
9547 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
9549 /// Look up a namespace name within a C++ using directive or
9550 /// namespace alias definition, ignoring non-namespace names (C++
9551 /// [basic.lookup.udir]p1).
9553 /// Look up all declarations in a scope with the given name,
9554 /// including resolved using declarations. This is appropriate
9555 /// for checking redeclarations for a using declaration.
9557 /// Look up an ordinary name that is going to be redeclared as a
9558 /// name with linkage. This lookup ignores any declarations that
9559 /// are outside of the current scope unless they have linkage. See
9560 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
9562 /// Look up a friend of a local class. This lookup does not look
9563 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
9565 /// Look up the name of an Objective-C protocol.
9567 /// Look up implicit 'self' parameter of an objective-c method.
9569 /// Look up the name of an OpenMP user-defined reduction operation.
9571 /// Look up the name of an OpenMP user-defined mapper.
9573 /// Look up any declaration with any name.
9575 };
9576
9577 /// The possible outcomes of name lookup for a literal operator.
9579 /// The lookup resulted in an error.
9581 /// The lookup found no match but no diagnostic was issued.
9583 /// The lookup found a single 'cooked' literal operator, which
9584 /// expects a normal literal to be built and passed to it.
9586 /// The lookup found a single 'raw' literal operator, which expects
9587 /// a string literal containing the spelling of the literal token.
9589 /// The lookup found an overload set of literal operator templates,
9590 /// which expect the characters of the spelling of the literal token to be
9591 /// passed as a non-type template argument pack.
9593 /// The lookup found an overload set of literal operator templates,
9594 /// which expect the character type and characters of the spelling of the
9595 /// string literal token to be passed as template arguments.
9597 };
9598
9599 SpecialMemberOverloadResult
9601 bool VolatileArg, bool RValueThis, bool ConstThis,
9602 bool VolatileThis);
9603
9605
9606 /// Look up a name, looking for a single declaration. Return
9607 /// null if the results were absent, ambiguous, or overloaded.
9608 ///
9609 /// It is preferable to use the elaborated form and explicitly handle
9610 /// ambiguity and overloaded.
9612 Scope *S, DeclarationName Name, SourceLocation Loc,
9613 LookupNameKind NameKind,
9615
9616 /// Lookup a builtin function, when name lookup would otherwise
9617 /// fail.
9618 bool LookupBuiltin(LookupResult &R);
9619 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
9620
9621 /// Perform unqualified name lookup starting from a given
9622 /// scope.
9623 ///
9624 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
9625 /// used to find names within the current scope. For example, 'x' in
9626 /// @code
9627 /// int x;
9628 /// int f() {
9629 /// return x; // unqualified name look finds 'x' in the global scope
9630 /// }
9631 /// @endcode
9632 ///
9633 /// Different lookup criteria can find different names. For example, a
9634 /// particular scope can have both a struct and a function of the same
9635 /// name, and each can be found by certain lookup criteria. For more
9636 /// information about lookup criteria, see the documentation for the
9637 /// class LookupCriteria.
9638 ///
9639 /// @param S The scope from which unqualified name lookup will
9640 /// begin. If the lookup criteria permits, name lookup may also search
9641 /// in the parent scopes.
9642 ///
9643 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
9644 /// look up and the lookup kind), and is updated with the results of lookup
9645 /// including zero or more declarations and possibly additional information
9646 /// used to diagnose ambiguities.
9647 ///
9648 /// @returns \c true if lookup succeeded and false otherwise.
9649 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
9650 bool ForceNoCPlusPlus = false);
9651
9652 /// Perform qualified name lookup into a given context.
9653 ///
9654 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
9655 /// names when the context of those names is explicit specified, e.g.,
9656 /// "std::vector" or "x->member", or as part of unqualified name lookup.
9657 ///
9658 /// Different lookup criteria can find different names. For example, a
9659 /// particular scope can have both a struct and a function of the same
9660 /// name, and each can be found by certain lookup criteria. For more
9661 /// information about lookup criteria, see the documentation for the
9662 /// class LookupCriteria.
9663 ///
9664 /// \param R captures both the lookup criteria and any lookup results found.
9665 ///
9666 /// \param LookupCtx The context in which qualified name lookup will
9667 /// search. If the lookup criteria permits, name lookup may also search
9668 /// in the parent contexts or (for C++ classes) base classes.
9669 ///
9670 /// \param InUnqualifiedLookup true if this is qualified name lookup that
9671 /// occurs as part of unqualified name lookup.
9672 ///
9673 /// \returns true if lookup succeeded, false if it failed.
9674 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9675 bool InUnqualifiedLookup = false);
9676
9677 /// Performs qualified name lookup or special type of lookup for
9678 /// "__super::" scope specifier.
9679 ///
9680 /// This routine is a convenience overload meant to be called from contexts
9681 /// that need to perform a qualified name lookup with an optional C++ scope
9682 /// specifier that might require special kind of lookup.
9683 ///
9684 /// \param R captures both the lookup criteria and any lookup results found.
9685 ///
9686 /// \param LookupCtx The context in which qualified name lookup will
9687 /// search.
9688 ///
9689 /// \param SS An optional C++ scope-specifier.
9690 ///
9691 /// \returns true if lookup succeeded, false if it failed.
9692 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9693 CXXScopeSpec &SS);
9694
9695 /// Performs name lookup for a name that was parsed in the
9696 /// source code, and may contain a C++ scope specifier.
9697 ///
9698 /// This routine is a convenience routine meant to be called from
9699 /// contexts that receive a name and an optional C++ scope specifier
9700 /// (e.g., "N::M::x"). It will then perform either qualified or
9701 /// unqualified name lookup (with LookupQualifiedName or LookupName,
9702 /// respectively) on the given name and return those results. It will
9703 /// perform a special type of lookup for "__super::" scope specifier.
9704 ///
9705 /// @param S The scope from which unqualified name lookup will
9706 /// begin.
9707 ///
9708 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
9709 ///
9710 /// @param EnteringContext Indicates whether we are going to enter the
9711 /// context of the scope-specifier SS (if present).
9712 ///
9713 /// @returns True if any decls were found (but possibly ambiguous)
9715 QualType ObjectType, bool AllowBuiltinCreation = false,
9716 bool EnteringContext = false);
9717
9718 /// Perform qualified name lookup into all base classes of the given
9719 /// class.
9720 ///
9721 /// \param R captures both the lookup criteria and any lookup results found.
9722 ///
9723 /// \param Class The context in which qualified name lookup will
9724 /// search. Name lookup will search in all base classes merging the results.
9725 ///
9726 /// @returns True if any decls were found (but possibly ambiguous)
9728
9730 UnresolvedSetImpl &Functions);
9731
9732 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
9733 /// If GnuLabelLoc is a valid source location, then this is a definition
9734 /// of an __label__ label name, otherwise it is a normal label definition
9735 /// or use. If IsLabelStmt is true, then this is the label of a
9736 /// labeled-statement.
9738 SourceLocation GnuLabelLoc = SourceLocation(),
9739 bool IsLabelStmt = false);
9740
9741 /// Perform a name lookup for a label with the specified name; this does not
9742 /// create a new label if the lookup fails.
9744
9745 /// Look up the constructors for the given class.
9747
9748 /// Look up the default constructor for the given class.
9750
9751 /// Look up the copying constructor for the given class.
9753 unsigned Quals);
9754
9755 /// Look up the copying assignment operator for the given class.
9757 bool RValueThis, unsigned ThisQuals);
9758
9759 /// Look up the moving constructor for the given class.
9761 unsigned Quals);
9762
9763 /// Look up the moving assignment operator for the given class.
9765 bool RValueThis, unsigned ThisQuals);
9766
9767 /// Look for the destructor of the given class.
9768 ///
9769 /// During semantic analysis, this routine should be used in lieu of
9770 /// CXXRecordDecl::getDestructor().
9771 ///
9772 /// \returns The destructor for this class.
9774
9775 /// Force the declaration of any implicitly-declared members of this
9776 /// class.
9778
9779 /// Make a merged definition of an existing hidden definition \p ND
9780 /// visible at the specified location.
9782
9783 /// Check ODR hashes for C/ObjC when merging types from modules.
9784 /// Differently from C++, actually parse the body and reject in case
9785 /// of a mismatch.
9786 template <typename T,
9787 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
9789 if (Duplicate->getODRHash() != Previous->getODRHash())
9790 return false;
9791
9792 // Make the previous decl visible.
9794 return true;
9795 }
9796
9797 /// Get the set of additional modules that should be checked during
9798 /// name lookup. A module and its imports become visible when instanting a
9799 /// template defined within it.
9800 llvm::DenseSet<Module *> &getLookupModules();
9801
9802 bool hasVisibleMergedDefinition(const NamedDecl *Def);
9804
9805 /// Determine if the template parameter \p D has a visible default argument.
9806 bool
9808 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9809 /// Determine if the template parameter \p D has a reachable default argument.
9811 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9812 /// Determine if the template parameter \p D has a reachable default argument.
9816
9817 /// Determine if there is a visible declaration of \p D that is an explicit
9818 /// specialization declaration for a specialization of a template. (For a
9819 /// member specialization, use hasVisibleMemberSpecialization.)
9821 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9822 /// Determine if there is a reachable declaration of \p D that is an explicit
9823 /// specialization declaration for a specialization of a template. (For a
9824 /// member specialization, use hasReachableMemberSpecialization.)
9826 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9827
9828 /// Determine if there is a visible declaration of \p D that is a member
9829 /// specialization declaration (as opposed to an instantiated declaration).
9831 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9832 /// Determine if there is a reachable declaration of \p D that is a member
9833 /// specialization declaration (as opposed to an instantiated declaration).
9835 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9836
9837 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
9838
9839 /// Determine whether any declaration of an entity is visible.
9840 bool
9842 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9843 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
9844 }
9845
9848 /// Determine whether any declaration of an entity is reachable.
9849 bool
9851 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9852 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
9853 }
9855 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9856
9857 void diagnoseTypo(const TypoCorrection &Correction,
9858 const PartialDiagnostic &TypoDiag,
9859 bool ErrorRecovery = true);
9860
9861 /// Diagnose a successfully-corrected typo. Separated from the correction
9862 /// itself to allow external validation of the result, etc.
9863 ///
9864 /// \param Correction The result of performing typo correction.
9865 /// \param TypoDiag The diagnostic to produce. This will have the corrected
9866 /// string added to it (and usually also a fixit).
9867 /// \param PrevNote A note to use when indicating the location of the entity
9868 /// to which we are correcting. Will have the correction string added
9869 /// to it.
9870 /// \param ErrorRecovery If \c true (the default), the caller is going to
9871 /// recover from the typo as if the corrected string had been typed.
9872 /// In this case, \c PDiag must be an error, and we will attach a fixit
9873 /// to it.
9874 void diagnoseTypo(const TypoCorrection &Correction,
9875 const PartialDiagnostic &TypoDiag,
9876 const PartialDiagnostic &PrevNote,
9877 bool ErrorRecovery = true);
9878
9879 /// Find the associated classes and namespaces for
9880 /// argument-dependent lookup for a call with the given set of
9881 /// arguments.
9882 ///
9883 /// This routine computes the sets of associated classes and associated
9884 /// namespaces searched by argument-dependent lookup
9885 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
9887 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
9888 AssociatedNamespaceSet &AssociatedNamespaces,
9889 AssociatedClassSet &AssociatedClasses);
9890
9891 /// Produce a diagnostic describing the ambiguity that resulted
9892 /// from name lookup.
9893 ///
9894 /// \param Result The result of the ambiguous lookup to be diagnosed.
9896
9897 /// LookupLiteralOperator - Determine which literal operator should be used
9898 /// for a user-defined literal, per C++11 [lex.ext].
9899 ///
9900 /// Normal overload resolution is not used to select which literal operator to
9901 /// call for a user-defined literal. Look up the provided literal operator
9902 /// name, and filter the results to the appropriate set for the given argument
9903 /// types.
9906 bool AllowRaw, bool AllowTemplate,
9907 bool AllowStringTemplate, bool DiagnoseMissing,
9908 StringLiteral *StringLit = nullptr);
9909
9911 ArrayRef<Expr *> Args, ADLResult &Functions);
9912
9913 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
9915 bool IncludeGlobalScope = true,
9916 bool LoadExternal = true);
9917 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
9919 bool IncludeGlobalScope = true,
9920 bool IncludeDependentBases = false,
9921 bool LoadExternal = true);
9922
9923 /// Try to "correct" a typo in the source code by finding
9924 /// visible declarations whose names are similar to the name that was
9925 /// present in the source code.
9926 ///
9927 /// \param TypoName the \c DeclarationNameInfo structure that contains
9928 /// the name that was present in the source code along with its location.
9929 ///
9930 /// \param LookupKind the name-lookup criteria used to search for the name.
9931 ///
9932 /// \param S the scope in which name lookup occurs.
9933 ///
9934 /// \param SS the nested-name-specifier that precedes the name we're
9935 /// looking for, if present.
9936 ///
9937 /// \param CCC A CorrectionCandidateCallback object that provides further
9938 /// validation of typo correction candidates. It also provides flags for
9939 /// determining the set of keywords permitted.
9940 ///
9941 /// \param MemberContext if non-NULL, the context in which to look for
9942 /// a member access expression.
9943 ///
9944 /// \param EnteringContext whether we're entering the context described by
9945 /// the nested-name-specifier SS.
9946 ///
9947 /// \param OPT when non-NULL, the search for visible declarations will
9948 /// also walk the protocols in the qualified interfaces of \p OPT.
9949 ///
9950 /// \returns a \c TypoCorrection containing the corrected name if the typo
9951 /// along with information such as the \c NamedDecl where the corrected name
9952 /// was declared, and any additional \c NestedNameSpecifier needed to access
9953 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
9955 Sema::LookupNameKind LookupKind, Scope *S,
9957 CorrectTypoKind Mode,
9958 DeclContext *MemberContext = nullptr,
9959 bool EnteringContext = false,
9960 const ObjCObjectPointerType *OPT = nullptr,
9961 bool RecordFailure = true);
9962
9963 /// Kinds of missing import. Note, the values of these enumerators correspond
9964 /// to %select values in diagnostics.
9972
9973 /// Diagnose that the specified declaration needs to be visible but
9974 /// isn't, and suggest a module import that would resolve the problem.
9976 MissingImportKind MIK, bool Recover = true);
9978 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
9979 MissingImportKind MIK, bool Recover);
9980
9981 /// Called on #pragma clang __debug dump II
9983
9984 /// Called on #pragma clang __debug dump E
9985 void ActOnPragmaDump(Expr *E);
9986
9987private:
9988 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
9989 //
9990 // The boolean value will be true to indicate that the namespace was loaded
9991 // from an AST/PCH file, or false otherwise.
9992 llvm::MapVector<NamespaceDecl *, bool> KnownNamespaces;
9993
9994 /// Whether we have already loaded known namespaces from an extenal
9995 /// source.
9996 bool LoadedExternalKnownNamespaces;
9997
9998 bool CppLookupName(LookupResult &R, Scope *S);
9999
10000 /// Determine if we could use all the declarations in the module.
10001 bool isUsableModule(const Module *M);
10002
10003 /// Helper for CorrectTypo used to create and populate a new
10004 /// TypoCorrectionConsumer. Returns nullptr if typo correction should be
10005 /// skipped entirely.
10006 std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(
10007 const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind,
10009 DeclContext *MemberContext, bool EnteringContext,
10010 const ObjCObjectPointerType *OPT, bool ErrorRecovery);
10011
10012 /// Cache for module units which is usable for current module.
10013 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
10014
10015 /// Record the typo correction failure and return an empty correction.
10016 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
10017 bool RecordFailure = true) {
10018 if (RecordFailure)
10019 TypoCorrectionFailures[Typo].insert(TypoLoc);
10020 return TypoCorrection();
10021 }
10022
10023 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
10024
10025 /// Determine whether two declarations should be linked together, given that
10026 /// the old declaration might not be visible and the new declaration might
10027 /// not have external linkage.
10028 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
10029 const NamedDecl *New) {
10030 if (isVisible(Old))
10031 return true;
10032 // See comment in below overload for why it's safe to compute the linkage
10033 // of the new declaration here.
10034 if (New->isExternallyDeclarable()) {
10035 assert(Old->isExternallyDeclarable() &&
10036 "should not have found a non-externally-declarable previous decl");
10037 return true;
10038 }
10039 return false;
10040 }
10041 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
10042
10043 ///@}
10044
10045 //
10046 //
10047 // -------------------------------------------------------------------------
10048 //
10049 //
10050
10051 /// \name Modules
10052 /// Implementations are in SemaModule.cpp
10053 ///@{
10054
10055public:
10056 /// Get the module unit whose scope we are currently within.
10058 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
10059 }
10060
10061 /// Is the module scope we are an implementation unit?
10063 if (ModuleScopes.empty())
10064 return false;
10065 const Module *M = ModuleScopes.back().Module;
10067 }
10068
10069 // When loading a non-modular PCH files, this is used to restore module
10070 // visibility.
10072 VisibleModules.setVisible(Mod, ImportLoc);
10073 }
10074
10075 enum class ModuleDeclKind {
10076 Interface, ///< 'export module X;'
10077 Implementation, ///< 'module X;'
10078 PartitionInterface, ///< 'export module X:Y;'
10079 PartitionImplementation, ///< 'module X:Y;'
10080 };
10081
10082 /// An enumeration to represent the transition of states in parsing module
10083 /// fragments and imports. If we are not parsing a C++20 TU, or we find
10084 /// an error in state transition, the state is set to NotACXX20Module.
10086 FirstDecl, ///< Parsing the first decl in a TU.
10087 GlobalFragment, ///< after 'module;' but before 'module X;'
10088 ImportAllowed, ///< after 'module X;' but before any non-import decl.
10089 ImportFinished, ///< after any non-import decl.
10090 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
10091 ///< non-import decl.
10092 PrivateFragmentImportFinished, ///< after 'module :private;' but a
10093 ///< non-import decl has already been seen.
10094 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
10095 };
10096
10097 /// The parser has processed a module-declaration that begins the definition
10098 /// of a module interface or implementation.
10100 SourceLocation ModuleLoc, ModuleDeclKind MDK,
10101 ModuleIdPath Path, ModuleIdPath Partition,
10102 ModuleImportState &ImportState,
10103 bool SeenNoTrivialPPDirective);
10104
10105 /// The parser has processed a global-module-fragment declaration that begins
10106 /// the definition of the global module fragment of the current module unit.
10107 /// \param ModuleLoc The location of the 'module' keyword.
10109
10110 /// The parser has processed a private-module-fragment declaration that begins
10111 /// the definition of the private module fragment of the current module unit.
10112 /// \param ModuleLoc The location of the 'module' keyword.
10113 /// \param PrivateLoc The location of the 'private' keyword.
10115 SourceLocation PrivateLoc);
10116
10117 /// The parser has processed a module import declaration.
10118 ///
10119 /// \param StartLoc The location of the first token in the declaration. This
10120 /// could be the location of an '@', 'export', or 'import'.
10121 /// \param ExportLoc The location of the 'export' keyword, if any.
10122 /// \param ImportLoc The location of the 'import' keyword.
10123 /// \param Path The module toplevel name as an access path.
10124 /// \param IsPartition If the name is for a partition.
10126 SourceLocation ExportLoc,
10127 SourceLocation ImportLoc, ModuleIdPath Path,
10128 bool IsPartition = false);
10130 SourceLocation ExportLoc,
10131 SourceLocation ImportLoc, Module *M,
10132 ModuleIdPath Path = {});
10133
10134 /// The parser has processed a module import translated from a
10135 /// #include or similar preprocessing directive.
10136 void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10137 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10138
10139 /// The parsed has entered a submodule.
10140 void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
10141 /// The parser has left a submodule.
10142 void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
10143
10144 /// Create an implicit import of the given module at the given
10145 /// source location, for error recovery, if possible.
10146 ///
10147 /// This routine is typically used when an entity found by name lookup
10148 /// is actually hidden within a module that we know about but the user
10149 /// has forgotten to import.
10150 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
10151 Module *Mod);
10152
10153 /// We have parsed the start of an export declaration, including the '{'
10154 /// (if present).
10155 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
10156 SourceLocation LBraceLoc);
10157
10158 /// Complete the definition of an export declaration.
10159 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
10160 SourceLocation RBraceLoc);
10161
10162private:
10163 /// The parser has begun a translation unit to be compiled as a C++20
10164 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
10165 void HandleStartOfHeaderUnit();
10166
10167 struct ModuleScope {
10168 SourceLocation BeginLoc;
10169 clang::Module *Module = nullptr;
10170 VisibleModuleSet OuterVisibleModules;
10171 };
10172 /// The modules we're currently parsing.
10173 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
10174
10175 /// For an interface unit, this is the implicitly imported interface unit.
10176 clang::Module *ThePrimaryInterface = nullptr;
10177
10178 /// The explicit global module fragment of the current translation unit.
10179 /// The explicit Global Module Fragment, as specified in C++
10180 /// [module.global.frag].
10181 clang::Module *TheGlobalModuleFragment = nullptr;
10182
10183 /// The implicit global module fragments of the current translation unit.
10184 ///
10185 /// The contents in the implicit global module fragment can't be discarded.
10186 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
10187
10188 /// Namespace definitions that we will export when they finish.
10189 llvm::SmallPtrSet<const NamespaceDecl *, 8> DeferredExportedNamespaces;
10190
10191 /// In a C++ standard module, inline declarations require a definition to be
10192 /// present at the end of a definition domain. This set holds the decls to
10193 /// be checked at the end of the TU.
10194 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
10195
10196 /// Helper function to judge if we are in module purview.
10197 /// Return false if we are not in a module.
10198 bool isCurrentModulePurview() const;
10199
10200 /// Enter the scope of the explicit global module fragment.
10201 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
10202 /// Leave the scope of the explicit global module fragment.
10203 void PopGlobalModuleFragment();
10204
10205 /// Enter the scope of an implicit global module fragment.
10206 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
10207 /// Leave the scope of an implicit global module fragment.
10208 void PopImplicitGlobalModuleFragment();
10209
10210 VisibleModuleSet VisibleModules;
10211
10212 /// Whether we had imported any named modules.
10213 bool HadImportedNamedModules = false;
10214 /// The set of instantiations we need to check if they references TU-local
10215 /// entity from TUs. This only makes sense if we imported any named modules.
10216 llvm::SmallVector<std::pair<FunctionDecl *, SourceLocation>>
10217 PendingCheckReferenceForTULocal;
10218 /// Implement [basic.link]p18, which requires that we can't use TU-local
10219 /// entities from other TUs (ignoring header units).
10220 void checkReferenceToTULocalFromOtherTU(FunctionDecl *FD,
10221 SourceLocation PointOfInstantiation);
10222 /// Implement [basic.link]p17, which diagnose for non TU local exposure in
10223 /// module interface or module partition.
10224 void checkExposure(const TranslationUnitDecl *TU);
10225
10226 ///@}
10227
10228 //
10229 //
10230 // -------------------------------------------------------------------------
10231 //
10232 //
10233
10234 /// \name C++ Overloading
10235 /// Implementations are in SemaOverload.cpp
10236 ///@{
10237
10238public:
10239 /// Whether deferrable diagnostics should be deferred.
10240 bool DeferDiags = false;
10241
10242 /// RAII class to control scope of DeferDiags.
10244 Sema &S;
10245 bool SavedDeferDiags = false;
10246
10247 public:
10249 : S(S), SavedDeferDiags(S.DeferDiags) {
10250 S.DeferDiags = SavedDeferDiags || DeferDiags;
10251 }
10252 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
10255 };
10256
10257 /// Flag indicating if Sema is building a recovery call expression.
10258 ///
10259 /// This flag is used to avoid building recovery call expressions
10260 /// if Sema is already doing so, which would cause infinite recursions.
10262
10263 /// Determine whether the given New declaration is an overload of the
10264 /// declarations in Old. This routine returns OverloadKind::Match or
10265 /// OverloadKind::NonFunction if New and Old cannot be overloaded, e.g., if
10266 /// New has the same signature as some function in Old (C++ 1.3.10) or if the
10267 /// Old declarations aren't functions (or function templates) at all. When it
10268 /// does return OverloadKind::Match or OverloadKind::NonFunction, MatchedDecl
10269 /// will point to the decl that New cannot be overloaded with. This decl may
10270 /// be a UsingShadowDecl on top of the underlying declaration.
10271 ///
10272 /// Example: Given the following input:
10273 ///
10274 /// void f(int, float); // #1
10275 /// void f(int, int); // #2
10276 /// int f(int, int); // #3
10277 ///
10278 /// When we process #1, there is no previous declaration of "f", so IsOverload
10279 /// will not be used.
10280 ///
10281 /// When we process #2, Old contains only the FunctionDecl for #1. By
10282 /// comparing the parameter types, we see that #1 and #2 are overloaded (since
10283 /// they have different signatures), so this routine returns
10284 /// OverloadKind::Overload; MatchedDecl is unchanged.
10285 ///
10286 /// When we process #3, Old is an overload set containing #1 and #2. We
10287 /// compare the signatures of #3 to #1 (they're overloaded, so we do nothing)
10288 /// and then #3 to #2. Since the signatures of #3 and #2 are identical (return
10289 /// types of functions are not part of the signature), IsOverload returns
10290 /// OverloadKind::Match and MatchedDecl will be set to point to the
10291 /// FunctionDecl for #2.
10292 ///
10293 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a
10294 /// class by a using declaration. The rules for whether to hide shadow
10295 /// declarations ignore some properties which otherwise figure into a function
10296 /// template's signature.
10298 const LookupResult &OldDecls, NamedDecl *&OldDecl,
10299 bool UseMemberUsingDeclRules);
10301 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10302
10303 // Checks whether MD constitutes an override the base class method BaseMD.
10304 // When checking for overrides, the object object members are ignored.
10305 bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
10306 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10307
10308 enum class AllowedExplicit {
10309 /// Allow no explicit functions to be used.
10311 /// Allow explicit conversion functions but not explicit constructors.
10313 /// Allow both explicit conversion functions and explicit constructors.
10315 };
10316
10318 Expr *From, QualType ToType, bool SuppressUserConversions,
10319 AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle,
10320 bool AllowObjCWritebackConversion);
10321
10322 /// PerformImplicitConversion - Perform an implicit conversion of the
10323 /// expression From to the type ToType. Returns the
10324 /// converted expression. Flavor is the kind of conversion we're
10325 /// performing, used in the error message. If @p AllowExplicit,
10326 /// explicit user-defined conversions are permitted.
10328 AssignmentAction Action,
10329 bool AllowExplicit = false);
10330
10331 /// IsIntegralPromotion - Determines whether the conversion from the
10332 /// expression From (whose potentially-adjusted type is FromType) to
10333 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
10334 /// sets PromotedType to the promoted type.
10335 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
10336
10337 /// IsFloatingPointPromotion - Determines whether the conversion from
10338 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
10339 /// returns true and sets PromotedType to the promoted type.
10340 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
10341
10342 /// Determine if a conversion is a complex promotion.
10343 ///
10344 /// A complex promotion is defined as a complex -> complex conversion
10345 /// where the conversion between the underlying real types is a
10346 /// floating-point or integral promotion.
10347 bool IsComplexPromotion(QualType FromType, QualType ToType);
10348
10349 /// IsOverflowBehaviorTypePromotion - Determines whether the conversion from
10350 /// FromType to ToType involves an OverflowBehaviorType FromType being
10351 /// promoted to an OverflowBehaviorType ToType which has a larger bitwidth.
10352 /// If so, returns true and sets FromType to ToType.
10353 bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType);
10354
10355 /// IsOverflowBehaviorTypeConversion - Determines whether the conversion from
10356 /// FromType to ToType necessarily involves both an OverflowBehaviorType and
10357 /// a non-OverflowBehaviorType. If so, returns true and sets FromType to
10358 /// ToType.
10359 bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType);
10360
10361 /// IsPointerConversion - Determines whether the conversion of the
10362 /// expression From, which has the (possibly adjusted) type FromType,
10363 /// can be converted to the type ToType via a pointer conversion (C++
10364 /// 4.10). If so, returns true and places the converted type (that
10365 /// might differ from ToType in its cv-qualifiers at some level) into
10366 /// ConvertedType.
10367 ///
10368 /// This routine also supports conversions to and from block pointers
10369 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
10370 /// pointers to interfaces. FIXME: Once we've determined the
10371 /// appropriate overloading rules for Objective-C, we may want to
10372 /// split the Objective-C checks into a different routine; however,
10373 /// GCC seems to consider all of these conversions to be pointer
10374 /// conversions, so for now they live here. IncompatibleObjC will be
10375 /// set if the conversion is an allowed Objective-C conversion that
10376 /// should result in a warning.
10377 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
10378 bool InOverloadResolution, QualType &ConvertedType,
10379 bool &IncompatibleObjC);
10380
10381 /// isObjCPointerConversion - Determines whether this is an
10382 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
10383 /// with the same arguments and return values.
10384 bool isObjCPointerConversion(QualType FromType, QualType ToType,
10385 QualType &ConvertedType, bool &IncompatibleObjC);
10386 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
10387 QualType &ConvertedType);
10388
10389 /// FunctionParamTypesAreEqual - This routine checks two function proto types
10390 /// for equality of their parameter types. Caller has already checked that
10391 /// they have same number of parameters. If the parameters are different,
10392 /// ArgPos will have the parameter index of the first different parameter.
10393 /// If `Reversed` is true, the parameters of `NewType` will be compared in
10394 /// reverse order. That's useful if one of the functions is being used as a
10395 /// C++20 synthesized operator overload with a reversed parameter order.
10398 unsigned *ArgPos = nullptr,
10399 bool Reversed = false);
10400
10402 const FunctionProtoType *NewType,
10403 unsigned *ArgPos = nullptr,
10404 bool Reversed = false);
10405
10406 bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
10407 const FunctionDecl *NewFunction,
10408 unsigned *ArgPos = nullptr,
10409 bool Reversed = false);
10410
10411 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
10412 /// function types. Catches different number of parameter, mismatch in
10413 /// parameter types, and different return types.
10415 QualType ToType);
10416
10417 /// CheckPointerConversion - Check the pointer conversion from the
10418 /// expression From to the type ToType. This routine checks for
10419 /// ambiguous or inaccessible derived-to-base pointer
10420 /// conversions for which IsPointerConversion has already returned
10421 /// true. It returns true and produces a diagnostic if there was an
10422 /// error, or returns false otherwise.
10423 bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind,
10424 CXXCastPath &BasePath, bool IgnoreBaseAccess,
10425 bool Diagnose = true);
10426
10427 /// IsMemberPointerConversion - Determines whether the conversion of the
10428 /// expression From, which has the (possibly adjusted) type FromType, can be
10429 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
10430 /// If so, returns true and places the converted type (that might differ from
10431 /// ToType in its cv-qualifiers at some level) into ConvertedType.
10432 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
10433 bool InOverloadResolution,
10434 QualType &ConvertedType);
10435
10445 /// CheckMemberPointerConversion - Check the member pointer conversion from
10446 /// the expression From to the type ToType. This routine checks for ambiguous
10447 /// or virtual or inaccessible base-to-derived member pointer conversions for
10448 /// which IsMemberPointerConversion has already returned true. It produces a
10449 // diagnostic if there was an error.
10451 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
10452 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
10453 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction);
10454
10455 /// IsQualificationConversion - Determines whether the conversion from
10456 /// an rvalue of type FromType to ToType is a qualification conversion
10457 /// (C++ 4.4).
10458 ///
10459 /// \param ObjCLifetimeConversion Output parameter that will be set to
10460 /// indicate when the qualification conversion involves a change in the
10461 /// Objective-C object lifetime.
10462 bool IsQualificationConversion(QualType FromType, QualType ToType,
10463 bool CStyle, bool &ObjCLifetimeConversion);
10464
10465 /// Determine whether the conversion from FromType to ToType is a valid
10466 /// conversion of ExtInfo/ExtProtoInfo on the nested function type.
10467 /// More precisely, this method checks whether FromType can be transformed
10468 /// into an exact match for ToType, by transforming its extended function
10469 /// type information in legal manner (e.g. by strictly stripping "noreturn"
10470 /// or "noexcept", or by stripping "noescape" for arguments).
10471 bool IsFunctionConversion(QualType FromType, QualType ToType) const;
10472
10473 /// Same as `IsFunctionConversion`, but if this would return true, it sets
10474 /// `ResultTy` to `ToType`.
10475 bool TryFunctionConversion(QualType FromType, QualType ToType,
10476 QualType &ResultTy) const;
10477
10480 DeclarationName Name,
10481 OverloadCandidateSet &CandidateSet,
10482 FunctionDecl *Fn, MultiExprArg Args,
10483 bool IsMember = false);
10484
10486 FunctionDecl *Fun);
10488 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
10490
10491 /// PerformContextuallyConvertToBool - Perform a contextual conversion
10492 /// of the expression From to bool (C++0x [conv]p3).
10494
10495 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
10496 /// conversion of the expression From to an Objective-C pointer type.
10497 /// Returns a valid but null ExprResult if no conversion sequence exists.
10499
10501 CCEKind CCE,
10502 NamedDecl *Dest = nullptr);
10503
10505 llvm::APSInt &Value, CCEKind CCE);
10507 APValue &Value, CCEKind CCE,
10508 NamedDecl *Dest = nullptr);
10509
10510 /// EvaluateConvertedConstantExpression - Evaluate an Expression
10511 /// That is a converted constant expression
10512 /// (which was built with BuildConvertedConstantExpression)
10515 CCEKind CCE, bool RequireInt,
10516 const APValue &PreNarrowingValue);
10517
10518 /// Abstract base class used to perform a contextual implicit
10519 /// conversion from an expression to any type passing a filter.
10521 public:
10524
10528
10529 /// Determine whether the specified type is a valid destination type
10530 /// for this conversion.
10531 virtual bool match(QualType T) = 0;
10532
10533 /// Emits a diagnostic complaining that the expression does not have
10534 /// integral or enumeration type.
10536 QualType T) = 0;
10537
10538 /// Emits a diagnostic when the expression has incomplete class type.
10539 virtual SemaDiagnosticBuilder
10541
10542 /// Emits a diagnostic when the only matching conversion function
10543 /// is explicit.
10545 SourceLocation Loc,
10546 QualType T,
10547 QualType ConvTy) = 0;
10548
10549 /// Emits a note for the explicit conversion function.
10550 virtual SemaDiagnosticBuilder
10552
10553 /// Emits a diagnostic when there are multiple possible conversion
10554 /// functions.
10556 QualType T) = 0;
10557
10558 /// Emits a note for one of the candidate conversions.
10559 virtual SemaDiagnosticBuilder
10561
10562 /// Emits a diagnostic when we picked a conversion function
10563 /// (for cases when we are not allowed to pick a conversion function).
10565 SourceLocation Loc,
10566 QualType T,
10567 QualType ConvTy) = 0;
10568
10570 };
10571
10573 bool AllowScopedEnumerations;
10574
10575 public:
10576 ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress,
10577 bool SuppressConversion)
10579 AllowScopedEnumerations(AllowScopedEnumerations) {}
10580
10581 /// Match an integral or (possibly scoped) enumeration type.
10582 bool match(QualType T) override;
10583
10585 QualType T) override {
10586 return diagnoseNotInt(S, Loc, T);
10587 }
10588
10589 /// Emits a diagnostic complaining that the expression does not have
10590 /// integral or enumeration type.
10592 QualType T) = 0;
10593 };
10594
10595 /// Perform a contextual implicit conversion.
10598 ContextualImplicitConverter &Converter);
10599
10600 /// ReferenceCompareResult - Expresses the result of comparing two
10601 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10602 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10604 /// Ref_Incompatible - The two types are incompatible, so direct
10605 /// reference binding is not possible.
10607 /// Ref_Related - The two types are reference-related, which means
10608 /// that their unqualified forms (T1 and T2) are either the same
10609 /// or T1 is a base class of T2.
10611 /// Ref_Compatible - The two types are reference-compatible.
10613 };
10614
10615 // Fake up a scoped enumeration that still contextually converts to bool.
10617 /// The conversions that would be performed on an lvalue of type T2 when
10618 /// binding a reference of type T1 to it, as determined when evaluating
10619 /// whether T1 is reference-compatible with T2.
10625 ObjC = 0x10,
10627
10628 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
10629 };
10630 };
10632
10633 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
10634 /// determine whether they are reference-compatible,
10635 /// reference-related, or incompatible, for use in C++ initialization by
10636 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
10637 /// type, and the first type (T1) is the pointee type of the reference
10638 /// type being initialized.
10641 ReferenceConversions *Conv = nullptr);
10642
10643 /// AddOverloadCandidate - Adds the given function to the set of
10644 /// candidate functions, using the given function call arguments. If
10645 /// @p SuppressUserConversions, then don't allow user-defined
10646 /// conversions via constructors or conversion operators.
10647 ///
10648 /// \param PartialOverloading true if we are performing "partial" overloading
10649 /// based on an incomplete set of function arguments. This feature is used by
10650 /// code completion.
10653 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10654 bool PartialOverloading = false, bool AllowExplicit = true,
10655 bool AllowExplicitConversion = false,
10656 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10657 ConversionSequenceList EarlyConversions = {},
10659 bool AggregateCandidateDeduction = false, bool StrictPackMatch = false);
10660
10661 /// Add all of the function declarations in the given function set to
10662 /// the overload candidate set.
10664 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10665 OverloadCandidateSet &CandidateSet,
10666 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
10667 bool SuppressUserConversions = false, bool PartialOverloading = false,
10668 bool FirstArgumentIsBase = false);
10669
10670 /// AddMethodCandidate - Adds a named decl (which is some kind of
10671 /// method) as a method candidate to the given overload set.
10672 void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
10673 Expr::Classification ObjectClassification,
10674 ArrayRef<Expr *> Args,
10675 OverloadCandidateSet &CandidateSet,
10676 bool SuppressUserConversion = false,
10677 OverloadCandidateParamOrder PO = {});
10678
10679 /// AddMethodCandidate - Adds the given C++ member function to the set
10680 /// of candidate functions, using the given function call arguments
10681 /// and the object argument (@c Object). For example, in a call
10682 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
10683 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
10684 /// allow user-defined conversions via constructors or conversion
10685 /// operators.
10686 void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
10687 CXXRecordDecl *ActingContext, QualType ObjectType,
10688 Expr::Classification ObjectClassification,
10689 ArrayRef<Expr *> Args,
10690 OverloadCandidateSet &CandidateSet,
10691 bool SuppressUserConversions = false,
10692 bool PartialOverloading = false,
10693 ConversionSequenceList EarlyConversions = {},
10695 bool StrictPackMatch = false);
10696
10697 /// Add a C++ member function template as a candidate to the candidate
10698 /// set, using template argument deduction to produce an appropriate member
10699 /// function template specialization.
10701 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
10702 CXXRecordDecl *ActingContext,
10703 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
10704 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
10705 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10706 bool PartialOverloading = false, OverloadCandidateParamOrder PO = {});
10707
10708 /// Add a C++ function template specialization as a candidate
10709 /// in the candidate set, using template argument deduction to produce
10710 /// an appropriate function template specialization.
10712 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10713 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
10714 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10715 bool PartialOverloading = false, bool AllowExplicit = true,
10716 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10718 bool AggregateCandidateDeduction = false);
10719
10721 /// Do not consider any user-defined conversions when constructing the
10722 /// initializing sequence.
10724
10725 /// Before constructing the initializing sequence, we check whether the
10726 /// parameter type and argument type contain any user defined conversions.
10727 /// If so, do not initialize them. This effectively bypasses some undesired
10728 /// instantiation before checking constaints, which might otherwise result
10729 /// in non-SFINAE errors e.g. recursive constraints.
10731
10738 };
10739
10740 /// Check that implicit conversion sequences can be formed for each argument
10741 /// whose corresponding parameter has a non-dependent type, per DR1391's
10742 /// [temp.deduct.call]p10.
10745 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
10747 CheckNonDependentConversionsFlag UserConversionFlag,
10748 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
10749 Expr::Classification ObjectClassification = {},
10750 OverloadCandidateParamOrder PO = {});
10751
10752 /// AddConversionCandidate - Add a C++ conversion function as a
10753 /// candidate in the candidate set (C++ [over.match.conv],
10754 /// C++ [over.match.copy]). From is the expression we're converting from,
10755 /// and ToType is the type that we're eventually trying to convert to
10756 /// (which may or may not be the same type as the type that the
10757 /// conversion function produces).
10759 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
10760 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10761 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10762 bool AllowExplicit, bool AllowResultConversion = true,
10763 bool StrictPackMatch = false);
10764
10765 /// Adds a conversion function template specialization
10766 /// candidate to the overload set, using template argument deduction
10767 /// to deduce the template arguments of the conversion function
10768 /// template from the type that we are converting to (C++
10769 /// [temp.deduct.conv]).
10771 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10772 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10773 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10774 bool AllowExplicit, bool AllowResultConversion = true);
10775
10776 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
10777 /// converts the given @c Object to a function pointer via the
10778 /// conversion function @c Conversion, and then attempts to call it
10779 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
10780 /// the type of function that we'll eventually be calling.
10781 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
10782 DeclAccessPair FoundDecl,
10783 CXXRecordDecl *ActingContext,
10784 const FunctionProtoType *Proto, Expr *Object,
10785 ArrayRef<Expr *> Args,
10786 OverloadCandidateSet &CandidateSet);
10787
10788 /// Add all of the non-member operator function declarations in the given
10789 /// function set to the overload candidate set.
10791 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10792 OverloadCandidateSet &CandidateSet,
10793 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10794
10795 /// Add overload candidates for overloaded operators that are
10796 /// member functions.
10797 ///
10798 /// Add the overloaded operator candidates that are member functions
10799 /// for the operator Op that was used in an operator expression such
10800 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
10801 /// CandidateSet will store the added overload candidates. (C++
10802 /// [over.match.oper]).
10804 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10805 OverloadCandidateSet &CandidateSet,
10807
10808 /// AddBuiltinCandidate - Add a candidate for a built-in
10809 /// operator. ResultTy and ParamTys are the result and parameter types
10810 /// of the built-in candidate, respectively. Args and NumArgs are the
10811 /// arguments being passed to the candidate. IsAssignmentOperator
10812 /// should be true when this built-in candidate is an assignment
10813 /// operator. NumContextualBoolArguments is the number of arguments
10814 /// (at the beginning of the argument list) that will be contextually
10815 /// converted to bool.
10816 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
10817 OverloadCandidateSet &CandidateSet,
10818 bool IsAssignmentOperator = false,
10819 unsigned NumContextualBoolArguments = 0);
10820
10821 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
10822 /// operator overloads to the candidate set (C++ [over.built]), based
10823 /// on the operator @p Op and the arguments given. For example, if the
10824 /// operator is a binary '+', this routine might add "int
10825 /// operator+(int, int)" to cover integer addition.
10827 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10828 OverloadCandidateSet &CandidateSet);
10829
10830 /// Add function candidates found via argument-dependent lookup
10831 /// to the set of overloading candidates.
10832 ///
10833 /// This routine performs argument-dependent name lookup based on the
10834 /// given function name (which may also be an operator name) and adds
10835 /// all of the overload candidates found by ADL to the overload
10836 /// candidate set (C++ [basic.lookup.argdep]).
10838 DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args,
10839 TemplateArgumentListInfo *ExplicitTemplateArgs,
10840 OverloadCandidateSet &CandidateSet, bool PartialOverloading = false);
10841
10842 /// Check the enable_if expressions on the given function. Returns the first
10843 /// failing attribute, or NULL if they were all successful.
10844 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
10845 ArrayRef<Expr *> Args,
10846 bool MissingImplicitThis = false);
10847
10848 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10849 /// non-ArgDependent DiagnoseIfAttrs.
10850 ///
10851 /// Argument-dependent diagnose_if attributes should be checked each time a
10852 /// function is used as a direct callee of a function call.
10853 ///
10854 /// Returns true if any errors were emitted.
10855 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
10856 const Expr *ThisArg,
10857 ArrayRef<const Expr *> Args,
10858 SourceLocation Loc);
10859
10860 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10861 /// ArgDependent DiagnoseIfAttrs.
10862 ///
10863 /// Argument-independent diagnose_if attributes should be checked on every use
10864 /// of a function.
10865 ///
10866 /// Returns true if any errors were emitted.
10867 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
10868 SourceLocation Loc);
10869
10870 /// Determine if \p A and \p B are equivalent internal linkage declarations
10871 /// from different modules, and thus an ambiguity error can be downgraded to
10872 /// an extension warning.
10873 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10874 const NamedDecl *B);
10876 SourceLocation Loc, const NamedDecl *D,
10877 ArrayRef<const NamedDecl *> Equiv);
10878
10879 // Emit as a 'note' the specific overload candidate
10881 const NamedDecl *Found, const FunctionDecl *Fn,
10883 QualType DestType = QualType(), bool TakingAddress = false);
10884
10885 // Emit as a series of 'note's all template and non-templates identified by
10886 // the expression Expr
10887 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
10888 bool TakingAddress = false);
10889
10890 /// Returns whether the given function's address can be taken or not,
10891 /// optionally emitting a diagnostic if the address can't be taken.
10892 ///
10893 /// Returns false if taking the address of the function is illegal.
10894 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10895 bool Complain = false,
10896 SourceLocation Loc = SourceLocation());
10897
10898 // [PossiblyAFunctionType] --> [Return]
10899 // NonFunctionType --> NonFunctionType
10900 // R (A) --> R(A)
10901 // R (*)(A) --> R (A)
10902 // R (&)(A) --> R (A)
10903 // R (S::*)(A) --> R (A)
10904 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
10905
10906 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10907 /// an overloaded function (C++ [over.over]), where @p From is an
10908 /// expression with overloaded function type and @p ToType is the type
10909 /// we're trying to resolve to. For example:
10910 ///
10911 /// @code
10912 /// int f(double);
10913 /// int f(int);
10914 ///
10915 /// int (*pfd)(double) = f; // selects f(double)
10916 /// @endcode
10917 ///
10918 /// This routine returns the resulting FunctionDecl if it could be
10919 /// resolved, and NULL otherwise. When @p Complain is true, this
10920 /// routine will emit diagnostics if there is an error.
10921 FunctionDecl *
10922 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
10923 bool Complain, DeclAccessPair &Found,
10924 bool *pHadMultipleCandidates = nullptr);
10925
10926 /// Given an expression that refers to an overloaded function, try to
10927 /// resolve that function to a single function that can have its address
10928 /// taken. This will modify `Pair` iff it returns non-null.
10929 ///
10930 /// This routine can only succeed if from all of the candidates in the
10931 /// overload set for SrcExpr that can have their addresses taken, there is one
10932 /// candidate that is more constrained than the rest.
10933 FunctionDecl *
10934 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
10935
10936 /// Given an overloaded function, tries to turn it into a non-overloaded
10937 /// function reference using resolveAddressOfSingleOverloadCandidate. This
10938 /// will perform access checks, diagnose the use of the resultant decl, and,
10939 /// if requested, potentially perform a function-to-pointer decay.
10940 ///
10941 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
10942 /// Otherwise, returns true. This may emit diagnostics and return true.
10944 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
10945
10946 /// Given an expression that refers to an overloaded function, try to
10947 /// resolve that overloaded function expression down to a single function.
10948 ///
10949 /// This routine can only resolve template-ids that refer to a single function
10950 /// template, where that template-id refers to a single template whose
10951 /// template arguments are either provided by the template-id or have
10952 /// defaults, as described in C++0x [temp.arg.explicit]p3.
10953 ///
10954 /// If no template-ids are found, no diagnostics are emitted and NULL is
10955 /// returned.
10957 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
10958 TemplateSpecCandidateSet *FailedTSC = nullptr,
10959 bool ForTypeDeduction = false);
10960
10961 // Resolve and fix an overloaded expression that can be resolved
10962 // because it identifies a single function template specialization.
10963 //
10964 // Last three arguments should only be supplied if Complain = true
10965 //
10966 // Return true if it was logically possible to so resolve the
10967 // expression, regardless of whether or not it succeeded. Always
10968 // returns true if 'complain' is set.
10970 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
10971 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
10972 QualType DestTypeForComplaining = QualType(),
10973 unsigned DiagIDForComplaining = 0);
10974
10975 /// Add the overload candidates named by callee and/or found by argument
10976 /// dependent lookup to the given overload set.
10977 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10978 ArrayRef<Expr *> Args,
10979 OverloadCandidateSet &CandidateSet,
10980 bool PartialOverloading = false);
10981
10982 /// Add the call candidates from the given set of lookup results to the given
10983 /// overload set. Non-function lookup results are ignored.
10985 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
10986 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
10987
10988 // An enum used to represent the different possible results of building a
10989 // range-based for loop.
10995
10996 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
10997 /// given LookupResult is non-empty, it is assumed to describe a member which
10998 /// will be invoked. Otherwise, the function will be found via argument
10999 /// dependent lookup.
11000 /// CallExpr is set to a valid expression and FRS_Success returned on success,
11001 /// otherwise CallExpr is set to ExprError() and some non-success value
11002 /// is returned.
11004 SourceLocation RangeLoc,
11005 const DeclarationNameInfo &NameInfo,
11006 LookupResult &MemberLookup,
11007 OverloadCandidateSet *CandidateSet,
11008 Expr *Range, ExprResult *CallExpr);
11009
11010 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11011 /// (which eventually refers to the declaration Func) and the call
11012 /// arguments Args/NumArgs, attempt to resolve the function call down
11013 /// to a specific function. If overload resolution succeeds, returns
11014 /// the call expression produced by overload resolution.
11015 /// Otherwise, emits diagnostics and returns ExprError.
11017 Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
11018 MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig,
11019 bool AllowTypoCorrection = true, bool CalleesAddressIsTaken = false);
11020
11021 /// Constructs and populates an OverloadedCandidateSet from
11022 /// the given function.
11023 /// \returns true when an the ExprResult output parameter has been set.
11025 MultiExprArg Args, SourceLocation RParenLoc,
11026 OverloadCandidateSet *CandidateSet,
11028
11032 const UnresolvedSetImpl &Fns,
11033 bool PerformADL = true);
11034
11035 /// Perform lookup for an overloaded unary operator.
11038 const UnresolvedSetImpl &Fns,
11039 ArrayRef<Expr *> Args, bool RequiresADL = true);
11040
11041 /// Create a unary operation that may resolve to an overloaded
11042 /// operator.
11043 ///
11044 /// \param OpLoc The location of the operator itself (e.g., '*').
11045 ///
11046 /// \param Opc The UnaryOperatorKind that describes this operator.
11047 ///
11048 /// \param Fns The set of non-member functions that will be
11049 /// considered by overload resolution. The caller needs to build this
11050 /// set based on the context using, e.g.,
11051 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11052 /// set should not contain any member functions; those will be added
11053 /// by CreateOverloadedUnaryOp().
11054 ///
11055 /// \param Input The input argument.
11058 const UnresolvedSetImpl &Fns, Expr *input,
11059 bool RequiresADL = true);
11060
11061 /// Perform lookup for an overloaded binary operator.
11064 const UnresolvedSetImpl &Fns,
11065 ArrayRef<Expr *> Args, bool RequiresADL = true);
11066
11067 /// Create a binary operation that may resolve to an overloaded
11068 /// operator.
11069 ///
11070 /// \param OpLoc The location of the operator itself (e.g., '+').
11071 ///
11072 /// \param Opc The BinaryOperatorKind that describes this operator.
11073 ///
11074 /// \param Fns The set of non-member functions that will be
11075 /// considered by overload resolution. The caller needs to build this
11076 /// set based on the context using, e.g.,
11077 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11078 /// set should not contain any member functions; those will be added
11079 /// by CreateOverloadedBinOp().
11080 ///
11081 /// \param LHS Left-hand argument.
11082 /// \param RHS Right-hand argument.
11083 /// \param PerformADL Whether to consider operator candidates found by ADL.
11084 /// \param AllowRewrittenCandidates Whether to consider candidates found by
11085 /// C++20 operator rewrites.
11086 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
11087 /// the function in question. Such a function is never a candidate in
11088 /// our overload resolution. This also enables synthesizing a three-way
11089 /// comparison from < and == as described in C++20 [class.spaceship]p1.
11091 const UnresolvedSetImpl &Fns, Expr *LHS,
11092 Expr *RHS, bool RequiresADL = true,
11093 bool AllowRewrittenCandidates = true,
11094 FunctionDecl *DefaultedFn = nullptr);
11096 const UnresolvedSetImpl &Fns,
11097 Expr *LHS, Expr *RHS,
11098 FunctionDecl *DefaultedFn);
11099
11101 SourceLocation RLoc, Expr *Base,
11102 MultiExprArg Args);
11103
11104 /// BuildCallToMemberFunction - Build a call to a member
11105 /// function. MemExpr is the expression that refers to the member
11106 /// function (and includes the object parameter), Args/NumArgs are the
11107 /// arguments to the function call (not including the object
11108 /// parameter). The caller needs to validate that the member
11109 /// expression refers to a non-static member function or an overloaded
11110 /// member function.
11112 Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args,
11113 SourceLocation RParenLoc, Expr *ExecConfig = nullptr,
11114 bool IsExecConfig = false, bool AllowRecovery = false);
11115
11116 /// BuildCallToObjectOfClassType - Build a call to an object of class
11117 /// type (C++ [over.call.object]), which can end up invoking an
11118 /// overloaded function call operator (@c operator()) or performing a
11119 /// user-defined conversion on the object argument.
11121 SourceLocation LParenLoc,
11122 MultiExprArg Args,
11123 SourceLocation RParenLoc);
11124
11125 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11126 /// (if one exists), where @c Base is an expression of class type and
11127 /// @c Member is the name of the member we're trying to find.
11129 SourceLocation OpLoc,
11130 bool *NoArrowOperatorFound = nullptr);
11131
11134 bool HadMultipleCandidates);
11135
11136 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call
11137 /// to a literal operator described by the provided lookup results.
11140 SourceLocation LitEndLoc,
11141 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
11142
11143 /// FixOverloadedFunctionReference - E is an expression that refers to
11144 /// a C++ overloaded function (possibly with some parentheses and
11145 /// perhaps a '&' around it). We have resolved the overloaded function
11146 /// to the function declaration Fn, so patch up the expression E to
11147 /// refer (possibly indirectly) to Fn. Returns the new expr.
11149 FunctionDecl *Fn);
11151 DeclAccessPair FoundDecl,
11152 FunctionDecl *Fn);
11153
11154 /// - Returns a selector which best matches given argument list or
11155 /// nullptr if none could be found
11157 bool IsInstance,
11159
11160 ///@}
11161
11162 //
11163 //
11164 // -------------------------------------------------------------------------
11165 //
11166 //
11167
11168 /// \name Statements
11169 /// Implementations are in SemaStmt.cpp
11170 ///@{
11171
11172public:
11173 /// Stack of active SEH __finally scopes. Can be empty.
11175
11176 /// Stack of '_Defer' statements that are currently being parsed, as well
11177 /// as the locations of their '_Defer' keywords. Can be empty.
11179
11180 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
11182
11184 bool HasLeadingEmptyMacro = false);
11185
11187 SourceLocation EndLoc);
11189
11190 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
11191 /// whose result is unused, warn.
11192 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
11193
11194 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
11198 ArrayRef<Stmt *> Elts, bool isStmtExpr);
11199
11201
11204 SourceLocation DotDotDotLoc, ExprResult RHS,
11205 SourceLocation ColonLoc);
11206
11207 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
11208 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
11209
11211 SourceLocation ColonLoc, Stmt *SubStmt,
11212 Scope *CurScope);
11214 SourceLocation ColonLoc, Stmt *SubStmt);
11215
11217 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
11219 Stmt *SubStmt);
11220
11221 /// Check whether the given statement can have musttail applied to it,
11222 /// issuing a diagnostic and returning false if not. In the success case,
11223 /// the statement is rewritten to remove implicit nodes from the return
11224 /// value.
11225 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11226
11228 SourceLocation LParenLoc, Stmt *InitStmt,
11229 ConditionResult Cond, SourceLocation RParenLoc,
11230 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11232 SourceLocation LParenLoc, Stmt *InitStmt,
11233 ConditionResult Cond, SourceLocation RParenLoc,
11234 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11235
11237
11239 SourceLocation LParenLoc, Stmt *InitStmt,
11240 ConditionResult Cond,
11241 SourceLocation RParenLoc);
11243 Stmt *Body);
11244
11245 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11246 /// integer not in the range of enum values.
11247 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11248 Expr *SrcExpr);
11249
11251 ConditionResult Cond, SourceLocation RParenLoc,
11252 Stmt *Body);
11254 SourceLocation WhileLoc, SourceLocation CondLParen,
11255 Expr *Cond, SourceLocation CondRParen);
11256
11258 Stmt *First, ConditionResult Second,
11259 FullExprArg Third, SourceLocation RParenLoc,
11260 Stmt *Body);
11261
11262 /// In an Objective C collection iteration statement:
11263 /// for (x in y)
11264 /// x can be an arbitrary l-value expression. Bind it up as a
11265 /// full-expression.
11267
11269 /// Initial building of a for-range statement.
11271 /// Instantiation or recovery rebuild of a for-range statement. Don't
11272 /// attempt any typo-correction.
11274 /// Determining whether a for-range statement could be built. Avoid any
11275 /// unnecessary or irreversible actions.
11277 };
11278
11279 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
11280 ///
11281 /// C++11 [stmt.ranged]:
11282 /// A range-based for statement is equivalent to
11283 ///
11284 /// {
11285 /// auto && __range = range-init;
11286 /// for ( auto __begin = begin-expr,
11287 /// __end = end-expr;
11288 /// __begin != __end;
11289 /// ++__begin ) {
11290 /// for-range-declaration = *__begin;
11291 /// statement
11292 /// }
11293 /// }
11294 ///
11295 /// The body of the loop is not available yet, since it cannot be analysed
11296 /// until we have determined the type of the for-range-declaration.
11298 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc,
11299 Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection,
11300 SourceLocation RParenLoc, BuildForRangeKind Kind,
11301 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11302
11303 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
11304 StmtResult BuildCXXForRangeStmt(
11305 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
11306 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
11307 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
11308 BuildForRangeKind Kind,
11309 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11310
11311 /// Set the type of a for-range declaration whose for-range or expansion
11312 /// initialiser is dependent.
11313 void ActOnDependentForRangeInitializer(VarDecl *LoopVar,
11314 BuildForRangeKind BFRK);
11315
11316 /// Holds the 'begin' and 'end' variables of a range-based for loop or
11317 /// expansion statement; begin-expr and end-expr are also provided; the
11318 /// latter are used in some diagnostics.
11320 VarDecl *BeginVar = nullptr;
11321 VarDecl *EndVar = nullptr;
11322 Expr *BeginExpr = nullptr;
11323 Expr *EndExpr = nullptr;
11324 bool isValid() const { return BeginVar != nullptr && EndVar != nullptr; }
11325 };
11326
11327 /// Determine begin-expr and end-expr and build variable declarations for
11328 /// them as per [stmt.ranged].
11329 ForRangeBeginEndInfo BuildCXXForRangeBeginEndVars(
11330 Scope *S, VarDecl *RangeVar, SourceLocation ColonLoc,
11331 SourceLocation CoawaitLoc,
11332 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps,
11333 BuildForRangeKind Kind, bool IsConstexpr,
11334 StmtResult *RebuildResult = nullptr,
11335 llvm::function_ref<StmtResult()> RebuildWithDereference = {},
11336 IdentifierInfo *BeginName = nullptr, IdentifierInfo *EndName = nullptr);
11337
11338 /// Helper used by the expansion statements and for-range code to build
11339 /// a variable declaration for e.g. 'begin' and 'end'.
11340 VarDecl *BuildForRangeVarDecl(SourceLocation Loc, QualType Type,
11341 IdentifierInfo *Name, bool IsConstexpr);
11342
11343 /// Build the range variable of a range-based for loop or iterating
11344 /// expansion statement and return its DeclStmt.
11345 StmtResult BuildCXXForRangeRangeVar(Scope *S, Expr *Range, QualType Type,
11346 bool IsConstexpr = false);
11347
11348 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
11349 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
11350 /// body cannot be performed until after the type of the range variable is
11351 /// determined.
11352 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
11353
11354 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
11355 LabelDecl *TheDecl);
11356 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
11357 SourceLocation StarLoc, Expr *DestExp);
11358 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope,
11359 LabelDecl *Label, SourceLocation LabelLoc);
11360 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope,
11361 LabelDecl *Label, SourceLocation LabelLoc);
11362
11363 void ActOnStartOfDeferStmt(SourceLocation DeferLoc, Scope *CurScope);
11364 void ActOnDeferStmtError(Scope *CurScope);
11365 StmtResult ActOnEndOfDeferStmt(Stmt *Body, Scope *CurScope);
11366
11369
11372
11373 bool isMoveEligible() const { return S != None; };
11375 };
11377
11378 /// Determine whether the given expression might be move-eligible or
11379 /// copy-elidable in either a (co_)return statement or throw expression,
11380 /// without considering function return type, if applicable.
11381 ///
11382 /// \param E The expression being returned from the function or block,
11383 /// being thrown, or being co_returned from a coroutine. This expression
11384 /// might be modified by the implementation.
11385 ///
11386 /// \param Mode Overrides detection of current language mode
11387 /// and uses the rules for C++23.
11388 ///
11389 /// \returns An aggregate which contains the Candidate and isMoveEligible
11390 /// and isCopyElidable methods. If Candidate is non-null, it means
11391 /// isMoveEligible() would be true under the most permissive language
11392 /// standard.
11393 NamedReturnInfo getNamedReturnInfo(
11395
11396 /// Determine whether the given NRVO candidate variable is move-eligible or
11397 /// copy-elidable, without considering function return type.
11398 ///
11399 /// \param VD The NRVO candidate variable.
11400 ///
11401 /// \returns An aggregate which contains the Candidate and isMoveEligible
11402 /// and isCopyElidable methods. If Candidate is non-null, it means
11403 /// isMoveEligible() would be true under the most permissive language
11404 /// standard.
11405 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
11406
11407 /// Updates given NamedReturnInfo's move-eligible and
11408 /// copy-elidable statuses, considering the function
11409 /// return type criteria as applicable to return statements.
11410 ///
11411 /// \param Info The NamedReturnInfo object to update.
11412 ///
11413 /// \param ReturnType This is the return type of the function.
11414 /// \returns The copy elision candidate, in case the initial return expression
11415 /// was copy elidable, or nullptr otherwise.
11416 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
11417 QualType ReturnType);
11418
11419 /// Perform the initialization of a potentially-movable value, which
11420 /// is the result of return value.
11421 ///
11422 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
11423 /// treat returned lvalues as rvalues in certain cases (to prefer move
11424 /// construction), then falls back to treating them as lvalues if that failed.
11427 const NamedReturnInfo &NRInfo, Expr *Value,
11428 bool SupressSimplerImplicitMoves = false);
11429
11431
11432 /// Deduce the return type for a function from a returned expression, per
11433 /// C++1y [dcl.spec.auto]p6.
11435 SourceLocation ReturnLoc, Expr *RetExpr,
11436 const AutoType *AT);
11437
11438 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11439 Scope *CurScope);
11440 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11441 bool AllowRecovery = false);
11442
11443 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
11444 /// for capturing scopes.
11446 NamedReturnInfo &NRInfo,
11447 bool SupressSimplerImplicitMoves);
11448
11449 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
11450 /// and creates a proper catch handler from them.
11452 Stmt *HandlerBlock);
11453
11454 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
11455 /// handlers and creates a try statement from them.
11457 ArrayRef<Stmt *> Handlers);
11458
11459 void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry);
11460
11461 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
11462 SourceLocation TryLoc, Stmt *TryBlock,
11463 Stmt *Handler);
11465 Stmt *Block);
11470
11472 bool IsIfExists,
11473 NestedNameSpecifierLoc QualifierLoc,
11474 DeclarationNameInfo NameInfo,
11475 Stmt *Nested);
11477 bool IsIfExists, CXXScopeSpec &SS,
11478 UnqualifiedId &Name, Stmt *Nested);
11479
11480 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11481 CapturedRegionKind Kind, unsigned NumParams);
11482 typedef std::pair<StringRef, QualType> CapturedParamNameType;
11483 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11484 CapturedRegionKind Kind,
11486 unsigned OpenMPCaptureLevel = 0);
11490 SourceLocation Loc,
11491 unsigned NumParams);
11492
11494 VarDecl *RangeVar, ArrayRef<MaterializeTemporaryExpr *> Temporaries);
11495
11496private:
11497 /// Check whether the given statement can have musttail applied to it,
11498 /// issuing a diagnostic and returning false if not.
11499 bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11500
11501 ///@}
11502
11503 //
11504 //
11505 // -------------------------------------------------------------------------
11506 //
11507 //
11508
11509 /// \name `inline asm` Statement
11510 /// Implementations are in SemaStmtAsm.cpp
11511 ///@{
11512
11513public:
11514 ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel);
11515 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
11516 bool IsVolatile, unsigned NumOutputs,
11517 unsigned NumInputs, IdentifierInfo **Names,
11518 MultiExprArg Constraints, MultiExprArg Exprs,
11519 Expr *AsmString, MultiExprArg Clobbers,
11520 unsigned NumLabels, SourceLocation RParenLoc);
11521
11523 llvm::InlineAsmIdentifierInfo &Info);
11525 SourceLocation TemplateKWLoc,
11526 UnqualifiedId &Id,
11527 bool IsUnevaluatedContext);
11528 bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset,
11529 SourceLocation AsmLoc);
11531 SourceLocation AsmLoc);
11533 ArrayRef<Token> AsmToks, StringRef AsmString,
11534 unsigned NumOutputs, unsigned NumInputs,
11535 ArrayRef<StringRef> Constraints,
11536 ArrayRef<StringRef> Clobbers,
11537 ArrayRef<Expr *> Exprs, SourceLocation EndLoc);
11538 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
11539 SourceLocation Location, bool AlwaysCreate);
11540
11541 ///@}
11542
11543 //
11544 //
11545 // -------------------------------------------------------------------------
11546 //
11547 //
11548
11549 /// \name Statement Attribute Handling
11550 /// Implementations are in SemaStmtAttr.cpp
11551 ///@{
11552
11553public:
11554 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11555 const AttributeCommonInfo &A);
11556 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11557 const AttributeCommonInfo &A);
11558
11559 CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E);
11561
11562 /// Process the attributes before creating an attributed statement. Returns
11563 /// the semantic attributes that have been processed.
11564 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
11566
11568 SourceRange Range);
11570 const IdentifierInfo *AttrName,
11571 SourceRange Range);
11572
11573 ///@}
11574
11575 //
11576 //
11577 // -------------------------------------------------------------------------
11578 //
11579 //
11580
11581 /// \name C++ Templates
11582 /// Implementations are in SemaTemplate.cpp
11583 ///@{
11584
11585public:
11586 // Saves the current floating-point pragma stack and clear it in this Sema.
11588 public:
11590 : S(S), SavedStack(std::move(S.FpPragmaStack)) {
11591 S.FpPragmaStack.Stack.clear();
11592 }
11593 ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); }
11596
11597 private:
11598 Sema &S;
11600 };
11601
11603 CurFPFeatures = FPO;
11604 FpPragmaStack.CurrentValue = FPO.getChangesFrom(FPOptions(LangOpts));
11605 }
11606
11612
11617
11618 typedef llvm::MapVector<const FunctionDecl *,
11619 std::unique_ptr<LateParsedTemplate>>
11622
11623 /// Determine the number of levels of enclosing template parameters. This is
11624 /// only usable while parsing. Note that this does not include dependent
11625 /// contexts in which no template parameters have yet been declared, such as
11626 /// in a terse function template or generic lambda before the first 'auto' is
11627 /// encountered.
11628 unsigned getTemplateDepth(Scope *S) const;
11629
11631 bool AllowFunctionTemplates = true,
11632 bool AllowDependent = true);
11634 bool AllowFunctionTemplates = true,
11635 bool AllowDependent = true,
11636 bool AllowNonTemplateFunctions = false);
11637 /// Try to interpret the lookup result D as a template-name.
11638 ///
11639 /// \param D A declaration found by name lookup.
11640 /// \param AllowFunctionTemplates Whether function templates should be
11641 /// considered valid results.
11642 /// \param AllowDependent Whether unresolved using declarations (that might
11643 /// name templates) should be considered valid results.
11645 bool AllowFunctionTemplates = true,
11646 bool AllowDependent = true);
11647
11649 /// Whether and why a template name is required in this lookup.
11651 public:
11652 /// Template name is required if TemplateKWLoc is valid.
11654 : TemplateKW(TemplateKWLoc) {}
11655 /// Template name is unconditionally required.
11657
11659 return TemplateKW.value_or(SourceLocation());
11660 }
11661 bool hasTemplateKeyword() const {
11662 return getTemplateKeywordLoc().isValid();
11663 }
11664 bool isRequired() const { return TemplateKW != SourceLocation(); }
11665 explicit operator bool() const { return isRequired(); }
11666
11667 private:
11668 std::optional<SourceLocation> TemplateKW;
11669 };
11670
11672 /// This is not assumed to be a template name.
11674 /// This is assumed to be a template name because lookup found nothing.
11676 /// This is assumed to be a template name because lookup found one or more
11677 /// functions (but no function templates).
11679 };
11680
11681 bool
11683 QualType ObjectType, bool EnteringContext,
11684 RequiredTemplateKind RequiredTemplate = SourceLocation(),
11685 AssumedTemplateKind *ATK = nullptr,
11686 bool AllowTypoCorrection = true);
11687
11689 bool hasTemplateKeyword,
11690 const UnqualifiedId &Name,
11691 ParsedType ObjectType, bool EnteringContext,
11693 bool &MemberOfUnknownSpecialization,
11694 bool AllowTypoCorrection = true);
11695
11696 /// Try to resolve an undeclared template name as a type template.
11697 ///
11698 /// Sets II to the identifier corresponding to the template name, and updates
11699 /// Name to a corresponding (typo-corrected) type template name and TNK to
11700 /// the corresponding kind, if possible.
11702 TemplateNameKind &TNK,
11703 SourceLocation NameLoc,
11704 IdentifierInfo *&II);
11705
11706 /// Determine whether a particular identifier might be the name in a C++1z
11707 /// deduction-guide declaration.
11708 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
11709 SourceLocation NameLoc, CXXScopeSpec &SS,
11710 ParsedTemplateTy *Template = nullptr);
11711
11713 SourceLocation IILoc, Scope *S,
11714 const CXXScopeSpec *SS,
11715 TemplateTy &SuggestedTemplate,
11716 TemplateNameKind &SuggestedKind);
11717
11718 /// Determine whether we would be unable to instantiate this template (because
11719 /// it either has no definition, or is in the process of being instantiated).
11721 SourceLocation PointOfInstantiation, NamedDecl *Instantiation,
11722 bool InstantiatedFromMember, const NamedDecl *Pattern,
11723 const NamedDecl *PatternDef, TemplateSpecializationKind TSK,
11724 bool Complain = true, bool *Unreachable = nullptr);
11725
11726 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
11727 /// that the template parameter 'PrevDecl' is being shadowed by a new
11728 /// declaration at location Loc. Returns true to indicate that this is
11729 /// an error, and false otherwise.
11730 ///
11731 /// \param Loc The location of the declaration that shadows a template
11732 /// parameter.
11733 ///
11734 /// \param PrevDecl The template parameter that the declaration shadows.
11735 ///
11736 /// \param SupportedForCompatibility Whether to issue the diagnostic as
11737 /// a warning for compatibility with older versions of clang.
11738 /// Ignored when MSVC compatibility is enabled.
11740 bool SupportedForCompatibility = false);
11741
11742 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
11743 /// the parameter D to reference the templated declaration and return a
11744 /// pointer to the template declaration. Otherwise, do nothing to D and return
11745 /// null.
11747
11748 /// ActOnTypeParameter - Called when a C++ template type parameter
11749 /// (e.g., "typename T") has been parsed. Typename specifies whether
11750 /// the keyword "typename" was used to declare the type parameter
11751 /// (otherwise, "class" was used), and KeyLoc is the location of the
11752 /// "class" or "typename" keyword. ParamName is the name of the
11753 /// parameter (NULL indicates an unnamed template parameter) and
11754 /// ParamNameLoc is the location of the parameter name (if any).
11755 /// If the type parameter has a default argument, it will be added
11756 /// later via ActOnTypeParameterDefault.
11758 SourceLocation EllipsisLoc,
11759 SourceLocation KeyLoc,
11760 IdentifierInfo *ParamName,
11761 SourceLocation ParamNameLoc, unsigned Depth,
11762 unsigned Position, SourceLocation EqualLoc,
11763 ParsedType DefaultArg, bool HasTypeConstraint);
11764
11766
11767 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
11769 TemplateTypeParmDecl *ConstrainedParameter,
11770 SourceLocation EllipsisLoc);
11771 bool BuildTypeConstraint(const CXXScopeSpec &SS,
11773 TemplateTypeParmDecl *ConstrainedParameter,
11774 SourceLocation EllipsisLoc,
11775 bool AllowUnexpandedPack);
11776
11777 /// Attach a type-constraint to a template parameter.
11778 /// \returns true if an error occurred. This can happen if the
11779 /// immediately-declared constraint could not be formed (e.g. incorrect number
11780 /// of arguments for the named concept).
11782 DeclarationNameInfo NameInfo,
11783 TemplateName NamedConcept, NamedDecl *FoundDecl,
11784 const TemplateArgumentListInfo *TemplateArgs,
11785 TemplateTypeParmDecl *ConstrainedParameter,
11786 SourceLocation EllipsisLoc);
11787
11789 NonTypeTemplateParmDecl *NewConstrainedParm,
11790 NonTypeTemplateParmDecl *OrigConstrainedParm,
11791 SourceLocation EllipsisLoc);
11792
11793 /// Require the given type to be a structural type, and diagnose if it is not.
11794 ///
11795 /// \return \c true if an error was produced.
11797
11798 /// Check that the type of a non-type template parameter is
11799 /// well-formed.
11800 ///
11801 /// \returns the (possibly-promoted) parameter type if valid;
11802 /// otherwise, produces a diagnostic and returns a NULL type.
11804 SourceLocation Loc);
11806
11808 unsigned Depth, unsigned Position,
11809 SourceLocation EqualLoc,
11810 Expr *DefaultArg);
11811
11812 /// ActOnTemplateTemplateParameter - Called when a C++ template template
11813 /// parameter (e.g. T in template <template <typename> class T> class array)
11814 /// has been parsed. S is the current scope.
11816 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind,
11817 bool TypenameKeyword, TemplateParameterList *Params,
11818 SourceLocation EllipsisLoc, IdentifierInfo *ParamName,
11819 SourceLocation ParamNameLoc, unsigned Depth, unsigned Position,
11820 SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg);
11821
11822 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
11823 /// constrained by RequiresClause, that contains the template parameters in
11824 /// Params.
11826 unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc,
11827 SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params,
11828 SourceLocation RAngleLoc, Expr *RequiresClause);
11829
11830 /// The context in which we are checking a template parameter list.
11832 // For this context, Class, Variable, TypeAlias, and non-pack Template
11833 // Template Parameters are treated uniformly.
11835
11842 };
11843
11844 /// Checks the validity of a template parameter list, possibly
11845 /// considering the template parameter list from a previous
11846 /// declaration.
11847 ///
11848 /// If an "old" template parameter list is provided, it must be
11849 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
11850 /// template parameter list.
11851 ///
11852 /// \param NewParams Template parameter list for a new template
11853 /// declaration. This template parameter list will be updated with any
11854 /// default arguments that are carried through from the previous
11855 /// template parameter list.
11856 ///
11857 /// \param OldParams If provided, template parameter list from a
11858 /// previous declaration of the same template. Default template
11859 /// arguments will be merged from the old template parameter list to
11860 /// the new template parameter list.
11861 ///
11862 /// \param TPC Describes the context in which we are checking the given
11863 /// template parameter list.
11864 ///
11865 /// \param SkipBody If we might have already made a prior merged definition
11866 /// of this template visible, the corresponding body-skipping information.
11867 /// Default argument redefinition is not an error when skipping such a body,
11868 /// because (under the ODR) we can assume the default arguments are the same
11869 /// as the prior merged definition.
11870 ///
11871 /// \returns true if an error occurred, false otherwise.
11873 TemplateParameterList *OldParams,
11875 SkipBodyInfo *SkipBody = nullptr);
11876
11877 /// Match the given template parameter lists to the given scope
11878 /// specifier, returning the template parameter list that applies to the
11879 /// name.
11880 ///
11881 /// \param DeclStartLoc the start of the declaration that has a scope
11882 /// specifier or a template parameter list.
11883 ///
11884 /// \param DeclLoc The location of the declaration itself.
11885 ///
11886 /// \param SS the scope specifier that will be matched to the given template
11887 /// parameter lists. This scope specifier precedes a qualified name that is
11888 /// being declared.
11889 ///
11890 /// \param TemplateId The template-id following the scope specifier, if there
11891 /// is one. Used to check for a missing 'template<>'.
11892 ///
11893 /// \param ParamLists the template parameter lists, from the outermost to the
11894 /// innermost template parameter lists.
11895 ///
11896 /// \param IsFriend Whether to apply the slightly different rules for
11897 /// matching template parameters to scope specifiers in friend
11898 /// declarations.
11899 ///
11900 /// \param IsMemberSpecialization will be set true if the scope specifier
11901 /// denotes a fully-specialized type, and therefore this is a declaration of
11902 /// a member specialization.
11903 ///
11904 /// \returns the template parameter list, if any, that corresponds to the
11905 /// name that is preceded by the scope specifier @p SS. This template
11906 /// parameter list may have template parameters (if we're declaring a
11907 /// template) or may have no template parameters (if we're declaring a
11908 /// template specialization), or may be NULL (if what we're declaring isn't
11909 /// itself a template).
11911 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
11912 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
11913 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
11914 bool &IsMemberSpecialization, bool &Invalid,
11915 bool SuppressDiagnostic = false);
11916
11917 /// Returns the template parameter list with all default template argument
11918 /// information.
11920
11922 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11923 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
11924 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
11925 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
11926 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
11927 TemplateParameterList **OuterTemplateParamLists,
11928 bool IsMemberSpecialization, SkipBodyInfo *SkipBody = nullptr);
11929
11930 /// Translates template arguments as provided by the parser
11931 /// into template arguments used by semantic analysis.
11934
11935 /// Convert a parsed type into a parsed template argument. This is mostly
11936 /// trivial, except that we may have parsed a C++17 deduced class template
11937 /// specialization type, in which case we should form a template template
11938 /// argument instead of a type template argument.
11940
11942
11945 SourceLocation TemplateLoc,
11946 TemplateArgumentListInfo &TemplateArgs,
11947 Scope *Scope, bool ForNestedNameSpecifier);
11948
11950 ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
11951 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
11952 SourceLocation TemplateKWLoc, TemplateTy Template,
11953 const IdentifierInfo *TemplateII,
11954 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11955 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
11956 bool IsCtorOrDtorName = false, bool IsClassName = false,
11957 ImplicitTypenameContext AllowImplicitTypename =
11959
11960 /// Parsed an elaborated-type-specifier that refers to a template-id,
11961 /// such as \c class T::template apply<U>.
11963 TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc,
11964 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD,
11965 SourceLocation TemplateLoc, SourceLocation LAngleLoc,
11966 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc);
11967
11970 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
11972
11973 /// Get the specialization of the given variable template corresponding to
11974 /// the specified argument list, or a null-but-valid result if the arguments
11975 /// are dependent.
11977 SourceLocation TemplateLoc,
11978 SourceLocation TemplateNameLoc,
11979 const TemplateArgumentListInfo &TemplateArgs,
11980 bool SetWrittenArgs);
11981
11982 /// Form a reference to the specialization of the given variable template
11983 /// corresponding to the specified argument list, or a null-but-valid result
11984 /// if the arguments are dependent.
11986 const DeclarationNameInfo &NameInfo,
11988 SourceLocation TemplateLoc,
11989 const TemplateArgumentListInfo *TemplateArgs);
11990
11992 const DeclarationNameInfo &NameInfo, TemplateName Template,
11993 const TemplateArgumentListInfo *TemplateArgs);
11994
11996 CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11997 const DeclarationNameInfo &ConceptNameInfo,
11998 NamedDecl *FoundDecl, TemplateDecl *NamedConcept,
11999 const TemplateArgumentListInfo *TemplateArgs,
12000 bool DoCheckConstraintSatisfaction = true);
12001
12004 bool TemplateKeyword, TemplateDecl *TD,
12005 SourceLocation Loc);
12006
12008 SourceLocation TemplateKWLoc, LookupResult &R,
12009 bool RequiresADL,
12010 const TemplateArgumentListInfo *TemplateArgs);
12011
12012 // We actually only call this from template instantiation.
12015 const DeclarationNameInfo &NameInfo,
12016 const TemplateArgumentListInfo *TemplateArgs,
12017 bool IsAddressOfOperand);
12018
12020 return Pack.pack_size() - 1 - *ArgPackSubstIndex;
12021 }
12022
12025 Arg = Arg.pack_elements()[*ArgPackSubstIndex];
12026 if (Arg.isPackExpansion())
12027 Arg = Arg.getPackExpansionPattern();
12028 return Arg;
12029 }
12030
12032 BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
12033 QualType ParamType, SourceLocation loc,
12034 TemplateArgument Replacement,
12035 UnsignedOrNone PackIndex, bool Final);
12036
12037 /// Form a template name from a name that is syntactically required to name a
12038 /// template, either due to use of the 'template' keyword or because a name in
12039 /// this syntactic context is assumed to name a template (C++
12040 /// [temp.names]p2-4).
12041 ///
12042 /// This action forms a template name given the name of the template and its
12043 /// optional scope specifier. This is used when the 'template' keyword is used
12044 /// or when the parsing context unambiguously treats a following '<' as
12045 /// introducing a template argument list. Note that this may produce a
12046 /// non-dependent template name if we can perform the lookup now and identify
12047 /// the named template.
12048 ///
12049 /// For example, given "x.MetaFun::template apply", the scope specifier
12050 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
12051 /// of the "template" keyword, and "apply" is the \p Name.
12053 SourceLocation TemplateKWLoc,
12054 const UnqualifiedId &Name,
12055 ParsedType ObjectType,
12056 bool EnteringContext, TemplateTy &Template,
12057 bool AllowInjectedClassName = false);
12058
12060 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
12061 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
12063 MultiTemplateParamsArg TemplateParameterLists,
12064 SkipBodyInfo *SkipBody = nullptr);
12065
12066 /// Check the non-type template arguments of a class template
12067 /// partial specialization according to C++ [temp.class.spec]p9.
12068 ///
12069 /// \param TemplateNameLoc the location of the template name.
12070 /// \param PrimaryTemplate the template parameters of the primary class
12071 /// template.
12072 /// \param NumExplicit the number of explicitly-specified template arguments.
12073 /// \param TemplateArgs the template arguments of the class template
12074 /// partial specialization.
12075 ///
12076 /// \returns \c true if there was an error, \c false otherwise.
12078 TemplateDecl *PrimaryTemplate,
12079 unsigned NumExplicitArgs,
12085
12087 MultiTemplateParamsArg TemplateParameterLists,
12088 Declarator &D);
12089
12090 /// Diagnose cases where we have an explicit template specialization
12091 /// before/after an explicit template instantiation, producing diagnostics
12092 /// for those cases where they are required and determining whether the
12093 /// new specialization/instantiation will have any effect.
12094 ///
12095 /// \param NewLoc the location of the new explicit specialization or
12096 /// instantiation.
12097 ///
12098 /// \param NewTSK the kind of the new explicit specialization or
12099 /// instantiation.
12100 ///
12101 /// \param PrevDecl the previous declaration of the entity.
12102 ///
12103 /// \param PrevTSK the kind of the old explicit specialization or
12104 /// instantiatin.
12105 ///
12106 /// \param PrevPointOfInstantiation if valid, indicates where the previous
12107 /// declaration was instantiated (either implicitly or explicitly).
12108 ///
12109 /// \param HasNoEffect will be set to true to indicate that the new
12110 /// specialization or instantiation has no effect and should be ignored.
12111 ///
12112 /// \returns true if there was an error that should prevent the introduction
12113 /// of the new declaration into the AST, false otherwise.
12115 SourceLocation NewLoc,
12116 TemplateSpecializationKind ActOnExplicitInstantiationNewTSK,
12117 NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK,
12118 SourceLocation PrevPtOfInstantiation, bool &SuppressNew);
12119
12120 /// Perform semantic analysis for the given dependent function
12121 /// template specialization.
12122 ///
12123 /// The only possible way to get a dependent function template specialization
12124 /// is with a friend declaration, like so:
12125 ///
12126 /// \code
12127 /// template <class T> void foo(T);
12128 /// template <class T> class A {
12129 /// friend void foo<>(T);
12130 /// };
12131 /// \endcode
12132 ///
12133 /// There really isn't any useful analysis we can do here, so we
12134 /// just store the information.
12136 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
12138
12139 /// Perform semantic analysis for the given function template
12140 /// specialization.
12141 ///
12142 /// This routine performs all of the semantic analysis required for an
12143 /// explicit function template specialization. On successful completion,
12144 /// the function declaration \p FD will become a function template
12145 /// specialization.
12146 ///
12147 /// \param FD the function declaration, which will be updated to become a
12148 /// function template specialization.
12149 ///
12150 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
12151 /// if any. Note that this may be valid info even when 0 arguments are
12152 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
12153 /// as it anyway contains info on the angle brackets locations.
12154 ///
12155 /// \param Previous the set of declarations that may be specialized by
12156 /// this function specialization.
12157 ///
12158 /// \param QualifiedFriend whether this is a lookup for a qualified friend
12159 /// declaration with no explicit template argument list that might be
12160 /// befriending a function template specialization.
12162 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
12163 LookupResult &Previous, bool QualifiedFriend = false);
12164
12165 /// Perform semantic analysis for the given non-template member
12166 /// specialization.
12167 ///
12168 /// This routine performs all of the semantic analysis required for an
12169 /// explicit member function specialization. On successful completion,
12170 /// the function declaration \p FD will become a member function
12171 /// specialization.
12172 ///
12173 /// \param Member the member declaration, which will be updated to become a
12174 /// specialization.
12175 ///
12176 /// \param Previous the set of declarations, one of which may be specialized
12177 /// by this function specialization; the set will be modified to contain the
12178 /// redeclared member.
12181
12182 // Explicit instantiation of a class template specialization
12184 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
12185 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
12186 TemplateTy Template, SourceLocation TemplateNameLoc,
12187 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
12188 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
12189
12190 // Explicit instantiation of a member class of a class template.
12192 SourceLocation TemplateLoc,
12193 unsigned TagSpec, SourceLocation KWLoc,
12194 CXXScopeSpec &SS, IdentifierInfo *Name,
12195 SourceLocation NameLoc,
12196 const ParsedAttributesView &Attr);
12197
12199 SourceLocation TemplateLoc,
12200 Declarator &D);
12201
12202 /// If the given template parameter has a default template
12203 /// argument, substitute into that default template argument and
12204 /// return the corresponding template argument.
12206 TemplateDecl *Template, SourceLocation TemplateKWLoc,
12207 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
12208 ArrayRef<TemplateArgument> SugaredConverted,
12209 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
12210
12211 /// Returns the top most location responsible for the definition of \p N.
12212 /// If \p N is a a template specialization, this is the location
12213 /// of the top of the instantiation stack.
12214 /// Otherwise, the location of \p N is returned.
12216
12217 /// Specifies the context in which a particular template
12218 /// argument is being checked.
12220 /// The template argument was specified in the code or was
12221 /// instantiated with some deduced template arguments.
12223
12224 /// The template argument was deduced via template argument
12225 /// deduction.
12227
12228 /// The template argument was deduced from an array bound
12229 /// via template argument deduction.
12231 };
12232
12240
12241 /// The checked, converted argument will be added to the
12242 /// end of these vectors.
12244
12245 /// The check is being performed in the context of partial ordering.
12247
12248 /// If true, assume these template arguments are
12249 /// the injected template arguments for a template template parameter.
12250 /// This will relax the requirement that all its possible uses are valid:
12251 /// TTP checking is loose, and assumes that invalid uses will be diagnosed
12252 /// during instantiation.
12254
12255 /// Is set to true when, in the context of TTP matching, a pack parameter
12256 /// matches non-pack arguments.
12257 bool StrictPackMatch = false;
12258 };
12259
12260 /// Check that the given template argument corresponds to the given
12261 /// template parameter.
12262 ///
12263 /// \param Param The template parameter against which the argument will be
12264 /// checked.
12265 ///
12266 /// \param Arg The template argument, which may be updated due to conversions.
12267 ///
12268 /// \param Template The template in which the template argument resides.
12269 ///
12270 /// \param TemplateLoc The location of the template name for the template
12271 /// whose argument list we're matching.
12272 ///
12273 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
12274 /// the template argument list.
12275 ///
12276 /// \param ArgumentPackIndex The index into the argument pack where this
12277 /// argument will be placed. Only valid if the parameter is a parameter pack.
12278 ///
12279 /// \param CTAK Describes how we arrived at this particular template argument:
12280 /// explicitly written, deduced, etc.
12281 ///
12282 /// \returns true on error, false otherwise.
12284 NamedDecl *Template, SourceLocation TemplateLoc,
12285 SourceLocation RAngleLoc,
12286 unsigned ArgumentPackIndex,
12289
12290 /// Check that the given template arguments can be provided to
12291 /// the given template, converting the arguments along the way.
12292 ///
12293 /// \param Template The template to which the template arguments are being
12294 /// provided.
12295 ///
12296 /// \param TemplateLoc The location of the template name in the source.
12297 ///
12298 /// \param TemplateArgs The list of template arguments. If the template is
12299 /// a template template parameter, this function may extend the set of
12300 /// template arguments to also include substituted, defaulted template
12301 /// arguments.
12302 ///
12303 /// \param PartialTemplateArgs True if the list of template arguments is
12304 /// intentionally partial, e.g., because we're checking just the initial
12305 /// set of template arguments.
12306 ///
12307 /// \param Converted Will receive the converted, canonicalized template
12308 /// arguments.
12309 ///
12310 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
12311 /// contain the converted forms of the template arguments as written.
12312 /// Otherwise, \p TemplateArgs will not be modified.
12313 ///
12314 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
12315 /// receive true if the cause for the error is the associated constraints of
12316 /// the template not being satisfied by the template arguments.
12317 ///
12318 /// \param DefaultArgs any default arguments from template specialization
12319 /// deduction.
12320 ///
12321 /// \returns true if an error occurred, false otherwise.
12323 SourceLocation TemplateLoc,
12324 TemplateArgumentListInfo &TemplateArgs,
12325 const DefaultArguments &DefaultArgs,
12326 bool PartialTemplateArgs,
12328 bool UpdateArgsWithConversions = true,
12329 bool *ConstraintsNotSatisfied = nullptr);
12330
12333 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
12334 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
12335 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions = true,
12336 bool *ConstraintsNotSatisfied = nullptr);
12337
12340 SmallVectorImpl<TemplateArgument> &SugaredConverted,
12341 SmallVectorImpl<TemplateArgument> &CanonicalConverted);
12342
12343 /// Check a template argument against its corresponding
12344 /// template type parameter.
12345 ///
12346 /// This routine implements the semantics of C++ [temp.arg.type]. It
12347 /// returns true if an error occurred, and false otherwise.
12349
12350 /// Check a template argument against its corresponding
12351 /// non-type template parameter.
12352 ///
12353 /// This routine implements the semantics of C++ [temp.arg.nontype].
12354 /// If an error occurred, it returns ExprError(); otherwise, it
12355 /// returns the converted template argument. \p ParamType is the
12356 /// type of the non-type template parameter after it has been instantiated.
12358 QualType InstantiatedParamType, Expr *Arg,
12359 TemplateArgument &SugaredConverted,
12360 TemplateArgument &CanonicalConverted,
12361 bool StrictCheck,
12363
12364 /// Check a template argument against its corresponding
12365 /// template template parameter.
12366 ///
12367 /// This routine implements the semantics of C++ [temp.arg.template].
12368 /// It returns true if an error occurred, and false otherwise.
12370 TemplateParameterList *Params,
12372 bool PartialOrdering,
12373 bool *StrictPackMatch);
12374
12377 const TemplateArgumentLoc &Arg);
12378
12380 std::optional<SourceRange> ParamRange = {});
12382
12383 /// Given a non-type template argument that refers to a
12384 /// declaration and the type of its corresponding non-type template
12385 /// parameter, produce an expression that properly refers to that
12386 /// declaration.
12387 /// FIXME: This is used in some contexts where the resulting expression
12388 /// doesn't need to live too long. It would be useful if this function
12389 /// could return a temporary expression.
12391 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc);
12394 SourceLocation Loc);
12395
12396 /// Enumeration describing how template parameter lists are compared
12397 /// for equality.
12399 /// We are matching the template parameter lists of two templates
12400 /// that might be redeclarations.
12401 ///
12402 /// \code
12403 /// template<typename T> struct X;
12404 /// template<typename T> struct X;
12405 /// \endcode
12407
12408 /// We are matching the template parameter lists of two template
12409 /// template parameters as part of matching the template parameter lists
12410 /// of two templates that might be redeclarations.
12411 ///
12412 /// \code
12413 /// template<template<int I> class TT> struct X;
12414 /// template<template<int Value> class Other> struct X;
12415 /// \endcode
12417
12418 /// We are determining whether the template-parameters are equivalent
12419 /// according to C++ [temp.over.link]/6. This comparison does not consider
12420 /// constraints.
12421 ///
12422 /// \code
12423 /// template<C1 T> void f(T);
12424 /// template<C2 T> void f(T);
12425 /// \endcode
12427 };
12428
12429 // A struct to represent the 'new' declaration, which is either itself just
12430 // the named decl, or the important information we need about it in order to
12431 // do constraint comparisons.
12433 const NamedDecl *ND = nullptr;
12434 const DeclContext *DC = nullptr;
12435 const DeclContext *LexicalDC = nullptr;
12436 SourceLocation Loc;
12437
12438 public:
12441 const DeclContext *LexicalDeclCtx,
12442 SourceLocation Loc)
12443
12444 : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) {
12445 assert(DC && LexicalDC &&
12446 "Constructor only for cases where we have the information to put "
12447 "in here");
12448 }
12449
12450 // If this was constructed with no information, we cannot do substitution
12451 // for constraint comparison, so make sure we can check that.
12452 bool isInvalid() const { return !ND && !DC; }
12453
12454 const NamedDecl *getDecl() const { return ND; }
12455
12456 bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; }
12457
12459 return ND ? ND->getLexicalDeclContext() : LexicalDC;
12460 }
12461
12463 return ND ? ND->getDeclContext() : DC;
12464 }
12465
12466 SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; }
12467 };
12468
12469 /// Determine whether the given template parameter lists are
12470 /// equivalent.
12471 ///
12472 /// \param New The new template parameter list, typically written in the
12473 /// source code as part of a new template declaration.
12474 ///
12475 /// \param Old The old template parameter list, typically found via
12476 /// name lookup of the template declared with this template parameter
12477 /// list.
12478 ///
12479 /// \param Complain If true, this routine will produce a diagnostic if
12480 /// the template parameter lists are not equivalent.
12481 ///
12482 /// \param Kind describes how we are to match the template parameter lists.
12483 ///
12484 /// \param TemplateArgLoc If this source location is valid, then we
12485 /// are actually checking the template parameter list of a template
12486 /// argument (New) against the template parameter list of its
12487 /// corresponding template template parameter (Old). We produce
12488 /// slightly different diagnostics in this scenario.
12489 ///
12490 /// \returns True if the template parameter lists are equal, false
12491 /// otherwise.
12493 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
12494 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
12496 SourceLocation TemplateArgLoc = SourceLocation());
12497
12499 TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
12501 SourceLocation TemplateArgLoc = SourceLocation()) {
12502 return TemplateParameterListsAreEqual(nullptr, New, nullptr, Old, Complain,
12503 Kind, TemplateArgLoc);
12504 }
12505
12506 /// Check whether a template can be declared within this scope.
12507 ///
12508 /// If the template declaration is valid in this scope, returns
12509 /// false. Otherwise, issues a diagnostic and returns true.
12510 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
12511
12512 /// Called when the parser has parsed a C++ typename
12513 /// specifier, e.g., "typename T::type".
12514 ///
12515 /// \param S The scope in which this typename type occurs.
12516 /// \param TypenameLoc the location of the 'typename' keyword
12517 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12518 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
12519 /// \param IdLoc the location of the identifier.
12520 /// \param IsImplicitTypename context where T::type refers to a type.
12522 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
12523 const IdentifierInfo &II, SourceLocation IdLoc,
12525
12526 /// Called when the parser has parsed a C++ typename
12527 /// specifier that ends in a template-id, e.g.,
12528 /// "typename MetaFun::template apply<T1, T2>".
12529 ///
12530 /// \param S The scope in which this typename type occurs.
12531 /// \param TypenameLoc the location of the 'typename' keyword
12532 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12533 /// \param TemplateLoc the location of the 'template' keyword, if any.
12534 /// \param TemplateName The template name.
12535 /// \param TemplateII The identifier used to name the template.
12536 /// \param TemplateIILoc The location of the template name.
12537 /// \param LAngleLoc The location of the opening angle bracket ('<').
12538 /// \param TemplateArgs The template arguments.
12539 /// \param RAngleLoc The location of the closing angle bracket ('>').
12541 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
12542 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
12543 TemplateTy TemplateName, const IdentifierInfo *TemplateII,
12544 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
12545 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc);
12546
12548 SourceLocation KeywordLoc,
12549 NestedNameSpecifierLoc QualifierLoc,
12550 const IdentifierInfo &II, SourceLocation IILoc,
12551 TypeSourceInfo **TSI, bool DeducedTSTContext);
12552
12554 SourceLocation KeywordLoc,
12555 NestedNameSpecifierLoc QualifierLoc,
12556 const IdentifierInfo &II, SourceLocation IILoc,
12557 bool DeducedTSTContext = true);
12558
12559 /// Rebuilds a type within the context of the current instantiation.
12560 ///
12561 /// The type \p T is part of the type of an out-of-line member definition of
12562 /// a class template (or class template partial specialization) that was
12563 /// parsed and constructed before we entered the scope of the class template
12564 /// (or partial specialization thereof). This routine will rebuild that type
12565 /// now that we have entered the declarator's scope, which may produce
12566 /// different canonical types, e.g.,
12567 ///
12568 /// \code
12569 /// template<typename T>
12570 /// struct X {
12571 /// typedef T* pointer;
12572 /// pointer data();
12573 /// };
12574 ///
12575 /// template<typename T>
12576 /// typename X<T>::pointer X<T>::data() { ... }
12577 /// \endcode
12578 ///
12579 /// Here, the type "typename X<T>::pointer" will be created as a
12580 /// DependentNameType, since we do not know that we can look into X<T> when we
12581 /// parsed the type. This function will rebuild the type, performing the
12582 /// lookup of "pointer" in X<T> and returning an ElaboratedType whose
12583 /// canonical type is the same as the canonical type of T*, allowing the
12584 /// return types of the out-of-line definition and the declaration to match.
12586 SourceLocation Loc,
12587 DeclarationName Name);
12589
12591
12592 /// Rebuild the template parameters now that we know we're in a current
12593 /// instantiation.
12594 bool
12596
12597 /// Produces a formatted string that describes the binding of
12598 /// template parameters to template arguments.
12599 std::string
12601 const TemplateArgumentList &Args);
12602
12603 std::string
12605 const TemplateArgument *Args,
12606 unsigned NumArgs);
12607
12611
12612 /// ActOnDependentIdExpression - Handle a dependent id-expression that
12613 /// was just parsed. This is only possible with an explicit scope
12614 /// specifier naming a dependent type.
12616 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
12617 const DeclarationNameInfo &NameInfo, bool isAddressOfOperand,
12618 const TemplateArgumentListInfo *TemplateArgs);
12619
12622 SourceLocation TemplateKWLoc,
12623 const DeclarationNameInfo &NameInfo,
12624 const TemplateArgumentListInfo *TemplateArgs);
12625
12626 // Calculates whether the expression Constraint depends on an enclosing
12627 // template, for the purposes of [temp.friend] p9.
12628 // TemplateDepth is the 'depth' of the friend function, which is used to
12629 // compare whether a declaration reference is referring to a containing
12630 // template, or just the current friend function. A 'lower' TemplateDepth in
12631 // the AST refers to a 'containing' template. As the constraint is
12632 // uninstantiated, this is relative to the 'top' of the TU.
12633 bool
12635 unsigned TemplateDepth,
12636 const Expr *Constraint);
12637
12638 /// Find the failed Boolean condition within a given Boolean
12639 /// constant expression, and describe it with a string.
12640 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
12641
12643
12645 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
12646 const IdentifierInfo *Name, SourceLocation NameLoc);
12647
12649 Expr *ConstraintExpr,
12650 const ParsedAttributesView &Attrs);
12651
12653 bool &AddToScope);
12655
12656 TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12657 const CXXScopeSpec &SS,
12658 const IdentifierInfo *Name,
12659 SourceLocation TagLoc, SourceLocation NameLoc);
12660
12662 CachedTokens &Toks);
12665
12666 /// We've found a use of a templated declaration that would trigger an
12667 /// implicit instantiation. Check that any relevant explicit specializations
12668 /// and partial specializations are visible/reachable, and diagnose if not.
12671
12672 ///@}
12673
12674 //
12675 //
12676 // -------------------------------------------------------------------------
12677 //
12678 //
12679
12680 /// \name C++ Template Argument Deduction
12681 /// Implementations are in SemaTemplateDeduction.cpp
12682 ///@{
12683
12684public:
12685 class SFINAETrap;
12686
12689 : S(S), Prev(std::exchange(S.CurrentSFINAEContext, Cur)) {}
12690
12691 protected:
12693 ~SFINAEContextBase() { S.CurrentSFINAEContext = Prev; }
12696
12697 private:
12698 SFINAETrap *Prev;
12699 };
12700
12704
12705 /// RAII class used to determine whether SFINAE has
12706 /// trapped any errors that occur during template argument
12707 /// deduction.
12708 class SFINAETrap : SFINAEContextBase {
12709 bool HasErrorOcurred = false;
12710 bool WithAccessChecking = false;
12711 bool PrevLastDiagnosticIgnored =
12712 S.getDiagnostics().isLastDiagnosticIgnored();
12713 sema::TemplateDeductionInfo *DeductionInfo = nullptr;
12714
12715 SFINAETrap(Sema &S, sema::TemplateDeductionInfo *Info,
12716 bool WithAccessChecking)
12717 : SFINAEContextBase(S, this), WithAccessChecking(WithAccessChecking),
12718 DeductionInfo(Info) {}
12719
12720 public:
12721 /// \param WithAccessChecking If true, discard all diagnostics (from the
12722 /// immediate context) instead of adding them to the currently active
12723 /// \ref TemplateDeductionInfo.
12724 explicit SFINAETrap(Sema &S, bool WithAccessChecking = false)
12725 : SFINAETrap(S, /*Info=*/nullptr, WithAccessChecking) {}
12726
12728 : SFINAETrap(S, &Info, /*WithAccessChecking=*/false) {}
12729
12731 S.getDiagnostics().setLastDiagnosticIgnored(PrevLastDiagnosticIgnored);
12732 }
12733
12734 SFINAETrap(const SFINAETrap &) = delete;
12735 SFINAETrap &operator=(const SFINAETrap &) = delete;
12736
12738 return DeductionInfo;
12739 }
12740
12741 /// Determine whether any SFINAE errors have been trapped.
12742 bool hasErrorOccurred() const { return HasErrorOcurred; }
12743 void setErrorOccurred() { HasErrorOcurred = true; }
12744
12745 bool withAccessChecking() const { return WithAccessChecking; }
12746 };
12747
12748 /// RAII class used to indicate that we are performing provisional
12749 /// semantic analysis to determine the validity of a construct, so
12750 /// typo-correction and diagnostics in the immediate context (not within
12751 /// implicitly-instantiated templates) should be suppressed.
12753 Sema &SemaRef;
12754 // FIXME: Using a SFINAETrap for this is a hack.
12755 SFINAETrap Trap;
12756 bool PrevDisableTypoCorrection;
12757
12758 public:
12759 explicit TentativeAnalysisScope(Sema &SemaRef)
12760 : SemaRef(SemaRef), Trap(SemaRef, /*ForValidityCheck=*/true),
12761 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
12762 SemaRef.DisableTypoCorrection = true;
12763 }
12765 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
12766 }
12767
12770 };
12771
12772 /// For each declaration that involved template argument deduction, the
12773 /// set of diagnostics that were suppressed during that template argument
12774 /// deduction.
12775 ///
12776 /// FIXME: Serialize this structure to the AST file.
12777 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1>>
12780
12781 /// Compare types for equality with respect to possibly compatible
12782 /// function types (noreturn adjustment, implicit calling conventions). If any
12783 /// of parameter and argument is not a function, just perform type comparison.
12784 ///
12785 /// \param P the template parameter type.
12786 ///
12787 /// \param A the argument type.
12789
12790 /// Allocate a TemplateArgumentLoc where all locations have
12791 /// been initialized to the given location.
12792 ///
12793 /// \param Arg The template argument we are producing template argument
12794 /// location information for.
12795 ///
12796 /// \param NTTPType For a declaration template argument, the type of
12797 /// the non-type template parameter that corresponds to this template
12798 /// argument. Can be null if no type sugar is available to add to the
12799 /// type from the template argument.
12800 ///
12801 /// \param Loc The source location to use for the resulting template
12802 /// argument.
12804 QualType NTTPType,
12805 SourceLocation Loc);
12806
12807 /// Get a template argument mapping the given template parameter to itself,
12808 /// e.g. for X in \c template<int X>, this would return an expression template
12809 /// argument referencing X.
12811 SourceLocation Location);
12812
12813 /// Adjust the type \p ArgFunctionType to match the calling convention,
12814 /// noreturn, and optionally the exception specification of \p FunctionType.
12815 /// Deduction often wants to ignore these properties when matching function
12816 /// types.
12818 bool AdjustExceptionSpec = false);
12819
12822 ArrayRef<TemplateArgument> TemplateArgs,
12824
12827 ArrayRef<TemplateArgument> TemplateArgs,
12829
12830 /// Deduce the template arguments of the given template from \p FromType.
12831 /// Used to implement the IsDeducible constraint for alias CTAD per C++
12832 /// [over.match.class.deduct]p4.
12833 ///
12834 /// It only supports class or type alias templates.
12838
12843 bool NumberOfArgumentsMustMatch);
12844
12845 /// Substitute the explicitly-provided template arguments into the
12846 /// given function template according to C++ [temp.arg.explicit].
12847 ///
12848 /// \param FunctionTemplate the function template into which the explicit
12849 /// template arguments will be substituted.
12850 ///
12851 /// \param ExplicitTemplateArgs the explicitly-specified template
12852 /// arguments.
12853 ///
12854 /// \param Deduced the deduced template arguments, which will be populated
12855 /// with the converted and checked explicit template arguments.
12856 ///
12857 /// \param ParamTypes will be populated with the instantiated function
12858 /// parameters.
12859 ///
12860 /// \param FunctionType if non-NULL, the result type of the function template
12861 /// will also be instantiated and the pointed-to value will be updated with
12862 /// the instantiated function type.
12863 ///
12864 /// \param Info if substitution fails for any reason, this object will be
12865 /// populated with more information about the failure.
12866 ///
12867 /// \returns TemplateDeductionResult::Success if substitution was successful,
12868 /// or some failure condition.
12871 TemplateArgumentListInfo &ExplicitTemplateArgs,
12875
12876 /// brief A function argument from which we performed template argument
12877 // deduction for a call.
12890
12891 /// Finish template argument deduction for a function template,
12892 /// checking the deduced template arguments for completeness and forming
12893 /// the function template specialization.
12894 ///
12895 /// \param OriginalCallArgs If non-NULL, the original call arguments against
12896 /// which the deduced argument types should be compared.
12897 /// \param CheckNonDependent Callback before substituting into the declaration
12898 /// with the deduced template arguments.
12899 /// \param OnlyInitializeNonUserDefinedConversions is used as a workaround for
12900 /// some breakages introduced by CWG2369, where non-user-defined conversions
12901 /// are checked first before the constraints.
12905 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
12907 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
12908 bool PartialOverloading, bool PartialOrdering,
12909 bool ForOverloadSetAddressResolution,
12910 llvm::function_ref<bool(bool)> CheckNonDependent =
12911 [](bool /*OnlyInitializeNonUserDefinedConversions*/) {
12912 return false;
12913 });
12914
12915 /// Perform [temp.friend] p5 template argument deduction for a dependent
12916 /// friend declaration and a candidate class template specialization.
12918 ClassTemplateDecl *PatternCTD,
12919 ClassTemplateDecl *CandidateCTD,
12921 ArrayRef<TemplateArgument> PatternArgs,
12922 ArrayRef<TemplateArgument> CandidateArgs,
12923 SourceLocation Loc,
12924 TemplateSpecCandidateSet *FailedTSC,
12925 MultiLevelTemplateArgumentList &DeducedArgs);
12926
12927 /// Perform template argument deduction from a function call
12928 /// (C++ [temp.deduct.call]).
12929 ///
12930 /// \param FunctionTemplate the function template for which we are performing
12931 /// template argument deduction.
12932 ///
12933 /// \param ExplicitTemplateArgs the explicit template arguments provided
12934 /// for this call.
12935 ///
12936 /// \param Args the function call arguments
12937 ///
12938 /// \param Specialization if template argument deduction was successful,
12939 /// this will be set to the function template specialization produced by
12940 /// template argument deduction.
12941 ///
12942 /// \param Info the argument will be updated to provide additional information
12943 /// about template argument deduction.
12944 ///
12945 /// \param CheckNonDependent A callback to invoke to check conversions for
12946 /// non-dependent parameters, between deduction and substitution, per DR1391.
12947 /// If this returns true, substitution will be skipped and we return
12948 /// TemplateDeductionResult::NonDependentConversionFailure. The callback is
12949 /// passed the parameter types (after substituting explicit template
12950 /// arguments).
12951 ///
12952 /// \returns the result of template argument deduction.
12955 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12957 bool PartialOverloading, bool AggregateDeductionCandidate,
12958 bool PartialOrdering, QualType ObjectType,
12959 Expr::Classification ObjectClassification,
12960 bool ForOverloadSetAddressResolution,
12961 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent);
12962
12963 /// Deduce template arguments when taking the address of a function
12964 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
12965 /// a template.
12966 ///
12967 /// \param FunctionTemplate the function template for which we are performing
12968 /// template argument deduction.
12969 ///
12970 /// \param ExplicitTemplateArgs the explicitly-specified template
12971 /// arguments.
12972 ///
12973 /// \param ArgFunctionType the function type that will be used as the
12974 /// "argument" type (A) when performing template argument deduction from the
12975 /// function template's function type. This type may be NULL, if there is no
12976 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
12977 ///
12978 /// \param Specialization if template argument deduction was successful,
12979 /// this will be set to the function template specialization produced by
12980 /// template argument deduction.
12981 ///
12982 /// \param Info the argument will be updated to provide additional information
12983 /// about template argument deduction.
12984 ///
12985 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12986 /// the address of a function template per [temp.deduct.funcaddr] and
12987 /// [over.over]. If \c false, we are looking up a function template
12988 /// specialization based on its signature, per [temp.deduct.decl].
12989 ///
12990 /// \returns the result of template argument deduction.
12993 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
12995 bool IsAddressOfFunction = false);
12996
12997 /// Deduce template arguments for a templated conversion
12998 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
12999 /// conversion function template specialization.
13002 Expr::Classification ObjectClassification, QualType ToType,
13004
13005 /// Deduce template arguments for a function template when there is
13006 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
13007 ///
13008 /// \param FunctionTemplate the function template for which we are performing
13009 /// template argument deduction.
13010 ///
13011 /// \param ExplicitTemplateArgs the explicitly-specified template
13012 /// arguments.
13013 ///
13014 /// \param Specialization if template argument deduction was successful,
13015 /// this will be set to the function template specialization produced by
13016 /// template argument deduction.
13017 ///
13018 /// \param Info the argument will be updated to provide additional information
13019 /// about template argument deduction.
13020 ///
13021 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
13022 /// the address of a function template in a context where we do not have a
13023 /// target type, per [over.over]. If \c false, we are looking up a function
13024 /// template specialization based on its signature, which only happens when
13025 /// deducing a function parameter type from an argument that is a template-id
13026 /// naming a function template specialization.
13027 ///
13028 /// \returns the result of template argument deduction.
13031 TemplateArgumentListInfo *ExplicitTemplateArgs,
13034 bool IsAddressOfFunction = false);
13035
13036 /// Substitute Replacement for \p auto in \p TypeWithAuto
13037 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
13038 /// Substitute Replacement for auto in TypeWithAuto
13040 QualType Replacement);
13041
13042 // Substitute auto in TypeWithAuto for a Dependent auto type
13044
13045 // Substitute auto in TypeWithAuto for a Dependent auto type
13048
13049 /// Completely replace the \c auto in \p TypeWithAuto by
13050 /// \p Replacement. This does not retain any \c auto type sugar.
13051 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
13053 QualType Replacement);
13054
13055 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
13056 ///
13057 /// Note that this is done even if the initializer is dependent. (This is
13058 /// necessary to support partial ordering of templates using 'auto'.)
13059 /// A dependent type will be produced when deducing from a dependent type.
13060 ///
13061 /// \param Type the type pattern using the auto type-specifier.
13062 /// \param Init the initializer for the variable whose type is to be deduced.
13063 /// \param Result if type deduction was successful, this will be set to the
13064 /// deduced type.
13065 /// \param Info the argument will be updated to provide additional information
13066 /// about template argument deduction.
13067 /// \param DependentDeduction Set if we should permit deduction in
13068 /// dependent cases. This is necessary for template partial ordering
13069 /// with 'auto' template parameters. The template parameter depth to be
13070 /// used should be specified in the 'Info' parameter.
13071 /// \param IgnoreConstraints Set if we should not fail if the deduced type
13072 /// does not satisfy the type-constraint in the auto
13073 /// type.
13077 bool DependentDeduction = false,
13078 bool IgnoreConstraints = false,
13079 TemplateSpecCandidateSet *FailedTSC = nullptr);
13080 void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init);
13082 bool Diagnose = true);
13083
13085 SourceLocation Loc);
13086
13087 /// Returns the more specialized class template partial specialization
13088 /// according to the rules of partial ordering of class template partial
13089 /// specializations (C++ [temp.class.order]).
13090 ///
13091 /// \param PS1 the first class template partial specialization
13092 ///
13093 /// \param PS2 the second class template partial specialization
13094 ///
13095 /// \returns the more specialized class template partial specialization. If
13096 /// neither partial specialization is more specialized, returns NULL.
13101
13104
13108
13111
13113 TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
13114 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
13115 bool PartialOrdering, bool *StrictPackMatch);
13116
13117 /// Determine the declared type of the constant template parameter that \p Arg
13118 /// names, if any.
13119 static QualType
13121
13122 /// Mark which template parameters are used in a given expression.
13123 ///
13124 /// \param E the expression from which template parameters will be deduced.
13125 ///
13126 /// \param Used a bit vector whose elements will be set to \c true
13127 /// to indicate when the corresponding template parameter will be
13128 /// deduced.
13129 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
13130 unsigned Depth, llvm::SmallBitVector &Used);
13131
13132 /// Mark which template parameters are named in a given expression.
13133 ///
13134 /// Unlike MarkUsedTemplateParameters, this excludes parameter that
13135 /// are used but not directly named by an expression - i.e. it excludes
13136 /// any template parameter that denotes the type of a referenced NTTP.
13137 ///
13138 /// \param Used a bit vector whose elements will be set to \c true
13139 /// to indicate when the corresponding template parameter will be
13140 /// deduced.
13142 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used);
13143
13144 /// Mark which template parameters can be deduced from a given
13145 /// template argument list.
13146 ///
13147 /// \param TemplateArgs the template argument list from which template
13148 /// parameters will be deduced.
13149 ///
13150 /// \param Used a bit vector whose elements will be set to \c true
13151 /// to indicate when the corresponding template parameter will be
13152 /// deduced.
13153 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
13154 bool OnlyDeduced, unsigned Depth,
13155 llvm::SmallBitVector &Used);
13156
13158 bool OnlyDeduced, unsigned Depth,
13159 llvm::SmallBitVector &Used);
13160
13162 unsigned Depth, llvm::SmallBitVector &Used);
13163
13164 void
13169
13170 /// Marks all of the template parameters that will be deduced by a
13171 /// call to the given function template.
13172 static void
13175 llvm::SmallBitVector &Deduced);
13176
13177 /// Returns the more specialized function template according
13178 /// to the rules of function template partial ordering (C++
13179 /// [temp.func.order]).
13180 ///
13181 /// \param FT1 the first function template
13182 ///
13183 /// \param FT2 the second function template
13184 ///
13185 /// \param TPOC the context in which we are performing partial ordering of
13186 /// function templates.
13187 ///
13188 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
13189 /// only when \c TPOC is \c TPOC_Call. Does not include the object argument
13190 /// when calling a member function.
13191 ///
13192 /// \param RawObj1Ty The type of the object parameter of FT1 if a member
13193 /// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function
13194 /// template from a member function
13195 ///
13196 /// \param RawObj2Ty The type of the object parameter of FT2 if a member
13197 /// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function
13198 /// template from a member function
13199 ///
13200 /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
13201 /// candidate with a reversed parameter order. In this case, the corresponding
13202 /// P/A pairs between FT1 and FT2 are reversed.
13203 ///
13204 /// \returns the more specialized function template. If neither
13205 /// template is more specialized, returns NULL.
13208 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
13209 QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false,
13210 bool PartialOverloading = false);
13211
13212 /// Retrieve the most specialized of the given function template
13213 /// specializations.
13214 ///
13215 /// \param SpecBegin the start iterator of the function template
13216 /// specializations that we will be comparing.
13217 ///
13218 /// \param SpecEnd the end iterator of the function template
13219 /// specializations, paired with \p SpecBegin.
13220 ///
13221 /// \param Loc the location where the ambiguity or no-specializations
13222 /// diagnostic should occur.
13223 ///
13224 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
13225 /// no matching candidates.
13226 ///
13227 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
13228 /// occurs.
13229 ///
13230 /// \param CandidateDiag partial diagnostic used for each function template
13231 /// specialization that is a candidate in the ambiguous ordering. One
13232 /// parameter in this diagnostic should be unbound, which will correspond to
13233 /// the string describing the template arguments for the function template
13234 /// specialization.
13235 ///
13236 /// \returns the most specialized function template specialization, if
13237 /// found. Otherwise, returns SpecEnd.
13238 UnresolvedSetIterator
13239 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
13240 TemplateSpecCandidateSet &FailedCandidates,
13241 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
13242 const PartialDiagnostic &AmbigDiag,
13243 const PartialDiagnostic &CandidateDiag,
13244 bool Complain = true, QualType TargetType = QualType());
13245
13246 /// Returns the more constrained function according to the rules of
13247 /// partial ordering by constraints (C++ [temp.constr.order]).
13248 ///
13249 /// \param FD1 the first function
13250 ///
13251 /// \param FD2 the second function
13252 ///
13253 /// \returns the more constrained function. If neither function is
13254 /// more constrained, returns NULL.
13255 FunctionDecl *getMoreConstrainedFunction(FunctionDecl *FD1,
13256 FunctionDecl *FD2);
13257
13258 ///@}
13259
13260 //
13261 //
13262 // -------------------------------------------------------------------------
13263 //
13264 //
13265
13266 /// \name C++ Template Deduction Guide
13267 /// Implementations are in SemaTemplateDeductionGuide.cpp
13268 ///@{
13269
13270 /// Declare implicit deduction guides for a class template if we've
13271 /// not already done so.
13272 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
13273 SourceLocation Loc);
13274
13275 CXXDeductionGuideDecl *DeclareAggregateDeductionGuideFromInitList(
13276 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
13277 SourceLocation Loc);
13278
13279 ///@}
13280
13281 //
13282 //
13283 // -------------------------------------------------------------------------
13284 //
13285 //
13286
13287 /// \name C++ Template Instantiation
13288 /// Implementations are in SemaTemplateInstantiate.cpp
13289 ///@{
13290
13291public:
13292 /// A helper class for building up ExtParameterInfos.
13295 bool HasInteresting = false;
13296
13297 public:
13298 /// Set the ExtParameterInfo for the parameter at the given index,
13299 ///
13301 assert(Infos.size() <= index);
13302 Infos.resize(index);
13303 Infos.push_back(info);
13304
13305 if (!HasInteresting)
13306 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
13307 }
13308
13309 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
13310 /// ExtParameterInfo array we've built up.
13312 getPointerOrNull(unsigned numParams) {
13313 if (!HasInteresting)
13314 return nullptr;
13315 Infos.resize(numParams);
13316 return Infos.data();
13317 }
13318 };
13319
13320 /// The current instantiation scope used to store local
13321 /// variables.
13323
13324 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
13326
13327 /// A mapping from parameters with unparsed default arguments to the
13328 /// set of instantiations of each parameter.
13329 ///
13330 /// This mapping is a temporary data structure used when parsing
13331 /// nested class templates or nested classes of class templates,
13332 /// where we might end up instantiating an inner class before the
13333 /// default arguments of its methods have been parsed.
13335
13336 using InstantiatingSpecializationsKey = llvm::PointerIntPair<Decl *, 2>;
13337
13344
13346 : S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
13347 auto [_, Created] = S.InstantiatingSpecializations.insert(Key);
13348 if (!Created)
13349 Key = {};
13350 }
13351
13353 if (Key.getOpaqueValue()) {
13354 [[maybe_unused]] bool Erased =
13355 S.InstantiatingSpecializations.erase(Key);
13356 assert(Erased);
13357 }
13358 }
13359
13362
13363 operator bool() const { return Key.getOpaqueValue() == nullptr; }
13364
13365 private:
13366 Sema &S;
13368 };
13369
13370 /// A context in which code is being synthesized (where a source location
13371 /// alone is not sufficient to identify the context). This covers template
13372 /// instantiation and various forms of implicitly-generated functions.
13374 /// The kind of template instantiation we are performing
13376 /// We are instantiating a template declaration. The entity is
13377 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
13379
13380 /// We are instantiating a default argument for a template
13381 /// parameter. The Entity is the template parameter whose argument is
13382 /// being instantiated, the Template is the template, and the
13383 /// TemplateArgs/NumTemplateArguments provide the template arguments as
13384 /// specified.
13386
13387 /// We are instantiating a default argument for a function.
13388 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
13389 /// provides the template arguments as specified.
13391
13392 /// We are substituting explicit template arguments provided for
13393 /// a function template. The entity is a FunctionTemplateDecl.
13395
13396 /// We are substituting template argument determined as part of
13397 /// template argument deduction for either a class template
13398 /// partial specialization or a function template. The
13399 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
13400 /// a TemplateDecl.
13402
13403 /// We are substituting into a lambda expression.
13405
13406 /// We are substituting prior template arguments into a new
13407 /// template parameter. The template parameter itself is either a
13408 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
13410
13411 /// We are checking the validity of a default template argument that
13412 /// has been used when naming a template-id.
13414
13415 /// We are computing the exception specification for a defaulted special
13416 /// member function.
13418
13419 /// We are instantiating the exception specification for a function
13420 /// template which was deferred until it was needed.
13422
13423 /// We are instantiating a requirement of a requires expression.
13425
13426 /// We are checking the satisfaction of a nested requirement of a requires
13427 /// expression.
13429
13430 /// We are declaring an implicit special member function.
13432
13433 /// We are declaring an implicit 'operator==' for a defaulted
13434 /// 'operator<=>'.
13436
13437 /// We are defining a synthesized function (such as a defaulted special
13438 /// member).
13440
13441 // We are checking the constraints associated with a constrained entity or
13442 // the constraint expression of a concept. This includes the checks that
13443 // atomic constraints have the type 'bool' and that they can be constant
13444 // evaluated.
13446
13447 // We are substituting template arguments into a constraint expression.
13449
13450 // Instantiating a Requires Expression parameter clause.
13452
13453 // We are substituting into the parameter mapping of an atomic constraint
13454 // during normalization.
13456
13457 /// We are rewriting a comparison operator in terms of an operator<=>.
13459
13460 /// We are initializing a structured binding.
13462
13463 /// We are marking a class as __dllexport.
13465
13466 /// We are building an implied call from __builtin_dump_struct. The
13467 /// arguments are in CallArgs.
13469
13470 /// Added for Template instantiation observation.
13471 /// Memoization means we are _not_ instantiating a template because
13472 /// it is already instantiated (but we entered a context where we
13473 /// would have had to if it was not already instantiated).
13475
13476 /// We are building deduction guides for a class.
13478
13479 /// We are instantiating a type alias template declaration.
13481
13482 /// We are performing partial ordering for template template parameters.
13484
13485 /// We are performing name lookup for a function template or variable
13486 /// template named 'sycl_kernel_launch'.
13488
13489 /// We are performing overload resolution for a call to a function
13490 /// template or variable template named 'sycl_kernel_launch'.
13492
13493 /// We are instantiating an expansion statement.
13495 } Kind;
13496
13497 /// Whether we're substituting into constraints.
13499
13500 /// Whether we're substituting into the parameter mapping of a constraint.
13502
13503 /// The point of instantiation or synthesis within the source code.
13505
13506 /// The entity that is being synthesized.
13508
13509 /// The template (or partial specialization) in which we are
13510 /// performing the instantiation, for substitutions of prior template
13511 /// arguments.
13513
13514 union {
13515 /// The list of template arguments we are substituting, if they
13516 /// are not part of the entity.
13518
13519 /// The list of argument expressions in a synthesized call.
13520 const Expr *const *CallArgs;
13521 };
13522
13523 // FIXME: Wrap this union around more members, or perhaps store the
13524 // kind-specific members in the RAII object owning the context.
13525 union {
13526 /// The number of template arguments in TemplateArgs.
13528
13529 /// The number of expressions in CallArgs.
13530 unsigned NumCallArgs;
13531
13532 /// The special member being declared or defined.
13534 };
13535
13540
13541 /// The source range that covers the construct that cause
13542 /// the instantiation, e.g., the template-id that causes a class
13543 /// template instantiation.
13545
13550
13551 /// Determines whether this template is an actual instantiation
13552 /// that should be counted toward the maximum instantiation depth.
13553 bool isInstantiationRecord() const;
13554 };
13555
13556 /// A stack object to be created when performing template
13557 /// instantiation.
13558 ///
13559 /// Construction of an object of type \c InstantiatingTemplate
13560 /// pushes the current instantiation onto the stack of active
13561 /// instantiations. If the size of this stack exceeds the maximum
13562 /// number of recursive template instantiations, construction
13563 /// produces an error and evaluates true.
13564 ///
13565 /// Destruction of this object will pop the named instantiation off
13566 /// the stack.
13568 /// Note that we are instantiating a class template,
13569 /// function template, variable template, alias template,
13570 /// or a member thereof.
13571 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13572 Decl *Entity,
13573 SourceRange InstantiationRange = SourceRange());
13574
13576 /// Note that we are instantiating an exception specification
13577 /// of a function template.
13578 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13580 SourceRange InstantiationRange = SourceRange());
13581
13582 /// Note that we are instantiating a type alias template declaration.
13583 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13584 TypeAliasTemplateDecl *Entity,
13585 ArrayRef<TemplateArgument> TemplateArgs,
13586 SourceRange InstantiationRange = SourceRange());
13587
13588 /// Note that we are instantiating a default argument in a
13589 /// template-id.
13590 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13592 ArrayRef<TemplateArgument> TemplateArgs,
13593 SourceRange InstantiationRange = SourceRange());
13594
13595 /// Note that we are substituting either explicitly-specified or
13596 /// deduced template arguments during function template argument deduction.
13597 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13599 ArrayRef<TemplateArgument> TemplateArgs,
13601 SourceRange InstantiationRange = SourceRange());
13602
13603 /// Note that we are instantiating as part of template
13604 /// argument deduction for a class template declaration.
13605 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13607 ArrayRef<TemplateArgument> TemplateArgs,
13608 SourceRange InstantiationRange = SourceRange());
13609
13610 /// Note that we are instantiating as part of template
13611 /// argument deduction for a class template partial
13612 /// specialization.
13613 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13615 ArrayRef<TemplateArgument> TemplateArgs,
13616 SourceRange InstantiationRange = SourceRange());
13617
13618 /// Note that we are instantiating as part of template
13619 /// argument deduction for a variable template partial
13620 /// specialization.
13621 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13623 ArrayRef<TemplateArgument> TemplateArgs,
13624 SourceRange InstantiationRange = SourceRange());
13625
13626 /// Note that we are instantiating a default argument for a function
13627 /// parameter.
13628 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13629 ParmVarDecl *Param,
13630 ArrayRef<TemplateArgument> TemplateArgs,
13631 SourceRange InstantiationRange = SourceRange());
13632
13633 /// Note that we are substituting prior template arguments into a
13634 /// non-type parameter.
13635 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13637 ArrayRef<TemplateArgument> TemplateArgs,
13638 SourceRange InstantiationRange);
13639
13640 /// Note that we are substituting prior template arguments into a
13641 /// template template parameter.
13642 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13644 ArrayRef<TemplateArgument> TemplateArgs,
13645 SourceRange InstantiationRange);
13646
13647 /// Note that we are checking the default template argument
13648 /// against the template parameter for a given template-id.
13649 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13651 ArrayRef<TemplateArgument> TemplateArgs,
13652 SourceRange InstantiationRange);
13653
13655 /// \brief Note that we are checking the constraints associated with some
13656 /// constrained entity (a concept declaration or a template with associated
13657 /// constraints).
13658 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13660 ArrayRef<TemplateArgument> TemplateArgs,
13661 SourceRange InstantiationRange);
13662
13664 /// \brief Note that we are checking a constraint expression associated
13665 /// with a template declaration or as part of the satisfaction check of a
13666 /// concept.
13667 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13669 SourceRange InstantiationRange);
13670
13672 /// \brief Note that we are subtituting into the parameter mapping of an
13673 /// atomic constraint during constraint normalization.
13674 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13676 SourceRange InstantiationRange);
13677
13678 /// \brief Note that we are substituting template arguments into a part of
13679 /// a requirement of a requires expression.
13680 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13682 SourceRange InstantiationRange = SourceRange());
13683
13684 /// \brief Note that we are substituting the body of an expansion statement.
13685 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13686 CXXExpansionStmtPattern *ExpansionStmt,
13688 SourceRange InstantiationRange);
13689
13690 /// \brief Note that we are checking the satisfaction of the constraint
13691 /// expression inside of a nested requirement.
13692 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13694 SourceRange InstantiationRange = SourceRange());
13695
13696 /// \brief Note that we are checking a requires clause.
13697 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13698 const RequiresExpr *E,
13699 SourceRange InstantiationRange);
13700
13702 /// \brief Note that we are building deduction guides.
13703 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13705 SourceRange InstantiationRange = SourceRange());
13706
13708 /// \brief Note that we are partial ordering template template parameters.
13709 InstantiatingTemplate(Sema &SemaRef, SourceLocation ArgLoc,
13711 SourceRange InstantiationRange = SourceRange());
13712
13713 /// Note that we have finished instantiating this template.
13714 void Clear();
13715
13717
13718 /// Determines whether we have exceeded the maximum
13719 /// recursive template instantiations.
13720 bool isInvalid() const { return Invalid; }
13721
13722 private:
13723 Sema &SemaRef;
13724 bool Invalid;
13725
13728 SourceLocation PointOfInstantiation,
13729 SourceRange InstantiationRange, Decl *Entity,
13730 NamedDecl *Template = nullptr,
13731 ArrayRef<TemplateArgument> TemplateArgs = {});
13732
13734
13735 InstantiatingTemplate &operator=(const InstantiatingTemplate &) = delete;
13736 };
13737
13738 bool SubstTemplateArgument(const TemplateArgumentLoc &Input,
13739 const MultiLevelTemplateArgumentList &TemplateArgs,
13740 TemplateArgumentLoc &Output,
13741 SourceLocation Loc = {},
13742 const DeclarationName &Entity = {});
13743 bool
13744 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
13745 const MultiLevelTemplateArgumentList &TemplateArgs,
13746 TemplateArgumentListInfo &Outputs);
13747
13748 /// Substitute concept template arguments in the constraint expression
13749 /// of a concept-id. This is used to implement [temp.constr.normal].
13751 SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE,
13752 const Expr *ConstraintExpr,
13753 const MultiLevelTemplateArgumentList &MLTAL);
13754
13756 ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,
13757 const MultiLevelTemplateArgumentList &TemplateArgs,
13758 TemplateArgumentListInfo &Out);
13759
13760 /// Retrieve the template argument list(s) that should be used to
13761 /// instantiate the definition of the given declaration.
13762 ///
13763 /// \param ND the declaration for which we are computing template
13764 /// instantiation arguments.
13765 ///
13766 /// \param DC In the event we don't HAVE a declaration yet, we instead provide
13767 /// the decl context where it will be created. In this case, the `Innermost`
13768 /// should likely be provided. If ND is non-null, this is ignored.
13769 ///
13770 /// \param Innermost if non-NULL, specifies a template argument list for the
13771 /// template declaration passed as ND.
13772 ///
13773 /// \param RelativeToPrimary true if we should get the template
13774 /// arguments relative to the primary template, even when we're
13775 /// dealing with a specialization. This is only relevant for function
13776 /// template specializations.
13777 ///
13778 /// \param Pattern If non-NULL, indicates the pattern from which we will be
13779 /// instantiating the definition of the given declaration, \p ND. This is
13780 /// used to determine the proper set of template instantiation arguments for
13781 /// friend function template specializations.
13782 ///
13783 /// \param ForConstraintInstantiation when collecting arguments,
13784 /// ForConstraintInstantiation indicates we should continue looking when
13785 /// encountering a lambda generic call operator, and continue looking for
13786 /// arguments on an enclosing class template.
13787 ///
13788 /// \param SkipForSpecialization when specified, any template specializations
13789 /// in a traversal would be ignored.
13790 ///
13791 /// \param ForDefaultArgumentSubstitution indicates we should continue looking
13792 /// when encountering a specialized member function template, rather than
13793 /// returning immediately.
13794 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
13795 const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
13796 std::optional<ArrayRef<TemplateArgument>> Innermost = std::nullopt,
13797 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr,
13798 bool ForConstraintInstantiation = false,
13799 bool SkipForSpecialization = false,
13800 bool ForDefaultArgumentSubstitution = false);
13801
13802 /// RAII object to handle the state changes required to synthesize
13803 /// a function body.
13805 Sema &S;
13806 Sema::ContextRAII SavedContext;
13807 bool PushedCodeSynthesisContext = false;
13808
13809 public:
13811 : S(S), SavedContext(S, DC) {
13812 auto *FD = dyn_cast<FunctionDecl>(DC);
13813 S.PushFunctionScope();
13814 S.PushExpressionEvaluationContextForFunction(
13816 if (FD)
13817 FD->setWillHaveBody(true);
13818 else
13819 assert(isa<ObjCMethodDecl>(DC));
13820 }
13821
13823 assert(!PushedCodeSynthesisContext);
13824
13827 Ctx.PointOfInstantiation = UseLoc;
13828 Ctx.Entity = cast<Decl>(S.CurContext);
13829 S.pushCodeSynthesisContext(Ctx);
13830
13831 PushedCodeSynthesisContext = true;
13832 }
13833
13835 if (PushedCodeSynthesisContext)
13836 S.popCodeSynthesisContext();
13837 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
13838 FD->setWillHaveBody(false);
13839 S.CheckImmediateEscalatingFunctionDefinition(FD, S.getCurFunction());
13840 }
13841 S.PopExpressionEvaluationContext();
13842 S.PopFunctionScopeInfo();
13843 }
13844
13848 };
13849
13850 /// RAII object to ensure that a code synthesis context is popped on scope
13851 /// exit.
13853 Sema &S;
13854
13855 public:
13857 : S(S) {
13858 S.pushCodeSynthesisContext(Ctx);
13859 }
13860
13861 ~ScopedCodeSynthesisContext() { S.popCodeSynthesisContext(); }
13865 };
13866
13867 /// List of active code synthesis contexts.
13868 ///
13869 /// This vector is treated as a stack. As synthesis of one entity requires
13870 /// synthesis of another, additional contexts are pushed onto the stack.
13872
13873 /// Specializations whose definitions are currently being instantiated.
13874 llvm::DenseSet<InstantiatingSpecializationsKey> InstantiatingSpecializations;
13875
13876 /// Non-dependent types used in templates that have already been instantiated
13877 /// by some template instantiation.
13878 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
13879
13880 /// Extra modules inspected when performing a lookup during a template
13881 /// instantiation. Computed lazily.
13883
13884 /// Cache of additional modules that should be used for name lookup
13885 /// within the current template instantiation. Computed lazily; use
13886 /// getLookupModules() to get a complete set.
13887 llvm::DenseSet<Module *> LookupModulesCache;
13888
13889 /// Map from the most recent declaration of a namespace to the most
13890 /// recent visible declaration of that namespace.
13891 llvm::DenseMap<NamedDecl *, NamedDecl *> VisibleNamespaceCache;
13892
13894
13895 /// The number of \p CodeSynthesisContexts that are not template
13896 /// instantiations and, therefore, should not be counted as part of the
13897 /// instantiation depth.
13898 ///
13899 /// When the instantiation depth reaches the user-configurable limit
13900 /// \p LangOptions::InstantiationDepth we will abort instantiation.
13901 // FIXME: Should we have a similar limit for other forms of synthesis?
13903
13904 /// The depth of the context stack at the point when the most recent
13905 /// error or warning was produced.
13906 ///
13907 /// This value is used to suppress printing of redundant context stacks
13908 /// when there are multiple errors or warnings in the same instantiation.
13909 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
13911
13912 /// The current index into pack expansion arguments that will be
13913 /// used for substitution of parameter packs.
13914 ///
13915 /// The pack expansion index will be none to indicate that parameter packs
13916 /// should be instantiated as themselves. Otherwise, the index specifies
13917 /// which argument within the parameter pack will be used for substitution.
13919
13920 /// RAII object used to change the argument pack substitution index
13921 /// within a \c Sema object.
13922 ///
13923 /// See \c ArgPackSubstIndex for more information.
13925 Sema &Self;
13926 UnsignedOrNone OldSubstIndex;
13927
13928 public:
13930 : Self(Self),
13931 OldSubstIndex(std::exchange(Self.ArgPackSubstIndex, NewSubstIndex)) {}
13932
13933 ~ArgPackSubstIndexRAII() { Self.ArgPackSubstIndex = OldSubstIndex; }
13936 };
13937
13940
13951 /// Prints the current instantiation stack through a series of
13952 /// notes.
13957
13958 /// Returns a pointer to the current SFINAE context, if any.
13959 [[nodiscard]] SFINAETrap *getSFINAEContext() const {
13960 return CurrentSFINAEContext;
13961 }
13962 [[nodiscard]] bool isSFINAEContext() const {
13963 return CurrentSFINAEContext != nullptr;
13964 }
13965
13966 /// Perform substitution on the type T with a given set of template
13967 /// arguments.
13968 ///
13969 /// This routine substitutes the given template arguments into the
13970 /// type T and produces the instantiated type.
13971 ///
13972 /// \param T the type into which the template arguments will be
13973 /// substituted. If this type is not dependent, it will be returned
13974 /// immediately.
13975 ///
13976 /// \param Args the template arguments that will be
13977 /// substituted for the top-level template parameters within T.
13978 ///
13979 /// \param Loc the location in the source code where this substitution
13980 /// is being performed. It will typically be the location of the
13981 /// declarator (if we're instantiating the type of some declaration)
13982 /// or the location of the type in the source code (if, e.g., we're
13983 /// instantiating the type of a cast expression).
13984 ///
13985 /// \param Entity the name of the entity associated with a declaration
13986 /// being instantiated (if any). May be empty to indicate that there
13987 /// is no such entity (if, e.g., this is a type that occurs as part of
13988 /// a cast expression) or that the entity has no name (e.g., an
13989 /// unnamed function parameter).
13990 ///
13991 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
13992 /// acceptable as the top level type of the result.
13993 ///
13994 /// \param IsIncompleteSubstitution If provided, the pointee will be set
13995 /// whenever substitution would perform a replacement with a null or
13996 /// non-existent template argument.
13997 ///
13998 /// \returns If the instantiation succeeds, the instantiated
13999 /// type. Otherwise, produces diagnostics and returns a NULL type.
14001 const MultiLevelTemplateArgumentList &TemplateArgs,
14002 SourceLocation Loc, DeclarationName Entity,
14003 bool AllowDeducedTST = false);
14004
14006 const MultiLevelTemplateArgumentList &TemplateArgs,
14007 SourceLocation Loc, DeclarationName Entity,
14008 bool *IsIncompleteSubstitution = nullptr);
14009
14011 const MultiLevelTemplateArgumentList &TemplateArgs,
14012 SourceLocation Loc, DeclarationName Entity);
14013
14016 const MultiLevelTemplateArgumentList &TemplateArgs,
14017 SourceLocation Loc, DeclarationName Entity);
14018
14019 /// A form of SubstType intended specifically for instantiating the
14020 /// type of a FunctionDecl. Its purpose is solely to force the
14021 /// instantiation of default-argument expressions and to avoid
14022 /// instantiating an exception-specification.
14024 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
14025 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
14026 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
14028 const MultiLevelTemplateArgumentList &Args);
14031 SmallVectorImpl<QualType> &ExceptionStorage,
14032 const MultiLevelTemplateArgumentList &Args);
14033 /// An attribute whose instantiation is deferred, together with the
14034 /// instantiation scope to instantiate it in.
14045
14046 /// Substitute into a function parameter. If \p LateAttrs is given, its
14047 /// late-parsed attributes are deferred there, since they may name a
14048 /// parameter that is not substituted yet; see \ref InstantiateLateAttrs.
14049 ParmVarDecl *
14051 const MultiLevelTemplateArgumentList &TemplateArgs,
14052 int indexAdjustment, UnsignedOrNone NumExpansions,
14053 bool ExpectParameterPack, bool EvaluateConstraints = true,
14054 LateInstantiatedAttrVec *LateAttrs = nullptr);
14055
14056 /// Substitute the given template arguments into the given set of
14057 /// parameters, producing the set of parameter types that would be generated
14058 /// from such a substitution. If there is a parameter with no ParmVarDecl to
14059 /// substitute (a null entry of \p Params, as from a typedef'd function
14060 /// type), its type needs to come from \p OldParamTypes instead, which must
14061 /// then be passed, and \p OutParams gets null for it.
14063 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
14064 const MultiLevelTemplateArgumentList &TemplateArgs,
14065 SmallVectorImpl<QualType> &ParamTypes,
14067 ExtParameterInfoBuilder &ParamInfos,
14068 const QualType *OldParamTypes = nullptr,
14069 bool EvaluateConstraints = true);
14070
14071 /// Substitute the given template arguments into the default argument.
14073 const MultiLevelTemplateArgumentList &TemplateArgs,
14074 bool ForCallExpr = false);
14076 const MultiLevelTemplateArgumentList &TemplateArgs);
14077 /// Substitute an expression as if it is a address-of-operand, which makes it
14078 /// act like a CXXIdExpression rather than an attempt to call.
14080 const MultiLevelTemplateArgumentList &TemplateArgs);
14081
14082 // Must be used instead of SubstExpr at 'constraint checking' time.
14085 const MultiLevelTemplateArgumentList &TemplateArgs);
14086 // Unlike the above, this does not evaluate constraints.
14088 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs);
14089
14090 /// Substitute the given template arguments into a list of
14091 /// expressions, expanding pack expansions if required.
14092 ///
14093 /// \param Exprs The list of expressions to substitute into.
14094 ///
14095 /// \param IsCall Whether this is some form of call, in which case
14096 /// default arguments will be dropped.
14097 ///
14098 /// \param TemplateArgs The set of template arguments to substitute.
14099 ///
14100 /// \param Outputs Will receive all of the substituted arguments.
14101 ///
14102 /// \returns true if an error occurred, false otherwise.
14103 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
14104 const MultiLevelTemplateArgumentList &TemplateArgs,
14105 SmallVectorImpl<Expr *> &Outputs);
14106
14108 const MultiLevelTemplateArgumentList &TemplateArgs);
14109
14112 bool CXXDirectInit);
14113
14114 /// Perform substitution on the base class specifiers of the
14115 /// given class template specialization.
14116 ///
14117 /// Produces a diagnostic and returns true on error, returns false and
14118 /// attaches the instantiated base classes to the class template
14119 /// specialization if successful.
14120 bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
14121 const MultiLevelTemplateArgumentList &TemplateArgs);
14122
14123 /// Instantiate the definition of a class from a given pattern.
14124 ///
14125 /// \param PointOfInstantiation The point of instantiation within the
14126 /// source code.
14127 ///
14128 /// \param Instantiation is the declaration whose definition is being
14129 /// instantiated. This will be either a class template specialization
14130 /// or a member class of a class template specialization.
14131 ///
14132 /// \param Pattern is the pattern from which the instantiation
14133 /// occurs. This will be either the declaration of a class template or
14134 /// the declaration of a member class of a class template.
14135 ///
14136 /// \param TemplateArgs The template arguments to be substituted into
14137 /// the pattern.
14138 ///
14139 /// \param TSK the kind of implicit or explicit instantiation to perform.
14140 ///
14141 /// \param Complain whether to complain if the class cannot be instantiated
14142 /// due to the lack of a definition.
14143 ///
14144 /// \returns true if an error occurred, false otherwise.
14145 bool InstantiateClass(SourceLocation PointOfInstantiation,
14146 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
14147 const MultiLevelTemplateArgumentList &TemplateArgs,
14148 TemplateSpecializationKind TSK, bool Complain = true);
14149
14150private:
14151 bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
14152 CXXRecordDecl *Instantiation,
14153 CXXRecordDecl *Pattern,
14154 const MultiLevelTemplateArgumentList &TemplateArgs,
14155 TemplateSpecializationKind TSK, bool Complain);
14156
14157public:
14158 /// Instantiate the definition of an enum from a given pattern.
14159 ///
14160 /// \param PointOfInstantiation The point of instantiation within the
14161 /// source code.
14162 /// \param Instantiation is the declaration whose definition is being
14163 /// instantiated. This will be a member enumeration of a class
14164 /// temploid specialization, or a local enumeration within a
14165 /// function temploid specialization.
14166 /// \param Pattern The templated declaration from which the instantiation
14167 /// occurs.
14168 /// \param TemplateArgs The template arguments to be substituted into
14169 /// the pattern.
14170 /// \param TSK The kind of implicit or explicit instantiation to perform.
14171 ///
14172 /// \return \c true if an error occurred, \c false otherwise.
14173 bool InstantiateEnum(SourceLocation PointOfInstantiation,
14174 EnumDecl *Instantiation, EnumDecl *Pattern,
14175 const MultiLevelTemplateArgumentList &TemplateArgs,
14177
14178 /// Instantiate the definition of a field from the given pattern.
14179 ///
14180 /// \param PointOfInstantiation The point of instantiation within the
14181 /// source code.
14182 /// \param Instantiation is the declaration whose definition is being
14183 /// instantiated. This will be a class of a class temploid
14184 /// specialization, or a local enumeration within a function temploid
14185 /// specialization.
14186 /// \param Pattern The templated declaration from which the instantiation
14187 /// occurs.
14188 /// \param TemplateArgs The template arguments to be substituted into
14189 /// the pattern.
14190 ///
14191 /// \return \c true if an error occurred, \c false otherwise.
14193 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
14194 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
14195
14197 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
14198
14200 SourceLocation PointOfInstantiation,
14201 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14202 TemplateSpecializationKind TSK, bool Complain,
14203 bool PrimaryStrictPackMatch);
14204
14205 /// Instantiates the definitions of all of the member
14206 /// of the given class, which is an instantiation of a class template
14207 /// or a member class of a template.
14208 void
14209 InstantiateClassMembers(SourceLocation PointOfInstantiation,
14210 CXXRecordDecl *Instantiation,
14211 const MultiLevelTemplateArgumentList &TemplateArgs,
14213
14214 /// Instantiate the definitions of all of the members of the
14215 /// given class template specialization, which was named as part of an
14216 /// explicit instantiation.
14218 SourceLocation PointOfInstantiation,
14219 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14221
14224 const MultiLevelTemplateArgumentList &TemplateArgs);
14225
14226 /// Do template substitution on declaration name info.
14229 const MultiLevelTemplateArgumentList &TemplateArgs);
14231 SubstTemplateName(SourceLocation TemplateKWLoc,
14232 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
14233 SourceLocation NameLoc,
14234 const MultiLevelTemplateArgumentList &TemplateArgs);
14235
14237 const MultiLevelTemplateArgumentList &TemplateArgs,
14238 bool EvaluateConstraint);
14239
14240 /// Determine whether we are currently performing template instantiation.
14243 }
14244
14245 /// Determine whether we are currently performing constraint substitution.
14247 return !CodeSynthesisContexts.empty() &&
14248 CodeSynthesisContexts.back().InConstraintSubstitution;
14249 }
14250
14252 return !CodeSynthesisContexts.empty() &&
14253 CodeSynthesisContexts.back().InParameterMappingSubstitution &&
14255 }
14256
14257 using EntityPrinter = llvm::function_ref<void(llvm::raw_ostream &)>;
14258
14259 /// \brief create a Requirement::SubstitutionDiagnostic with only a
14260 /// SubstitutedEntity and DiagLoc using ASTContext's allocator.
14263
14264 ///@}
14265
14266 //
14267 //
14268 // -------------------------------------------------------------------------
14269 //
14270 //
14271
14272 /// \name C++ Template Declaration Instantiation
14273 /// Implementations are in SemaTemplateInstantiateDecl.cpp
14274 ///@{
14275
14276public:
14277 /// An entity for which implicit template instantiation is required.
14278 ///
14279 /// The source location associated with the declaration is the first place in
14280 /// the source code where the declaration was "used". It is not necessarily
14281 /// the point of instantiation (which will be either before or after the
14282 /// namespace-scope declaration that triggered this implicit instantiation),
14283 /// However, it is the location that diagnostics should generally refer to,
14284 /// because users will need to know what code triggered the instantiation.
14285 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
14286
14287 /// The queue of implicit template instantiations that are required
14288 /// but have not yet been performed.
14289 std::deque<PendingImplicitInstantiation> PendingInstantiations;
14290
14291 /// Queue of implicit template instantiations that cannot be performed
14292 /// eagerly.
14294
14298
14299 /// The queue of implicit template instantiations that are required
14300 /// and must be performed within the current local scope.
14301 ///
14302 /// This queue is only used for member functions of local classes in
14303 /// templates, which must be instantiated in the same scope as their
14304 /// enclosing function, so that they can reference function-local
14305 /// types, static variables, enumerators, etc.
14306 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
14307
14309 public:
14311 : S(S), AtEndOfTU(AtEndOfTU) {
14312 SavedPendingLocalImplicitInstantiations.swap(
14313 S.PendingLocalImplicitInstantiations);
14314 }
14315
14316 void perform() {
14317 S.PerformPendingInstantiations(/*LocalOnly=*/true,
14318 /*AtEndOfTU=*/AtEndOfTU);
14319 }
14320
14322 assert(S.PendingLocalImplicitInstantiations.empty() &&
14323 "there shouldn't be any pending local implicit instantiations");
14324 SavedPendingLocalImplicitInstantiations.swap(
14325 S.PendingLocalImplicitInstantiations);
14326 }
14327
14331
14332 private:
14333 Sema &S;
14334 bool AtEndOfTU;
14335 std::deque<PendingImplicitInstantiation>
14336 SavedPendingLocalImplicitInstantiations;
14337 };
14338
14339 /// Records and restores the CurFPFeatures state on entry/exit of compound
14340 /// statements.
14342 public:
14347 FPOptionsOverride getOverrides() { return OldOverrides; }
14348
14349 private:
14350 Sema &S;
14351 FPOptions OldFPFeaturesState;
14352 FPOptionsOverride OldOverrides;
14353 LangOptions::FPEvalMethodKind OldEvalMethod;
14354 SourceLocation OldFPPragmaLocation;
14355 };
14356
14358 public:
14359 GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
14360 : S(S), Enabled(Enabled), AtEndOfTU(AtEndOfTU) {
14361 if (!Enabled)
14362 return;
14363
14364 S.SavedPendingInstantiations.emplace_back();
14365 S.SavedPendingInstantiations.back().swap(S.PendingInstantiations);
14366
14367 S.SavedVTableUses.emplace_back();
14368 S.SavedVTableUses.back().swap(S.VTableUses);
14369 }
14370
14371 void perform() {
14372 if (Enabled) {
14373 S.DefineUsedVTables();
14374 S.PerformPendingInstantiations(/*LocalOnly=*/false,
14375 /*AtEndOfTU=*/AtEndOfTU);
14376 }
14377 }
14378
14380 if (!Enabled)
14381 return;
14382
14383 // Restore the set of pending vtables.
14384 assert(S.VTableUses.empty() &&
14385 "VTableUses should be empty before it is discarded.");
14386 S.VTableUses.swap(S.SavedVTableUses.back());
14387 S.SavedVTableUses.pop_back();
14388
14389 // Restore the set of pending implicit instantiations.
14390 if ((S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) &&
14391 AtEndOfTU) {
14392 assert(S.PendingInstantiations.empty() &&
14393 "PendingInstantiations should be empty before it is discarded.");
14394 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
14395 S.SavedPendingInstantiations.pop_back();
14396 } else {
14397 // Template instantiations in the PCH may be delayed until the TU.
14398 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
14399 S.PendingInstantiations.insert(
14400 S.PendingInstantiations.end(),
14401 S.SavedPendingInstantiations.back().begin(),
14402 S.SavedPendingInstantiations.back().end());
14403 S.SavedPendingInstantiations.pop_back();
14404 }
14405 }
14406
14408 delete;
14411
14412 private:
14413 Sema &S;
14414 bool Enabled;
14415 bool AtEndOfTU;
14416 };
14417
14419 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES);
14420
14421 /// Recheck instantiated thread-safety attributes that could not be validated
14422 /// on the dependent pattern declaration.
14423 bool checkInstantiatedThreadSafetyAttrs(const Decl *D, const Attr *A);
14424
14425 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
14426 const Decl *Pattern, Decl *Inst,
14427 LateInstantiatedAttrVec *LateAttrs = nullptr,
14428 LocalInstantiationScope *OuterMostScope = nullptr);
14429
14430 /// Instantiate the attributes that \ref InstantiateAttrs deferred to \p
14431 /// LateAttrs, and attach them to their declarations. They are instantiated
14432 /// in the scopes saved with them, which extend \p OuterMostScope, the
14433 /// current scope.
14435 LateInstantiatedAttrVec &LateAttrs,
14436 LocalInstantiationScope *OuterMostScope);
14437
14438 /// Update instantiation attributes after template was late parsed.
14439 ///
14440 /// Some attributes are evaluated based on the body of template. If it is
14441 /// late parsed, such attributes cannot be evaluated when declaration is
14442 /// instantiated. This function is used to update instantiation attributes
14443 /// when template definition is ready.
14444 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
14445
14446 void
14448 const Decl *Pattern, Decl *Inst,
14449 LateInstantiatedAttrVec *LateAttrs = nullptr,
14450 LocalInstantiationScope *OuterMostScope = nullptr);
14451
14453 bool IsCopy = false);
14454
14456 ParmVarDecl *Param);
14457 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
14459
14460 /// Instantiate (or find existing instantiation of) a function template with a
14461 /// given set of template arguments.
14462 ///
14463 /// Usually this should not be used, and template argument deduction should be
14464 /// used in its place.
14467 SourceLocation Loc,
14470
14471 /// Instantiate the definition of the given function from its
14472 /// template.
14473 ///
14474 /// \param PointOfInstantiation the point at which the instantiation was
14475 /// required. Note that this is not precisely a "point of instantiation"
14476 /// for the function, but it's close.
14477 ///
14478 /// \param Function the already-instantiated declaration of a
14479 /// function template specialization or member function of a class template
14480 /// specialization.
14481 ///
14482 /// \param Recursive if true, recursively instantiates any functions that
14483 /// are required by this instantiation.
14484 ///
14485 /// \param DefinitionRequired if true, then we are performing an explicit
14486 /// instantiation where the body of the function is required. Complain if
14487 /// there is no such body.
14488 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
14490 bool Recursive = false,
14491 bool DefinitionRequired = false,
14492 bool AtEndOfTU = false);
14495 const TemplateArgumentList *PartialSpecArgs,
14497 SourceLocation PointOfInstantiation,
14498 LateInstantiatedAttrVec *LateAttrs = nullptr,
14499 LocalInstantiationScope *StartingScope = nullptr);
14500
14501 /// Instantiates a variable template specialization by completing it
14502 /// with appropriate type information and initializer.
14504 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
14505 const MultiLevelTemplateArgumentList &TemplateArgs);
14506
14507 /// BuildVariableInstantiation - Used after a new variable has been created.
14508 /// Sets basic variable data and decides whether to postpone the
14509 /// variable instantiation.
14510 void
14512 const MultiLevelTemplateArgumentList &TemplateArgs,
14513 LateInstantiatedAttrVec *LateAttrs,
14514 DeclContext *Owner,
14515 LocalInstantiationScope *StartingScope,
14516 bool InstantiatingVarTemplate = false,
14517 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
14518
14519 /// Instantiate the initializer of a variable.
14521 VarDecl *Var, VarDecl *OldVar,
14522 const MultiLevelTemplateArgumentList &TemplateArgs);
14523
14524 /// Instantiate the definition of the given variable from its
14525 /// template.
14526 ///
14527 /// \param PointOfInstantiation the point at which the instantiation was
14528 /// required. Note that this is not precisely a "point of instantiation"
14529 /// for the variable, but it's close.
14530 ///
14531 /// \param Var the already-instantiated declaration of a templated variable.
14532 ///
14533 /// \param Recursive if true, recursively instantiates any functions that
14534 /// are required by this instantiation.
14535 ///
14536 /// \param DefinitionRequired if true, then we are performing an explicit
14537 /// instantiation where a definition of the variable is required. Complain
14538 /// if there is no such definition.
14539 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
14540 VarDecl *Var, bool Recursive = false,
14541 bool DefinitionRequired = false,
14542 bool AtEndOfTU = false);
14543
14546 const MultiLevelTemplateArgumentList &TemplateArgs);
14547
14548 /// Find the instantiation of the given declaration within the
14549 /// current instantiation.
14550 ///
14551 /// This routine is intended to be used when \p D is a declaration
14552 /// referenced from within a template, that needs to mapped into the
14553 /// corresponding declaration within an instantiation. For example,
14554 /// given:
14555 ///
14556 /// \code
14557 /// template<typename T>
14558 /// struct X {
14559 /// enum Kind {
14560 /// KnownValue = sizeof(T)
14561 /// };
14562 ///
14563 /// bool getKind() const { return KnownValue; }
14564 /// };
14565 ///
14566 /// template struct X<int>;
14567 /// \endcode
14568 ///
14569 /// In the instantiation of X<int>::getKind(), we need to map the \p
14570 /// EnumConstantDecl for \p KnownValue (which refers to
14571 /// X<T>::<Kind>::KnownValue) to its instantiation
14572 /// (X<int>::<Kind>::KnownValue).
14573 /// \p FindInstantiatedDecl performs this mapping from within the
14574 /// instantiation of X<int>.
14575 NamedDecl *
14577 const MultiLevelTemplateArgumentList &TemplateArgs,
14578 bool FindingInstantiatedContext = false);
14579
14580 /// Finds the instantiation of the given declaration context
14581 /// within the current instantiation.
14582 ///
14583 /// \returns NULL if there was an error
14584 DeclContext *
14586 const MultiLevelTemplateArgumentList &TemplateArgs);
14587
14588 Decl *SubstDecl(Decl *D, DeclContext *Owner,
14589 const MultiLevelTemplateArgumentList &TemplateArgs);
14590
14591 /// Substitute the name and return type of a defaulted 'operator<=>' to form
14592 /// an implicit 'operator=='.
14594 FunctionDecl *Spaceship);
14595
14596 /// Performs template instantiation for all implicit template
14597 /// instantiations we have seen until this point.
14598 void PerformPendingInstantiations(bool LocalOnly = false,
14599 bool AtEndOfTU = true);
14600
14603 const MultiLevelTemplateArgumentList &TemplateArgs,
14604 bool EvaluateConstraints = true);
14605
14607 const DeclContext *Pattern,
14608 const MultiLevelTemplateArgumentList &TemplateArgs);
14609
14610private:
14611 /// Introduce the instantiated local variables into the local
14612 /// instantiation scope.
14613 void addInstantiatedLocalVarsToScope(FunctionDecl *Function,
14614 const FunctionDecl *PatternDecl,
14616 /// Introduce the instantiated function parameters into the local
14617 /// instantiation scope, and set the parameter names to those used
14618 /// in the template.
14619 bool addInstantiatedParametersToScope(
14620 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14622 const MultiLevelTemplateArgumentList &TemplateArgs);
14623
14624 /// Introduce the instantiated captures of the lambda into the local
14625 /// instantiation scope.
14626 bool addInstantiatedCapturesToScope(
14627 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14629 const MultiLevelTemplateArgumentList &TemplateArgs);
14630
14631 int ParsingClassDepth = 0;
14632
14633 class SavePendingParsedClassStateRAII {
14634 public:
14635 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
14636
14637 ~SavePendingParsedClassStateRAII() {
14638 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
14639 "there shouldn't be any pending delayed exception spec checks");
14640 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
14641 "there shouldn't be any pending delayed exception spec checks");
14642 swapSavedState();
14643 }
14644
14645 SavePendingParsedClassStateRAII(const SavePendingParsedClassStateRAII &) =
14646 delete;
14647 SavePendingParsedClassStateRAII &
14648 operator=(const SavePendingParsedClassStateRAII &) = delete;
14649
14650 private:
14651 Sema &S;
14653 SavedOverridingExceptionSpecChecks;
14655 SavedEquivalentExceptionSpecChecks;
14656
14657 void swapSavedState() {
14658 SavedOverridingExceptionSpecChecks.swap(
14659 S.DelayedOverridingExceptionSpecChecks);
14660 SavedEquivalentExceptionSpecChecks.swap(
14661 S.DelayedEquivalentExceptionSpecChecks);
14662 }
14663 };
14664
14665 ///@}
14666
14667 //
14668 //
14669 // -------------------------------------------------------------------------
14670 //
14671 //
14672
14673 /// \name C++ Variadic Templates
14674 /// Implementations are in SemaTemplateVariadic.cpp
14675 ///@{
14676
14677public:
14678 /// Determine whether an unexpanded parameter pack might be permitted in this
14679 /// location. Useful for error recovery.
14681
14682 /// The context in which an unexpanded parameter pack is
14683 /// being diagnosed.
14684 ///
14685 /// Note that the values of this enumeration line up with the first
14686 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
14688 /// An arbitrary expression.
14690
14691 /// The base type of a class type.
14693
14694 /// The type of an arbitrary declaration.
14696
14697 /// The type of a data member.
14699
14700 /// The size of a bit-field.
14702
14703 /// The expression in a static assertion.
14705
14706 /// The fixed underlying type of an enumeration.
14708
14709 /// The enumerator value.
14711
14712 /// A using declaration.
14714
14715 /// A friend declaration.
14717
14718 /// A declaration qualifier.
14720
14721 /// An initializer.
14723
14724 /// A default argument.
14726
14727 /// The type of a non-type template parameter.
14729
14730 /// The type of an exception.
14732
14733 /// Explicit specialization.
14735
14736 /// Partial specialization.
14738
14739 /// Microsoft __if_exists.
14741
14742 /// Microsoft __if_not_exists.
14744
14745 /// Lambda expression.
14747
14748 /// Block expression.
14750
14751 /// A type constraint.
14753
14754 // A requirement in a requires-expression.
14756
14757 // A requires-clause.
14759 };
14760
14761 /// Diagnose unexpanded parameter packs.
14762 ///
14763 /// \param Loc The location at which we should emit the diagnostic.
14764 ///
14765 /// \param UPPC The context in which we are diagnosing unexpanded
14766 /// parameter packs.
14767 ///
14768 /// \param Unexpanded the set of unexpanded parameter packs.
14769 ///
14770 /// \returns true if an error occurred, false otherwise.
14774
14775 /// If the given type contains an unexpanded parameter pack,
14776 /// diagnose the error.
14777 ///
14778 /// \param Loc The source location where a diagnostc should be emitted.
14779 ///
14780 /// \param T The type that is being checked for unexpanded parameter
14781 /// packs.
14782 ///
14783 /// \returns true if an error occurred, false otherwise.
14786
14787 /// If the given expression contains an unexpanded parameter
14788 /// pack, diagnose the error.
14789 ///
14790 /// \param E The expression that is being checked for unexpanded
14791 /// parameter packs.
14792 ///
14793 /// \returns true if an error occurred, false otherwise.
14796
14797 /// If the given requirees-expression contains an unexpanded reference to one
14798 /// of its own parameter packs, diagnose the error.
14799 ///
14800 /// \param RE The requiress-expression that is being checked for unexpanded
14801 /// parameter packs.
14802 ///
14803 /// \returns true if an error occurred, false otherwise.
14805
14806 /// If the given nested-name-specifier contains an unexpanded
14807 /// parameter pack, diagnose the error.
14808 ///
14809 /// \param SS The nested-name-specifier that is being checked for
14810 /// unexpanded parameter packs.
14811 ///
14812 /// \returns true if an error occurred, false otherwise.
14815
14816 /// If the given name contains an unexpanded parameter pack,
14817 /// diagnose the error.
14818 ///
14819 /// \param NameInfo The name (with source location information) that
14820 /// is being checked for unexpanded parameter packs.
14821 ///
14822 /// \returns true if an error occurred, false otherwise.
14825
14826 /// If the given template name contains an unexpanded parameter pack,
14827 /// diagnose the error.
14828 ///
14829 /// \param Loc The location of the template name.
14830 ///
14831 /// \param Template The template name that is being checked for unexpanded
14832 /// parameter packs.
14833 ///
14834 /// \returns true if an error occurred, false otherwise.
14838
14839 /// If the given template argument contains an unexpanded parameter
14840 /// pack, diagnose the error.
14841 ///
14842 /// \param Arg The template argument that is being checked for unexpanded
14843 /// parameter packs.
14844 ///
14845 /// \returns true if an error occurred, false otherwise.
14848
14849 /// Collect the set of unexpanded parameter packs within the given
14850 /// template argument.
14851 ///
14852 /// \param Arg The template argument that will be traversed to find
14853 /// unexpanded parameter packs.
14855 TemplateArgument Arg,
14857
14858 /// Collect the set of unexpanded parameter packs within the given
14859 /// template argument.
14860 ///
14861 /// \param Arg The template argument that will be traversed to find
14862 /// unexpanded parameter packs.
14866
14867 /// Collect the set of unexpanded parameter packs within the given
14868 /// type.
14869 ///
14870 /// \param T The type that will be traversed to find
14871 /// unexpanded parameter packs.
14874
14875 /// Collect the set of unexpanded parameter packs within the given
14876 /// template name.
14877 ///
14878 /// \param Template The template name that will be traversed to find
14879 /// unexpanded parameter packs.
14883
14884 /// Collect the set of unexpanded parameter packs within the given
14885 /// type.
14886 ///
14887 /// \param TL The type that will be traversed to find
14888 /// unexpanded parameter packs.
14891
14892 /// Collect the set of unexpanded parameter packs within the given
14893 /// nested-name-specifier.
14894 ///
14895 /// \param NNS The nested-name-specifier that will be traversed to find
14896 /// unexpanded parameter packs.
14900
14901 /// Collect the set of unexpanded parameter packs within the given
14902 /// name.
14903 ///
14904 /// \param NameInfo The name that will be traversed to find
14905 /// unexpanded parameter packs.
14907 const DeclarationNameInfo &NameInfo,
14909
14910 /// Collect the set of unexpanded parameter packs within the given
14911 /// expression.
14914
14915 /// Invoked when parsing a template argument.
14916 ///
14917 /// \param Arg the template argument, which may already be invalid.
14918 ///
14919 /// If it is followed by ellipsis, this function is called before
14920 /// `ActOnPackExpansion`.
14923
14924 /// Invoked when parsing a template argument followed by an
14925 /// ellipsis, which creates a pack expansion.
14926 ///
14927 /// \param Arg The template argument preceding the ellipsis, which
14928 /// may already be invalid.
14929 ///
14930 /// \param EllipsisLoc The location of the ellipsis.
14932 SourceLocation EllipsisLoc);
14933
14934 /// Invoked when parsing a type followed by an ellipsis, which
14935 /// creates a pack expansion.
14936 ///
14937 /// \param Type The type preceding the ellipsis, which will become
14938 /// the pattern of the pack expansion.
14939 ///
14940 /// \param EllipsisLoc The location of the ellipsis.
14942
14943 /// Construct a pack expansion type from the pattern of the pack
14944 /// expansion.
14946 SourceLocation EllipsisLoc,
14947 UnsignedOrNone NumExpansions);
14948
14949 /// Construct a pack expansion type from the pattern of the pack
14950 /// expansion.
14951 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
14952 SourceLocation EllipsisLoc,
14953 UnsignedOrNone NumExpansions);
14954
14955 /// Invoked when parsing an expression followed by an ellipsis, which
14956 /// creates a pack expansion.
14957 ///
14958 /// \param Pattern The expression preceding the ellipsis, which will become
14959 /// the pattern of the pack expansion.
14960 ///
14961 /// \param EllipsisLoc The location of the ellipsis.
14962 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
14963
14964 /// Invoked when parsing an expression followed by an ellipsis, which
14965 /// creates a pack expansion.
14966 ///
14967 /// \param Pattern The expression preceding the ellipsis, which will become
14968 /// the pattern of the pack expansion.
14969 ///
14970 /// \param EllipsisLoc The location of the ellipsis.
14971 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
14972 UnsignedOrNone NumExpansions);
14973
14974 /// Determine whether we could expand a pack expansion with the
14975 /// given set of parameter packs into separate arguments by repeatedly
14976 /// transforming the pattern.
14977 ///
14978 /// \param EllipsisLoc The location of the ellipsis that identifies the
14979 /// pack expansion.
14980 ///
14981 /// \param PatternRange The source range that covers the entire pattern of
14982 /// the pack expansion.
14983 ///
14984 /// \param Unexpanded The set of unexpanded parameter packs within the
14985 /// pattern.
14986 ///
14987 /// \param ShouldExpand Will be set to \c true if the transformer should
14988 /// expand the corresponding pack expansions into separate arguments. When
14989 /// set, \c NumExpansions must also be set.
14990 ///
14991 /// \param RetainExpansion Whether the caller should add an unexpanded
14992 /// pack expansion after all of the expanded arguments. This is used
14993 /// when extending explicitly-specified template argument packs per
14994 /// C++0x [temp.arg.explicit]p9.
14995 ///
14996 /// \param NumExpansions The number of separate arguments that will be in
14997 /// the expanded form of the corresponding pack expansion. This is both an
14998 /// input and an output parameter, which can be set by the caller if the
14999 /// number of expansions is known a priori (e.g., due to a prior substitution)
15000 /// and will be set by the callee when the number of expansions is known.
15001 /// The callee must set this value when \c ShouldExpand is \c true; it may
15002 /// set this value in other cases.
15003 ///
15004 /// \returns true if an error occurred (e.g., because the parameter packs
15005 /// are to be instantiated with arguments of different lengths), false
15006 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
15007 /// must be set.
15009 SourceLocation EllipsisLoc, SourceRange PatternRange,
15011 const MultiLevelTemplateArgumentList &TemplateArgs,
15012 bool FailOnPackProducingTemplates, bool &ShouldExpand,
15013 bool &RetainExpansion, UnsignedOrNone &NumExpansions,
15014 bool Diagnose = true);
15015
15016 /// Determine the number of arguments in the given pack expansion
15017 /// type.
15018 ///
15019 /// This routine assumes that the number of arguments in the expansion is
15020 /// consistent across all of the unexpanded parameter packs in its pattern.
15021 ///
15022 /// Returns an empty Optional if the type can't be expanded.
15024 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
15025
15028 const MultiLevelTemplateArgumentList &TemplateArgs);
15029
15030 /// Determine whether the given declarator contains any unexpanded
15031 /// parameter packs.
15032 ///
15033 /// This routine is used by the parser to disambiguate function declarators
15034 /// with an ellipsis prior to the ')', e.g.,
15035 ///
15036 /// \code
15037 /// void f(T...);
15038 /// \endcode
15039 ///
15040 /// To determine whether we have an (unnamed) function parameter pack or
15041 /// a variadic function.
15042 ///
15043 /// \returns true if the declarator contains any unexpanded parameter packs,
15044 /// false otherwise.
15046
15047 /// Returns the pattern of the pack expansion for a template argument.
15048 ///
15049 /// \param OrigLoc The template argument to expand.
15050 ///
15051 /// \param Ellipsis Will be set to the location of the ellipsis.
15052 ///
15053 /// \param NumExpansions Will be set to the number of expansions that will
15054 /// be generated from this pack expansion, if known a priori.
15057 SourceLocation &Ellipsis,
15058 UnsignedOrNone &NumExpansions) const;
15059
15060 /// Given a template argument that contains an unexpanded parameter pack, but
15061 /// which has already been substituted, attempt to determine the number of
15062 /// elements that will be produced once this argument is fully-expanded.
15063 ///
15064 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
15065 /// avoid actually expanding the pack where possible.
15067
15068 /// Called when an expression computing the size of a parameter pack
15069 /// is parsed.
15070 ///
15071 /// \code
15072 /// template<typename ...Types> struct count {
15073 /// static const unsigned value = sizeof...(Types);
15074 /// };
15075 /// \endcode
15076 ///
15077 //
15078 /// \param OpLoc The location of the "sizeof" keyword.
15079 /// \param Name The name of the parameter pack whose size will be determined.
15080 /// \param NameLoc The source location of the name of the parameter pack.
15081 /// \param RParenLoc The location of the closing parentheses.
15083 IdentifierInfo &Name,
15084 SourceLocation NameLoc,
15085 SourceLocation RParenLoc);
15086
15087 ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression,
15088 SourceLocation EllipsisLoc,
15089 SourceLocation LSquareLoc, Expr *IndexExpr,
15090 SourceLocation RSquareLoc);
15091
15092 ExprResult BuildPackIndexingExpr(Expr *PackExpression,
15093 SourceLocation EllipsisLoc, Expr *IndexExpr,
15094 SourceLocation RSquareLoc,
15095 ArrayRef<Expr *> ExpandedExprs = {},
15096 bool FullySubstituted = false);
15097
15099 SourceLocation NameLoc,
15100 Expr *IndexExpr);
15101
15103 BuildPackIndexingTemplateName(TemplateName Pattern, Expr *IndexExpr,
15104 bool FullySubstituted = false,
15105 ArrayRef<TemplateName> Expansions = {});
15106
15109 SourceLocation NameLoc);
15110
15111 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
15112 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
15113 tok::TokenKind Operator,
15114 SourceLocation EllipsisLoc, Expr *RHS,
15115 SourceLocation RParenLoc);
15116 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
15117 SourceLocation LParenLoc, Expr *LHS,
15118 BinaryOperatorKind Operator,
15119 SourceLocation EllipsisLoc, Expr *RHS,
15120 SourceLocation RParenLoc,
15121 UnsignedOrNone NumExpansions);
15122 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
15123 BinaryOperatorKind Operator);
15124
15125 ///@}
15126
15127 //
15128 //
15129 // -------------------------------------------------------------------------
15130 //
15131 //
15132
15133 /// \name Constraints and Concepts
15134 /// Implementations are in SemaConcept.cpp
15135 ///@{
15136
15137public:
15138 ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI);
15139
15140 ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc,
15141 TypeSourceInfo *TSI);
15142
15143public:
15145 const llvm::FoldingSetNodeID &ID) {
15146 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
15147 SatisfactionStack.emplace_back(Can, ID);
15148 }
15149
15150 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
15151
15153 const llvm::FoldingSetNodeID &ID) const {
15154 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
15155 return llvm::is_contained(SatisfactionStack,
15156 SatisfactionStackEntryTy{Can, ID});
15157 }
15158
15160 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
15161
15162 // Resets the current SatisfactionStack for cases where we are instantiating
15163 // constraints as a 'side effect' of normal instantiation in a way that is not
15164 // indicative of recursive definition.
15167 Sema &SemaRef;
15168
15169 public:
15171 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
15172 }
15173
15175 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
15176 }
15177
15181 };
15182
15185 SatisfactionStack.swap(NewSS);
15186 }
15187
15189 llvm::PointerUnion<const NamedDecl *,
15191
15192 /// Check whether the given expression is a valid constraint expression.
15193 /// A diagnostic is emitted if it is not, false is returned, and
15194 /// PossibleNonPrimary will be set to true if the failure might be due to a
15195 /// non-primary expression being used as an atomic constraint.
15196 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
15197 bool *PossibleNonPrimary = nullptr,
15198 bool IsTrailingRequiresClause = false);
15199
15200 /// \brief Check whether the given list of constraint expressions are
15201 /// satisfied (as if in a 'conjunction') given template arguments.
15202 /// \param Template the template-like entity that triggered the constraints
15203 /// check (either a concept or a constrained entity).
15204 /// \param ConstraintExprs a list of constraint expressions, treated as if
15205 /// they were 'AND'ed together.
15206 /// \param TemplateArgLists the list of template arguments to substitute into
15207 /// the constraint expression.
15208 /// \param TemplateIDRange The source range of the template id that
15209 /// caused the constraints check.
15210 /// \param Satisfaction if true is returned, will contain details of the
15211 /// satisfaction, with enough information to diagnose an unsatisfied
15212 /// expression.
15213 /// \returns true if an error occurred and satisfaction could not be checked,
15214 /// false otherwise.
15217 ArrayRef<AssociatedConstraint> AssociatedConstraints,
15218 const MultiLevelTemplateArgumentList &TemplateArgLists,
15219 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction,
15220 const ConceptReference *TopLevelConceptId = nullptr,
15221 Expr **ConvertedExpr = nullptr);
15222
15223 /// Check whether the given function decl's trailing requires clause is
15224 /// satisfied, if any. Returns false and updates Satisfaction with the
15225 /// satisfaction verdict if successful, emits a diagnostic and returns true if
15226 /// an error occurred and satisfaction could not be determined.
15227 ///
15228 /// \returns true if an error occurred, false otherwise.
15230 ConstraintSatisfaction &Satisfaction,
15231 SourceLocation UsageLoc = SourceLocation(),
15232 bool ForOverloadResolution = false);
15233
15234 // Calculates whether two constraint expressions are equal irrespective of a
15235 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
15236 // 'New', which are the "source" of the constraint, since this is necessary
15237 // for figuring out the relative 'depth' of the constraint. The depth of the
15238 // 'primary template' and the 'instantiated from' templates aren't necessarily
15239 // the same, such as a case when one is a 'friend' defined in a class.
15241 const Expr *OldConstr,
15243 const Expr *NewConstr);
15244
15245 // Calculates whether the friend function depends on an enclosing template for
15246 // the purposes of [temp.friend] p9.
15248
15249 /// \brief Ensure that the given template arguments satisfy the constraints
15250 /// associated with the given template, emitting a diagnostic if they do not.
15251 ///
15252 /// \param Template The template to which the template arguments are being
15253 /// provided.
15254 ///
15255 /// \param TemplateArgs The converted, canonicalized template arguments.
15256 ///
15257 /// \param TemplateIDRange The source range of the template id that
15258 /// caused the constraints check.
15259 ///
15260 /// \returns true if the constrains are not satisfied or could not be checked
15261 /// for satisfaction, false if the constraints are satisfied.
15264 const MultiLevelTemplateArgumentList &TemplateArgs,
15265 SourceRange TemplateIDRange);
15266
15267 bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation,
15269 ArrayRef<TemplateArgument> TemplateArgs,
15270 ConstraintSatisfaction &Satisfaction);
15271
15272 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15273 /// unsatisfied.
15274 /// \param First whether this is the first time an unsatisfied constraint is
15275 /// diagnosed for this error.
15277 SourceLocation Loc = {},
15278 bool First = true);
15279
15280 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15281 /// unsatisfied.
15282 void
15284 bool First = true);
15285
15287 bool First = true);
15288
15291 ArrayRef<AssociatedConstraint> AssociatedConstraints);
15292
15293 /// \brief Check whether the given declaration's associated constraints are
15294 /// at least as constrained than another declaration's according to the
15295 /// partial ordering of constraints.
15296 ///
15297 /// \param Result If no error occurred, receives the result of true if D1 is
15298 /// at least constrained than D2, and false otherwise.
15299 ///
15300 /// \returns true if an error occurred, false otherwise.
15301 bool IsAtLeastAsConstrained(const NamedDecl *D1,
15303 const NamedDecl *D2,
15305 bool &Result);
15306
15307 /// If D1 was not at least as constrained as D2, but would've been if a pair
15308 /// of atomic constraints involved had been declared in a concept and not
15309 /// repeated in two separate places in code.
15310 /// \returns true if such a diagnostic was emitted, false otherwise.
15314
15315private:
15318
15319 UnsignedOrNone EvaluateFoldExpandedConstraintSize(
15320 const Expr *Pattern, const MultiLevelTemplateArgumentList &MLTAL);
15321
15322 /// Cache the satisfaction of an atomic constraint.
15323 /// The key is based on the unsubstituted expression and the parameter
15324 /// mapping. This lets us not substituting the mapping more than once,
15325 /// which is (very!) expensive.
15326 llvm::DenseMap<llvm::FoldingSetNodeIDRef,
15328 UnsubstitutedConstraintSatisfactionCache;
15329
15330 /// Cache the instantiation results of template parameter mappings within
15331 /// concepts. Substituting into normalized concepts can be extremely expensive
15332 /// due to the redundancy of template parameters. This cache is intended for
15333 /// use by TemplateInstantiator to avoid redundant semantic checking.
15334 llvm::DenseMap<llvm::FoldingSetNodeIDRef, TemplateArgumentLoc>
15335 *CurrentCachedTemplateArgs = nullptr;
15336
15337 /// Caches pairs of template-like decls whose associated constraints were
15338 /// checked for subsumption and whether or not the first's constraints did in
15339 /// fact subsume the second's.
15340 llvm::DenseMap<std::pair<const NamedDecl *, const NamedDecl *>, bool>
15341 SubsumptionCache;
15342 /// Caches the normal form of constraint expressions (and their pack
15343 /// substitution index). These are shared by e.g. the members of all
15344 /// specializations of a class template. If an error occurred while
15345 /// normalizing an expression, nullptr will be cached here.
15346 llvm::DenseMap<std::pair<const Expr *, unsigned>, NormalizedConstraint *>
15347 NormalizedConstraintExprCache;
15348
15349 /// Cache whether the associated constraint of a declaration
15350 /// is satisfied.
15351 llvm::DenseMap<llvm::FoldingSetNodeIDRef, ConstraintSatisfaction *>
15352 SatisfactionCache;
15353
15354 // The current stack of constraint satisfactions, so we can exit-early.
15356
15357 /// Used by SetupConstraintCheckingTemplateArgumentsAndScope to set up the
15358 /// LocalInstantiationScope of the current non-lambda function. For lambdas,
15359 /// use LambdaScopeForCallOperatorInstantiationRAII.
15360 bool
15361 SetupConstraintScope(FunctionDecl *FD,
15362 std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15363 const MultiLevelTemplateArgumentList &MLTAL,
15365
15366 /// Used during constraint checking, sets up the constraint template argument
15367 /// lists, and calls SetupConstraintScope to set up the
15368 /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
15369 std::optional<MultiLevelTemplateArgumentList>
15370 SetupConstraintCheckingTemplateArgumentsAndScope(
15371 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15373
15374 ///@}
15375
15376 //
15377 //
15378 // -------------------------------------------------------------------------
15379 //
15380 //
15381
15382 /// \name Types
15383 /// Implementations are in SemaType.cpp
15384 ///@{
15385
15386public:
15387 /// A mapping that describes the nullability we've seen in each header file.
15389
15390 static int getPrintable(int I) { return I; }
15391 static unsigned getPrintable(unsigned I) { return I; }
15392 static bool getPrintable(bool B) { return B; }
15393 static const char *getPrintable(const char *S) { return S; }
15394 static StringRef getPrintable(StringRef S) { return S; }
15395 static const std::string &getPrintable(const std::string &S) { return S; }
15396 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
15397 return II;
15398 }
15400 static QualType getPrintable(QualType T) { return T; }
15401 static SourceRange getPrintable(SourceRange R) { return R; }
15403 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
15405
15406 enum class CompleteTypeKind {
15407 /// Apply the normal rules for complete types. In particular,
15408 /// treat all sizeless types as incomplete.
15410
15411 /// Relax the normal rules for complete types so that they include
15412 /// sizeless built-in types.
15414
15415 // FIXME: Eventually we should flip the default to Normal and opt in
15416 // to AcceptSizeless rather than opt out of it.
15418 };
15419
15421 const DeclSpec *DS = nullptr);
15423 const DeclSpec *DS = nullptr);
15424
15425 /// Build a pointer type.
15426 ///
15427 /// \param T The type to which we'll be building a pointer.
15428 ///
15429 /// \param Loc The location of the entity whose type involves this
15430 /// pointer type or, if there is no such entity, the location of the
15431 /// type that will have pointer type.
15432 ///
15433 /// \param Entity The name of the entity that involves the pointer
15434 /// type, if known.
15435 ///
15436 /// \returns A suitable pointer type, if there are no
15437 /// errors. Otherwise, returns a NULL type.
15439 DeclarationName Entity);
15440
15441 /// Build a reference type.
15442 ///
15443 /// \param T The type to which we'll be building a reference.
15444 ///
15445 /// \param Loc The location of the entity whose type involves this
15446 /// reference type or, if there is no such entity, the location of the
15447 /// type that will have reference type.
15448 ///
15449 /// \param Entity The name of the entity that involves the reference
15450 /// type, if known.
15451 ///
15452 /// \returns A suitable reference type, if there are no
15453 /// errors. Otherwise, returns a NULL type.
15455 DeclarationName Entity);
15456
15457 /// Build an array type.
15458 ///
15459 /// \param T The type of each element in the array.
15460 ///
15461 /// \param ASM C99 array size modifier (e.g., '*', 'static').
15462 ///
15463 /// \param ArraySize Expression describing the size of the array.
15464 ///
15465 /// \param Brackets The range from the opening '[' to the closing ']'.
15466 ///
15467 /// \param Entity The name of the entity that involves the array
15468 /// type, if known.
15469 ///
15470 /// \returns A suitable array type, if there are no errors. Otherwise,
15471 /// returns a NULL type.
15473 unsigned Quals, SourceRange Brackets,
15474 DeclarationName Entity);
15475
15476 /// Diagnose an array of \p NumElements elements of type \p ElementType
15477 /// that is too large. Returns true if a diagnostic was emitted.
15478 bool checkArrayTooLarge(QualType ElementType, const llvm::APSInt &NumElements,
15479 SourceLocation Loc,
15480 SourceRange Range = SourceRange());
15482
15483 /// Build an ext-vector type.
15484 ///
15485 /// Run the required checks for the extended vector type.
15487 SourceLocation AttrLoc);
15488 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
15489 SourceLocation AttrLoc);
15490
15492 Expr *CountExpr,
15493 bool CountInBytes,
15494 bool OrNull);
15495
15496 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an
15497 /// expression is uninstantiated. If instantiated it will apply the
15498 /// appropriate address space to the type. This function allows dependent
15499 /// template variables to be used in conjunction with the address_space
15500 /// attribute
15501 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
15502 SourceLocation AttrLoc);
15503
15504 /// Same as above, but constructs the AddressSpace index if not provided.
15506 SourceLocation AttrLoc);
15507
15509
15511
15512 /// Build a function type.
15513 ///
15514 /// This routine checks the function type according to C++ rules and
15515 /// under the assumption that the result type and parameter types have
15516 /// just been instantiated from a template. It therefore duplicates
15517 /// some of the behavior of GetTypeForDeclarator, but in a much
15518 /// simpler form that is only suitable for this narrow use case.
15519 ///
15520 /// \param T The return type of the function.
15521 ///
15522 /// \param ParamTypes The parameter types of the function. This array
15523 /// will be modified to account for adjustments to the types of the
15524 /// function parameters.
15525 ///
15526 /// \param Loc The location of the entity whose type involves this
15527 /// function type or, if there is no such entity, the location of the
15528 /// type that will have function type.
15529 ///
15530 /// \param Entity The name of the entity that involves the function
15531 /// type, if known.
15532 ///
15533 /// \param EPI Extra information about the function type. Usually this will
15534 /// be taken from an existing function with the same prototype.
15535 ///
15536 /// \returns A suitable function type, if there are no errors. The
15537 /// unqualified type will always be a FunctionProtoType.
15538 /// Otherwise, returns a NULL type.
15540 SourceLocation Loc, DeclarationName Entity,
15542
15543 /// Build a member pointer type \c T Class::*.
15544 ///
15545 /// \param T the type to which the member pointer refers.
15546 /// \param Class the class type into which the member pointer points.
15547 /// \param Loc the location where this type begins
15548 /// \param Entity the name of the entity that will have this member pointer
15549 /// type
15550 ///
15551 /// \returns a member pointer type, if successful, or a NULL type if there was
15552 /// an error.
15554 CXXRecordDecl *Cls, SourceLocation Loc,
15555 DeclarationName Entity);
15556
15557 /// Build a block pointer type.
15558 ///
15559 /// \param T The type to which we'll be building a block pointer.
15560 ///
15561 /// \param Loc The source location, used for diagnostics.
15562 ///
15563 /// \param Entity The name of the entity that involves the block pointer
15564 /// type, if known.
15565 ///
15566 /// \returns A suitable block pointer type, if there are no
15567 /// errors. Otherwise, returns a NULL type.
15569 DeclarationName Entity);
15570
15571 /// Build a paren type including \p T.
15574
15575 /// Build a Read-only Pipe type.
15576 ///
15577 /// \param T The type to which we'll be building a Pipe.
15578 ///
15579 /// \param Loc We do not use it for now.
15580 ///
15581 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15582 /// a NULL type.
15584
15585 /// Build a Write-only Pipe type.
15586 ///
15587 /// \param T The type to which we'll be building a Pipe.
15588 ///
15589 /// \param Loc We do not use it for now.
15590 ///
15591 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15592 /// a NULL type.
15594
15595 /// Build a bit-precise integer type.
15596 ///
15597 /// \param IsUnsigned Boolean representing the signedness of the type.
15598 ///
15599 /// \param BitWidth Size of this int type in bits, or an expression
15600 /// representing that.
15601 ///
15602 /// \param Loc Location of the keyword.
15603 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
15604
15605 /// GetTypeForDeclarator - Convert the type for the specified
15606 /// declarator to Type instances.
15607 ///
15608 /// The result of this call will never be null, but the associated
15609 /// type may be a null type if there's an unrecoverable error.
15612
15613 /// Package the given type and TSI into a ParsedType.
15616 TypeSourceInfo **TInfo = nullptr);
15617
15619
15620 // Check whether the size of array element of type \p EltTy is a multiple of
15621 // its alignment and return false if it isn't.
15623
15624 void
15625 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
15626 SourceLocation FallbackLoc,
15627 SourceLocation ConstQualLoc = SourceLocation(),
15628 SourceLocation VolatileQualLoc = SourceLocation(),
15629 SourceLocation RestrictQualLoc = SourceLocation(),
15630 SourceLocation AtomicQualLoc = SourceLocation(),
15631 SourceLocation UnalignedQualLoc = SourceLocation());
15632
15633 /// Retrieve the keyword associated
15635
15636 /// Adjust the calling convention of a method to be the ABI default if it
15637 /// wasn't specified explicitly. This handles method types formed from
15638 /// function type typedefs and typename template arguments.
15639 void adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
15640 bool IsCtorOrDtor, SourceLocation Loc);
15641
15642 // Check if there is an explicit attribute, but only look through parens.
15643 // The intent is to look for an attribute on the current declarator, but not
15644 // one that came from a typedef.
15646
15647 /// Check whether a nullability type specifier can be added to the given
15648 /// type through some means not written in source (e.g. API notes).
15649 ///
15650 /// \param Type The type to which the nullability specifier will be
15651 /// added. On success, this type will be updated appropriately.
15652 ///
15653 /// \param Nullability The nullability specifier to add.
15654 ///
15655 /// \param DiagLoc The location to use for diagnostics.
15656 ///
15657 /// \param AllowArrayTypes Whether to accept nullability specifiers on an
15658 /// array type (e.g., because it will decay to a pointer).
15659 ///
15660 /// \param OverrideExisting Whether to override an existing, locally-specified
15661 /// nullability specifier rather than complaining about the conflict.
15662 ///
15663 /// \returns true if nullability cannot be applied, false otherwise.
15665 NullabilityKind Nullability,
15666 SourceLocation DiagLoc,
15667 bool AllowArrayTypes,
15668 bool OverrideExisting);
15669
15670 /// Check whether the given variable declaration has a size that fits within
15671 /// the address space it is declared in. This issues a diagnostic if not.
15672 ///
15673 /// \param VD The variable declaration to check the size of.
15674 ///
15675 /// \param AS The address space to check the size of \p VD against.
15676 ///
15677 /// \returns true if the variable's size fits within the address space, false
15678 /// otherwise.
15679 bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS);
15680
15681 /// Get the type of expression E, triggering instantiation to complete the
15682 /// type if necessary -- that is, if the expression refers to a templated
15683 /// static data member of incomplete array type.
15684 ///
15685 /// May still return an incomplete type if instantiation was not possible or
15686 /// if the type is incomplete for a different reason. Use
15687 /// RequireCompleteExprType instead if a diagnostic is expected for an
15688 /// incomplete expression type.
15690
15692
15693 /// Ensure that the type of the given expression is complete.
15694 ///
15695 /// This routine checks whether the expression \p E has a complete type. If
15696 /// the expression refers to an instantiable construct, that instantiation is
15697 /// performed as needed to complete its type. Furthermore
15698 /// Sema::RequireCompleteType is called for the expression's type (or in the
15699 /// case of a reference type, the referred-to type).
15700 ///
15701 /// \param E The expression whose type is required to be complete.
15702 /// \param Kind Selects which completeness rules should be applied.
15703 /// \param Diagnoser The object that will emit a diagnostic if the type is
15704 /// incomplete.
15705 ///
15706 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
15707 /// otherwise.
15709 TypeDiagnoser &Diagnoser);
15710 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
15711
15712 template <typename... Ts>
15713 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
15714 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15716 }
15717
15718 // Returns the underlying type of a decltype with the given expression.
15720
15722 /// If AsUnevaluated is false, E is treated as though it were an evaluated
15723 /// context, such as when building a type for decltype(auto).
15724 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
15725
15726 QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr,
15727 SourceLocation Loc);
15728 QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr,
15729 SourceLocation Loc,
15730 bool FullySubstituted = false,
15731 ArrayRef<QualType> Expansions = {});
15732
15733 using UTTKind = UnaryTransformType::UTTKind;
15735 SourceLocation Loc);
15741 SourceLocation Loc);
15743 SourceLocation Loc);
15745 SourceLocation Loc);
15746
15748 return BuiltinRemoveReference(BaseType, UTTKind::RemoveCVRef, Loc);
15749 }
15750
15752 SourceLocation Loc);
15754 SourceLocation Loc);
15755
15756 bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT);
15757
15758 /// Ensure that the type T is a literal type.
15759 ///
15760 /// This routine checks whether the type @p T is a literal type. If @p T is an
15761 /// incomplete type, an attempt is made to complete it. If @p T is a literal
15762 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
15763 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
15764 /// it the type @p T), along with notes explaining why the type is not a
15765 /// literal type, and returns true.
15766 ///
15767 /// @param Loc The location in the source that the non-literal type
15768 /// diagnostic should refer to.
15769 ///
15770 /// @param T The type that this routine is examining for literalness.
15771 ///
15772 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
15773 ///
15774 /// @returns @c true if @p T is not a literal type and a diagnostic was
15775 /// emitted, @c false otherwise.
15777 TypeDiagnoser &Diagnoser);
15778 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
15779
15780 template <typename... Ts>
15781 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
15782 const Ts &...Args) {
15783 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15784 return RequireLiteralType(Loc, T, Diagnoser);
15785 }
15786
15789 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
15790 }
15791
15792 /// Ensure that the type T is a complete type.
15793 ///
15794 /// This routine checks whether the type @p T is complete in any
15795 /// context where a complete type is required. If @p T is a complete
15796 /// type, returns false. If @p T is a class template specialization,
15797 /// this routine then attempts to perform class template
15798 /// instantiation. If instantiation fails, or if @p T is incomplete
15799 /// and cannot be completed, issues the diagnostic @p diag (giving it
15800 /// the type @p T) and returns true.
15801 ///
15802 /// @param Loc The location in the source that the incomplete type
15803 /// diagnostic should refer to.
15804 ///
15805 /// @param T The type that this routine is examining for completeness.
15806 ///
15807 /// @param Kind Selects which completeness rules should be applied.
15808 ///
15809 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
15810 /// @c false otherwise.
15812 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
15814 CompleteTypeKind Kind, unsigned DiagID);
15815
15817 TypeDiagnoser &Diagnoser) {
15818 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
15819 }
15820 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
15821 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
15822 }
15823
15824 template <typename... Ts>
15825 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
15826 const Ts &...Args) {
15827 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15828 return RequireCompleteType(Loc, T, Diagnoser);
15829 }
15830
15831 /// Determine whether a declaration is visible to name lookup.
15832 bool isVisible(const NamedDecl *D) {
15833 return D->isUnconditionallyVisible() ||
15834 isAcceptableSlow(D, AcceptableKind::Visible);
15835 }
15836
15837 /// Determine whether a declaration is reachable.
15838 bool isReachable(const NamedDecl *D) {
15839 // All visible declarations are reachable.
15840 return D->isUnconditionallyVisible() ||
15841 isAcceptableSlow(D, AcceptableKind::Reachable);
15842 }
15843
15844 /// Determine whether a declaration is acceptable (visible/reachable).
15846 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
15847 }
15848
15849 /// Determine if \p D and \p Suggested have a structurally compatible
15850 /// layout as described in C11 6.2.7/1.
15851 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
15852
15853 /// Determine if \p D has a visible definition. If not, suggest a declaration
15854 /// that should be made visible to expose the definition.
15855 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
15856 bool OnlyNeedComplete = false);
15858 NamedDecl *Hidden;
15859 return hasVisibleDefinition(const_cast<NamedDecl *>(D), &Hidden);
15860 }
15861 /// Determine if \p D has a definition which allows we redefine it in current
15862 /// TU. \p Suggested is the definition that should be made visible to expose
15863 /// the definition.
15864 bool isRedefinitionAllowedFor(NamedDecl *D, SourceLocation NewDefinitionLoc,
15865 NamedDecl **Suggested, bool &Visible);
15867 bool &Visible) {
15868 NamedDecl *Hidden;
15869 return isRedefinitionAllowedFor(const_cast<NamedDecl *>(D), NewLoc, &Hidden,
15870 Visible);
15871 }
15872
15873 /// Determine if \p D has a reachable definition. If not, suggest a
15874 /// declaration that should be made reachable to expose the definition.
15875 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
15876 bool OnlyNeedComplete = false);
15878 NamedDecl *Hidden;
15879 return hasReachableDefinition(D, &Hidden);
15880 }
15881
15882 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
15883 AcceptableKind Kind,
15884 bool OnlyNeedComplete = false);
15886 NamedDecl *Hidden;
15887 return hasAcceptableDefinition(D, &Hidden, Kind);
15888 }
15889
15890 /// Determine if a definition at \p NewLoc coincides with \p PrevD.
15891 ///
15892 /// Including the same header as a non-modular and a modular allows to process
15893 /// its content twice despite guards against multiple inclusions. To handle
15894 /// such cases this method allows to detect if a currently-parsed decl is at
15895 /// the same location as an existing decl imported from a module.
15896 bool isFromSameSingleIncludeHeader(const Decl *PrevD, SourceLocation NewLoc);
15897
15898 /// Try to parse the conditional expression attached to an effect attribute
15899 /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty
15900 /// optional on error.
15901 std::optional<FunctionEffectMode>
15902 ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName);
15903
15904 void ActOnCleanupAttr(Decl *D, const Attr *A);
15905 void ActOnInitPriorityAttr(Decl *D, const Attr *A);
15906
15907private:
15908 /// The implementation of RequireCompleteType
15909 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
15910 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
15911
15912 /// Nullability type specifiers.
15913 IdentifierInfo *Ident__Nonnull = nullptr;
15914 IdentifierInfo *Ident__Nullable = nullptr;
15915 IdentifierInfo *Ident__Nullable_result = nullptr;
15916 IdentifierInfo *Ident__Null_unspecified = nullptr;
15917
15918 ///@}
15919
15920 //
15921 //
15922 // -------------------------------------------------------------------------
15923 //
15924 //
15925
15926 /// \name FixIt Helpers
15927 /// Implementations are in SemaFixItUtils.cpp
15928 ///@{
15929
15930public:
15931 /// Get a string to suggest for zero-initialization of a type.
15933 SourceLocation Loc) const;
15934 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
15935
15936 ///@}
15937
15938 //
15939 //
15940 // -------------------------------------------------------------------------
15941 //
15942 //
15943
15944 /// \name Function Effects
15945 /// Implementations are in SemaFunctionEffects.cpp
15946 ///@{
15947public:
15950
15953 std::optional<FunctionEffectWithCondition>
15954 Old; // Invalid when 'Kind' is 'Added'.
15955 std::optional<FunctionEffectWithCondition>
15956 New; // Invalid when 'Kind' is 'Removed'.
15957
15958 StringRef effectName() const {
15959 if (Old)
15960 return Old.value().Effect.name();
15961 return New.value().Effect.name();
15962 }
15963
15964 /// Describes the result of effects differing between a base class's virtual
15965 /// method and an overriding method in a subclass.
15966 enum class OverrideResult {
15969 Merge // Merge missing effect from base to derived.
15970 };
15971
15972 /// Return true if adding or removing the effect as part of a type
15973 /// conversion should generate a diagnostic.
15975 const FunctionEffectsRef &SrcFX,
15976 QualType DstType,
15977 const FunctionEffectsRef &DstFX) const;
15978
15979 /// Return true if adding or removing the effect in a redeclaration should
15980 /// generate a diagnostic.
15981 bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction,
15982 const FunctionEffectsRef &OldFX,
15983 const FunctionDecl &NewFunction,
15984 const FunctionEffectsRef &NewFX) const;
15985
15986 /// Return true if adding or removing the effect in a C++ virtual method
15987 /// override should generate a diagnostic.
15989 const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,
15990 const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const;
15991 };
15992
15993 struct FunctionEffectDiffVector : public SmallVector<FunctionEffectDiff> {
15994 /// Caller should short-circuit by checking for equality first.
15996 const FunctionEffectsRef &New);
15997 };
15998
15999 /// All functions/lambdas/blocks which have bodies and which have a non-empty
16000 /// FunctionEffectsRef to be verified.
16002
16003 /// The union of all effects present on DeclsWithEffectsToVerify. Conditions
16004 /// are all null.
16006
16007public:
16008 /// Warn and return true if adding a function effect to a set would create a
16009 /// conflict.
16012 SourceLocation NewAttrLoc);
16013
16014 // Report a failure to merge function effects between declarations due to a
16015 // conflict.
16016 void
16018 SourceLocation NewLoc,
16019 SourceLocation OldLoc);
16020
16021 /// Inline checks from the start of maybeAddDeclWithEffects, to
16022 /// minimize performance impact on code not using effects.
16023 template <class FuncOrBlockDecl>
16024 void maybeAddDeclWithEffects(FuncOrBlockDecl *D) {
16025 if (Context.hasAnyFunctionEffects())
16026 if (FunctionEffectsRef FX = D->getFunctionEffects(); !FX.empty())
16028 }
16029
16030 /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify.
16031 void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
16032
16033 /// Unconditionally add a Decl to DeclsWithEfffectsToVerify.
16034 void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
16035
16037
16038 ///@}
16039
16040 //
16041 //
16042 // -------------------------------------------------------------------------
16043 //
16044 //
16045
16046 /// \name Expansion Statements
16047 /// Implementations are in SemaExpand.cpp
16048 ///@{
16049public:
16050 CXXExpansionStmtDecl *ActOnCXXExpansionStmtDecl(unsigned TemplateDepth,
16051 SourceLocation TemplateKWLoc);
16052
16056
16058 SourceLocation LBraceLoc,
16059 SourceLocation RBraceLoc);
16060
16062 CXXExpansionStmtDecl *ESD, Stmt *Init, Stmt *ExpansionVarStmt,
16063 Expr *ExpansionInitializer, SourceLocation LParenLoc,
16064 SourceLocation ColonLoc, SourceLocation RParenLoc,
16065 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps);
16066
16067 StmtResult FinishCXXExpansionStmt(Stmt *Expansion, Stmt *Body);
16068
16070 Stmt *ExpansionVar,
16071 SourceLocation LParenLoc,
16072 SourceLocation ColonLoc,
16073 SourceLocation RParenLoc);
16074
16076 CXXExpansionStmtDecl *ESD, Stmt *Init, DeclStmt *ExpansionVarStmt,
16077 Expr *ExpansionInitializer, SourceLocation LParenLoc,
16078 SourceLocation ColonLoc, SourceLocation RParenLoc,
16079 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
16080
16081 ExprResult BuildCXXExpansionSelectExpr(InitListExpr *Range, Expr *Idx);
16082
16083 std::optional<uint64_t>
16084 ComputeExpansionSize(CXXExpansionStmtPattern *Expansion);
16085 ///@}
16086};
16087
16091
16092/// Contains a late templated function.
16093/// Will be parsed at the end of the translation unit, used by Sema & Parser.
16096 /// The template function declaration to be late parsed.
16098 /// Floating-point options in the point of definition.
16100};
16101
16102template <>
16104 PragmaMsStackAction Action,
16105 llvm::StringRef StackSlotLabel,
16107
16108} // end namespace clang
16109
16110#endif
#define V(N, I)
Forward declaration of all AST node types.
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enumerations for traits support.
Defines enum values for all the target-independent builtin functions.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines Expressions and AST nodes for C++2a concepts.
Token Tok
The Token.
FormatToken * Previous
The previous token in the unwrapped line.
static const Decl * getCanonicalDecl(const Decl *D)
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines several types used to describe C++ lambda expressions that are shared between the parser and ...
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::Module class, which describes a module in the source code.
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
llvm::json::Object Object
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
@ NotForRedeclaration
The lookup is a reference to this name that is not for the purpose of redeclaring the name.
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
AccessResult
A copy of Sema's enum without AR_delayed.
CastType
Definition SemaCast.cpp:51
static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, bool inFunctionCall, VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, bool IgnoreStringsWithoutSpecifiers)
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
Sema::AllowedExplicit AllowedExplicit
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
Defines a utilitiy for warning once when close to out of stack space.
Defines the clang::TemplateNameKind enum.
Defines the clang::TokenKind enum and support functions.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
Represents a member of a struct/union/class.
Definition Decl.h:3341
a trap message and trap category.
A class for storing results from argument-dependent lookup.
Definition Lookup.h:871
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:75
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition ASTConsumer.h:35
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Reads an AST files chain containing the contents of a translation unit.
Definition ASTReader.h:427
Writes an AST file containing the contents of a translation unit.
Definition ASTWriter.h:98
Represents an access specifier followed by colon ':'.
Definition DeclCXX.h:86
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2790
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
Attr - This represents one attribute.
Definition Attr.h:47
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3534
A binding in a decomposition declaration.
Definition DeclCXX.h:4223
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4856
[BoundsSafety] Represents a parent type class for CountAttributedType and similar sugar types that wi...
Definition TypeBase.h:3457
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ constructor within a class.
Definition DeclCXX.h:2645
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2985
Represents a C++ base or member initializer.
Definition DeclCXX.h:2410
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2631
Represents a C++ destructor within a class.
Definition DeclCXX.h:2915
Represents a C++26 expansion statement declaration.
CXXExpansionStmtPattern - Represents an unexpanded C++ expansion statement.
Definition StmtCXX.h:675
CXXFieldCollector - Used to keep track of CXXFieldDecls during parsing of C++ classes.
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:77
Represents the this expression in C++.
Definition ExprCXX.h:1159
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:70
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition Decl.h:5128
CaseStmt - Represent a case statement.
Definition Stmt.h:1931
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3745
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
Declaration of a class template.
Represents a class template specialization, which refers to a class template with a given set of temp...
Abstract interface for a consumer of code-completion information.
Declaration of a C++20 concept.
A reference to a concept and its template args, as it appears in the code.
Definition ASTConcept.h:127
Represents the specialization of a concept - evaluates to a prvalue of type bool.
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition DeclCXX.h:3715
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
The information about the darwin SDK that was used during this compilation.
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition DeclBase.h:1400
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
Captures information about "declaration specifiers".
Definition DeclSpec.h:279
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1642
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:872
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:855
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
The name of a declaration.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:782
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1996
A decomposition declaration.
Definition DeclCXX.h:4287
Captures a template argument whose value has been deduced via c++ template argument deduction.
Definition Template.h:339
A dependently-generated diagnostic.
Designation - Represent a full designation, which is a sequence of designators.
Definition Designator.h:221
A little helper class used to produce diagnostics.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:241
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3604
Represents an enum.
Definition Decl.h:4192
Store information needed for an explicit specifier.
Definition DeclCXX.h:1949
The return type of classify().
Definition Expr.h:341
This represents one expression.
Definition Expr.h:114
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:847
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
An abstract interface that should be implemented by external AST sources that also provide informatio...
virtual void ReadTentativeDefinitions(SmallVectorImpl< VarDecl * > &TentativeDefs)
Read the set of tentative definitions known to the external Sema source.
virtual void ReadUnusedFileScopedDecls(SmallVectorImpl< const DeclaratorDecl * > &Decls)
Read the set of unused file-scope declarations known to the external Sema source.
virtual void ReadExtVectorDecls(SmallVectorImpl< TypedefNameDecl * > &Decls)
Read the set of ext_vector type declarations known to the external Sema source.
virtual void ReadDelegatingConstructors(SmallVectorImpl< CXXConstructorDecl * > &Decls)
Read the set of delegating constructors known to the external Sema source.
Represents difference between two FPOptions values.
FPOptionsOverride getChangesFrom(const FPOptions &Base) const
Return difference with the given option set.
Represents a member of a struct/union/class.
Definition Decl.h:3341
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
A mapping from file IDs to a record of whether we've seen nullability information in that file.
Definition Sema.h:264
FileNullability & operator[](FileID file)
Definition Sema.h:275
FileNullability Nullability
Definition Sema.h:271
Declaration of a friend template.
Represents a function declaration or definition.
Definition Decl.h:2082
A mutable set of FunctionEffect::Kind.
Definition TypeBase.h:5402
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5516
Kind
Identifies the particular effect.
Definition TypeBase.h:5164
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5348
Represents a reference to a function parameter pack, init-capture pack, or binding pack that has been...
Definition ExprCXX.h:4895
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
Declaration of a template function.
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4770
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4744
One of these records is kept for each identifier that is lexed.
A simple pair of identifier info and location.
IdentifierResolver - Keeps track of shadowed decls on enclosing scopes.
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:626
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3648
Describes an C or C++ initializer list.
Definition Expr.h:5377
Describes the kind of initialization being performed, along with location information for tokens rela...
Describes the sequence of initializations required to initialize a given object or reference with a s...
Describes an entity that is being initialized.
Represents the declaration of a label.
Definition Decl.h:526
FPEvalMethodKind
Possible float expression evaluation method choices.
ComplexRangeKind
Controls the various implementations for complex multiplication and.
FPExceptionModeKind
Possible floating point exception behavior.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Represents a lazily-loaded vector of data.
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:377
Represents the results of name lookup.
Definition Lookup.h:147
A global _GUID constant.
Definition DeclCXX.h:4459
An instance of this class represents the declaration of a property member.
Definition DeclCXX.h:4405
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4974
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3433
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
Abstract interface for a module loader.
Describes a module or submodule.
Definition Module.h:340
bool isModulePartitionImplementation() const
Is this a module partition implementation unit.
Definition Module.h:880
Module(ModuleConstructorTag, StringRef Name, SourceLocation DefinitionLoc, Module *Parent, bool IsFramework, bool IsExplicit, unsigned VisibilityID)
Construct a new module or submodule.
Definition Module.cpp:37
bool isModuleImplementation() const
Is this a module implementation.
Definition Module.h:885
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
This represents a decl that may have a name.
Definition Decl.h:276
Represent a C++ namespace.
Definition Decl.h:594
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:8219
Wrapper for void* pointer.
Definition Ownership.h:51
static OpaquePtr make(QualType P)
Definition Ownership.h:61
OpenCL supported extensions and optional core features.
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1164
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:280
static constexpr unsigned IdxBitWidth
Definition Attr.h:282
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2251
Represents a parameter to a function.
Definition Decl.h:1832
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:958
Represents the parsed form of a C++ template argument.
void Emit(const DiagnosticBuilder &DB) const
PreferredTypeBuilder(ASTContext *Ctx, bool Enabled)
Definition Sema.h:298
void enterFunctionArgument(SourceLocation Tok, llvm::function_ref< QualType()> ComputeType)
Computing a type for the function argument may require running overloading, so we postpone its comput...
void enterCondition(Sema &S, SourceLocation Tok)
void enterTypeCast(SourceLocation Tok, QualType CastType)
Handles all type casts, including C-style cast, C++ casts, etc.
void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base)
void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS)
void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc)
void enterReturn(Sema &S, SourceLocation Tok)
void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType, const Designation &D)
Handles e.g. BaseType{ .D = Tok...
void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op)
void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc)
void enterVariableInit(SourceLocation Tok, Decl *D)
QualType get(SourceLocation Tok) const
Get the expected type associated with this location, if any.
Definition Sema.h:334
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Stores the type being destroyed by a pseudo-destructor expression.
Definition ExprCXX.h:2699
A (possibly-)qualified type.
Definition TypeBase.h:938
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
Represents a struct/union/class.
Definition Decl.h:4506
Represents the body of a requires-expression.
Definition DeclCXX.h:2122
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Smart pointer class that efficiently represents Objective-C method names.
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaBase(Sema &S)
Definition SemaBase.cpp:7
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
Definition Sema.h:1902
bool operator==(const AlignPackInfo &Info) const
Definition Sema.h:1962
static AlignPackInfo getFromRawEncoding(unsigned Encoding)
Definition Sema.h:1934
unsigned getPackNumber() const
Definition Sema.h:1952
bool IsXLStack() const
Definition Sema.h:1960
bool IsPackSet() const
Definition Sema.h:1954
AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
Definition Sema.h:1908
bool IsAlignAttr() const
Definition Sema.h:1948
bool IsPackAttr() const
Definition Sema.h:1946
bool operator!=(const AlignPackInfo &Info) const
Definition Sema.h:1968
AlignPackInfo(bool IsXL)
Definition Sema.h:1912
static uint32_t getRawEncoding(const AlignPackInfo &Info)
Definition Sema.h:1919
Mode getAlignMode() const
Definition Sema.h:1950
ArgPackSubstIndexRAII(Sema &Self, UnsignedOrNone NewSubstIndex)
Definition Sema.h:13929
ArgPackSubstIndexRAII & operator=(const ArgPackSubstIndexRAII &)=delete
ArgPackSubstIndexRAII(const ArgPackSubstIndexRAII &)=delete
BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
Definition Sema.h:8463
void diagnose(Sema &S, SourceLocation Loc, QualType T) override
Definition Sema.h:8468
void emit(const SemaDiagnosticBuilder &DB, std::index_sequence< Is... >) const
Definition Sema.h:8455
std::tuple< const Ts &... > Args
Definition Sema.h:8452
CXXThisScopeRAII(const CXXThisScopeRAII &)=delete
CXXThisScopeRAII & operator=(const CXXThisScopeRAII &)=delete
CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled=true)
Introduce a new scope where 'this' may be allowed (when enabled), using the given declaration (which ...
CompoundScopeRAII & operator=(const CompoundScopeRAII &)=delete
CompoundScopeRAII(Sema &S, bool IsStmtExpr=false)
Definition Sema.h:1342
CompoundScopeRAII(const CompoundScopeRAII &)=delete
std::pair< VarDecl *, Expr * > get() const
Definition Sema.h:8003
std::optional< bool > getKnownValue() const
Definition Sema.h:8007
A RAII object to temporarily push a declaration context.
Definition Sema.h:3639
ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext=true)
Definition Sema.h:3649
ContextRAII & operator=(const ContextRAII &)=delete
ContextRAII(const ContextRAII &)=delete
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10520
virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when the only matching conversion function is explicit.
virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when there are multiple possible conversion functions.
ContextualImplicitConverter(bool Suppress=false, bool SuppressConversion=false)
Definition Sema.h:10525
virtual bool match(QualType T)=0
Determine whether the specified type is a valid destination type for this conversion.
virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when the expression has incomplete class type.
DeferDiagsRAII(Sema &S, bool DeferDiags)
Definition Sema.h:10248
DeferDiagsRAII & operator=(const DeferDiagsRAII &)=delete
DeferDiagsRAII(const DeferDiagsRAII &)=delete
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1411
DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool)
Enter a new scope.
Definition Sema.h:1430
void popUndelayed(DelayedDiagnosticsState state)
Undo a previous pushUndelayed().
Definition Sema.h:1454
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1423
sema::DelayedDiagnosticPool * getCurrentPool() const
Returns the current delayed-diagnostics pool.
Definition Sema.h:1426
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
void popWithoutEmitting(DelayedDiagnosticsState state)
Leave a delayed-diagnostic state that was previously pushed.
Definition Sema.h:1440
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1446
A helper class for building up ExtParameterInfos.
Definition Sema.h:13293
const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams)
Return a pointer (suitable for setting in an ExtProtoInfo) to the ExtParameterInfo array we've built ...
Definition Sema.h:13312
void set(unsigned index, FunctionProtoType::ExtParameterInfo info)
Set the ExtParameterInfo for the parameter at the given index,.
Definition Sema.h:13300
FPFeaturesStateRAII(const FPFeaturesStateRAII &)=delete
FPOptionsOverride getOverrides()
Definition Sema.h:14347
FPFeaturesStateRAII & operator=(const FPFeaturesStateRAII &)=delete
FpPragmaStackSaveRAII(const FpPragmaStackSaveRAII &)=delete
FpPragmaStackSaveRAII & operator=(const FpPragmaStackSaveRAII &)=delete
FullExprArg(Sema &actions)
Definition Sema.h:7947
ExprResult release()
Definition Sema.h:7949
friend class Sema
Definition Sema.h:7958
Expr * get() const
Definition Sema.h:7951
GlobalEagerInstantiationScope(const GlobalEagerInstantiationScope &)=delete
GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
Definition Sema.h:14359
GlobalEagerInstantiationScope & operator=(const GlobalEagerInstantiationScope &)=delete
SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
Definition Sema.h:10584
virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
bool match(QualType T) override
Match an integral or (possibly scoped) enumeration type.
ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress, bool SuppressConversion)
Definition Sema.h:10576
unsigned size() const
The number of exceptions in the exception specification.
Definition Sema.h:5710
ExceptionSpecificationType getExceptionSpecType() const
Get the computed exception specification type.
Definition Sema.h:5703
const QualType * data() const
The set of exceptions in the exception specification.
Definition Sema.h:5713
void CalledStmt(Stmt *S)
Integrate an invoked statement into the collected data.
void CalledExpr(Expr *E)
Integrate an invoked expression into the collected data.
Definition Sema.h:5719
FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const
Overwrite an EPI's exception specification with this computed exception specification.
Definition Sema.h:5726
LambdaScopeForCallOperatorInstantiationRAII(Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope=true)
LocalEagerInstantiationScope & operator=(const LocalEagerInstantiationScope &)=delete
LocalEagerInstantiationScope(Sema &S, bool AtEndOfTU)
Definition Sema.h:14310
LocalEagerInstantiationScope(const LocalEagerInstantiationScope &)=delete
static NameClassification DependentNonType()
Definition Sema.h:3865
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3875
ExprResult getExpression() const
Definition Sema.h:3901
NameClassification(const IdentifierInfo *Keyword)
Definition Sema.h:3838
static NameClassification Unknown()
Definition Sema.h:3845
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3849
NameClassificationKind getKind() const
Definition Sema.h:3899
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3893
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3881
NamedDecl * getNonTypeDecl() const
Definition Sema.h:3911
NameClassification(ParsedType Type)
Definition Sema.h:3835
TemplateName getTemplateName() const
Definition Sema.h:3916
ParsedType getType() const
Definition Sema.h:3906
TemplateNameKind getTemplateNameKind() const
Definition Sema.h:3925
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3855
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3887
static NameClassification UndeclaredNonType()
Definition Sema.h:3861
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3869
static NameClassification Error()
Definition Sema.h:3841
void operator()(sema::FunctionScopeInfo *Scope) const
Definition Sema.cpp:2648
PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct)
Definition SemaAttr.cpp:29
PragmaStackSentinelRAII(const PragmaStackSentinelRAII &)=delete
PragmaStackSentinelRAII & operator=(const PragmaStackSentinelRAII &)=delete
RequiredTemplateKind(TemplateNameIsRequiredTag)
Template name is unconditionally required.
Definition Sema.h:11656
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11658
RequiredTemplateKind(SourceLocation TemplateKWLoc=SourceLocation())
Template name is required if TemplateKWLoc is valid.
Definition Sema.h:11653
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12708
SFINAETrap & operator=(const SFINAETrap &)=delete
SFINAETrap(const SFINAETrap &)=delete
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12742
SFINAETrap(Sema &S, bool WithAccessChecking=false)
Definition Sema.h:12724
bool withAccessChecking() const
Definition Sema.h:12745
sema::TemplateDeductionInfo * getDeductionInfo() const
Definition Sema.h:12737
SFINAETrap(Sema &S, sema::TemplateDeductionInfo &Info)
Definition Sema.h:12727
SatisfactionStackResetRAII(const SatisfactionStackResetRAII &)=delete
SatisfactionStackResetRAII & operator=(const SatisfactionStackResetRAII &)=delete
ScopedCodeSynthesisContext(Sema &S, const CodeSynthesisContext &Ctx)
Definition Sema.h:13856
ScopedCodeSynthesisContext & operator=(const ScopedCodeSynthesisContext &)=delete
ScopedCodeSynthesisContext(const ScopedCodeSynthesisContext &)=delete
A derivative of BoundTypeDiagnoser for which the diagnostic's type parameter is preceded by a 0/1 enu...
Definition Sema.h:8480
void diagnose(Sema &S, SourceLocation Loc, QualType T) override
Definition Sema.h:8485
SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
Definition Sema.h:8482
SpecialMemberOverloadResult(CXXMethodDecl *MD)
Definition Sema.h:9500
CXXMethodDecl * getMethod() const
Definition Sema.h:9503
void setMethod(CXXMethodDecl *MD)
Definition Sema.h:9504
void addContextNote(SourceLocation UseLoc)
Definition Sema.h:13822
SynthesizedFunctionScope(const SynthesizedFunctionScope &)=delete
SynthesizedFunctionScope(Sema &S, DeclContext *DC)
Definition Sema.h:13810
SynthesizedFunctionScope & operator=(const SynthesizedFunctionScope &)=delete
SourceLocation getLocation() const
Definition Sema.h:12466
bool ContainsDecl(const NamedDecl *ND) const
Definition Sema.h:12456
const DeclContext * getDeclContext() const
Definition Sema.h:12462
TemplateCompareNewDeclInfo(const DeclContext *DeclCtx, const DeclContext *LexicalDeclCtx, SourceLocation Loc)
Definition Sema.h:12440
const NamedDecl * getDecl() const
Definition Sema.h:12454
TemplateCompareNewDeclInfo(const NamedDecl *ND)
Definition Sema.h:12439
const DeclContext * getLexicalDeclContext() const
Definition Sema.h:12458
TentativeAnalysisScope(Sema &SemaRef)
Definition Sema.h:12759
TentativeAnalysisScope & operator=(const TentativeAnalysisScope &)=delete
TentativeAnalysisScope(const TentativeAnalysisScope &)=delete
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
VerifyICEDiagnoser(bool Suppress=false)
Definition Sema.h:7906
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:862
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
void DeclareGlobalNewDelete()
DeclareGlobalNewDelete - Declare the global forms of operator new and delete.
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo)
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const
Returns true if From is a function or pointer to a function with the cfi_unchecked_callee attribute b...
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
QualType BuildParenType(QualType T)
Build a paren type including T.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1473
bool ActOnLateParsedTypeAttrArgument(BoundsAttributedType *BATy, FieldDecl *FD, Expr *Arg)
Supply the parsed argument of a late-parsed bounds attribute to the type built for it by ProcessLateP...
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition Sema.h:3743
FunctionDecl * FindUsualDeallocationFunction(SourceLocation StartLoc, ImplicitDeallocationParameters, DeclarationName Name, bool Diagnose=true)
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc)
ActOnCXXTypeid - Parse typeid( something ).
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition Sema.h:13887
ExprResult ActOnCXXParenListInitExpr(ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn)
pragma optimize("[optimization-list]", on | off).
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraint)
DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody=nullptr)
ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc)
ActOnCXXUuidof - Parse __uuidof( something ).
bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is a constant expression represen...
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range)
CheckSpecifiedExceptionType - Check if the given type is valid in an exception specification.
ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E, UnresolvedLookupExpr *Lookup)
Build a call to 'operator co_await' if there is a suitable operator for the given expression.
ConceptDecl * ActOnStartConceptDefinition(Scope *S, MultiTemplateParamsArg TemplateParameterLists, const IdentifierInfo *Name, SourceLocation NameLoc)
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition Sema.h:8389
bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs (unless they are value dependent ...
Definition SemaAttr.cpp:546
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13871
bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base, const TypeSourceInfo *Derived)
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef< const Expr * > Args, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any non-ArgDependent DiagnoseIf...
bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum, unsigned Multiple)
BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr TheCall is a constant expr...
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From)
PerformContextuallyConvertToObjCPointer - Perform a contextual conversion of the expression From to a...
bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result)
Constructs and populates an OverloadedCandidateSet from the given function.
SmallVector< Scope *, 2 > CurrentSEHFinally
Stack of active SEH __finally scopes. Can be empty.
Definition Sema.h:11174
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13322
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2721
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1164
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls)
MergeTypedefNameDecl - We just parsed a typedef 'New' which has the same name and scope as a previous...
TemplateDeductionResult DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType, sema::TemplateDeductionInfo &Info)
Deduce the template arguments of the given template from FromType.
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S)
Register the given locally-scoped extern "C" declaration so that it can be found later for redeclarat...
friend class ASTWriter
Definition Sema.h:1616
BTFDeclTagAttr * mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL)
StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope, LabelDecl *Label, SourceLocation LabelLoc)
SmallVector< SmallVector< VTableUse, 16 >, 8 > SavedVTableUses
Definition Sema.h:14295
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
void PopParsingClass(ParsingClassState state)
Definition Sema.h:6730
void DiagnoseAbstractType(const CXXRecordDecl *RD)
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow)
Hides a using shadow declaration.
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R=nullptr, const UsingDecl *UD=nullptr)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition Sema.h:10261
void LoadExternalWeakUndeclaredIdentifiers()
Load weak undeclared identifiers from the external source.
Definition Sema.cpp:1099
bool containsUnexpandedParameterPacks(Declarator &D)
Determine whether the given declarator contains any unexpanded parameter packs.
std::optional< QualType > BuiltinVectorMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
std::optional< uint64_t > ComputeExpansionSize(CXXExpansionStmtPattern *Expansion)
bool CheckExplicitObjectOverride(CXXMethodDecl *New, const CXXMethodDecl *Old)
llvm::SmallPtrSet< SpecialMemberDecl, 4 > SpecialMembersBeingDeclared
The C++ special members which we are currently in the process of declaring.
Definition Sema.h:6719
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc)
void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc, Scope *curScope)
ActonPragmaExport - called on well-formed '#pragma export'.
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs, SmallVectorImpl< const Attr * > &OutAttrs)
Process the attributes before creating an attributed statement.
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8435
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
llvm::DenseSet< Module * > & getLookupModules()
Get the set of additional modules that should be checked during name lookup.
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
bool isAlwaysConstantEvaluatedContext() const
Definition Sema.h:8357
bool isExternalWithNoLinkageType(const ValueDecl *VD) const
Determine if VD, which must be a variable or function, is an external symbol that nonetheless can't b...
Definition Sema.cpp:967
bool isAttrContext() const
Definition Sema.h:7126
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested)
void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, const IdentifierInfo *Namespace)
ExprResult BuildBoolLiteral(SourceLocation Loc, bool Value)
Build a boolean-typed literal expression.
ExprResult IgnoredValueConversions(Expr *E)
IgnoredValueConversions - Given that an expression's result is syntactically ignored,...
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8428
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition Sema.cpp:2890
bool isFromSameSingleIncludeHeader(const Decl *PrevD, SourceLocation NewLoc)
Determine if a definition at NewLoc coincides with PrevD.
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9525
@ LookupLabel
Label name lookup.
Definition Sema.h:9534
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9529
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9556
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9548
@ LookupOMPReductionName
Look up the name of an OpenMP user-defined reduction operation.
Definition Sema.h:9570
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9564
@ LookupObjCProtocolName
Look up the name of an Objective-C protocol.
Definition Sema.h:9566
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9561
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9541
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition Sema.h:9568
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition Sema.h:9552
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9537
@ LookupDestructorName
Look up a name following ~ in a destructor name.
Definition Sema.h:9544
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9532
@ LookupOMPMapperName
Look up the name of an OpenMP user-defined mapper.
Definition Sema.h:9572
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9574
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition SemaExpr.cpp:419
llvm::DenseMap< IdentifierInfo *, SrcLocSet > IdentifierSourceLocations
Definition Sema.h:9479
UnaryTransformType::UTTKind UTTKind
Definition Sema.h:15733
bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend)
Check that the expression co_await promise.final_suspend() shall not be potentially-throwing.
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc)
BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression is uninstantiated.
void ActOnPragmaAttributePop(SourceLocation PragmaLoc, const IdentifierInfo *Namespace)
Called on well-formed '#pragma clang attribute pop'.
void ActOnPopScope(SourceLocation Loc, Scope *S)
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx, SourceLocation RBLoc)
QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement)
Completely replace the auto in TypeWithAuto by Replacement.
ExprResult ActOnConstantExpression(ExprResult Res)
void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value)
ActOnPragmaDetectMismatch - Call on well-formed #pragma detect_mismatch.
Definition SemaAttr.cpp:671
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:6464
SemaM68k & M68k()
Definition Sema.h:1523
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Decl * BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc, bool Failed)
void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD)
Evaluate the implicit exception specification for a defaulted special member function.
bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount)
Checks that a call expression's argument count is at most the desired number.
void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod)
The parsed has entered a submodule.
bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind, unsigned &IntVal)
void PrintContextStack(InstantiationContextDiagFuncRef DiagFunc)
Definition Sema.h:13941
StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef< Token > AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef< StringRef > Constraints, ArrayRef< StringRef > Clobbers, ArrayRef< Expr * > Exprs, SourceLocation EndLoc)
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E)
ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression found in an explicit(bool)...
bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum)
Returns true if the argument consists of one contiguous run of 1s with any number of 0s on either sid...
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
VarDecl * createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx)
Create a dummy variable within the declcontext of the lambda's call operator, for name lookup purpose...
bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, RecordDecl *ClassDecl, const IdentifierInfo *Name)
void ActOnFinishCXXNonNestedClass()
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body)
ActOnLambdaExpr - This is called when the body of a lambda expression was successfully completed.
ExprResult SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE, const Expr *ConstraintExpr, const MultiLevelTemplateArgumentList &MLTAL)
Substitute concept template arguments in the constraint expression of a concept-id.
std::pair< const CXXRecordDecl *, unsigned > SpecialMemberCacheKey
Definition Sema.h:9510
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
DelayedDiagnosticsState ParsingDeclState
Definition Sema.h:1406
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
NamedDecl * FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext=false)
Find the instantiation of the given declaration within the current instantiation.
bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack)
void deduceOpenCLAddressSpace(VarDecl *decl)
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
const Decl * PragmaAttributeCurrentTargetDecl
The declaration that is currently receiving an attribute from the pragma attribute stack.
Definition Sema.h:2174
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld, bool NewDeclIsDefn)
MergeFunctionDecl - We just parsed a function 'New' from declarator D which has the same name and sco...
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK)
Given a non-tag type declaration, returns an enum useful for indicating what kind of non-tag type thi...
bool hasReachableDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
MissingImportKind
Kinds of missing import.
Definition Sema.h:9965
bool isValidPointerAttrType(QualType T, bool RefOkay=false)
Determine if type T is a valid subject for a nonnull and similar attributes.
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, ImplicitDeallocationParameters, bool Diagnose=true)
ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E)
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class)
Force the declaration of any implicitly-declared members of this class.
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc, Expr *DefaultArg)
ActOnParamDefaultArgumentError - Parsing or semantic analysis of the default argument for the paramet...
bool areVectorTypesSameSize(QualType srcType, QualType destType)
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, TemplateIdAnnotation *TemplateId, bool IsMemberSpecialization)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val, SkipBodyInfo *SkipBody=nullptr)
bool hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules)
TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
ActOnTemplateParameterList - Builds a TemplateParameterList, optionally constrained by RequiresClause...
static std::enable_if_t< std::is_base_of_v< Attr, AttrInfo >, SourceLocation > getAttrLoc(const AttrInfo &AL)
A helper function to provide Attribute Location for the Attr types AND the ParsedAttr.
Definition Sema.h:5031
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
void DiagnoseStaticAssertDetails(const Expr *E)
Try to print more useful information about a failed static_assert with expression \E.
void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod)
The parser has processed a module import translated from a include or similar preprocessing directive...
RetainOwnershipKind
Definition Sema.h:5260
OpaquePtr< QualType > TypeTy
Definition Sema.h:1324
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition SemaInit.cpp:169
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
TypeSourceInfo * SubstFriendType(TypeSourceInfo *TSI, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity)
void ActOnFinishDelayedMemberInitializers(Decl *Record)
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
bool CheckCXXThisType(SourceLocation Loc, QualType Type)
Check whether the type of 'this' is valid in the current context.
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class)
Perform qualified name lookup into all base classes of the given class.
void addImplicitTypedef(StringRef Name, QualType T)
Definition Sema.cpp:371
void PrintContextStack()
Definition Sema.h:13950
void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs)
Decomposes the given name into a DeclarationNameInfo, its location, and possibly a list of template a...
bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, StringRef Keyword)
QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc)
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
StmtResult BuildAttributedStmt(SourceLocation AttrsLoc, ArrayRef< const Attr * > Attrs, Stmt *SubStmt)
Definition SemaStmt.cpp:697
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
SemaOpenMP & OpenMP()
Definition Sema.h:1558
void CheckDelegatingCtorCycles()
llvm::SmallSet< SourceLocation, 2 > SrcLocSet
Definition Sema.h:9478
void ActOnStartStmtExpr()
bool ActOnTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
llvm::function_ref< void(SourceLocation, PartialDiagnostic)> InstantiationContextDiagFuncRef
Definition Sema.h:2351
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition Sema.h:6502
bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is visible.
Definition Sema.h:9841
bool FormatStringHasSArg(const StringLiteral *FExpr)
StmtResult BuildCXXForRangeRangeVar(Scope *S, Expr *Range, QualType Type, bool IsConstexpr=false)
Build the range variable of a range-based for loop or iterating expansion statement and return its De...
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec)
Emit a warning for all pending noderef expressions that we recorded.
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis)
void ActOnStmtExprError()
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false, ArrayRef< const Expr * > StopAt={})
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
bool IsLastErrorImmediate
Is the last error level diagnostic immediate.
Definition Sema.h:1394
StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope)
bool BoundsSafetyCheckAssignmentToCountAttrPtr(QualType LHSTy, Expr *RHSExpr, AssignmentAction Action, SourceLocation Loc, const ValueDecl *Assignee, bool ShowFullyQualifiedAssigneeName)
Perform Bounds Safety Semantic checks for assigning to a __counted_by or __counted_by_or_null pointer...
void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode)
Called to set constant rounding mode for floating point operations.
llvm::DenseMap< const EnumDecl *, llvm::SmallVector< llvm::APSInt > > AssignEnumCache
A cache of enumerator values for enums checked by -Wassign-enum.
Definition Sema.h:3694
void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion)
AddAlignedAttr - Adds an aligned attribute to a particular declaration.
void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, QualType R, bool IsLambda, DeclContext *DC=nullptr)
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
AccessResult CheckFriendAccess(NamedDecl *D)
Checks access to the target of a friend declaration.
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
static const IdentifierInfo * getPrintable(const IdentifierInfo *II)
Definition Sema.h:15396
StmtResult ActOnForEachLValueExpr(Expr *E)
In an Objective C collection iteration statement: for (x in y) x can be an arbitrary l-value expressi...
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition Sema.h:1285
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition Sema.h:4933
void CheckFloatComparison(SourceLocation Loc, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1874
QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc)
Looks for the std::type_identity template and instantiates it with Type, or returns a null type if ty...
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D)
ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a C++ if/switch/while/for statem...
std::optional< FunctionEffectMode > ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName)
Try to parse the conditional expression attached to an effect attribute (e.g.
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
void NoteAllFoundTemplates(TemplateName Name)
CXXRecordDecl * createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, unsigned LambdaDependencyKind, LambdaCaptureDefault CaptureDefault)
Create a new lambda closure type.
bool hasVisibleDefinition(const NamedDecl *D)
Definition Sema.h:15857
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, const IdentifierInfo *IIEnvironment, const IdentifierInfo *InferredPlatformII=nullptr)
DelegatingCtorDeclsType DelegatingCtorDecls
All the delegating constructors seen so far in the file, used for cycle detection at the end of the T...
Definition Sema.h:6692
bool checkFunctionOrMethodParameterIndex(const Decl *D, const AttrInfo &AI, unsigned AttrArgNum, const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis=false, bool CanIndexVariadicArguments=false)
Check if IdxExpr is a valid parameter index for a function or instance method D.
Definition Sema.h:5359
void emitAndClearUnusedLocalTypedefWarnings()
Definition Sema.cpp:1213
bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs)
ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition Sema.h:6673
bool areDocumentationDiagsEnabled(SourceLocation Loc)
Returns true if any of the documentation warnings is enabled at Loc.
Definition Sema.cpp:2808
void ActOnForEachDeclStmt(DeclGroupPtrTy Decl)
Definition SemaStmt.cpp:86
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function)
TemplateName SubstTemplateName(SourceLocation TemplateKWLoc, NestedNameSpecifierLoc &QualifierLoc, TemplateName Name, SourceLocation NameLoc, const MultiLevelTemplateArgumentList &TemplateArgs)
TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, const IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc)
void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE)
AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular declaration.
bool checkSectionName(SourceLocation LiteralLoc, StringRef Str)
VarDecl * buildCoroutinePromise(SourceLocation Loc)
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition Sema.h:1274
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen)
ActOnExpressionTrait - Parsed one of the unary type trait support pseudo-functions.
SemaCUDA & CUDA()
Definition Sema.h:1498
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD)
Check a completed declaration of an implicit special member.
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A, bool SkipArgCountCheck=false)
Handles semantic checking for features that are common to all attributes, such as checking whether a ...
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
void InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Instantiate the definitions of all of the members of the given class template specialization,...
void Initialize()
Perform initialization that occurs after the parser has been initialized but before it parses anythin...
Definition Sema.cpp:377
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
Definition Sema.h:8023
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:8025
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:8024
void LateTemplateParserCB(void *P, LateParsedTemplate &LPT)
Callback to the parser to parse templated functions when needed.
Definition Sema.h:1375
void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc)
Adds the 'optnone' attribute to the function declaration if there are no conflicts; Loc represents th...
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Definition Sema.h:15816
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
static SourceRange getPrintable(SourceLocation L)
Definition Sema.h:15402
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
Decl * ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
bool needsRebuildOfDefaultArgOrInit() const
Definition Sema.h:8377
void CheckOverrideControl(NamedDecl *D)
CheckOverrideControl - Check C++11 override control semantics.
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicCallType::DoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
@ PartitionImplementation
'module X:Y;'
Definition Sema.h:10079
@ Interface
'export module X;'
Definition Sema.h:10076
@ Implementation
'module X;'
Definition Sema.h:10077
@ PartitionInterface
'export module X:Y;'
Definition Sema.h:10078
SourceLocation LocationOfExcessPrecisionNotSatisfied
Definition Sema.h:8515
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1267
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
void ActOnExitFunctionContext()
bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous)
Check ODR hashes for C/ObjC when merging types from modules.
Definition Sema.h:9788
void clearDocumentationDiagsCache()
Discard the areDocumentationDiagsEnabled() cache, for when a #pragma clang diagnostic has changed dia...
Definition Sema.cpp:2803
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition Sema.h:10603
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10606
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10612
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10610
void inferLifetimeCaptureByAttribute(FunctionDecl *FD)
Add [[clang:lifetime_capture_by(this)]] to STL container methods.
Definition SemaAttr.cpp:318
void RefersToMemberWithReducedAlignment(Expr *E, llvm::function_ref< void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action)
This function calls Action when it determines that E designates a misaligned member due to the packed...
bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType)
Definition Sema.h:1832
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
@ AR_dependent
Definition Sema.h:1717
@ AR_accessible
Definition Sema.h:1715
@ AR_inaccessible
Definition Sema.h:1716
@ AR_delayed
Definition Sema.h:1718
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
@ Normal
Apply the normal rules for complete types.
Definition Sema.h:15409
@ AcceptSizeless
Relax the normal rules for complete types so that they include sizeless built-in types.
Definition Sema.h:15413
bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA)
Check whether the given statement can have musttail applied to it, issuing a diagnostic and returning...
Definition SemaStmt.cpp:726
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc)
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
Adds a conversion function template specialization candidate to the overload set, using template argu...
Preprocessor & getPreprocessor() const
Definition Sema.h:933
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7104
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2493
StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope, LabelDecl *Label, SourceLocation LabelLoc)
QualType GetSignedSizelessVectorType(QualType V)
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of 'this' is actually available in the current context, if it is a potentially ev...
void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro, Scope *CurContext)
Once the Lambdas capture are known, we can start to create the closure, call operator method,...
ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, Expr *Operand, SourceLocation RParenLoc)
Definition SemaCast.cpp:440
void AddTemplateParametersToLambdaCallOperator(CXXMethodDecl *CallOperator, CXXRecordDecl *Class, TemplateParameterList *TemplateParams)
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
class clang::Sema::DelayedDiagnostics DelayedDiagnostics
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList)
Annotation attributes are the only attributes allowed after an access specifier.
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void AddBuiltinCandidate(QualType *ParamTys, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool IsAssignmentOperator=false, unsigned NumContextualBoolArguments=0)
AddBuiltinCandidate - Add a candidate for a built-in operator.
llvm::SmallPtrSet< ConstantExpr *, 4 > FailedImmediateInvocations
Definition Sema.h:8504
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl)
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2105
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
static SourceRange getPrintable(const Expr *E)
Definition Sema.h:15403
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2099
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope)
void AddRangeBasedOptnone(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based o...
void referenceDLLExportedClassMethods()
StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, bool IsImplicit=false)
void InstantiateLateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec &LateAttrs, LocalInstantiationScope *OuterMostScope)
Instantiate the attributes that InstantiateAttrs deferred to LateAttrs, and attach them to their decl...
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
NamedDecl * ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle)
ActOnCXXMemberDeclarator - This is invoked when a C++ class member declarator is parsed.
void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex)
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member function overrides a virtual...
DLLImportAttr * mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI)
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add function candidates found via argument-dependent lookup to the set of overloading candidates.
void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX)
Unconditionally add a Decl to DeclsWithEfffectsToVerify.
FunctionEffectKindSet AllEffectsToVerify
The union of all effects present on DeclsWithEffectsToVerify.
Definition Sema.h:16005
void setFunctionHasBranchIntoScope()
Definition Sema.cpp:2674
ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor)
ExprResult BuildCXXAssumeExpr(Expr *Assumption, const IdentifierInfo *AttrName, SourceRange Range)
ExtVectorDeclsType ExtVectorDecls
ExtVectorDecls - This is a list all the extended vector types.
Definition Sema.h:5091
ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val)
Definition SemaStmt.cpp:526
SourceLocation getOptimizeOffPragmaLocation() const
Get the location for the currently active "\#pragma clang optimizeoff". If this location is invalid,...
Definition Sema.h:2183
llvm::SmallSetVector< Expr *, 4 > MaybeODRUseExprSet
Store a set of either DeclRefExprs or MemberExprs that contain a reference to a variable (constant) t...
Definition Sema.h:6933
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, StringRef Arg)
ActOnPragmaMSComment - Called on well formed #pragma comment(kind, "arg").
Definition SemaAttr.cpp:663
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc)
Build an ext-vector type.
StmtResult BuildNonEnumeratingCXXExpansionStmtPattern(CXXExpansionStmtDecl *ESD, Stmt *Init, DeclStmt *ExpansionVarStmt, Expr *ExpansionInitializer, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation RParenLoc, ArrayRef< MaterializeTemporaryExpr * > LifetimeExtendTemps={})
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
SmallVector< AlignPackIncludeState, 8 > AlignPackIncludeStack
Definition Sema.h:2094
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec)
tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
SimplerImplicitMoveMode
Definition Sema.h:11376
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition SemaAttr.cpp:54
void PopParsingDeclaration(ParsingDeclState state, Decl *decl)
ErrorAttr * mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, StringRef NewUserDiagnostic)
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
bool CheckFormatStringsCompatible(FormatStringType FST, const StringLiteral *AuthoritativeFormatString, const StringLiteral *TestedFormatString, const Expr *FunctionCallArg=nullptr)
Verify that two format strings (as understood by attribute(format) and attribute(format_matches) are ...
void CheckMain(FunctionDecl *FD, const DeclSpec &D)
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver)
If VD is set but not otherwise used, diagnose, for a parameter or a variable.
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext)
void ActOnComment(SourceRange Comment)
Definition Sema.cpp:2843
bool IsCXXTriviallyRelocatableType(QualType T)
Determines if a type is trivially relocatable according to the C++26 rules.
ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init)
@ Other
C++26 [dcl.fct.def.general]p1 function-body: ctor-initializer[opt] compound-statement function-try-bl...
Definition Sema.h:4320
@ Default
= default ;
Definition Sema.h:4322
@ Delete
deleted-function-body
Definition Sema.h:4328
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef< QualType > ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit=nullptr)
LookupLiteralOperator - Determine which literal operator should be used for a user-defined literal,...
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc)
Looks for the std::initializer_list template and instantiates it with Element, or emits an error if i...
bool RequireStructuralType(QualType T, SourceLocation Loc)
Require the given type to be a structural type, and diagnose if it is not.
ExprResult VerifyBitField(SourceLocation FieldLoc, const IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth)
VerifyBitField - verifies that a bit field expression is an ICE and has the correct width,...
concepts::Requirement * ActOnSimpleRequirement(Expr *E)
bool CheckOverflowBehaviorTypeConversion(Expr *E, QualType T, SourceLocation CC)
Check for overflow behavior type related implicit conversion diagnostics.
llvm::function_ref< void(llvm::raw_ostream &)> EntityPrinter
Definition Sema.h:14257
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue=true)
Definition SemaStmt.cpp:49
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS)
Check whether the given variable declaration has a size that fits within the address space it is decl...
TemplateDeductionResult FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl< OriginalCallArg > const *OriginalCallArgs, bool PartialOverloading, bool PartialOrdering, bool ForOverloadSetAddressResolution, llvm::function_ref< bool(bool)> CheckNonDependent=[](bool) { return false;})
Finish template argument deduction for a function template, checking the deduced template arguments f...
void ActOnEndOfTranslationUnit()
ActOnEndOfTranslationUnit - This is called at the very end of the translation unit when EOF is reache...
Definition Sema.cpp:1294
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList *PartialSpecArgs, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
ExprResult EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, const APValue &PreNarrowingValue)
EvaluateConvertedConstantExpression - Evaluate an Expression That is a converted constant expression ...
ConceptDecl * ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C, Expr *ConstraintExpr, const ParsedAttributesView &Attrs)
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2106
void redelayDiagnostics(sema::DelayedDiagnosticPool &pool)
Given a set of delayed diagnostics, re-emit them as if they had been delayed in the current context i...
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD)
Diagnose methods which overload virtual methods in a base class without overriding any.
SemaHexagon & Hexagon()
Definition Sema.h:1513
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation=false, bool RetainFunctionScopeInfo=false)
Performs semantic analysis at the end of a function body.
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types?
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef)
Add an init-capture to a lambda scope.
concepts::Requirement * ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc)
void ActOnPragmaMSSeg(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, StringLiteral *SegmentName, llvm::StringRef PragmaName)
Called on well formed #pragma bss_seg/data_seg/const_seg/code_seg.
Definition SemaAttr.cpp:888
UsingShadowDecl * BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, NamedDecl *Target, UsingShadowDecl *PrevDecl)
Builds a shadow declaration corresponding to a 'using' declaration.
void CheckThreadLocalForLargeAlignment(VarDecl *VD)
ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth)
bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc)
bool hasVisibleExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is an explicit specialization declaration for a...
TemplateName BuildPackIndexingTemplateName(TemplateName Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< TemplateName > Expansions={})
PersonalityAttr * mergePersonalityAttr(Decl *D, FunctionDecl *Routine, const AttributeCommonInfo &CI)
bool IsInsideALocalClassWithinATemplateFunction()
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound=nullptr)
BuildOverloadedArrowExpr - Build a call to an overloaded operator-> (if one exists),...
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
void ActOnTranslationUnitScope(Scope *S)
Scope actions.
Definition Sema.cpp:173
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD, bool Diagnose, bool LookForGlobal, DeclarationName Name)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
void ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt)
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand, Expr *Awaiter, bool IsImplicit=false)
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, const Designation &Desig, SourceLocation RParenLoc)
SemaSYCL & SYCL()
Definition Sema.h:1583
bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag)
Is the given member accessible for the purposes of deciding whether to define a special member functi...
concepts::Requirement::SubstitutionDiagnostic * createSubstDiagAt(SourceLocation Location, EntityPrinter Printer)
create a Requirement::SubstitutionDiagnostic with only a SubstitutedEntity and DiagLoc using ASTConte...
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
IdentifierInfo * getSuperIdentifier() const
Definition Sema.cpp:3117
StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition Sema.h:7116
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1779
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc)
void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, PragmaFloatControlKind Value)
ActOnPragmaFloatControl - Call on well-formed #pragma float_control.
Definition SemaAttr.cpp:706
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:848
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
LateParsedTemplateMapT LateParsedTemplateMap
Definition Sema.h:11621
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
QualType CheckMatrixCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:12219
@ CTAK_DeducedFromArrayBound
The template argument was deduced from an array bound via template argument deduction.
Definition Sema.h:12230
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12222
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12226
bool SubstExprs(ArrayRef< Expr * > Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< Expr * > &Outputs)
Substitute the given template arguments into a list of expressions, expanding pack expansions if requ...
BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, const ParsedAttributesView &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
isTagName() - This method is called for error recovery purposes only to determine if the specified na...
Definition SemaDecl.cpp:689
void ActOnFinishFunctionDeclarationDeclarator(Declarator &D)
Called after parsing a function declarator belonging to a function declaration.
void ActOnPragmaMSPointersToMembers(LangOptions::PragmaMSPointersToMembersKind Kind, SourceLocation PragmaLoc)
ActOnPragmaMSPointersToMembers - called on well formed #pragma pointers_to_members(representation met...
Definition SemaAttr.cpp:760
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
[module.interface]p6: A redeclaration of an entity X is implicitly exported if X was introduced by an...
void DiagnosePrecisionLossInComplexDivision()
ExprResult CheckUnevaluatedOperand(Expr *E)
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg)
ActOnParamDefaultArgument - Check whether the default argument provided for a function parameter is w...
bool DisableTypoCorrection
Tracks whether we are in a context where typo correction is disabled.
Definition Sema.h:9473
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand)
ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
AvailabilityAttr * mergeAndInferAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, const IdentifierInfo *IIEnvironment, const IdentifierInfo *InferredPlatformII)
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
SemaX86 & X86()
Definition Sema.h:1603
void markLateParsedBoundsTypeRejected(const BoundsAttributedType *BATy)
Definition Sema.h:2603
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Look for instances where it is likely the comma operator is confused with another operator.
llvm::DenseMap< NamedDecl *, NamedDecl * > VisibleNamespaceCache
Map from the most recent declaration of a namespace to the most recent visible declaration of that na...
Definition Sema.h:13891
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def)
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
std::vector< Token > ExpandFunctionLocalPredefinedMacros(ArrayRef< Token > Toks)
StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs)
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType)
Convert a parsed type into a parsed template argument.
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry)
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind)
ASTContext & Context
Definition Sema.h:1331
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading=false)
To be used for checking whether the arguments being passed to function exceeds the number of paramete...
Definition Sema.h:8344
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition Sema.cpp:698
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
the following "Check" methods will return a valid/converted QualType or a null QualType (indicating a...
bool DiagIfReachable(SourceLocation Loc, ArrayRef< const Stmt * > Stmts, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the statements's reachability analysis.
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E)
LLVM_DECLARE_VIRTUAL_ANCHOR_FUNCTION()
This virtual key function only exists to limit the emission of debug info describing the Sema class.
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E)
Perform Bounds Safety semantic checks for uses of invalid uses counted_by or counted_by_or_null point...
void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD)
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc)
ActOnCXXNullPtrLiteral - Parse 'nullptr'.
void ActOnCapturedRegionError()
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnFinishDelayedCXXMethodDeclaration - We have finished processing the delayed method declaration f...
ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc)
Build a C++ typeid expression with a type operand.
void MarkUsedTemplateParametersForSubsumptionParameterMapping(const Expr *E, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are named in a given expression.
IdentifierSourceLocations TypoCorrectionFailures
A cache containing identifiers for which typo correction failed and their locations,...
Definition Sema.h:9484
FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC)
Definition Sema.h:7968
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:229
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, SourceLocation PragmaLoc)
ActOnPragmaUnused - Called on well-formed '#pragma unused'.
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow)
Perform conversions on the LHS of a member access expression.
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
llvm::DenseMap< IdentifierInfo *, PendingPragmaInfo > PendingExportedNames
Definition Sema.h:2393
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:931
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME)
This is not an AltiVec-style cast or or C++ direct-initialization, so turn the ParenListExpr into a s...
concepts::TypeRequirement * BuildTypeRequirement(TypeSourceInfo *Type)
void DiagnoseTypeTraitDetails(const Expr *E)
If E represents a built-in type trait, or a known standard type trait, try to print more information ...
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
void ActOnReenterFunctionPrototypeParams(Scope *S, ArrayRef< ParmVarDecl * > Params)
Add Params to scope, so a late-parsed attribute can name them.
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateName NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod)
The parser has left a submodule.
void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC, bool *ICContext=nullptr, bool IsListInit=false)
bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef< QualType > ParamTypes, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, CheckNonDependentConversionsFlag UserConversionFlag, CXXRecordDecl *ActingContext=nullptr, QualType ObjectType=QualType(), Expr::Classification ObjectClassification={}, OverloadCandidateParamOrder PO={})
Check that implicit conversion sequences can be formed for each argument whose corresponding paramete...
void * SkippedDefinitionContext
Definition Sema.h:4546
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:15781
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
bool CheckCaseExpression(Expr *E)
TypeResult ActOnPackIndexingDeducedTemplateSpecializationType(TemplateName Name, SourceLocation NameLoc)
void resetFPOptions(FPOptions FPO)
Definition Sema.h:11602
bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind)
Definition Sema.h:15885
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool FailOnPackProducingTemplates, bool &ShouldExpand, bool &RetainExpansion, UnsignedOrNone &NumExpansions, bool Diagnose=true)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument, const Decl **MalformedDecl=nullptr)
Tests whether Ty is an instance of std::type_identity and, if it is and TypeArgument is not NULL,...
bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType, bool &IncompatibleObjC)
isObjCPointerConversion - Determines whether this is an Objective-C pointer conversion.
bool currentModuleIsImplementation() const
Is the module scope we are an implementation unit?
Definition Sema.h:10062
DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path, bool IsPartition=false)
The parser has processed a module import declaration.
static bool getPrintable(bool B)
Definition Sema.h:15392
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1543
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1398
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult SubstConstraintExprWithoutSatisfaction(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, TrivialABIHandling TAH=TrivialABIHandling::IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
NamedDecl * ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams)
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain=false, bool(*IsPlausibleResult)(QualType)=nullptr)
Try to recover by turning the given expression into a call.
Definition Sema.cpp:3072
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
bool FunctionParamTypesAreEqual(ArrayRef< QualType > Old, ArrayRef< QualType > New, unsigned *ArgPos=nullptr, bool Reversed=false)
FunctionParamTypesAreEqual - This routine checks two function proto types for equality of their param...
SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags
Diagnostics that are emitted only if we discover that the given function must be codegen'ed.
Definition Sema.h:1468
TemplateName ActOnPackIndexingTemplateName(TemplateName Pattern, SourceLocation NameLoc, Expr *IndexExpr)
void CheckDelayedMemberExceptionSpecs()
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:81
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
ExprResult BuildPackIndexingExpr(Expr *PackExpression, SourceLocation EllipsisLoc, Expr *IndexExpr, SourceLocation RSquareLoc, ArrayRef< Expr * > ExpandedExprs={}, bool FullySubstituted=false)
void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs)
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc, Scope *S=nullptr)
Mark the given declaration as explicitly defaulted.
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext)
void ActOnPragmaMSAllocText(SourceLocation PragmaLocation, StringRef Section, const SmallVector< std::tuple< IdentifierInfo *, SourceLocation > > &Functions)
Called on well-formed #pragma alloc_text().
Definition SemaAttr.cpp:970
ClassTemplateDecl * StdCoroutineTraitsCache
The C++ "std::coroutine_traits" template, which is defined in <coroutine_traits>
Definition Sema.h:3313
bool captureSwiftVersionIndependentAPINotes()
Whether APINotes should be gathered for all applicable Swift language versions, without being applied...
Definition Sema.h:1698
void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Name, bool InInstantiation=false)
AddModeAttr - Adds a mode attribute to a particular declaration.
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2102
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void PrintInstantiationStack()
Definition Sema.h:13954
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
UnusedFileScopedDeclsType UnusedFileScopedDecls
The set of file scoped decls seen so far that have not been used and must warn if not used.
Definition Sema.h:3733
bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a visible default argument.
void CleanupVarDeclMarking()
bool CheckConstraintExpression(const Expr *CE, Token NextToken=Token(), bool *PossibleNonPrimary=nullptr, bool IsTrailingRequiresClause=false)
Check whether the given expression is a valid constraint expression.
ExprResult PerformImplicitObjectArgumentInitialization(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method)
PerformObjectArgumentInitialization - Perform initialization of the implicit object parameter for the...
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:769
bool isImmediateFunctionContext() const
Definition Sema.h:8369
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
ASTContext & getASTContext() const
Definition Sema.h:934
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1076
void addExternalSource(IntrusiveRefCntPtr< ExternalSemaSource > E)
Registers an external source.
Definition Sema.cpp:673
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition SemaExpr.cpp:779
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef< QualType > Params)
DeclareGlobalAllocationFunction - Declares a single implicit global allocation function if it doesn't...
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE)
If the given requirees-expression contains an unexpanded reference to one of its own parameter packs,...
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
void CheckCoroutineWrapper(FunctionDecl *FD)
bool IsFloatingPointPromotion(QualType FromType, QualType ToType)
IsFloatingPointPromotion - Determines whether the conversion from FromType to ToType is a floating po...
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition Sema.h:6699
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD)
ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool)
Definition Sema.h:1460
void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules)
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
Decl * ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc)
We have parsed the start of an export declaration, including the '{' (if present).
void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl< QualType > &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI)
Check the given exception-specification and update the exception specification information with the r...
SmallVector< std::pair< FunctionDecl *, FunctionDecl * >, 2 > DelayedEquivalentExceptionSpecChecks
All the function redeclarations seen during a class definition that had their exception spec checks d...
Definition Sema.h:6783
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
void PopExpressionEvaluationContext()
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N)
PragmaStack< StringLiteral * > ConstSegStack
Definition Sema.h:2098
StmtResult ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:774
void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc)
ActOnPragmaOptionsAlign - Called on well formed #pragma options align.
Definition SemaAttr.cpp:377
bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, const FunctionDecl *NewFunction, unsigned *ArgPos=nullptr, bool Reversed=false)
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition SemaExpr.cpp:898
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth)
Called before parsing a function declarator belonging to a function declaration.
void LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded unary operator.
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName)
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition SemaDecl.cpp:713
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2745
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, bool DoCheckConstraintSatisfaction=true)
ParsingClassState PushParsingClass()
Definition Sema.h:6726
InitSegPragmaState CurInitSeg
Definition Sema.h:2145
@ FRS_Success
Definition Sema.h:10991
@ FRS_DiagnosticIssued
Definition Sema.h:10993
@ FRS_NoViableFunction
Definition Sema.h:10992
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
void ActOnPragmaCXLimitedRange(SourceLocation Loc, LangOptions::ComplexRangeKind Range)
ActOnPragmaCXLimitedRange - Called on well formed #pragma STDC CX_LIMITED_RANGE.
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
Returns the template parameter list with all default template argument information.
void ActOnPragmaFPExceptions(SourceLocation Loc, LangOptions::FPExceptionModeKind)
Called on well formed '#pragma clang fp' that has option 'exceptions'.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition SemaAttr.cpp:112
SmallVector< LateInstantiatedAttribute, 1 > LateInstantiatedAttrVec
Definition Sema.h:14044
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr)
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
llvm::SmallVector< DeleteExprLoc, 4 > DeleteLocs
Definition Sema.h:984
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
void mergeVisibilityType(Decl *D, SourceLocation Loc, VisibilityAttr::VisibilityType Type)
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9522
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose=true)
Checks access to an overloaded operator new or delete.
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg, const DefaultArguments &DefaultArgs, SourceLocation ArgLoc, bool PartialOrdering, bool *StrictPackMatch)
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
unsigned TyposCorrected
The number of typos corrected by CorrectTypo.
Definition Sema.h:9476
bool BuiltinVectorToScalarMath(CallExpr *TheCall)
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD=nullptr, CUDAFunctionTarget CFT=CUDAFunctionTarget::InvalidTarget)
Check validaty of calling convention attribute attr.
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen)
ActOnArrayTypeTrait - Parsed one of the binary type trait support pseudo-functions.
QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType)
friend class SubstituteParameterMappings
Definition Sema.h:15317
llvm::SmallVector< QualType, 4 > CurrentParameterCopyTypes
Stack of types that correspond to the parameter entities that are currently being copy-initialized.
Definition Sema.h:9209
bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType, bool &IncompatibleObjC)
IsPointerConversion - Determines whether the conversion of the expression From, which has the (possib...
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
SmallVector< const Decl * > DeclsWithEffectsToVerify
All functions/lambdas/blocks which have bodies and which have a non-empty FunctionEffectsRef to be ve...
Definition Sema.h:16001
@ Conversions
Allow explicit conversion functions but not explicit constructors.
Definition Sema.h:10312
@ All
Allow both explicit conversion functions and explicit constructors.
Definition Sema.h:10314
void ActOnFinishRequiresExpr()
QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull)
static const unsigned MaxAlignmentExponent
The maximum alignment, same as in llvm::Value.
Definition Sema.h:1257
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMemberKind > SpecialMemberDecl
Definition Sema.h:6714
QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, std::optional< Expr * > ArraySize, SourceRange DirectInitRange, Expr *Initializer)
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
void * SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS)
Given a C++ nested-name-specifier, produce an annotation value that the parser can use later to recon...
ValueDecl * tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase)
void ProcessPragmaWeak(Scope *S, Decl *D)
void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range, DeclarationName Name, OverloadCandidateSet &CandidateSet, FunctionDecl *Fn, MultiExprArg Args, bool IsMember=false)
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, const Designation &Desig, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
NamedDecl * BuildUsingDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation, bool IsUsingIfExists)
Builds a using declaration.
bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum, llvm::APSInt &Result)
BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr TheCall is a constant expression.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1235
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
bool IsComplexPromotion(QualType FromType, QualType ToType)
Determine if a conversion is a complex promotion.
llvm::PointerUnion< const NamedDecl *, const concepts::NestedRequirement * > ConstrainedDeclOrNestedRequirement
Definition Sema.h:15188
Decl * BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy)
BuildAnonymousStructOrUnion - Handle the declaration of an anonymous structure or union.
bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template, TemplateTemplateParmDecl *Param, const TemplateArgumentLoc &Arg)
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
void ActOnPragmaFPEvalMethod(SourceLocation Loc, LangOptions::FPEvalMethodKind Value)
Definition SemaAttr.cpp:679
Module * getOwningModule(const Decl *Entity)
Get the module owning an entity.
Definition Sema.h:3756
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
FieldDecl * BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture, bool IsOpenMP=false)
Build a FieldDecl suitable to hold the given capture.
bool CheckAttrNoArgs(const ParsedAttr &CurrAttr)
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1784
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr)
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition Sema.cpp:2764
unsigned InventedParameterInfosStart
The index of the first InventedParameterInfo that refers to the current context.
Definition Sema.h:3636
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
void CheckAttributesOnDeducedType(Decl *D)
CheckAttributesOnDeducedType - Calls Sema functions for attributes that requires the type to be deduc...
void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method, std::optional< CXXRecordDecl::LambdaNumbering > NumberingOverride=std::nullopt)
Number lambda for linkage purposes if necessary.
ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, UnsignedOrNone NumExpansions)
void setFunctionHasIndirectGoto()
Definition Sema.cpp:2684
void HandleDependentAccessCheck(const DependentDiagnostic &DD, const MultiLevelTemplateArgumentList &TemplateArgs)
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
bool CheckConstraintSatisfaction(ConstrainedDeclOrNestedRequirement Entity, ArrayRef< AssociatedConstraint > AssociatedConstraints, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction, const ConceptReference *TopLevelConceptId=nullptr, Expr **ConvertedExpr=nullptr)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc)
Build a bit-precise integer type.
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition Sema.h:12398
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12416
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12406
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12426
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
NamedDecl * ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg, bool HasTypeConstraint)
ActOnTypeParameter - Called when a C++ template type parameter (e.g., "typename T") has been parsed.
SmallVectorImpl< Decl * > & WeakTopLevelDecls()
WeakTopLevelDeclDecls - access to #pragma weak-generated Decls.
Definition Sema.h:5082
EnumDecl * getStdAlignValT() const
const NormalizedConstraint * getNormalizedAssociatedConstraints(ConstrainedDeclOrNestedRequirement Entity, ArrayRef< AssociatedConstraint > AssociatedConstraints)
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1798
QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind, SourceLocation Loc)
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< TypeSourceInfo * > Types, ArrayRef< Expr * > Exprs)
ControllingExprOrType is either a TypeSourceInfo * or an Expr *.
ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping=false)
Initialize the given capture with a suitable expression.
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true, bool StrictPackMatch=false)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8546
void ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action, PragmaClangSectionKind SecKind, StringRef SecName)
ActOnPragmaClangSection - Called on well formed #pragma clang section.
Definition SemaAttr.cpp:432
bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef< Expr * > Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses)
Find the associated classes and namespaces for argument-dependent lookup for a call with the given se...
AssumedTemplateKind
Definition Sema.h:11671
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11678
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11675
bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Target, bool SkipTargetFirstParameter, SourceLocation TargetLoc, const FunctionProtoType *Source, bool SkipSourceFirstParameter, SourceLocation SourceLoc)
CheckParamExceptionSpec - Check if the parameter and return types of the two functions have equivalen...
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, OverloadCandidateParamOrder PO={})
Add a C++ member function template as a candidate to the candidate set, using template argument deduc...
bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl)
Definition SemaAttr.cpp:838
StmtResult ActOnCXXExpansionStmtPattern(CXXExpansionStmtDecl *ESD, Stmt *Init, Stmt *ExpansionVarStmt, Expr *ExpansionInitializer, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation RParenLoc, ArrayRef< MaterializeTemporaryExpr * > LifetimeExtendTemps)
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, CheckTemplateArgumentInfo &CTAI, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
MergeVarDeclTypes - We parsed a variable 'New' which has the same name and scope as a previous declar...
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg)
Compare types for equality with respect to possibly compatible function types (noreturn adjustment,...
StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body)
AtomicArgumentOrder
Definition Sema.h:2852
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2512
ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken)
Act on the result of classifying a name as a specific non-type declaration.
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, ExprResult Operand, SourceLocation RParenLoc)
Definition SemaCast.cpp:428
SourceRange getExprRange(Expr *E) const
Definition SemaExpr.cpp:516
bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS)
The parser has parsed a global nested-name-specifier '::'.
NamedReturnInfo getNamedReturnInfo(Expr *&E, SimplerImplicitMoveMode Mode=SimplerImplicitMoveMode::Normal)
Determine whether the given expression might be move-eligible or copy-elidable in either a (co_)retur...
void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind)
Called to set exception behavior for floating point operations.
bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, bool *IsCorrectedToColon=nullptr, bool OnlyNamespace=false)
The parser has parsed a nested-name-specifier 'identifier::'.
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
bool CheckFunctionReturnType(QualType T, SourceLocation Loc)
ArrayRef< InventedTemplateParameterInfo > getInventedParameterInfos() const
Definition Sema.h:11607
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:170
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitCopyConstructor - Checks for feasibility of defining this constructor as the copy const...
std::optional< ExpressionEvaluationContextRecord::InitializationContext > OutermostDeclarationWithDelayedImmediateInvocations() const
Definition Sema.h:8404
NamedDecl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool TypenameKeyword, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg)
ActOnTemplateTemplateParameter - Called when a C++ template template parameter (e....
static DeclarationName getPrintable(DeclarationName N)
Definition Sema.h:15399
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition Sema.h:4772
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id, bool IsUDSuffix)
friend class ASTReader
Definition Sema.h:1614
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
void addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI)
Add a no_cluster attribute to a particular declaration.
void addImplicitCallingConvAbiTag(FunctionDecl *FD)
Attach the ABI tag a standard calling convention variant requires, as an implicit abi_tag attribute.
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition SemaStmt.cpp:406
FPOptions & getCurFPFeatures()
Definition Sema.h:929
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition Sema.h:8498
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:278
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
sema::LambdaScopeInfo * PushLambdaScope()
Definition Sema.cpp:2530
StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E)
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
void DiagnoseUnsatisfiedRequiresExpr(const RequiresExpr *RequiresExpr, bool First=true)
void PopCompoundScope()
Definition Sema.cpp:2663
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl * > Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams, ExtParameterInfoBuilder &ParamInfos, const QualType *OldParamTypes=nullptr, bool EvaluateConstraints=true)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:15825
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, const MultiLevelTemplateArgumentList &TemplateArgs, SourceRange TemplateIDRange)
Ensure that the given template arguments satisfy the constraints associated with the given template,...
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
UnexpandedParameterPackContext
The context in which an unexpanded parameter pack is being diagnosed.
Definition Sema.h:14687
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition Sema.h:14707
@ UPPC_RequiresClause
Definition Sema.h:14758
@ UPPC_UsingDeclaration
A using declaration.
Definition Sema.h:14713
@ UPPC_IfExists
Microsoft __if_exists.
Definition Sema.h:14740
@ UPPC_Requirement
Definition Sema.h:14755
@ UPPC_ExceptionType
The type of an exception.
Definition Sema.h:14731
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14710
@ UPPC_Lambda
Lambda expression.
Definition Sema.h:14746
@ UPPC_IfNotExists
Microsoft __if_not_exists.
Definition Sema.h:14743
@ UPPC_PartialSpecialization
Partial specialization.
Definition Sema.h:14737
@ UPPC_Initializer
An initializer.
Definition Sema.h:14722
@ UPPC_BaseType
The base type of a class type.
Definition Sema.h:14692
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14716
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14725
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14695
@ UPPC_Expression
An arbitrary expression.
Definition Sema.h:14689
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14734
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14719
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14698
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition Sema.h:14704
@ UPPC_Block
Block expression.
Definition Sema.h:14749
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14701
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14728
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14752
api_notes::APINotesManager APINotes
Definition Sema.h:1335
bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low, int High, bool RangeIsError=true)
BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr TheCall is a constant express...
CXXConstructorDecl * LookupDefaultConstructor(CXXRecordDecl *Class)
Look up the default constructor for the given class.
bool IsLayoutCompatible(QualType T1, QualType T2) const
Decl * ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl, bool IsNested)
ActOnStartNamespaceDef - This is called at the start of a namespace definition.
llvm::DenseMap< Decl *, SmallVector< PartialDiagnosticAt, 1 > > SuppressedDiagnosticsMap
For each declaration that involved template argument deduction, the set of diagnostics that were supp...
Definition Sema.h:12778
void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool Mutable)
Endow the lambda scope info with the relevant properties.
const LangOptions & getLangOpts() const
Definition Sema.h:927
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void DiagnoseInvalidJumps(Stmt *Body)
bool CaptureHasSideEffects(const sema::Capture &From)
Does copying/destroying the captured variable have side effects?
llvm::PointerIntPair< Decl *, 2 > InstantiatingSpecializationsKey
Definition Sema.h:13336
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent)
DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was not used in the declaration of ...
StmtResult ActOnFinishFullStmt(Stmt *Stmt)
SmallVector< VTableUse, 16 > VTableUses
The list of vtables that are required but have not yet been materialized.
Definition Sema.h:6079
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2624
AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field)
Checks implicit access to a member in a structured binding.
void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope=true, bool LoadExternal=true)
StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, ConditionResult Cond, SourceLocation RParenLoc, Stmt *Body)
QualType CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
bool isLateParsedBoundsTypeRejected(const BoundsAttributedType *BATy) const
Definition Sema.h:2607
void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispMode Value)
Called on well formed #pragma vtordisp().
Definition SemaAttr.cpp:767
SemaCodeCompletion & CodeCompletion()
Definition Sema.h:1493
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:lifetimebound]] attr for std:: functions and methods.
Definition SemaAttr.cpp:238
ModularFormatAttr * mergeModularFormatAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *ModularImplFn, StringRef ImplName, MutableArrayRef< StringRef > Aspects)
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition Sema.h:3750
QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc)
void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, const DeclSpec &DS)
ActOnStartOfLambdaDefinition - This is called just before we start parsing the body of a lambda; it a...
SemaOpenACC & OpenACC()
Definition Sema.h:1548
void SwapSatisfactionStack(llvm::SmallVectorImpl< SatisfactionStackEntryTy > &NewSS)
Definition Sema.h:15183
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
bool ProcessLateParsedTypeAttr(LateParsedTypeAttrInfo &LA, QualType &QT)
Validate the late-parsed type attribute LA and wrap QT in a CountAttributedType with no count yet,...
ReuseLambdaContextDecl_t
Definition Sema.h:7195
@ ReuseLambdaContextDecl
Definition Sema.h:7195
void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef< CXXBaseSpecifier * > Bases)
ActOnBaseSpecifiers - Attach the given base specifiers to the class, after checking whether there are...
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr, ExceptionSpecificationType &EST)
Check the given noexcept-specifier, convert its expression, and compute the appropriate ExceptionSpec...
void MarkExpressionAsImmediateEscalating(Expr *E)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
NamedDecl * findLocallyScopedExternCDecl(DeclarationName Name)
Look for a locally scoped extern "C" declaration by the given name.
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
void ActOnLambdaClosureParameters(Scope *LambdaScope, MutableArrayRef< DeclaratorChunk::ParamInfo > ParamInfo)
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
ASTConsumer & getASTConsumer() const
Definition Sema.h:935
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
bool isUnexpandedParameterPackPermitted()
Determine whether an unexpanded parameter pack might be permitted in this location.
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc)
Produce diagnostics if FD is an aligned allocation or deallocation function that is unavailable.
SemaBPF & BPF()
Definition Sema.h:1488
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E)
Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
void * OpaqueParser
Definition Sema.h:1377
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false)
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
Preprocessor & PP
Definition Sema.h:1330
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn)
QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc)
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
bool MSPragmaOptimizeIsOn
The "on" or "off" argument passed by #pragma optimize, that denotes whether the optimizations in the ...
Definition Sema.h:2192
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool SubstTemplateArgumentsInParameterMapping(ArrayRef< TemplateArgumentLoc > Args, SourceLocation BaseLoc, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Out)
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
threadSafety::BeforeSet * ThreadSafetyDeclCache
Definition Sema.h:1372
SmallVector< PragmaAttributeGroup, 2 > PragmaAttributeStack
Definition Sema.h:2170
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
bool BuildCtorClosureDefaultArgs(SourceLocation Loc, CXXConstructorDecl *Ctor, bool IsCopy=false)
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, CXXRecordDecl *Base, CXXRecordDecl *Derived, const CXXBasePath &Path, unsigned DiagID, llvm::function_ref< void(PartialDiagnostic &PD)> SetupPDiag, bool ForceCheck=false, bool ForceUnprivileged=false)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition Sema.cpp:2299
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl)
Perform access-control checking on a previously-unresolved member access which has now been resolved ...
bool hasVisibleMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is a member specialization declaration (as oppo...
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnCXXBoolLiteral - Parse {true,false} literals.
SemaDirectX & DirectX()
Definition Sema.h:1503
llvm::SmallSetVector< const NamedDecl *, 16 > NamedDeclSetType
Definition Sema.h:6675
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization)
SemaMSP430 & MSP430()
Definition Sema.h:1533
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
friend class ASTDeclReader
Definition Sema.h:1615
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1329
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
NamedDecl * FindFirstQualifierInScope(Scope *S, NestedNameSpecifier NNS)
If the given nested-name-specifier begins with a bare identifier (e.g., Base::), perform name lookup ...
bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS)
ActOnCXXExitDeclaratorScope - Called when a declarator that previously invoked ActOnCXXEnterDeclarato...
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
bool CheckExplicitlyDefaultedPostfixOperator(Scope *S, FunctionDecl *FD, PostfixOperatorKind Kind)
Check a defaulted postfix increment or decrement operator function (C++2d [over.inc....
ExprResult PerformQualificationConversion(Expr *E, QualType Ty, ExprValueKind VK=VK_PRValue, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly=false)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType)
IsMemberPointerConversion - Determines whether the conversion of the expression From,...
std::unique_ptr< sema::FunctionScopeInfo > CachedFunctionScope
Definition Sema.h:1263
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2739
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr * > Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
static const uint64_t MaximumAlignment
Definition Sema.h:1258
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
llvm::DenseMap< unsigned, CXXDeductionGuideDecl * > AggregateDeductionCandidates
Definition Sema.h:9212
ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK)
Check the use of the given variable as a C++ condition in an if, while, do-while, or switch statement...
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS)
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:967
void ActOnStartOfCompoundStmt(bool IsStmtExpr)
Definition SemaStmt.cpp:417
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:15838
CUDAClusterDimsAttr * createClusterDimsAttr(const AttributeCommonInfo &CI, Expr *X, Expr *Y, Expr *Z)
Add a cluster_dims attribute to a particular declaration.
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6677
SemaHLSL & HLSL()
Definition Sema.h:1508
VarTemplateSpecializationDecl * CompleteVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiates a variable template specialization by completing it with appropriate type information an...
llvm::MapVector< const FunctionDecl *, std::unique_ptr< LateParsedTemplate > > LateParsedTemplateMapT
Definition Sema.h:11620
bool CollectStats
Flag indicating whether or not to collect detailed statistics.
Definition Sema.h:1261
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9521
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind)
Definition Sema.cpp:1234
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
CXXRecordDecl * getStdBadAlloc() const
ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization)
ActOnCXXTypeConstructExpr - Parse construction of a specified type.
AlwaysInlineAttr * mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident)
FieldDecl * CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D=nullptr)
Build a new FieldDecl and check its well-formedness.
ExpressionEvaluationContextRecord & currentEvaluationContext()
Definition Sema.h:7110
bool shouldRetainCommentsInAST(SourceLocation Loc)
Returns true if a comment at Loc should be retained in the AST (some consumer such as -Wdocumentation...
Definition Sema.cpp:2772
void CheckUnusedVolatileAssignment(Expr *E)
Check whether E, which is either a discarded-value expression or an unevaluated operand,...
void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst)
Update instantiation attributes after template was late parsed.
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange)
Mark the given method pure.
void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
PragmaClangSection PragmaClangRelroSection
Definition Sema.h:1875
void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1528
IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName, unsigned Index)
Invent a new identifier for parameters of abbreviated templates.
Definition Sema.cpp:140
void InstantiateVariableInitializer(VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the initializer of a variable.
void CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc, SourceLocation CallOperatorLoc, const AssociatedConstraint &TrailingRequiresClause, TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind, StorageClass SC, ArrayRef< ParmVarDecl * > Params, bool HasExplicitResultType)
CXXMethodDecl * DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit move assignment operator for the given class.
SemaRISCV & RISCV()
Definition Sema.h:1573
bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, QualType BaseType)
Checks access to Target from the given class.
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition Sema.h:16024
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
SourceLocation ImplicitMSInheritanceAttrLoc
Source location for newly created implicit MSInheritanceAttrs.
Definition Sema.h:1864
llvm::DenseMap< CXXRecordDecl *, bool > VTablesUsed
The set of classes whose vtables have been used within this translation unit, and a bit that will be ...
Definition Sema.h:6085
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *RetExpr, const AutoType *AT)
Deduce the return type for a function from a returned expression, per C++1y [dcl.spec....
ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr)
Prepare SplattedExpr for a matrix splat operation, adding implicit casts if necessary.
bool convertArgumentToType(Expr *&Value, QualType Ty)
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:218
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes, bool OrNull)
Check if applying the specified attribute variant from the "counted by" family of attributes to Field...
ComparisonCategoryUsage
Definition Sema.h:5453
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
Definition Sema.h:5456
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
Definition Sema.h:5460
@ Builtin
A builtin needed 'std::strong_ordering' (eg. '__builtin_type_order').
Definition Sema.h:5462
MemberPointerConversionDirection
Definition Sema.h:10444
SmallVector< PendingImplicitInstantiation, 1 > LateParsedInstantiations
Queue of implicit template instantiations that cannot be performed eagerly.
Definition Sema.h:14293
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6670
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc, TypeSourceInfo *TSI)
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition SemaExpr.cpp:80
ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK)
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
void performFunctionEffectAnalysis(TranslationUnitDecl *TU)
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
EltwiseBuiltinArgTyRestriction
Definition Sema.h:2918
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R)
Checks that a type is suitable as the allocated type in a new-expression.
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Diagnose cases where a scalar was implicitly converted to a vector and diagnose the underlying types.
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any ArgDependent DiagnoseIfAttr...
static StringRef getPrintable(StringRef S)
Definition Sema.h:15394
SemaSwift & Swift()
Definition Sema.h:1588
NamedDecl * BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation NameLoc, TypeSourceInfo *EnumType, EnumDecl *ED)
void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based n...
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const
PragmaStack< AlignPackInfo > AlignPackStack
Definition Sema.h:2087
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used,...
SmallVector< std::pair< const CXXMethodDecl *, const CXXMethodDecl * >, 2 > DelayedOverridingExceptionSpecChecks
All the overriding functions seen during a class definition that had their exception spec checks dela...
Definition Sema.h:6775
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7140
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6707
StmtResult ActOnExprStmtError()
Definition SemaStmt.cpp:66
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2097
ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef< TypeSourceInfo * > Args, SourceLocation RParenLoc)
const VarDecl * getCopyElisionCandidate(NamedReturnInfo &Info, QualType ReturnType)
Updates given NamedReturnInfo's move-eligible and copy-elidable statuses, considering the function re...
CXXRecordDecl * getCurrentInstantiationOf(NestedNameSpecifier NNS)
If the given nested name specifier refers to the current instantiation, return the declaration that c...
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD)
Mark the exception specifications of all virtual member functions in the given class as needed.
StmtResult BuildCXXEnumeratingExpansionStmtPattern(Decl *ESD, Stmt *Init, Stmt *ExpansionVar, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation RParenLoc)
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
void completeExprArrayBound(Expr *E)
DeclContext * getCurLexicalContext() const
Definition Sema.h:1168
std::function< TypeResult(StringRef, StringRef, SourceLocation)> ParseTypeFromStringCallback
Callback to the parser to parse a type expressed as a string.
Definition Sema.h:1386
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
llvm::StringMap< std::tuple< StringRef, SourceLocation > > FunctionToSectionMap
Sections used with pragma alloc_text.
Definition Sema.h:2148
bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, SourceLocation ColonColonLoc, CXXScopeSpec &SS)
The parser has parsed a '__super' nested-name-specifier.
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1791
bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS=nullptr)
Require that the EnumDecl is completed with its enumerators defined or instantiated.
ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, SourceLocation LParenLoc, ArrayRef< ParmVarDecl * > LocalParameters, SourceLocation RParenLoc, ArrayRef< concepts::Requirement * > Requirements, SourceLocation ClosingBraceLoc)
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr)
AddAllocAlignAttr - Adds an alloc_align attribute to a particular declaration.
bool hasExplicitCallingConv(QualType T)
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition SemaDecl.cpp:912
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro=false)
Definition SemaStmt.cpp:71
OpenCLOptions OpenCLFeatures
Definition Sema.h:1326
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs=true)
Find a merged pointer type and convert the two expressions to it.
TemplateArgument getPackSubstitutedTemplateArgument(TemplateArgument Arg) const
Definition Sema.h:12024
ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand, UnresolvedLookupExpr *Lookup)
SmallVector< std::deque< PendingImplicitInstantiation >, 8 > SavedPendingInstantiations
Definition Sema.h:14297
void MarkVirtualBaseDestructorsReferenced(SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl< const CXXRecordDecl * > *DirectVirtualBases=nullptr)
Mark destructors of virtual bases of this class referenced.
llvm::SmallSetVector< StringRef, 4 > MSFunctionNoBuiltins
Set of no-builtin functions listed by #pragma function.
Definition Sema.h:2195
ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen)
bool isRedefinitionAllowedFor(const NamedDecl *D, SourceLocation NewLoc, bool &Visible)
Definition Sema.h:15866
void ExitDeclaratorContext(Scope *S)
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value)
Checks a regparm attribute, returning true if it is ill-formed and otherwise setting numParams to the...
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition Sema.cpp:881
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir)
RecordDecl * CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams)
bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D)
Determine if we're in a case where we need to (incorrectly) eagerly parse an exception specification ...
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
bool buildCoroutineParameterMoves(SourceLocation Loc)
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
llvm::SmallSetVector< Decl *, 4 > DeclsToCheckForDeferredDiags
Function or variable declarations to be checked for whether the deferred diagnostics should be emitte...
Definition Sema.h:4948
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceRange TyLoc, const IdentifierInfo &II, ParsedType Ty, const CXXScopeSpec &SS)
DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc)
The parser has processed a global-module-fragment declaration that begins the definition of the globa...
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
UnsignedOrNone getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
ReferenceConversionsScope::ReferenceConversions ReferenceConversions
Definition Sema.h:10631
FileNullabilityMap NullabilityMap
A mapping that describes the nullability we've seen in each header file.
Definition Sema.h:15388
ProcessingContextState ParsingClassState
Definition Sema.h:6725
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
CXXRecordDecl * getCurrentClass(Scope *S, const CXXScopeSpec *SS)
Get the class that is directly named by the current context.
ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc)
Build a Microsoft __uuidof expression with a type operand.
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1366
NamedDecl * lookupExternCFunctionOrVariable(IdentifierInfo *IdentId, SourceLocation NameLoc, Scope *curScope)
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
void PushCompoundScope(bool IsStmtExpr)
Definition Sema.cpp:2658
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
MemberPointerConversionResult CheckMemberPointerConversion(QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind, CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange, bool IgnoreBaseAccess, MemberPointerConversionDirection Direction)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx, StringEvaluationContext EvalContext, bool ErrorOnInvalidMessage)
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
ExprResult ActOnCXXExpansionInitList(MultiExprArg SubExprs, SourceLocation LBraceLoc, SourceLocation RBraceLoc)
ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, StringLiteral *BinaryData, StringRef FileName)
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
bool isDeclaratorFunctionLike(Declarator &D)
Determine whether.
Definition Sema.cpp:3161
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent)
Determine whether it's plausible that E was intended to be a template-name.
Definition Sema.h:4002
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition Sema.h:2825
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15747
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
bool CheckNontrivialField(FieldDecl *FD)
void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList)
Helper for delayed processing TransparentUnion or BPFPreserveAccessIndexAttr attribute.
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
ExprResult BuildCXXAggregateDefaultInitExpr(SourceLocation Loc, FieldDecl *Field, const InitializedEntity &MemberEntity)
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr)
DiagnoseAssignmentEnum - Warn if assignment to enum is a constant integer not in the range of enum va...
bool DiagnosePackIndexingInFriendNNS(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc)
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition Sema.h:7137
ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID, const FunctionProtoType *Superset, bool SkipSupersetFirstParameter, SourceLocation SuperLoc, const FunctionProtoType *Subset, bool SkipSubsetFirstParameter, SourceLocation SubLoc)
CheckExceptionSpecSubset - Check whether the second function type's exception specification is a subs...
bool checkArrayTooLarge(QualType ElementType, const llvm::APSInt &NumElements, SourceLocation Loc, SourceRange Range=SourceRange())
Diagnose an array of NumElements elements of type ElementType that is too large.
bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypeConversion - Determines whether the conversion from FromType to ToType necessar...
ExplicitSpecifier instantiateExplicitSpecifier(const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES)
StmtResult ActOnEndOfDeferStmt(Stmt *Body, Scope *CurScope)
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
TemplateDeductionResult SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< QualType > &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info)
Substitute the explicitly-provided template arguments into the given function template according to C...
ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E)
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, UnsignedOrNone NumExpansions, bool ExpectParameterPack, bool EvaluateConstraints=true, LateInstantiatedAttrVec *LateAttrs=nullptr)
Substitute into a function parameter.
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
Check the validity of a C++ base class specifier.
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2476
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation)
type checking for vector binary operators.
QualType BuildMemberPointerType(QualType T, const CXXScopeSpec &SS, CXXRecordDecl *Cls, SourceLocation Loc, DeclarationName Entity)
Build a member pointer type T Class::*.
UnsignedOrNone getPackIndex(TemplateArgument Pack) const
Definition Sema.h:12019
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl)
The main callback when the parser finds something like expression .
ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, bool IsDefiniteInstance, const Scope *S)
Builds an implicit member access expression.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition Sema.h:13334
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val, unsigned Idx=UINT_MAX, bool StrictlyUnsigned=false)
If Expr is a valid integer constant, get the value of the integer expression and return success or fa...
Definition Sema.h:5042
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID)
Emit DiagID if statement located on StmtLoc has a suspicious null statement as a Body,...
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
std::pair< CXXRecordDecl *, SourceLocation > VTableUse
The list of classes whose vtables have been used within this translation unit, and the source locatio...
Definition Sema.h:6075
DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, ModuleIdPath Partition, ModuleImportState &ImportState, bool SeenNoTrivialPPDirective)
The parser has processed a module-declaration that begins the definition of a module interface or imp...
void MarkThisReferenced(CXXThisExpr *This)
void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody)
Warn if a for/while loop statement S, which is followed by PossibleBody, has a suspicious null statem...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:649
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model)
bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15832
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition Sema.h:8373
llvm::MapVector< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3716
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
llvm::SmallPtrSet< const BoundsAttributedType *, 1 > RejectedLateParsedBoundsTypes
Late-parsed bounds types dropped while their declarator was built.
Definition Sema.h:2601
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:10057
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD)
AddOverriddenMethods - See if a method overrides any in the base classes, and if so,...
LazyVector< TypedefNameDecl *, &ExternalSemaSource::ReadExtVectorDecls, 2, 2 > ExtVectorDeclsType
Definition Sema.h:5086
InternalLinkageAttr * mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL)
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
static bool isCast(CheckedConversionKind CCK)
Definition Sema.h:2680
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< ParsedType > ArgTypes, ArrayRef< Expr * > ArgExprs)
ControllingExprOrType is either an opaque pointer coming out of a ParsedType or an Expr *.
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
bool IsAssignConvertCompatible(AssignConvertType ConvTy)
Definition Sema.h:8240
bool hasReachableDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a reachable default argument.
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition Sema.cpp:2694
ParsedTemplateArgument ActOnTemplateTemplateArgument(const ParsedTemplateArgument &Arg)
Invoked when parsing a template argument.
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType)
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:7152
void ApplyForRangeOrExpansionStatementLifetimeExtension(VarDecl *RangeVar, ArrayRef< MaterializeTemporaryExpr * > Temporaries)
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, ADLResult &Functions)
void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl)
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition Sema.h:6684
void CheckTCBEnforcement(const SourceLocation CallExprLoc, const NamedDecl *Callee)
Enforce the bounds of a TCB CheckTCBEnforcement - Enforces that every function in a named TCB only di...
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult)
Given an expression that refers to an overloaded function, try to resolve that function to a single f...
void ActOnExitFunctionPrototypeParams(Scope *S, ArrayRef< ParmVarDecl * > Params)
Undo the above, for when S outlives the attribute so no scope pop removes them.
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1471
auto getDefaultDiagFunc()
Definition Sema.h:2353
void ActOnInitPriorityAttr(Decl *D, const Attr *A)
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
VarDecl * BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id)
Perform semantic analysis for the variable declaration that occurs within a C++ catch clause,...
bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount)
Checks that a call expression's argument count is at least the desired number.
bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypePromotion - Determines whether the conversion from FromType to ToType involves ...
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path)
Check a cast of an unknown-any type.
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc)
ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const,addrspace}_cast's.
Definition SemaCast.cpp:316
DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, SourceLocation PrivateLoc)
The parser has processed a private-module-fragment declaration that begins the definition of the priv...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition Sema.h:12779
ClassTemplateDecl * StdTypeIdentity
The C++ "std::type_identity" template, which is defined in <type_traits>.
Definition Sema.h:6703
SemaOpenCL & OpenCL()
Definition Sema.h:1553
void ActOnPragmaMSFunction(SourceLocation Loc, const llvm::SmallVectorImpl< StringRef > &NoBuiltins)
Call on well formed #pragma function.
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition Sema.h:14306
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams, SourceLocation EllipsisLoc)
Handle a friend type declaration.
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
void ActOnPragmaMSStruct(PragmaMSStructKind Kind)
ActOnPragmaMSStruct - Called on well formed #pragma ms_struct [on|off].
Definition SemaAttr.cpp:659
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool isPreciseFPEnabled()
Are precise floating point semantics currently enabled?
Definition Sema.h:2275
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
IdentifierInfo * getNullabilityKeyword(NullabilityKind nullability)
Retrieve the keyword associated.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression, SourceLocation EllipsisLoc, SourceLocation LSquareLoc, Expr *IndexExpr, SourceLocation RSquareLoc)
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp=false)
Checks access to a constructor.
static SourceRange getPrintable(TypeLoc TL)
Definition Sema.h:15404
bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation QuestionLoc)
Emit a specialized diagnostic when one expression is a null pointer constant and the other is not a p...
void ActOnStartOfDeferStmt(SourceLocation DeferLoc, Scope *CurScope)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer)
ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType)
FormatArgumentPassingKind
Definition Sema.h:2755
@ FAPK_Elsewhere
Definition Sema.h:2759
@ FAPK_Fixed
Definition Sema.h:2756
@ FAPK_Variadic
Definition Sema.h:2757
@ FAPK_VAList
Definition Sema.h:2758
void FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info)
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
CXXMethodDecl * LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals)
Look up the moving assignment operator for the given class.
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, NamedDecl *ScopeLookupResult, bool ErrorRecoveryLookup, bool *IsCorrectedToColon=nullptr, bool OnlyNamespace=false)
Build a new nested-name-specifier for "identifier::", as described by ActOnCXXNestedNameSpecifier.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8365
ObjCMethodDecl * SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl< ObjCMethodDecl * > &Methods)
llvm::DenseMap< ParmVarDecl *, llvm::TinyPtrVector< ParmVarDecl * > > UnparsedDefaultArgInstantiationsMap
Definition Sema.h:13325
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1758
StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, NamedReturnInfo &NRInfo, bool SupressSimplerImplicitMoves)
ActOnCapScopeReturnStmt - Utility routine to type-check return statements for capturing scopes.
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr, bool ForTypeDeduction=false)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
LazyVector< const DeclaratorDecl *, &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2 > UnusedFileScopedDeclsType
Definition Sema.h:3729
Stmt * MaybeCreateStmtWithCleanups(Stmt *SubStmt)
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl)
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
CXXMethodDecl * DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit copy assignment operator for the given class.
ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer)
Parsed a C++ 'new' expression (C++ 5.3.4).
CXXConstructorDecl * LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals)
Look up the moving constructor for the given class.
void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD)
Check that the C++ class annoated with "trivial_abi" satisfies all the conditions that are needed for...
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
StmtResult ActOnCapturedRegionEnd(Stmt *S)
bool ValidateBoundsAttrTypeForTypePosition(QualType Ty, AttributeCommonInfo::Kind AttrKind, SourceLocation AttrLoc, SourceRange AttrRange, unsigned PointerNestLevel, BoundsAttrFlags &Flags)
Check a counted_by-family attribute in type position and initialize Flags from AttrKind.
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
void applyFunctionAttributesBeforeParsingBody(Decl *FD)
ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen)
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
bool isAcceptable(const NamedDecl *D, AcceptableKind Kind)
Determine whether a declaration is acceptable (visible/reachable).
Definition Sema.h:15845
void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS)
Given an annotation pointer for a nested-name-specifier, restore the nested-name-specifier structure.
QualType getDecltypeForExpr(Expr *E)
getDecltypeForExpr - Given an expr, will return the decltype for that expression, according to the ru...
NamedDecl * DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II, SourceLocation Loc)
DeclClonePragmaWeak - clone existing decl (maybe definition), #pragma weak needs a non-definition dec...
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
CXXMethodDecl * LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals)
Look up the copying assignment operator for the given class.
bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint)
std::pair< const NamedDecl *, llvm::FoldingSetNodeID > SatisfactionStackEntryTy
Definition Sema.h:15159
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
void CleanupMergedEnum(Scope *S, Decl *New)
CleanupMergedEnum - We have just merged the decl 'New' by making another definition visible.
StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp)
bool GlobalNewDeleteDeclared
A flag to remember whether the implicit forms of operator new and delete have been declared.
Definition Sema.h:8557
TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a template name from a name that is syntactically required to name a template,...
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition Sema.h:3747
ExprResult CheckVarOrConceptTemplateTemplateId(const DeclarationNameInfo &NameInfo, TemplateName Template, const TemplateArgumentListInfo *TemplateArgs)
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition Sema.h:6936
ExprResult BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index, QualType ParamType, SourceLocation loc, TemplateArgument Replacement, UnsignedOrNone PackIndex, bool Final)
bool MSStructPragmaOn
Definition Sema.h:1861
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
ExprResult TransformToPotentiallyEvaluated(Expr *E)
CodeSegAttr * mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref< Scope *()> EnterScope)
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef< Expr * > Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
SectionAttr * mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, CXXConstructionKind ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
Definition Sema.h:13902
bool canSkipFunctionBody(Decl *D)
Determine whether we can skip parsing the body of a function definition, assuming we don't care about...
bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT)
Determines if we can perform a correct type check for D as a redeclaration of PrevDecl.
ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, NestedNameSpecifierLoc NNSLoc, DeclarationNameInfo DNI, const UnresolvedSetImpl &Fns, bool PerformADL=true)
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14241
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID)
Definition Sema.h:15820
SourceManager & getSourceManager() const
Definition Sema.h:932
void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod)
QualType BuiltinAddReference(QualType BaseType, UTTKind UKind, SourceLocation Loc)
void ActOnCleanupAttr(Decl *D, const Attr *A)
QualType CXXThisTypeOverride
When non-NULL, the C++ 'this' expression is allowed despite the current context not being a non-stati...
Definition Sema.h:8628
FunctionDecl * SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Substitute the name and return type of a defaulted 'operator<=>' to form an implicit 'operator=='.
static FormatStringType GetFormatStringType(StringRef FormatFlavor)
CallingConventionIgnoredReason
Describes the reason a calling convention specification was ignored, used for diagnostics.
Definition Sema.h:5020
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
bool CheckVecStepExpr(Expr *E)
bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason)
makeUnavailableInSystemHeader - There is an error in the current context.
Definition Sema.cpp:648
bool isModuleVisible(const Module *M, bool ModulePrivate=false)
void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversion=false, OverloadCandidateParamOrder PO={})
AddMethodCandidate - Adds a named decl (which is some kind of method) as a method candidate to the gi...
llvm::DenseMap< const EnumDecl *, llvm::APInt > FlagBitsCache
A cache of the flags available in enumerations with the flag_enum attribute.
Definition Sema.h:3690
bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
bool CheckRebuiltStmtAttributes(ArrayRef< const Attr * > Attrs)
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld)
Completes the merge of two function declarations that are known to be compatible.
bool hasVisibleMergedDefinition(const NamedDecl *Def)
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
void getUndefinedButUsed(SmallVectorImpl< std::pair< NamedDecl *, SourceLocation > > &Undefined)
Obtain a sorted list of functions that are undefined but ODR-used.
Definition Sema.cpp:984
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc)
Declare implicit deduction guides for a class template if we've not already done so.
void diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc, const NamedDecl *D, ArrayRef< const NamedDecl * > Equiv)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn when implicitly changing function effects.
Definition Sema.cpp:714
ClassTemplateDecl * lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc)
Lookup 'coroutine_traits' in std namespace and std::experimental namespace.
bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Definition Sema.h:12498
void PerformPendingInstantiations(bool LocalOnly=false, bool AtEndOfTU=true)
Performs template instantiation for all implicit template instantiations we have seen until this poin...
bool areMultiversionVariantFunctionsCompatible(const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer)
Checks if the variant/multiversion functions are compatible.
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value, bool SupressSimplerImplicitMoves=false)
Perform the initialization of a potentially-movable value, which is the result of return value.
bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK)
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method)
Whether this' shows up in the exception specification of a static member function.
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, ExprResult Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckVectorCompareOperands - vector comparisons are a clang extension that operates on extended vecto...
ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > TParams, SourceLocation RAngleLoc, ExprResult RequiresClause)
This is called after parsing the explicit template parameter list on a lambda (if it exists) in C++2a...
void PrintPragmaAttributeInstantiationPoint()
Definition Sema.h:2365
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, SourceLocation IncludeLoc)
Definition SemaAttr.cpp:593
Decl * ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc)
ActOnStartLinkageSpecification - Parsed the beginning of a C++ linkage specification,...
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
void FilterUsingLookup(Scope *S, LookupResult &lookup)
Remove decls we can't actually see from a lookup being used to declare shadow using decls.
bool inConstraintSubstitution() const
Determine whether we are currently performing constraint substitution.
Definition Sema.h:14246
CanThrowResult canThrow(const Stmt *E)
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
bool isThisOutsideMemberFunctionBody(QualType BaseType)
Determine whether the given type is the type of *this that is used outside of the body of a member fu...
void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, StringLiteral *DeletedMessage=nullptr, Scope *S=nullptr)
bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str)
Verify that one format string (as understood by attribute(format)) is self-consistent; for instance,...
Decl * ActOnExceptionDeclarator(Scope *S, Declarator &D)
ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch handler.
bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
StringEvaluationContext
Definition Sema.h:6195
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
CXXExpansionStmtDecl * ActOnCXXExpansionStmtDecl(unsigned TemplateDepth, SourceLocation TemplateKWLoc)
bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc)
PragmaClangSection PragmaClangTextSection
Definition Sema.h:1876
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks, ObjCInterfaceDecl *ClassReceiver)
CallExpr::ADLCallKind ADLCallKind
Definition Sema.h:7649
bool BoundsSafetyCheckInitialization(const InitializedEntity &Entity, const InitializationKind &Kind, AssignmentAction Action, QualType LHSType, Expr *RHSExpr)
Perform Bounds Safety Semantic checks for initializing a Bounds Safety pointer.
NonTrivialCUnionKind
Definition Sema.h:4259
@ NTCUK_Destruct
Definition Sema.h:4261
@ NTCUK_Init
Definition Sema.h:4260
@ NTCUK_Copy
Definition Sema.h:4262
FormatMatchesAttr * mergeFormatMatchesAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Format, int FormatIdx, StringLiteral *FormatStr)
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
DelayedDiagnosticsState ProcessingContextState
Definition Sema.h:1407
void CheckLookupAccess(const LookupResult &R)
Checks access to all the declarations in the given result set.
concepts::ExprRequirement * BuildExprRequirement(Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement)
void ActOnPragmaFPValueChangingOption(SourceLocation Loc, PragmaFPKind Kind, bool IsEnabled)
Called on well formed #pragma clang fp reassociate or #pragma clang fp reciprocal.
QualType BuildAtomicType(QualType T, SourceLocation Loc)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition Sema.h:8514
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1873
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
llvm::Error isValidSectionSpecifier(StringRef Str)
Used to implement to perform semantic checking on attribute((section("foo"))) specifiers.
LazyVector< VarDecl *, &ExternalSemaSource::ReadTentativeDefinitions, 2, 2 > TentativeDefinitionsType
Definition Sema.h:3737
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
ParsedType actOnLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init)
Perform initialization analysis of the init-capture and perform any implicit conversions such as an l...
Definition Sema.h:9313
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
CXXExpansionStmtDecl * BuildCXXExpansionStmtDecl(DeclContext *Ctx, SourceLocation TemplateKWLoc, NonTypeTemplateParmDecl *NTTP)
bool anyAltivecTypes(QualType srcType, QualType destType)
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc)
PushNamespaceVisibilityAttr - Note that we've entered a namespace with a visibility attribute.
ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, SourceLocation AsmLoc)
std::pair< AvailabilityResult, const NamedDecl * > ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message, ObjCInterfaceDecl *ClassReceiver)
The diagnostic we should emit for D, and the declaration that originated it, or AR_Available.
ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc)
Act on the result of classifying a name as an undeclared (ADL-only) non-type declaration.
StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind, ArrayRef< MaterializeTemporaryExpr * > LifetimeExtendTemps={})
ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition Sema.cpp:2524
bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX, const FunctionEffectWithCondition &EC, SourceLocation NewAttrLoc)
Warn and return true if adding a function effect to a set would create a conflict.
sema::FunctionScopeInfo * getCurFunctionAvailabilityContext()
Retrieve the current function, if any, that should be analyzed for potential availability violations.
void ActOnDefaultCtorInitializers(Decl *CDtorDecl)
void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef< CXXCtorInitializer * > MemInits, bool AnyErrors)
ActOnMemInitializers - Handle the member initializers for a constructor.
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaRedefineExtname - Called on well formed #pragma redefine_extname oldname newname.
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
PragmaStack< MSVtorDispMode > VtorDispStack
Whether to insert vtordisps prior to virtual bases in the Microsoft C++ ABI.
Definition Sema.h:2086
TypeSourceInfo * ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition SemaAttr.cpp:90
QualType CXXCheckConditionalOperands(ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc)
Check the operands of ?
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
TypeResult ActOnTypeName(Declarator &D)
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
MaybeODRUseExprSet MaybeODRUseExprs
Definition Sema.h:6934
void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro, SourceLocation MutableLoc)
ExternalSemaSource * getExternalSource() const
Definition Sema.h:937
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an initializer for the declaration ...
unsigned FunctionScopesStart
The index of the first FunctionScope that corresponds to the current context.
Definition Sema.h:1271
void * VisContext
VisContext - Manages the stack for #pragma GCC visibility.
Definition Sema.h:2151
SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const
Returns the top most location responsible for the definition of N.
bool isSFINAEContext() const
Definition Sema.h:13962
FunctionDecl * BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl, QualType AllocType, SourceLocation)
QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs=true)
Definition Sema.h:8983
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation=false)
ActOnLambdaError - If there is an error parsing a lambda, this callback is invoked to pop the informa...
static SourceRange getPrintable(SourceRange R)
Definition Sema.h:15401
void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks)
AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular declaration.
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
TopLevelStmtDecl * ActOnStartTopLevelStmtDecl(Scope *S)
concepts::Requirement * ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId)
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
UnsignedOrNone ArgPackSubstIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition Sema.h:13918
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc)
Invoked when parsing a template argument followed by an ellipsis, which creates a pack expansion.
void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II)
Try to resolve an undeclared template name as a type template.
ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, const IdentifierInfo &Name)
Handle the result of the special case name lookup for inheriting constructor declarations.
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
Decl * ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc)
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e....
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
void DiagnoseUnknownAttribute(const ParsedAttr &AL)
void PushSatisfactionStackEntry(const NamedDecl *D, const llvm::FoldingSetNodeID &ID)
Definition Sema.h:15144
ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI)
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, bool AllowRecovery=false)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15787
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, const PartialDiagnostic &PD, const FunctionDecl *FD=nullptr)
Definition Sema.h:1174
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel=0)
Definition Sema.cpp:3123
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
void ProcessPragmaExport(DeclaratorDecl *newDecl)
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void emitDeferredDiags()
Definition Sema.cpp:2162
void setFunctionHasMustTail()
Definition Sema.cpp:2689
ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType)
void checkUnusedDeclAttributes(Declarator &D)
checkUnusedDeclAttributes - Given a declarator which is not being used to build a declaration,...
bool hasReachableMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is a member specialization declaration (as op...
LabelDecl * LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc=SourceLocation(), bool IsLabelStmt=false)
LookupOrCreateLabel - Do a name lookup of a label with the specified name.
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind)
RecordDecl * CXXTypeInfoDecl
The C++ "type_info" declaration, which is defined in <typeinfo>.
Definition Sema.h:8553
bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, SourceRange FixItRange, const sema::Capture &From)
Diagnose if an explicit lambda capture is unused.
void CheckCompleteVariableDeclaration(VarDecl *VD)
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
ExprResult ActOnRequiresClause(ExprResult ConstraintExpr)
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
void PopSatisfactionStackEntry()
Definition Sema.h:15150
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class)
QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a pointer type.
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
void setFunctionHasBranchProtectedScope()
Definition Sema.cpp:2679
RedeclarationKind forRedeclarationInCurContext() const
bool hasReachableDefinition(NamedDecl *D)
Definition Sema.h:15877
void MergeVarDecl(VarDecl *New, LookupResult &Previous)
MergeVarDecl - We just parsed a variable 'New' which has the same name and scope as a previous declar...
bool isConstantEvaluatedContext() const
Definition Sema.h:2747
bool CheckAttrTarget(const ParsedAttr &CurrAttr)
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition Sema.h:6695
QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, UnsignedOrNone NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init)
StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block)
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg)
Attempt to behave like MSVC in situations where lookup of an unqualified type name has failed in a de...
Definition SemaDecl.cpp:641
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param, const MultiLevelTemplateArgumentList &TemplateArgs, bool ForCallExpr=false)
Substitute the given template arguments into the default argument.
QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc)
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
bool BuiltinElementwiseTernaryMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::FloatTy)
void ActOnStartOfTranslationUnit()
This is called before the very first declaration in the translation unit is parsed.
Definition Sema.cpp:1228
StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind, ArrayRef< MaterializeTemporaryExpr * > LifetimeExtendTemps={})
BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
friend class Parser
Definition Sema.h:1612
bool isRedefinitionAllowedFor(NamedDecl *D, SourceLocation NewDefinitionLoc, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A, SourceRange Range)
StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen)
CXXConstructorDecl * LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals)
Look up the copying constructor for the given class.
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
std::pair< StringRef, QualType > CapturedParamNameType
Definition Sema.h:11482
void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc)
void ApplyNullability(Decl *D, NullabilityKind Nullability)
Apply the 'Nullability:' annotation to the specified declaration.
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition SemaDecl.cpp:276
ExprResult SubstConstraintExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
IntrusiveRefCntPtr< ExternalSemaSource > ExternalSource
Source of additional semantic information.
Definition Sema.h:1609
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
ASTConsumer & Consumer
Definition Sema.h:1332
bool handlerCanCatch(QualType HandlerType, QualType ExceptionType)
RequiresExprBodyDecl * ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, ArrayRef< ParmVarDecl * > LocalParameters, Scope *BodyScope)
void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, bool SuppressUserConversions=false, bool PartialOverloading=false, bool FirstArgumentIsBase=false)
Add all of the function declarations in the given function set to the overload candidate set.
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand)
void ActOnFinishCXXMemberDecls()
Perform any semantic analysis which needs to be delayed until all pending class member declarations h...
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4835
bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount)
Checks that a call expression's argument count is the desired number.
void DefineDefaultedPostfixOperator(SourceLocation Loc, FunctionDecl *FD, PostfixOperatorKind Kind)
Synthesize the body of a defaulted postfix increment or decrement operator function (C++2d [over....
PragmaAlignPackDiagnoseKind
Definition Sema.h:2253
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType.
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:7144
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:128
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1371
bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg, bool PartialOrdering, bool *StrictPackMatch)
Check a template argument against its corresponding template template parameter.
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1905
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14289
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
ExprResult BuiltinShuffleVector(CallExpr *TheCall)
BuiltinShuffleVector - Handle __builtin_shufflevector.
bool CheckImplicitNullabilityTypeSpecifier(QualType &Type, NullabilityKind Nullability, SourceLocation DiagLoc, bool AllowArrayTypes, bool OverrideExisting)
Check whether a nullability type specifier can be added to the given type through some means not writ...
Decl * ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc)
ActOnFinishLinkageSpecification - Complete the definition of the C++ linkage specification LinkageSpe...
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
Definition Sema.h:10085
@ PrivateFragmentImportFinished
after 'module :private;' but a non-import decl has already been seen.
Definition Sema.h:10092
@ ImportFinished
after any non-import decl.
Definition Sema.h:10089
@ PrivateFragmentImportAllowed
after 'module :private;' but before any non-import decl.
Definition Sema.h:10090
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:10086
@ GlobalFragment
after 'module;' but before 'module X;'
Definition Sema.h:10087
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
Definition Sema.h:10094
@ ImportAllowed
after 'module X;' but before any non-import decl.
Definition Sema.h:10088
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
static QualType getPrintable(QualType T)
Definition Sema.h:15400
bool checkInstantiatedThreadSafetyAttrs(const Decl *D, const Attr *A)
Recheck instantiated thread-safety attributes that could not be validated on the dependent pattern de...
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
CUDALaunchBoundsAttr * CreateLaunchBoundsAttr(const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks, bool IgnoreArch=false)
Create a CUDALaunchBoundsAttr attribute.
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with the preprocessor.
Definition Sema.cpp:110
VarDecl * BuildForRangeVarDecl(SourceLocation Loc, QualType Type, IdentifierInfo *Name, bool IsConstexpr)
Helper used by the expansion statements and for-range code to build a variable declaration for e....
StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested)
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl)
void incrementMSManglingNumber() const
Definition Sema.h:1292
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
bool CheckDistantExceptionSpec(QualType T)
CheckDistantExceptionSpec - Check if the given type is a pointer or pointer to member to a function w...
bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, bool *CanCorrect=nullptr)
Determines whether the given declaration is an valid acceptable result for name lookup of a nested-na...
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr)
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
void AddNonMemberOperatorCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
Add all of the non-member operator function declarations in the given function set to the overload ca...
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X, Expr *Y, Expr *Z)
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition Sema.h:6878
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6900
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6890
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6905
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6895
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6915
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6884
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6910
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6925
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range)
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
unsigned LastEmittedCodeSynthesisContextDepth
The depth of the context stack at the point when the most recent error or warning was produced.
Definition Sema.h:13910
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind, SourceLocation Loc)
AvailabilityPriority
Describes the kind of priority given to an availability attribute.
Definition Sema.h:4996
@ AP_InferredFromAnyAppleOS
The availability attribute was inferred from an 'anyAppleOS' availability attribute.
Definition Sema.h:5010
@ AP_PragmaClangAttribute
The availability attribute was applied using 'pragma clang attribute'.
Definition Sema.h:5002
@ AP_InferredFromOtherPlatform
The availability attribute for a specific platform was inferred from an availability attribute for an...
Definition Sema.h:5006
@ AP_PragmaClangAttribute_InferredFromAnyAppleOS
The availability attribute was inferred from an 'anyAppleOS' availability attribute that was applied ...
Definition Sema.h:5015
@ AP_Explicit
The availability attribute was specified explicitly next to the declaration.
Definition Sema.h:4999
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Parse a __builtin_astype expression.
StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block)
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc)
std::pair< SourceLocation, bool > DeleteExprLoc
Definition Sema.h:983
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, const ParsedAttributesView &DeclAttrs, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e....
bool inParameterMappingSubstitution() const
Definition Sema.h:14251
SemaPPC & PPC()
Definition Sema.h:1563
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace)
ActOnFinishNamespaceDef - This callback is called after a namespace is exited.
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
void RecordParsingTemplateParameterDepth(unsigned Depth)
This is used to inform Sema what the current TemplateParameterDepth is during Parsing.
Definition Sema.cpp:2537
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc)
Handle a C++ member initializer.
void ActOnAfterCompoundStatementLeadingPragmas()
Definition SemaStmt.cpp:421
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition SemaStmt.cpp:76
SmallVector< Decl *, 2 > WeakTopLevelDecl
WeakTopLevelDecl - Translation-unit scoped declarations generated by #pragma weak during processing o...
Definition Sema.h:5079
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
void actOnDelayedExceptionSpecification(Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr)
Add an exception-specification to the given member or friend function (or function template).
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1290
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv=nullptr)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
void DiagnoseUnterminatedPragmaAttribute()
void FreeVisContext()
FreeVisContext - Deallocate and null out VisContext.
bool SatisfactionStackContains(const NamedDecl *D, const llvm::FoldingSetNodeID &ID) const
Definition Sema.h:15152
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
UnsignedOrNone getFullyPackExpandedSize(TemplateArgument Arg)
Given a template argument that contains an unexpanded parameter pack, but which has already been subs...
ASTContext::CXXRecordDeclRelocationInfo CheckCXX2CRelocatable(const clang::CXXRecordDecl *D)
LateTemplateParserCB * LateTemplateParser
Definition Sema.h:1376
bool CheckDependentFriend(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc, ArrayRef< TemplateParameterList * > TPLs, bool IsInstantiation)
void DiagnoseAmbiguousLookup(LookupResult &Result)
Produce a diagnostic describing the ambiguity that resulted from name lookup.
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void CheckExplicitObjectLambda(Declarator &D)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope.
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD)
Only called on function definitions; if there is a MSVC pragma optimize in scope, consider changing t...
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc)
PopPragmaVisibility - Pop the top element of the visibility stack; used for '#pragma GCC visibility' ...
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
llvm::MapVector< FieldDecl *, DeleteLocs > DeleteExprs
Delete-expressions to be analyzed at the end of translation unit.
Definition Sema.h:8564
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl)
Checks if the new declaration declared in dependent context must be put in the same redeclaration cha...
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition Sema.h:3740
static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx, unsigned FirstArg, FormatStringInfo *FSI)
Given a function and its FormatAttr or FormatMatchesAttr info, attempts to populate the FormatStringI...
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
bool DeferDiags
Whether deferrable diagnostics should be deferred.
Definition Sema.h:10240
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the initializer (and its subobjects) is sufficient for initializing the en...
QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, CallingConv CC)
Get the return type to use for a lambda's conversion function(s) to function pointer type,...
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition Sema.h:8355
SemaSystemZ & SystemZ()
Definition Sema.h:1593
DarwinSDKInfo * getDarwinSDKInfoForAvailabilityChecking()
Definition Sema.cpp:124
MultiExprArg getInitsWithEmbedExpanded(InitListExpr *ILE, SmallVectorImpl< Expr * > &Storage)
The initializers of ILE with each multi-element EmbedExpr split into one EmbedExpr per embedded eleme...
const llvm::MapVector< FieldDecl *, DeleteLocs > & getMismatchingDeleteExpressions() const
Retrieves list of suspicious delete-expressions that will be checked at the end of translation unit.
Definition Sema.cpp:3145
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind, SourceLocation Loc)
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
llvm::SmallPtrSet< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3720
static QualType getTypeOfConstantTemplateParameter(const TemplateArgument &Arg)
Determine the declared type of the constant template parameter that Arg names, if any.
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8501
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
void warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D)
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
MemberPointerConversionResult
Definition Sema.h:10436
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
static BoundsAttributedType::BoundsAttrKind getBoundsAttrKind(const BoundsAttrFlags &)
ParsedType ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS, const DeclSpec &DS, TypeSourceInfo *PatternLoc, SourceLocation ColonColonLoc, QualType Type)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
void makeModuleVisible(Module *Mod, SourceLocation ImportLoc)
Definition Sema.h:10071
bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of TheCall is a constant expression re...
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList, Stmt *SubStmt)
Definition SemaStmt.cpp:714
UuidAttr * mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl)
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true, bool *Unreachable=nullptr)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
LazyVector< CXXConstructorDecl *, &ExternalSemaSource::ReadDelegatingConstructors, 2, 2 > DelegatingCtorDeclsType
Definition Sema.h:6688
QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind, SourceLocation Loc)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition Sema.h:1334
DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs, bool SetWrittenArgs)
Get the specialization of the given variable template corresponding to the specified argument list,...
TemplateNameIsRequiredTag
Definition Sema.h:11648
@ TemplateNameIsRequired
Definition Sema.h:11648
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
NamedDecl * BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > Expansions)
MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef< Expr * > Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc)
Handle a C++ member initializer using parentheses syntax.
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc)
Called when an expression computing the size of a parameter pack is parsed.
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:798
ExprResult BuildCXXCtorDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const
Determine whether FD is an aligned allocation or deallocation function that is unavailable.
bool hasReachableExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is an explicit specialization declaration for...
Decl * BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record)
BuildMicrosoftCAnonymousStruct - Handle the declaration of an Microsoft C anonymous structure.
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, CXXScopeSpec &SS, ParsedTemplateTy *Template=nullptr)
Determine whether a particular identifier might be the name in a C++1z deduction-guide declaration.
TypeSourceInfo * SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, StringRef SlotLabel, Expr *Alignment)
ActOnPragmaPack - Called on well formed #pragma pack(...).
Definition SemaAttr.cpp:481
static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD)
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class,...
LabelDecl * GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate)
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1333
CXXMethodDecl * CreateLambdaCallOperator(SourceRange IntroducerRange, CXXRecordDecl *Class)
void DiagnoseUnterminatedPragmaAlignPack()
Definition SemaAttr.cpp:632
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition Sema.h:7972
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:928
FPOptions CurFPFeatures
Definition Sema.h:1327
void ActOnStartSEHFinallyBlock()
TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
static bool CanBeGetReturnObject(const FunctionDecl *FD)
NamespaceDecl * getStdNamespace() const
void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P)
Definition Sema.h:1379
QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc)
llvm::SmallPtrSet< const CXXRecordDecl *, 8 > RecordDeclSetTy
Definition Sema.h:6679
ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator)
void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship)
ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope)
bool IsAtLeastAsConstrained(const NamedDecl *D1, MutableArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, MutableArrayRef< AssociatedConstraint > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
bool ValidateBoundsAttrTypeShape(QualType Ty, SourceLocation AttrLoc, SourceRange AttrRange, BoundsAttrFlags &Flags, StringRef AttrSpelling={}, bool AllowRedecl=false, Expr *AttrArg=nullptr, bool UpdateFlags=true)
Check the type shape for counted_by, sized_by and their _or_null variants.
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
ExprResult BuildCXXExpansionSelectExpr(InitListExpr *Range, Expr *Idx)
void addLifetimeBoundToImplicitThis(CXXMethodDecl *MD)
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
void LoadExternalExtnameUndeclaredIdentifiers()
Load pragma redefine_extname'd undeclared identifiers from the external source.
Definition Sema.cpp:1109
QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity)
Build an array type.
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:525
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2096
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType)
Are the two types lax-compatible vector types?
NamedDecl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
friend class ConstraintSatisfactionChecker
Definition Sema.h:15316
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
Attr * CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef< Expr * > Args)
CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
Definition Sema.cpp:3184
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc, bool IsExplicit)
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
std::unique_ptr< APINotesSelectorDiagnosticState > APINotesSelectorDiagnostics
Definition Sema.h:1337
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef< ParsedType > Args, SourceLocation RParenLoc)
Parsed one of the type trait support pseudo-functions.
StmtResult FinishCXXExpansionStmt(Stmt *Expansion, Stmt *Body)
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition Sema.h:11831
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11841
@ TPC_FriendFunctionTemplate
Definition Sema.h:11839
@ TPC_ClassTemplateMember
Definition Sema.h:11837
@ TPC_FunctionTemplate
Definition Sema.h:11836
@ TPC_FriendClassTemplate
Definition Sema.h:11838
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11840
void ActOnPragmaVisibility(const IdentifierInfo *VisType, SourceLocation PragmaLoc)
ActOnPragmaVisibility - Called on well formed #pragma GCC visibility... .
void ActOnAbortSEHFinallyBlock()
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc)
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
SemaAVR & AVR()
Definition Sema.h:1483
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
friend class InitializationSequence
Definition Sema.h:1613
bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl)
Certain globally-unique variables might be accidentally duplicated if built into multiple shared libr...
void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName, IdentifierLoc *Func=nullptr)
Called on well-formed #pragma init_seg().
Definition SemaAttr.cpp:931
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
SourceLocation OptimizeOffPragmaLocation
This represents the last location of a "#pragma clang optimize off" directive if such a directive has...
Definition Sema.h:2179
bool isMainFileLoc(SourceLocation Loc) const
Determines whether the given source location is in the main file and we're in a context where we shou...
Definition Sema.cpp:976
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
void DiagnoseUnusedDecl(const NamedDecl *ND)
void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx)
bool hasAcceptableDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules, Sema::AcceptableKind Kind)
Determine if the template parameter D has a reachable default argument.
QualType BuildReadPipeType(QualType T, SourceLocation Loc)
Build a Read-only Pipe type.
void PopDeclContext()
ExprResult VerifyIntegerConstantExpression(Expr *E, AllowFoldKind CanFold=AllowFoldKind::No)
Definition Sema.h:7931
void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init)
CXXDeductionGuideDecl * DeclareAggregateDeductionGuideFromInitList(TemplateDecl *Template, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc)
bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS)
ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global scope or nested-name-specifi...
TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location)
Get a template argument mapping the given template parameter to itself, e.g.
bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD, SourceLocation Loc)
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc)
Complete a lambda-expression having processed and attached the lambda body.
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found)
Checks access to a member.
void ActOnDeferStmtError(Scope *CurScope)
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
concepts::NestedRequirement * BuildNestedRequirement(Expr *E)
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition Sema.h:6711
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition Sema.h:13882
void PrintStats() const
Print out statistics about the semantic analysis.
Definition Sema.cpp:688
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
static unsigned getPrintable(unsigned I)
Definition Sema.h:15391
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc)
Handle a C++1z fold-expression: ( expr op ... op expr ).
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod
Controls member pointer representation format under the MS ABI.
Definition Sema.h:1859
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W)
DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak applied to it,...
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
llvm::BumpPtrAllocator BumpAlloc
Definition Sema.h:1276
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
QualType BuildWritePipeType(QualType T, SourceLocation Loc)
Build a Write-only Pipe type.
void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddSurrogateCandidate - Adds a "surrogate" candidate function that converts the given Object to a fun...
SourceRange getRangeForNextToken(SourceLocation Loc, bool IncludeMacros, bool IncludeComments, std::optional< tok::TokenKind > ExpectedToken=std::nullopt)
Calls Lexer::findNextToken() to find the next token, and if the locations of both ends of the token c...
Definition Sema.cpp:89
MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs=nullptr)
BuildForRangeKind
Definition Sema.h:11268
@ BFRK_Check
Determining whether a for-range statement could be built.
Definition Sema.h:11276
@ BFRK_Build
Initial building of a for-range statement.
Definition Sema.h:11270
@ BFRK_Rebuild
Instantiation or recovery rebuild of a for-range statement.
Definition Sema.h:11273
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
SemaNVPTX & NVPTX()
Definition Sema.h:1538
void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD)
Check that VTable Pointer authentication is only being set on the first first instantiation of the vt...
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool AllowTypoCorrection=true)
StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock)
ActOnCXXCatchBlock - Takes an exception declaration and a handler block and creates a proper catch ha...
void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation, PragmaMsStackAction Action, bool Value)
ActOnPragmaMSStrictGuardStackCheck - Called on well formed #pragma strict_gs_check.
Definition SemaAttr.cpp:915
void ActOnUninitializedDecl(Decl *dcl)
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
void ApplyAPINotesType(Decl *D, StringRef TypeString)
Apply the 'Type:' annotation to the specified declaration.
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef< TemplateArgument > TemplateArgs, ConstraintSatisfaction &Satisfaction)
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction, const Expr *ThisArg, ArrayRef< const Expr * > Args)
void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt)
ActOnCaseStmtBody - This installs a statement as the body of a case.
Definition SemaStmt.cpp:626
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope)
ActOnBlockStmtExpr - This is called when the body of a block statement literal was successfully compl...
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind)
bool isUsualDeallocationFunction(const CXXMethodDecl *FD)
PragmaSectionKind
Definition Sema.h:2116
@ PSK_ConstSeg
Definition Sema.h:2119
@ PSK_DataSeg
Definition Sema.h:2117
@ PSK_CodeSeg
Definition Sema.h:2120
@ PSK_BSSSeg
Definition Sema.h:2118
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD)
Produce notes explaining why a defaulted function was defined as deleted.
bool isTagRedeclarationInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
Determine whether a tag-like declaration found by lookup can be redeclared in the given scope.
ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen)
TypeResult ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword, SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:643
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
bool CheckSpanLikeType(const AttributeCommonInfo &CI, const QualType &Ty)
Check that the type is a plain record with one field being a pointer type and the other field being a...
ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens)
Definition SemaCast.cpp:339
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition Sema.h:6501
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
ActOnField - Each field of a C struct/union is passed into this in order to create a FieldDecl object...
bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum)
BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a constant expression representing ...
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
CodeAlignAttr * BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E)
ExprResult ActOnStmtExprResult(ExprResult E)
void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate=false, VarTemplateSpecializationDecl *PrevVTSD=nullptr)
BuildVariableInstantiation - Used after a new variable has been created.
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc)
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition Sema.h:3709
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2280
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested, AcceptableKind Kind, bool OnlyNeedComplete=false)
UnsignedOrNone GetDecompositionElementCount(QualType DecompType, SourceLocation Loc)
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, bool IsMemberSpecialization, SkipBodyInfo *SkipBody=nullptr)
PragmaClangSection PragmaClangBSSSection
Definition Sema.h:1872
Decl * ActOnDeclarator(Scope *S, Declarator &D)
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
DeclarationName VAListTagName
VAListTagName - The declaration name corresponding to __va_list_tag.
Definition Sema.h:1390
QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel)
AbstractDiagSelID
Definition Sema.h:6447
@ AbstractSynthesizedIvarType
Definition Sema.h:6454
@ AbstractVariableType
Definition Sema.h:6451
@ AbstractReturnType
Definition Sema.h:6449
@ AbstractNone
Definition Sema.h:6448
@ AbstractFieldType
Definition Sema.h:6452
@ AbstractArrayType
Definition Sema.h:6455
@ AbstractParamType
Definition Sema.h:6450
@ AbstractIvarType
Definition Sema.h:6453
StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
MSPropertyDecl * HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr)
HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiate the definition of an enum from a given pattern.
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
ExprResult SubstCXXIdExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
Substitute an expression as if it is a address-of-operand, which makes it act like a CXXIdExpression ...
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
void CheckAlignasUnderalignment(Decl *D)
SemaSPIRV & SPIRV()
Definition Sema.h:1578
ParsedType getConstructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext)
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx)
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition Sema.h:8550
ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand)
Act on the result of classifying a name as an undeclared member of a dependent base class.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
void getSortedUnusedLocalTypedefNameCandidates(SmallVectorImpl< const TypedefNameDecl * > &Sorted) const
Store UnusedLocalTypedefNameCandidates in Sorted in a deterministic order.
Definition Sema.cpp:1200
ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder=AtomicArgumentOrder::API)
Decl * ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc)
Complete the definition of an export declaration.
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI)
Note that we have finished the explicit captures for the given lambda.
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind, SourceLocation Loc)
void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC)
ActOnPragmaFPContract - Called on well formed #pragma {STDC,OPENCL} FP_CONTRACT and #pragma clang fp ...
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
std::optional< ResolvedAllocation > FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, const ImplicitAllocationParameters &IAP, MultiExprArg PlaceArgs, bool Diagnose=true)
Finds the overloads of operator new and delete that are appropriate for the allocation.
llvm::DenseMap< SpecialMemberCacheKey, SpecialMemberOverloadResult > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition Sema.h:9515
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
void DiagnoseUnusedAPINotesSelectors()
Diagnose exact API notes selectors that were not matched by any declaration processed in this transla...
DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, SourceLocation EllipsisLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists, TemplateIdAnnotation *TemplateId)
Handle a friend tag declaration where the scope specifier was templated.
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc)
Called on well formed #pragma clang optimize.
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange)
ActOnUnaryExprOrTypeTraitExpr - Handle sizeof(type) and sizeof expr and the same for alignof and __al...
QualType PreferredConditionType(ConditionKind K) const
Definition Sema.h:8163
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr)
Build a call to 'begin' or 'end' for a C++11 for-range statement.
LiteralOperatorLookupResult
The possible outcomes of name lookup for a literal operator.
Definition Sema.h:9578
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition Sema.h:9582
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition Sema.h:9588
@ LOLR_Error
The lookup resulted in an error.
Definition Sema.h:9580
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition Sema.h:9585
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition Sema.h:9596
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition Sema.h:9592
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
sema::FunctionScopeInfo * getEnclosingFunction() const
Definition Sema.cpp:2709
const ExpressionEvaluationContextRecord & parentEvaluationContext() const
Definition Sema.h:7122
SemaLoongArch & LoongArch()
Definition Sema.h:1518
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
CheckConstexprKind
Definition Sema.h:6583
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6588
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6585
ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj, FunctionDecl *Fun)
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition Sema.h:14285
void CheckVariableDeclarationType(VarDecl *NewVD)
sema::CompoundScopeInfo & getCurCompoundScope() const
Definition SemaStmt.cpp:453
DeclContext * FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs)
Finds the instantiation of the given declaration context within the current instantiation.
sema::CapturedRegionScopeInfo * getCurCapturedRegion()
Retrieve the current captured region, if any.
Definition Sema.cpp:3137
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1323
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD)
Invoked when we enter a tag definition that we're skipping.
void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E)
Warn when implicitly casting 0 to nullptr.
Definition Sema.cpp:726
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E)
CheckCXXThrowOperand - Validate the operand of a throw.
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II)
Called on pragma clang __debug dump II.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled)
ActOnPragmaFenvAccess - Called on well formed #pragma STDC FENV_ACCESS.
bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New)
void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc, ArithConvKind ACK)
Check that the usual arithmetic conversions can be performed on this pair of expressions that might b...
bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Perform substitution on the base class specifiers of the given class template specialization.
void LoadExternalVTableUses()
Load any externally-stored vtable uses.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
llvm::SmallPtrSet< const NamedDecl *, 4 > TypoCorrectedFunctionDefinitions
The function definitions which were renamed as part of typo-correction to match their respective decl...
Definition Sema.h:3686
void ActOnFinishOfCompoundStmt()
Definition SemaStmt.cpp:429
concepts::Requirement * ActOnNestedRequirement(Expr *Constraint)
void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB)
Cause the built diagnostic to be emitted on the DiagosticsEngine.
Definition Sema.cpp:1804
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
Decl * ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList)
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
void AddSectionMSAllocText(FunctionDecl *FD)
Only called on function definitions; if there is a #pragma alloc_text that decides which code section...
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition Sema.h:15713
void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
AddAlignValueAttr - Adds an align_value attribute to a particular declaration.
UnsignedOrNone getNumArgumentsInExpansionFromUnexpanded(llvm::ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs)
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
static ConditionResult ConditionError()
Definition Sema.h:8009
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef< Stmt * > Elts, bool isStmtExpr)
Definition SemaStmt.cpp:457
void NoteTemplateParameterLocation(const NamedDecl &Decl)
SemaWasm & Wasm()
Definition Sema.h:1598
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ActOnConvertVectorExpr - create a new convert-vector expression from the provided arguments.
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D)
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Format, int FormatIdx, int FirstArg)
void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
Check if a method overloads virtual methods in a base class without overriding any.
IdentifierResolver IdResolver
Definition Sema.h:3632
bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo, bool EnteringContext)
IsInvalidUnlessNestedName - This method is used for error recovery purposes to determine whether the ...
llvm::DenseSet< QualType > InstantiatedNonDependentTypes
Non-dependent types used in templates that have already been instantiated by some template instantiat...
Definition Sema.h:13878
ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType)
Type-check an expression that's being passed to an __unknown_anytype parameter.
LifetimeCaptureByAttr * ParseLifetimeCaptureByAttr(const ParsedAttr &AL, StringRef ParamName)
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const
IsValueInFlagEnum - Determine if a value is allowed as part of a flag enum.
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
SemaPseudoObject & PseudoObject()
Definition Sema.h:1568
LabelDecl * LookupExistingLabel(IdentifierInfo *II, SourceLocation IdentLoc)
Perform a name lookup for a label with the specified name; this does not create a new label if the lo...
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2670
StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt)
Definition SemaStmt.cpp:654
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11613
StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef< Stmt * > Handlers)
ActOnCXXTryBlock - Takes a try compound-statement and a number of handlers and creates a try statemen...
FullExprArg MakeFullExpr(Expr *Arg)
Definition Sema.h:7965
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition SemaDecl.cpp:732
void DiagnoseSizeOfParametersAndReturnValue(ArrayRef< ParmVarDecl * > Parameters, QualType ReturnTy, NamedDecl *D)
Diagnose whether the size of parameters or return value of a function or obj-c method definition is p...
void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD, SourceLocation NameLoc)
Returns the TypeDeclType for the given type declaration, as ASTContext::getTypeDeclType would,...
Definition SemaDecl.cpp:149
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false, bool PartialOverloading=false)
Returns the more specialized function template according to the rules of function template partial or...
llvm::SmallVector< std::pair< SourceLocation, const BlockDecl * >, 1 > ImplicitlyRetainedSelfLocs
List of SourceLocations where 'self' is implicitly retained inside a block.
Definition Sema.h:8509
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1322
static int getPrintable(int I)
Definition Sema.h:15390
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply.
void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName)
Called on well formed #pragma section().
Definition SemaAttr.cpp:926
void ActOnDependentForRangeInitializer(VarDecl *LoopVar, BuildForRangeKind BFRK)
Set the type of a for-range declaration whose for-range or expansion initialiser is dependent.
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition Sema.h:9850
bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling)
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:13165
StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope)
Definition SemaStmt.cpp:631
ExprResult ActOnCXXThis(SourceLocation Loc)
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
TemplateNameKindForDiagnostics
Describes the detailed kind of a template name. Used in diagnostics.
Definition Sema.h:3988
bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy)
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument E is a ASCII string literal.
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
static const std::string & getPrintable(const std::string &S)
Definition Sema.h:15395
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
void warnOnReservedIdentifier(const NamedDecl *D)
StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, SourceLocation DotDotDotLoc, ExprResult RHS, SourceLocation ColonLoc)
Definition SemaStmt.cpp:592
TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, UnsignedOrNone &NumExpansions) const
Returns the pattern of the pack expansion for a template argument.
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, UnsignedOrNone NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
bool isCheckingDefaultArgumentOrInitializer() const
Definition Sema.h:8381
ForRangeBeginEndInfo BuildCXXForRangeBeginEndVars(Scope *S, VarDecl *RangeVar, SourceLocation ColonLoc, SourceLocation CoawaitLoc, ArrayRef< MaterializeTemporaryExpr * > LifetimeExtendTemps, BuildForRangeKind Kind, bool IsConstexpr, StmtResult *RebuildResult=nullptr, llvm::function_ref< StmtResult()> RebuildWithDereference={}, IdentifierInfo *BeginName=nullptr, IdentifierInfo *EndName=nullptr)
Determine begin-expr and end-expr and build variable declarations for them as per [stmt....
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
SFINAETrap * CurrentSFINAEContext
Definition Sema.h:13893
SemaARM & ARM()
Definition Sema.h:1478
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, SourceLocation DefaultLoc)
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined.
llvm::DenseSet< InstantiatingSpecializationsKey > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition Sema.h:13874
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:365
bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, const CXXScopeSpec &SS, const LookupResult &R)
Decl * ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList)
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
static const char * getPrintable(const char *S)
Definition Sema.h:15393
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO={})
Add overload candidates for overloaded operators that are member functions.
ExprResult ActOnDecltypeExpression(Expr *E)
Process the expression contained within a decltype.
SmallVector< std::pair< Scope *, SourceLocation >, 2 > CurrentDefer
Stack of '_Defer' statements that are currently being parsed, as well as the locations of their '_Def...
Definition Sema.h:11178
bool isAbstractType(SourceLocation Loc, QualType T)
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:669
QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a block pointer type.
PragmaMsStackAction
Definition Sema.h:1878
@ PSK_Push_Set
Definition Sema.h:1884
@ PSK_Reset
Definition Sema.h:1879
@ PSK_Pop_Set
Definition Sema.h:1885
StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body)
FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, SourceLocation Loc=SourceLocation())
Determine whether the callee of a particular function call can throw.
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers={})
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc)
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8845
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
TypeSourceInfo * SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals, bool EvaluateConstraints=true)
A form of SubstType intended specifically for instantiating the type of a FunctionDecl.
ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc)
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Definition Sema.h:13959
StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, unsigned NumLabels, SourceLocation RParenLoc)
void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod)
Create an implicit import of the given module at the given source location, for error recovery,...
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition Overload.h:301
Stmt - This represents one statement.
Definition Stmt.h:85
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1844
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3898
Exposes information about the current target.
Definition TargetInfo.h:228
A convenient class for passing around template argument information.
A template argument list.
Location wrapper for a TemplateArgument.
Represents a template argument.
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Represents a C++ template name within the type system.
Stores a list of template parameters for a TemplateDecl and its derived classes.
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
A declaration that models statements at global scope.
Definition Decl.h:4816
The top declaration context.
Definition Decl.h:107
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:224
Represents a declaration of a type.
Definition Decl.h:3694
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
A container of type source information.
Definition TypeBase.h:8549
The base class of the type hierarchy.
Definition TypeBase.h:1879
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3848
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3743
Simple class containing the result of Sema::CorrectTypo.
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1110
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3373
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4180
A set of unresolved declarations.
The iterator over UnresolvedSets.
Represents a C++ using-declaration.
Definition DeclCXX.h:3629
Represents C++ using-directive.
Definition DeclCXX.h:3134
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3437
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
Represents a variable declaration or definition.
Definition Decl.h:934
Declaration of a variable template.
Represents a variable template specialization, which refers to a variable template with a given set o...
Represents a GCC generic vector type.
Definition TypeBase.h:4398
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2888
Consumes visible declarations found when searching for all visible names within a given scope or cont...
Definition Lookup.h:838
Captures information about a #pragma weak directive.
Definition Weak.h:25
The API notes manager helps find API notes associated with declarations.
A requires-expression requirement which queries the validity and properties of an expression ('simple...
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
A static requirement that can be used in a requires-expression to check properties of types and expre...
A requires-expression requirement which queries the existence of a type name or type template special...
Retains information about a block that is currently being parsed.
Definition ScopeInfo.h:791
Retains information about a captured region.
Definition ScopeInfo.h:817
Contains information about the compound statement currently being parsed.
Definition ScopeInfo.h:67
A collection of diagnostics which were delayed.
A diagnostic message which has been conditionally emitted pending the complete parsing of the current...
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
Provides information about an attempted template argument deduction, whose success or failure was des...
#define UINT_MAX
Definition limits.h:64
Definition SPIR.cpp:47
Enums for the diagnostics of target, target_version and target_clones.
Definition Sema.h:848
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
llvm::DenseMap< int, SourceRange > ParsedSubjectMatchRuleSet
bool operator==(const ValueType &a, const ValueType &b)
void threadSafetyCleanup(BeforeSet *Cache)
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
Top level wrappers for InstallAPI frontend operations.
PragmaClangSectionAction
Definition Sema.h:469
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:56
ImplicitTypenameContext
Definition DeclSpec.h:1979
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
OverloadKind
Definition Sema.h:816
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:827
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:823
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:819
bool isa(CodeGen::Address addr)
Definition Address.h:330
OpaquePtr< TemplateName > ParsedTemplateTy
Definition Ownership.h:256
@ CPlusPlus
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
VariadicCallType
Definition Sema.h:506
FunctionEffectMode
Used with attributes/effects with a boolean condition, e.g. nonblocking.
Definition Sema.h:452
CUDAFunctionTarget
Definition Cuda.h:65
CanThrowResult
Possible results from evaluation of a noexcept expression.
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
AllocationFunctionScope
The scope in which to find allocation functions.
Definition Sema.h:784
@ Both
Look for allocation functions in both the global scope and in the scope of the allocated class.
Definition Sema.h:792
PragmaMSCommentKind
Definition PragmaKinds.h:14
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:36
ArrayRef< IdentifierLoc > ModuleIdPath
A sequence of identifier/location pairs used to describe a particular module or submodule,...
TryCaptureKind
Definition Sema.h:646
IfStatementKind
In an if statement, this denotes whether the statement is a constexpr or consteval if statement.
Definition Specifiers.h:40
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition Sema.h:654
@ BitwiseOp
A bitwise operation.
Definition Sema.h:658
@ Arithmetic
An arithmetic operation.
Definition Sema.h:656
@ Conditional
A conditional (?:) operator.
Definition Sema.h:662
@ CompAssign
A compound assignment expression.
Definition Sema.h:664
@ Comparison
A comparison.
Definition Sema.h:660
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:350
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:275
@ Success
Annotation was successful.
Definition Parser.h:65
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
CXXConstructionKind
Definition ExprCXX.h:1545
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:153
PointerAuthDiscArgKind
Definition Sema.h:587
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:597
@ TemplateTemplateArgument
Definition Sema.h:606
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition Overload.h:84
NonTrivialCUnionContext
Definition Sema.h:525
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition Sema.h:621
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:629
@ OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition Sema.h:635
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:626
@ ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition Sema.h:632
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:242
@ Private
'private' clause, allowed on 'parallel', 'serial', 'loop', 'parallel loop', and 'serial loop' constru...
TypeOfKind
The kind of 'typeof' expression we're after.
Definition TypeBase.h:919
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:127
@ AS_none
Definition Specifiers.h:131
LazyOffsetPtr< Decl, GlobalDeclID, &ExternalASTSource::GetExternalDecl > LazyDeclPtr
A lazy pointer to a declaration.
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
CapturedRegionKind
The different kinds of captured statement.
StorageClass
Storage classes.
Definition Specifiers.h:252
void inferNoReturnAttr(Sema &S, Decl *D)
llvm::MutableArrayRef< ImplicitConversionSequence > ConversionSequenceList
A list of implicit conversion sequences for the arguments of an OverloadCandidate.
Definition Overload.h:933
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
bool isFunctionOrMethodOrBlockForAttrSubject(const Decl *D)
Return true if the given decl has function type (function or function-typed variable) or an Objective...
Definition Attr.h:41
OverloadCandidateRewriteKind
The kinds of rewrite we perform on overload candidates.
Definition Overload.h:89
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
LambdaCaptureInitKind
Definition DeclSpec.h:2932
@ CopyInit
[a = b], [a = {b}]
Definition DeclSpec.h:2934
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
@ AANT_ArgumentIntegerConstant
PragmaOptionsAlignKind
Definition Sema.h:471
@ Undefined
Keep undefined.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OffsetOfKind
Definition Sema.h:609
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3817
SmallVector< ImplicitAllocationArguments, 3 > AllocationArgumentSet
Definition Sema.h:229
CorrectTypoKind
Definition Sema.h:811
ActionResult< CXXCtorInitializer * > MemInitResult
Definition Ownership.h:253
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
bool isFunctionOrMethodVariadic(const Decl *D)
Definition Attr.h:150
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:682
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:705
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition Sema.h:780
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition Sema.h:697
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition Sema.h:752
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition Sema.h:742
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition Sema.h:769
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition Sema.h:756
@ CompatibleOBTDiscards
CompatibleOBTDiscards - Assignment discards overflow behavior.
Definition Sema.h:776
@ IncompatibleOBTKinds
IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType kinds, e....
Definition Sema.h:773
@ CompatibleVoidPtrToNonVoidPtr
CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because a void * can implicitly convert...
Definition Sema.h:689
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition Sema.h:731
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:726
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition Sema.h:765
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:684
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition Sema.h:716
@ IncompatiblePointerDiscardsOverflowBehavior
IncompatiblePointerDiscardsOverflowBehavior - The assignment discards overflow behavior annotations b...
Definition Sema.h:736
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition Sema.h:693
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition Sema.h:701
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition Sema.h:748
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition Sema.h:710
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:722
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition Sema.h:760
TagUseKind
Definition Sema.h:444
MSVtorDispMode
In the Microsoft ABI, this controls the placement of virtual displacement members used to implement v...
Definition LangOptions.h:39
PragmaClangSectionKind
pragma clang section kind
Definition Sema.h:460
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6171
TUFragmentKind
Definition Sema.h:480
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
@ On
Always emit colors regardless of the output stream.
NameClassificationKind
Describes the result of the name lookup and resolution performed by Sema::ClassifyName().
Definition Sema.h:548
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:580
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:555
@ DependentNonType
The name denotes a member of a dependent type that could not be resolved.
Definition Sema.h:569
@ UndeclaredTemplate
The name was classified as an ADL-only function template name.
Definition Sema.h:582
@ NonType
The name was classified as a specific non-type, non-template declaration.
Definition Sema.h:561
@ Unknown
This name is not a type or template in this context, but might be something else.
Definition Sema.h:551
@ Error
Classification failed; an error has been produced.
Definition Sema.h:553
@ Type
The name was classified as a type.
Definition Sema.h:557
@ TypeTemplate
The name was classified as a template whose specializations are types.
Definition Sema.h:576
@ Concept
The name was classified as a concept name.
Definition Sema.h:584
@ OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
Definition Sema.h:574
@ UndeclaredNonType
The name was classified as an ADL-only function name.
Definition Sema.h:565
@ VarTemplate
The name was classified as a variable template name.
Definition Sema.h:578
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Decl.h:2053
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:492
CastKind
CastKind - The kind of operation required for a conversion.
unsigned getFunctionOrMethodNumParams(const Decl *D, bool IncludeThis=false)
getFunctionOrMethodNumParams - Return number of function or method parameters, optionally including t...
Definition Attr.h:66
AllowFoldKind
Definition Sema.h:648
TranslationUnitKind
Describes the kind of translation unit being processed.
@ TU_Complete
The translation unit is a complete translation unit.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
ComparisonCategoryType
An enumeration representing the different comparison categories types.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
VarArgKind
Definition Sema.h:669
PragmaMSStructKind
Definition PragmaKinds.h:24
AssignmentAction
Definition Sema.h:216
@ Deduced
The normal deduced case.
Definition TypeBase.h:1818
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Decl.h:2031
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
@ TNK_Function_template
The name refers to a function template or a set of overloaded functions that includes at least one fu...
@ TNK_Concept_template
The name refers to a concept.
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
BuiltinCountedByRefKind
Definition Sema.h:514
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool hasImplicitObjectParameter(const Decl *D)
Definition Attr.h:164
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition Lambda.h:22
PragmaFloatControlKind
Definition PragmaKinds.h:29
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
TypeAwareAllocationMode
Definition ExprCXX.h:2256
IfExistsResult
Describes the result of an "if-exists" condition check.
Definition Sema.h:796
@ Exists
The symbol exists.
Definition Sema.h:798
@ DoesNotExist
The symbol does not exist.
Definition Sema.h:801
MSInheritanceModel
Assigned inheritance model for a class in the MS C++ ABI.
Definition Specifiers.h:414
bool hasFunctionProto(const Decl *D)
hasFunctionProto - Return true if the given decl has a argument information.
Definition Attr.h:56
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
TPOC
The context in which partial ordering of function templates occurs.
Definition Template.h:310
TrivialABIHandling
Definition Sema.h:638
@ ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition Sema.h:643
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:640
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:373
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:423
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:418
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:421
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:394
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:380
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:416
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:425
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:413
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:383
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:397
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:386
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:400
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:389
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:410
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:427
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:404
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:407
PostfixOperatorKind
Kinds of defaulted postfix increment and decrement operator functions (C++2d [over....
Definition Decl.h:2043
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
U cast(CodeGen::Address addr)
Definition Address.h:327
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h:218
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:831
@ CaseValue
Expression in a case label.
Definition Sema.h:832
@ StaticAssertMessageData
Call to data() in a static assert message.
Definition Sema.h:842
@ Enumerator
Enumerator value with fixed underlying type.
Definition Sema.h:833
@ StaticAssertMessageSize
Call to size() in a static assert message.
Definition Sema.h:840
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:839
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:837
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:835
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:844
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:838
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
SourceLocIdentKind
Definition Expr.h:5082
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:6146
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6157
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6160
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6164
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2250
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Dynamic
throw(T1, T2)
PredefinedIdentKind
Definition Expr.h:2058
CheckedConversionKind
The kind of conversion being performed.
Definition Sema.h:431
@ Implicit
An implicit conversion.
Definition Sema.h:433
@ CStyleCast
A C-style cast.
Definition Sema.h:435
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
Definition Sema.h:441
@ OtherCast
A cast other than a C-style cast.
Definition Sema.h:439
@ FunctionalCast
A functional-style cast.
Definition Sema.h:437
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition Specifiers.h:177
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
int const char * function
Definition c++config.h:31
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 int64_t
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 __builtin_riscv_mqwacc_i64 uint8_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
Selector diagnostic state for all API notes readers used by one Sema.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
A structure used to record information about a failed template argument deduction,...
Describes whether we've seen any nullability information for the given file.
Definition Sema.h:246
SourceLocation PointerEndLoc
The end location for the first pointer declarator in the file.
Definition Sema.h:253
SourceLocation PointerLoc
The first pointer declarator (of any pointer kind) in the file that does not have a corresponding nul...
Definition Sema.h:249
bool SawTypeNullability
Whether we saw any type nullability annotations in the given file.
Definition Sema.h:259
uint8_t PointerKind
Which kind of pointer declarator we saw.
Definition Sema.h:256
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition TypeBase.h:5285
Holds information about the various types of exception specification.
Definition TypeBase.h:5605
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5607
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5610
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5613
Extra information about a function prototype.
Definition TypeBase.h:5633
Represents a complete lambda introducer.
Definition DeclSpec.h:2940
Contains a late templated function.
Definition Sema.h:16094
FPOptions FPO
Floating-point options in the point of definition.
Definition Sema.h:16099
Decl * D
The template function declaration to be late parsed.
Definition Sema.h:16097
The part of a late-parsed type attribute that Sema reads and fills in during type construction.
Definition DeclSpec.h:256
A normalized constraint, as defined in C++ [temp.constr.normal], is either an atomic constraint,...
Definition SemaConcept.h:36
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:937
Describes how types, statements, expressions, and declarations should be printed.
SourceLocation CurrentPragmaLocation
Definition Sema.h:2091
static BoundsAttrFlags get(AttributeCommonInfo::Kind K)
Return the flags for a bounds attribute of kind K.
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10723
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10730
CheckNonDependentConversionsFlag(bool SuppressUserConversions, bool OnlyInitializeNonUserDefinedConversions)
Definition Sema.h:10732
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:12257
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12253
CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &)=delete
CheckTemplateArgumentInfo(bool PartialOrdering=false, bool MatchingTTP=false)
Definition Sema.h:12234
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12246
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12243
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12243
CheckTemplateArgumentInfo & operator=(const CheckTemplateArgumentInfo &)=delete
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13373
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition Sema.h:13544
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
bool InParameterMappingSubstitution
Whether we're substituting into the parameter mapping of a constraint.
Definition Sema.h:13501
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition Sema.h:13517
ArrayRef< TemplateArgument > template_arguments() const
Definition Sema.h:13536
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation,...
Definition Sema.h:13512
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13504
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13530
bool InConstraintSubstitution
Whether we're substituting into constraints.
Definition Sema.h:13498
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13520
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition Sema.h:13527
SynthesisKind
The kind of template instantiation we are performing.
Definition Sema.h:13375
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13464
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition Sema.h:13385
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition Sema.h:13394
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition Sema.h:13413
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13461
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition Sema.h:13421
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition Sema.h:13428
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13468
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition Sema.h:13439
@ Memoization
Added for Template instantiation observation.
Definition Sema.h:13474
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition Sema.h:13404
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition Sema.h:13480
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13477
@ PartialOrderingTTP
We are performing partial ordering for template template parameters.
Definition Sema.h:13483
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13401
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition Sema.h:13409
@ SYCLKernelLaunchOverloadResolution
We are performing overload resolution for a call to a function template or variable template named 's...
Definition Sema.h:13491
@ ExpansionStmtInstantiation
We are instantiating an expansion statement.
Definition Sema.h:13494
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13417
@ TemplateInstantiation
We are instantiating a template declaration.
Definition Sema.h:13378
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition Sema.h:13431
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13435
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13390
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13458
@ SYCLKernelLaunchLookup
We are performing name lookup for a function template or variable template named 'sycl_kernel_launch'...
Definition Sema.h:13487
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition Sema.h:13424
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13507
CXXSpecialMemberKind SpecialMember
The special member being declared or defined.
Definition Sema.h:13533
bool isInstantiationRecord() const
Determines whether this template is an actual instantiation that should be counted toward the maximum...
InitializationContext(SourceLocation Loc, ValueDecl *Decl, DeclContext *Context)
Definition Sema.h:7039
Data structure used to record current or nested expression evaluation contexts.
Definition Sema.h:6940
SmallVector< CXXBindTemporaryExpr *, 8 > DelayedDecltypeBinds
If we are processing a decltype type, a set of temporary binding expressions for which we have deferr...
Definition Sema.h:6973
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition Sema.h:6975
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:7026
Decl * ManglingContextDecl
The declaration that provides context for lambda expressions and block literals if the normal declara...
Definition Sema.h:6960
SmallVector< CallExpr *, 8 > DelayedDecltypeCalls
If we are processing a decltype type, a set of call expressions for which we have deferred checking t...
Definition Sema.h:6969
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition Sema.h:6980
llvm::SmallPtrSet< DeclRefExpr *, 4 > ReferenceToConsteval
Set of DeclRefExprs referencing a consteval function when used in a context not already known to be i...
Definition Sema.h:6988
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition Sema.h:6984
bool IsCaseExpr
Whether evaluating an expression for a switch case label.
Definition Sema.h:7029
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6994
enum clang::Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext
SmallVector< LambdaExpr *, 2 > Lambdas
The lambdas that are present within this context, if it is indeed an unevaluated context.
Definition Sema.h:6955
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition Sema.h:7002
bool RebuildDefaultArgOrDefaultInit
Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
Definition Sema.h:7032
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6998
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition Sema.h:6945
VarDecl * DeclForInitializer
Declaration for initializer if one is currently being parsed.
Definition Sema.h:6965
std::optional< InitializationContext > DelayedDefaultInitializationContext
Definition Sema.h:7049
ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext)
Definition Sema.h:7051
ExpressionEvaluationContext Context
The expression evaluation context.
Definition Sema.h:6942
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition Sema.h:6949
Holds the 'begin' and 'end' variables of a range-based for loop or expansion statement; begin-expr an...
Definition Sema.h:11319
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2767
FunctionEffectDiffVector(const FunctionEffectsRef &Old, const FunctionEffectsRef &New)
Caller should short-circuit by checking for equality first.
std::optional< FunctionEffectWithCondition > Old
Definition Sema.h:15954
bool shouldDiagnoseConversion(QualType SrcType, const FunctionEffectsRef &SrcFX, QualType DstType, const FunctionEffectsRef &DstFX) const
Return true if adding or removing the effect as part of a type conversion should generate a diagnosti...
bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction, const FunctionEffectsRef &OldFX, const FunctionDecl &NewFunction, const FunctionEffectsRef &NewFX) const
Return true if adding or removing the effect in a redeclaration should generate a diagnostic.
StringRef effectName() const
Definition Sema.h:15958
OverrideResult shouldDiagnoseMethodOverride(const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX, const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const
Return true if adding or removing the effect in a C++ virtual method override should generate a diagn...
OverrideResult
Describes the result of effects differing between a base class's virtual method and an overriding met...
Definition Sema.h:15966
std::optional< FunctionEffectWithCondition > New
Definition Sema.h:15956
FunctionEffect::Kind EffectKind
Definition Sema.h:15951
Used for pragma init_seg.
Definition Sema.h:2140
SourceLocation PragmaLocation
Definition Sema.h:2141
StringLiteral * Segment
Definition Sema.h:2142
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13720
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange=SourceRange())
Note that we are instantiating a class template, function template, variable template,...
void Clear()
Note that we have finished instantiating this template.
LocalInstantiationScope * Scope
Definition Sema.h:14037
LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, Decl *D)
Definition Sema.h:14040
bool isMoveEligible() const
Definition Sema.h:11373
bool isCopyElidable() const
Definition Sema.h:11374
const VarDecl * Candidate
Definition Sema.h:11368
IdentifierInfo * Identifier
The identifier preceding the '::'.
Definition Sema.h:3446
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType=ParsedType())
Creates info object for the most typical case.
Definition Sema.h:3455
SourceLocation IdentifierLoc
The location of the identifier.
Definition Sema.h:3449
SourceLocation CCLoc
The location of the '::'.
Definition Sema.h:3452
ParsedType ObjectType
The type of the object, if we're parsing nested-name-specifier in a member access expression.
Definition Sema.h:3443
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType)
Definition Sema.h:3461
OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType)
Definition Sema.h:12879
Information from a C++ pragma export, for a symbol that we haven't seen the declaration for yet.
Definition Sema.h:2388
This an attribute introduced by #pragma clang attribute.
Definition Sema.h:2154
SmallVector< attr::SubjectMatchRule, 4 > MatchRules
Definition Sema.h:2157
A push'd group of PragmaAttributeEntries.
Definition Sema.h:2162
SourceLocation Loc
The location of the push attribute.
Definition Sema.h:2164
SmallVector< PragmaAttributeEntry, 2 > Entries
Definition Sema.h:2167
const IdentifierInfo * Namespace
The namespace of this push group.
Definition Sema.h:2166
SourceLocation PragmaLocation
Definition Sema.h:1869
PragmaMsStackAction Action
Definition Sema.h:1889
Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
Definition Sema.h:2002
llvm::StringRef StackSlotLabel
Definition Sema.h:1998
SourceLocation PragmaLocation
Definition Sema.h:2000
SourceLocation PragmaPushLocation
Definition Sema.h:2001
ValueType CurrentValue
Definition Sema.h:2072
void SentinelAction(PragmaMsStackAction Action, StringRef Label)
Definition Sema.h:2058
bool hasValue() const
Definition Sema.h:2068
SmallVector< Slot, 2 > Stack
Definition Sema.h:2070
ValueType DefaultValue
Definition Sema.h:2071
SourceLocation CurrentPragmaLocation
Definition Sema.h:2073
PragmaStack(const ValueType &Default)
Definition Sema.h:2065
void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value)
Definition Sema.h:2009
ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val)
Definition Sema.h:5294
ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val)
Definition Sema.h:5288
RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
Definition Sema.h:13345
RecursiveInstGuard(const RecursiveInstGuard &)=delete
RecursiveInstGuard & operator=(const RecursiveInstGuard &)=delete
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition Sema.h:10620
SFINAEContextBase & operator=(const SFINAEContextBase &)=delete
SFINAEContextBase(Sema &S, SFINAETrap *Cur)
Definition Sema.h:12688
SFINAEContextBase(const SFINAEContextBase &)=delete
Abstract class used to diagnose incomplete types.
Definition Sema.h:8442
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull)
Definition Sema.h:2809
unsigned LayoutCompatible
If true, Type should be compared with other expression's types for layout-compatibility.
Definition Sema.h:2818
bool CheckSameAsPrevious
Definition Sema.h:359
NamedDecl * Previous
Definition Sema.h:360
SkipBodyInfo()=default
NamedDecl * New
Definition Sema.h:361
Information about a template-id annotation token.