clang 23.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"
40#include "clang/Basic/Cuda.h"
44#include "clang/Basic/LLVM.h"
45#include "clang/Basic/Lambda.h"
47#include "clang/Basic/Module.h"
59#include "clang/Sema/Attr.h"
61#include "clang/Sema/DeclSpec.h"
67#include "clang/Sema/Scope.h"
68#include "clang/Sema/SemaBase.h"
72#include "clang/Sema/Weak.h"
73#include "llvm/ADT/APInt.h"
74#include "llvm/ADT/ArrayRef.h"
75#include "llvm/ADT/BitmaskEnum.h"
76#include "llvm/ADT/DenseMap.h"
77#include "llvm/ADT/DenseSet.h"
78#include "llvm/ADT/FloatingPointMode.h"
79#include "llvm/ADT/FoldingSet.h"
80#include "llvm/ADT/MapVector.h"
81#include "llvm/ADT/PointerIntPair.h"
82#include "llvm/ADT/PointerUnion.h"
83#include "llvm/ADT/STLExtras.h"
84#include "llvm/ADT/STLForwardCompat.h"
85#include "llvm/ADT/STLFunctionalExtras.h"
86#include "llvm/ADT/SetVector.h"
87#include "llvm/ADT/SmallBitVector.h"
88#include "llvm/ADT/SmallPtrSet.h"
89#include "llvm/ADT/SmallSet.h"
90#include "llvm/ADT/SmallVector.h"
91#include "llvm/ADT/StringExtras.h"
92#include "llvm/ADT/StringMap.h"
93#include "llvm/ADT/TinyPtrVector.h"
94#include "llvm/Support/Allocator.h"
95#include "llvm/Support/Compiler.h"
96#include "llvm/Support/Error.h"
97#include "llvm/Support/ErrorHandling.h"
98#include <cassert>
99#include <climits>
100#include <cstddef>
101#include <cstdint>
102#include <deque>
103#include <functional>
104#include <iterator>
105#include <memory>
106#include <optional>
107#include <string>
108#include <tuple>
109#include <type_traits>
110#include <utility>
111#include <vector>
112
113namespace llvm {
114struct InlineAsmIdentifierInfo;
115} // namespace llvm
116
117namespace clang {
118class ADLResult;
119class APValue;
121class ASTConsumer;
122class ASTContext;
123class ASTDeclReader;
125class ASTReader;
126class ASTWriter;
127class CXXBasePath;
128class CXXBasePaths;
131enum class ComparisonCategoryType : unsigned char;
133class DarwinSDKInfo;
134class DeclGroupRef;
138class Designation;
139class IdentifierInfo;
145enum class LangAS : unsigned int;
147class LookupResult;
150class ModuleLoader;
154class ObjCMethodDecl;
155struct OverloadCandidate;
156enum class OverloadCandidateParamOrder : char;
157enum OverloadCandidateRewriteKind : unsigned;
159class Preprocessor;
160class SemaAMDGPU;
161class SemaARM;
162class SemaAVR;
163class SemaBPF;
165class SemaCUDA;
166class SemaDirectX;
167class SemaHLSL;
168class SemaHexagon;
169class SemaLoongArch;
170class SemaM68k;
171class SemaMIPS;
172class SemaMSP430;
173class SemaNVPTX;
174class SemaObjC;
175class SemaOpenACC;
176class SemaOpenCL;
177class SemaOpenMP;
178class SemaPPC;
179class SemaPseudoObject;
180class SemaRISCV;
181class SemaSPIRV;
182class SemaSYCL;
183class SemaSwift;
184class SemaSystemZ;
185class SemaWasm;
186class SemaX86;
188class 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
227namespace threadSafety {
228class BeforeSet;
229void threadSafetyCleanup(BeforeSet *Cache);
230} // namespace threadSafety
231
232// FIXME: No way to easily map from TemplateTypeParmTypes to
233// TemplateTypeParmDecls, so we have this horrible PointerUnion.
234typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *,
235 const TemplateSpecializationType *,
236 const SubstBuiltinTemplatePackType *>,
239
240/// Describes whether we've seen any nullability information for the given
241/// file.
243 /// The first pointer declarator (of any pointer kind) in the file that does
244 /// not have a corresponding nullability annotation.
246
247 /// The end location for the first pointer declarator in the file. Used for
248 /// placing fix-its.
250
251 /// Which kind of pointer declarator we saw.
253
254 /// Whether we saw any type nullability annotations in the given file.
255 bool SawTypeNullability = false;
256};
257
258/// A mapping from file IDs to a record of whether we've seen nullability
259/// information in that file.
261 /// A mapping from file IDs to the nullability information for each file ID.
262 llvm::DenseMap<FileID, FileNullability> Map;
263
264 /// A single-element cache based on the file ID.
265 struct {
268 } Cache;
269
270public:
272 // Check the single-element cache.
273 if (file == Cache.File)
274 return Cache.Nullability;
275
276 // It's not in the single-element cache; flush the cache if we have one.
277 if (!Cache.File.isInvalid()) {
278 Map[Cache.File] = Cache.Nullability;
279 }
280
281 // Pull this entry into the cache.
282 Cache.File = file;
283 Cache.Nullability = Map[file];
284 return Cache.Nullability;
285 }
286};
287
288/// Tracks expected type during expression parsing, for use in code completion.
289/// The type is tied to a particular token, all functions that update or consume
290/// the type take a start location of the token they are looking at as a
291/// parameter. This avoids updating the type on hot paths in the parser.
293public:
295 : Ctx(Ctx), Enabled(Enabled) {}
296
300 /// Handles e.g. BaseType{ .D = Tok...
302 const Designation &D);
303 /// Computing a type for the function argument may require running
304 /// overloading, so we postpone its computation until it is actually needed.
305 ///
306 /// Clients should be very careful when using this function, as it stores a
307 /// function_ref, clients should make sure all calls to get() with the same
308 /// location happen while function_ref is alive.
309 ///
310 /// The callback should also emit signature help as a side-effect, but only
311 /// if the completion point has been reached.
313 llvm::function_ref<QualType()> ComputeType);
314
317 SourceLocation OpLoc);
320 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
321 /// Handles all type casts, including C-style cast, C++ casts, etc.
323
324 /// Get the expected type associated with this location, if any.
325 ///
326 /// If the location is a function argument, determining the expected type
327 /// involves considering all function overloads and the arguments so far.
328 /// In this case, signature help for these function overloads will be reported
329 /// as a side-effect (only if the completion point has been reached).
331 if (!Enabled || Tok != ExpectedLoc)
332 return QualType();
333 if (!Type.isNull())
334 return Type;
335 if (ComputeType)
336 return ComputeType();
337 return QualType();
338 }
339
340private:
341 ASTContext *Ctx;
342 bool Enabled;
343 /// Start position of a token for which we store expected type.
344 SourceLocation ExpectedLoc;
345 /// Expected type for a token starting at ExpectedLoc.
347 /// A function to compute expected type at ExpectedLoc. It is only considered
348 /// if Type is null.
349 llvm::function_ref<QualType()> ComputeType;
350};
351
353 SkipBodyInfo() = default;
354 bool ShouldSkip = false;
356 NamedDecl *Previous = nullptr;
357 NamedDecl *New = nullptr;
358};
359
360/// Describes the result of template argument deduction.
361///
362/// The TemplateDeductionResult enumeration describes the result of
363/// template argument deduction, as returned from
364/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
365/// structure provides additional information about the results of
366/// template argument deduction, e.g., the deduced template argument
367/// list (if successful) or the specific template parameters or
368/// deduced arguments that were involved in the failure.
370 /// Template argument deduction was successful.
372 /// The declaration was invalid; do nothing.
374 /// Template argument deduction exceeded the maximum template
375 /// instantiation depth (which has already been diagnosed).
377 /// Template argument deduction did not deduce a value
378 /// for every template parameter.
380 /// Template argument deduction did not deduce a value for every
381 /// expansion of an expanded template parameter pack.
383 /// Template argument deduction produced inconsistent
384 /// deduced values for the given template parameter.
386 /// Template argument deduction failed due to inconsistent
387 /// cv-qualifiers on a template parameter type that would
388 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
389 /// but were given a non-const "X".
391 /// Substitution of the deduced template argument values
392 /// resulted in an error.
394 /// After substituting deduced template arguments, a dependent
395 /// parameter type did not match the corresponding argument.
397 /// After substituting deduced template arguments, an element of
398 /// a dependent parameter type did not match the corresponding element
399 /// of the corresponding argument (when deducing from an initializer list).
401 /// A non-depnedent component of the parameter did not match the
402 /// corresponding component of the argument.
404 /// When performing template argument deduction for a function
405 /// template, there were too many call arguments.
407 /// When performing template argument deduction for a function
408 /// template, there were too few call arguments.
410 /// The explicitly-specified template arguments were not valid
411 /// template arguments for the given template.
413 /// Checking non-dependent argument conversions failed.
415 /// The deduced arguments did not satisfy the constraints associated
416 /// with the template.
418 /// Deduction failed; that's all we know.
420 /// CUDA Target attributes do not match.
422 /// Some error which was already diagnosed.
424};
425
426/// Kinds of C++ special members.
436
437/// The kind of conversion being performed.
439 /// An implicit conversion.
441 /// A C-style cast.
443 /// A functional-style cast.
445 /// A cast other than a C-style cast.
447 /// A conversion for an operand of a builtin overloaded operator.
449};
450
451enum class TagUseKind {
452 Reference, // Reference to a tag: 'struct foo *X;'
453 Declaration, // Fwd decl of a tag: 'struct foo;'
454 Definition, // Definition of a tag: 'struct foo { int X; } Y;'
455 Friend // Friend declaration: 'friend struct foo;'
456};
457
458/// Used with attributes/effects with a boolean condition, e.g. `nonblocking`.
460 None, // effect is not present.
461 False, // effect(false).
462 True, // effect(true).
463 Dependent // effect(expr) where expr is dependent.
464};
465
466/// pragma clang section kind
469 BSS = 1,
470 Data = 2,
472 Text = 4,
474};
475
476enum class PragmaClangSectionAction { Set = 0, Clear = 1 };
477
479 Native, // #pragma options align=native
480 Natural, // #pragma options align=natural
481 Packed, // #pragma options align=packed
482 Power, // #pragma options align=power
483 Mac68k, // #pragma options align=mac68k
484 Reset // #pragma options align=reset
485};
486
487enum class TUFragmentKind {
488 /// The global module fragment, between 'module;' and a module-declaration.
490 /// A normal translation unit fragment. For a non-module unit, this is the
491 /// entire translation unit. Otherwise, it runs from the module-declaration
492 /// to the private-module-fragment (if any) or the end of the TU (if not).
494 /// The private module fragment, between 'module :private;' and the end of
495 /// the translation unit.
497};
498
511
512// Used for emitting the right warning by DefaultVariadicArgumentPromotion
520
529
530// Contexts where using non-trivial C union types can be disallowed. This is
531// passed to err_non_trivial_c_union_in_invalid_context.
533 // Function parameter.
535 // Function return.
537 // Default-initialized object.
539 // Variable with automatic storage duration.
541 // Initializer expression that might copy from another object.
543 // Assignment.
545 // Compound literal.
547 // Block capture.
549 // lvalue-to-rvalue conversion of volatile type.
551};
552
553/// Describes the result of the name lookup and resolution performed
554/// by \c Sema::ClassifyName().
556 /// This name is not a type or template in this context, but might be
557 /// something else.
559 /// Classification failed; an error has been produced.
561 /// The name has been typo-corrected to a keyword.
563 /// The name was classified as a type.
565 /// The name was classified as a specific non-type, non-template
566 /// declaration. ActOnNameClassifiedAsNonType should be called to
567 /// convert the declaration to an expression.
569 /// The name was classified as an ADL-only function name.
570 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
571 /// result to an expression.
573 /// The name denotes a member of a dependent type that could not be
574 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
575 /// convert the result to an expression.
577 /// The name was classified as an overload set, and an expression
578 /// representing that overload set has been formed.
579 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
580 /// expression referencing the overload set.
582 /// The name was classified as a template whose specializations are types.
584 /// The name was classified as a variable template name.
586 /// The name was classified as a function template name.
588 /// The name was classified as an ADL-only function template name.
590 /// The name was classified as a concept name.
592};
593
595 // Address discrimination argument of __ptrauth.
597
598 // Extra discriminator argument of __ptrauth.
600};
601
602/// Common ways to introduce type names without a tag for use in diagnostics.
603/// Keep in sync with err_tag_reference_non_tag.
615
616enum class OffsetOfKind {
617 // Not parsing a type within __builtin_offsetof.
619 // Parsing a type within __builtin_offsetof.
621 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
622 // To improve our diagnostic message.
624};
625
626/// Describes the kind of merge to perform for availability
627/// attributes (including "deprecated", "unavailable", and "availability").
629 /// Don't merge availability attributes at all.
631 /// Merge availability attributes for a redeclaration, which requires
632 /// an exact match.
634 /// Merge availability attributes for an override, which requires
635 /// an exact match or a weakening of constraints.
637 /// Merge availability attributes for an implementation of
638 /// a protocol requirement.
640 /// Merge availability attributes for an implementation of
641 /// an optional protocol requirement.
643};
644
646 /// The triviality of a method unaffected by "trivial_abi".
648
649 /// The triviality of a method affected by "trivial_abi".
651};
652
654
655enum class AllowFoldKind {
658};
659
660/// Context in which we're performing a usual arithmetic conversion.
661enum class ArithConvKind {
662 /// An arithmetic operation.
664 /// A bitwise operation.
666 /// A comparison.
668 /// A conditional (?:) operator.
670 /// A compound assignment expression.
672};
673
674// Used for determining in which context a type is allowed to be passed to a
675// vararg function.
683
684/// AssignConvertType - All of the 'assignment' semantic checks return this
685/// enum to indicate whether the assignment was allowed. These checks are
686/// done for simple assignments, as well as initialization, return from
687/// function, argument passing, etc. The query is phrased in terms of a
688/// source and destination type.
690 /// Compatible - the types are compatible according to the standard.
692
693 /// CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because
694 /// a void * can implicitly convert to another pointer type, which we
695 /// differentiate for better diagnostic behavior.
697
698 /// PointerToInt - The assignment converts a pointer to an int, which we
699 /// accept as an extension.
701
702 /// IntToPointer - The assignment converts an int to a pointer, which we
703 /// accept as an extension.
705
706 /// FunctionVoidPointer - The assignment is between a function pointer and
707 /// void*, which the standard doesn't allow, but we accept as an extension.
709
710 /// IncompatiblePointer - The assignment is between two pointers types that
711 /// are not compatible, but we accept them as an extension.
713
714 /// IncompatibleFunctionPointer - The assignment is between two function
715 /// pointers types that are not compatible, but we accept them as an
716 /// extension.
718
719 /// IncompatibleFunctionPointerStrict - The assignment is between two
720 /// function pointer types that are not identical, but are compatible,
721 /// unless compiled with -fsanitize=cfi, in which case the type mismatch
722 /// may trip an indirect call runtime check.
724
725 /// IncompatiblePointerSign - The assignment is between two pointers types
726 /// which point to integers which have a different sign, but are otherwise
727 /// identical. This is a subset of the above, but broken out because it's by
728 /// far the most common case of incompatible pointers.
730
731 /// CompatiblePointerDiscardsQualifiers - The assignment discards
732 /// c/v/r qualifiers, which we accept as an extension.
734
735 /// IncompatiblePointerDiscardsQualifiers - The assignment
736 /// discards qualifiers that we don't permit to be discarded,
737 /// like address spaces.
739
740 /// IncompatiblePointerDiscardsOverflowBehavior - The assignment
741 /// discards overflow behavior annotations between otherwise compatible
742 /// pointer types.
744
745 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
746 /// changes address spaces in nested pointer types which is not allowed.
747 /// For instance, converting __private int ** to __generic int ** is
748 /// illegal even though __private could be converted to __generic.
750
751 /// IncompatibleNestedPointerQualifiers - The assignment is between two
752 /// nested pointer types, and the qualifiers other than the first two
753 /// levels differ e.g. char ** -> const char **, but we accept them as an
754 /// extension.
756
757 /// IncompatibleVectors - The assignment is between two vector types that
758 /// have the same size, which we accept as an extension.
760
761 /// IntToBlockPointer - The assignment converts an int to a block
762 /// pointer. We disallow this.
764
765 /// IncompatibleBlockPointer - The assignment is between two block
766 /// pointers types that are not compatible.
768
769 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
770 /// id type and something else (that is incompatible with it). For example,
771 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
773
774 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
775 /// object with __weak qualifier.
777
778 /// IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType
779 /// kinds, e.g., from __ob_trap to __ob_wrap or vice versa.
781
782 /// CompatibleOBTDiscards - Assignment discards overflow behavior
784
785 /// Incompatible - We reject this conversion outright, it is invalid to
786 /// represent it in the AST.
788};
789
790/// The scope in which to find allocation functions.
792 /// Only look for allocation functions in the global scope.
794 /// Only look for allocation functions in the scope of the
795 /// allocated class.
797 /// Look for allocation functions in both the global scope
798 /// and in the scope of the allocated class.
800};
801
802/// Describes the result of an "if-exists" condition check.
803enum class IfExistsResult {
804 /// The symbol exists.
806
807 /// The symbol does not exist.
809
810 /// The name is a dependent name, so the results will differ
811 /// from one instantiation to the next.
813
814 /// An error occurred.
816};
817
818enum class CorrectTypoKind {
819 NonError, // CorrectTypo used in a non error recovery situation.
820 ErrorRecovery // CorrectTypo used in normal error recovery.
821};
822
823enum class OverloadKind {
824 /// This is a legitimate overload: the existing declarations are
825 /// functions or function templates with different signatures.
827
828 /// This is not an overload because the signature exactly matches
829 /// an existing declaration.
831
832 /// This is not an overload because the lookup results contain a
833 /// non-function.
835};
836
837/// Contexts in which a converted constant expression is required.
838enum class CCEKind {
839 CaseValue, ///< Expression in a case label.
840 Enumerator, ///< Enumerator value with fixed underlying type.
841 TemplateArg, ///< Value of a non-type template parameter.
842 TempArgStrict, ///< As above, but applies strict template checking
843 ///< rules.
844 ArrayBound, ///< Array bound in array declarator or new-expression.
845 ExplicitBool, ///< Condition in an explicit(bool) specifier.
846 Noexcept, ///< Condition in a noexcept(bool) specifier.
847 StaticAssertMessageSize, ///< Call to size() in a static assert
848 ///< message.
849 StaticAssertMessageData, ///< Call to data() in a static assert
850 ///< message.
851 PackIndex ///< Index of a pack indexing expression or specifier.
852};
853
854/// Enums for the diagnostics of target, target_version and target_clones.
855namespace DiagAttrParams {
859} // end namespace DiagAttrParams
860
861void inferNoReturnAttr(Sema &S, Decl *D);
862
863#ifdef __GNUC__
864#pragma GCC diagnostic push
865#pragma GCC diagnostic ignored "-Wattributes"
866#endif
867/// Sema - This implements semantic analysis and AST building for C.
868/// \nosubgrouping
869class Sema final : public SemaBase {
870#ifdef __GNUC__
871#pragma GCC diagnostic pop
872#endif
873 // Table of Contents
874 // -----------------
875 // 1. Semantic Analysis (Sema.cpp)
876 // 2. API Notes (SemaAPINotes.cpp)
877 // 3. C++ Access Control (SemaAccess.cpp)
878 // 4. Attributes (SemaAttr.cpp)
879 // 5. Availability Attribute Handling (SemaAvailability.cpp)
880 // 6. Bounds Safety (SemaBoundsSafety.cpp)
881 // 7. Casts (SemaCast.cpp)
882 // 8. Extra Semantic Checking (SemaChecking.cpp)
883 // 9. C++ Coroutines (SemaCoroutine.cpp)
884 // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
885 // 11. Declarations (SemaDecl.cpp)
886 // 12. Declaration Attribute Handling (SemaDeclAttr.cpp)
887 // 13. C++ Declarations (SemaDeclCXX.cpp)
888 // 14. C++ Exception Specifications (SemaExceptionSpec.cpp)
889 // 15. Expressions (SemaExpr.cpp)
890 // 16. C++ Expressions (SemaExprCXX.cpp)
891 // 17. Member Access Expressions (SemaExprMember.cpp)
892 // 18. Initializers (SemaInit.cpp)
893 // 19. C++ Lambda Expressions (SemaLambda.cpp)
894 // 20. Name Lookup (SemaLookup.cpp)
895 // 21. Modules (SemaModule.cpp)
896 // 22. C++ Overloading (SemaOverload.cpp)
897 // 23. Statements (SemaStmt.cpp)
898 // 24. `inline asm` Statement (SemaStmtAsm.cpp)
899 // 25. Statement Attribute Handling (SemaStmtAttr.cpp)
900 // 26. C++ Templates (SemaTemplate.cpp)
901 // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
902 // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp)
903 // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
904 // 30. C++ Template Declaration Instantiation
905 // (SemaTemplateInstantiateDecl.cpp)
906 // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp)
907 // 32. Constraints and Concepts (SemaConcept.cpp)
908 // 33. Types (SemaType.cpp)
909 // 34. FixIt Helpers (SemaFixItUtils.cpp)
910 // 35. Function Effects (SemaFunctionEffects.cpp)
911
912 /// \name Semantic Analysis
913 /// Implementations are in Sema.cpp
914 ///@{
915
916public:
917 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
919 CodeCompleteConsumer *CompletionConsumer = nullptr);
920 ~Sema();
921
922 /// Perform initialization that occurs after the parser has been
923 /// initialized but before it parses anything.
924 void Initialize();
925
926 /// This virtual key function only exists to limit the emission of debug info
927 /// describing the Sema class. GCC and Clang only emit debug info for a class
928 /// with a vtable when the vtable is emitted. Sema is final and not
929 /// polymorphic, but the debug info size savings are so significant that it is
930 /// worth adding a vtable just to take advantage of this optimization.
932
933 const LangOptions &getLangOpts() const { return LangOpts; }
936
939 Preprocessor &getPreprocessor() const { return PP; }
940 ASTContext &getASTContext() const { return Context; }
944
946 StringRef Platform);
948
949 /// Registers an external source. If an external source already exists,
950 /// creates a multiplex external source and appends to it.
951 ///
952 ///\param[in] E - A non-null external sema source.
953 ///
955
956 /// Print out statistics about the semantic analysis.
957 void PrintStats() const;
958
959 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
960 /// guaranteed). Produces a warning if we're low on stack space and allocates
961 /// more in that case. Use this in code that may recurse deeply (for example,
962 /// in template instantiation) to avoid stack overflow.
964 llvm::function_ref<void()> Fn);
965
966 /// Returns default addr space for method qualifiers.
968
969 /// Load weak undeclared identifiers from the external source.
971
972 /// Load #pragma redefine_extname'd undeclared identifiers from the external
973 /// source.
975
976 /// Determine if VD, which must be a variable or function, is an external
977 /// symbol that nonetheless can't be referenced from outside this translation
978 /// unit because its type has no linkage and it's not extern "C".
979 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
980
981 /// Determines whether the given source location is in the main file
982 /// and we're in a context where we should warn about unused entities.
983 bool isMainFileLoc(SourceLocation Loc) const;
984
985 /// Obtain a sorted list of functions that are undefined but ODR-used.
987 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined);
988
989 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
991 /// Retrieves list of suspicious delete-expressions that will be checked at
992 /// the end of translation unit.
993 const llvm::MapVector<FieldDecl *, DeleteLocs> &
995
996 /// Cause the built diagnostic to be emitted on the DiagosticsEngine.
997 /// This is closely coupled to the SemaDiagnosticBuilder class and
998 /// should not be used elsewhere.
999 void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB);
1000
1001 void addImplicitTypedef(StringRef Name, QualType T);
1002
1003 /// Whether uncompilable error has occurred. This includes error happens
1004 /// in deferred diagnostics.
1005 bool hasUncompilableErrorOccurred() const;
1006
1007 /// Looks through the macro-expansion chain for the given
1008 /// location, looking for a macro expansion with the given name.
1009 /// If one is found, returns true and sets the location to that
1010 /// expansion loc.
1011 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1012
1013 /// Calls \c Lexer::getLocForEndOfToken()
1014 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1015
1016 /// Calls \c Lexer::findNextToken() to find the next token, and if the
1017 /// locations of both ends of the token can be resolved it return that
1018 /// range; Otherwise it returns an invalid SourceRange.
1020 SourceLocation Loc, bool IncludeMacros, bool IncludeComments,
1021 std::optional<tok::TokenKind> ExpectedToken = std::nullopt);
1022
1023 /// Retrieve the module loader associated with the preprocessor.
1025
1026 /// Invent a new identifier for parameters of abbreviated templates.
1029 unsigned Index);
1030
1032
1033 // Emit all deferred diagnostics.
1034 void emitDeferredDiags();
1035
1036 /// This is called before the very first declaration in the translation unit
1037 /// is parsed. Note that the ASTContext may have already injected some
1038 /// declarations.
1040 /// ActOnEndOfTranslationUnit - This is called at the very end of the
1041 /// translation unit when EOF is reached and all but the top-level scope is
1042 /// popped.
1045
1046 /// Determines the active Scope associated with the given declaration
1047 /// context.
1048 ///
1049 /// This routine maps a declaration context to the active Scope object that
1050 /// represents that declaration context in the parser. It is typically used
1051 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1052 /// declarations) that injects a name for name-lookup purposes and, therefore,
1053 /// must update the Scope.
1054 ///
1055 /// \returns The scope corresponding to the given declaraion context, or NULL
1056 /// if no such scope is open.
1058
1059 void PushFunctionScope();
1060 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1062
1063 /// This is used to inform Sema what the current TemplateParameterDepth
1064 /// is during Parsing. Currently it is used to pass on the depth
1065 /// when parsing generic lambda 'auto' parameters.
1066 void RecordParsingTemplateParameterDepth(unsigned Depth);
1067
1068 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1070 unsigned OpenMPCaptureLevel = 0);
1071
1072 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1073 /// time after they've been popped.
1075 Sema *Self;
1076
1077 public:
1078 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1080 };
1081
1083 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1084
1085 /// Pop a function (or block or lambda or captured region) scope from the
1086 /// stack.
1087 ///
1088 /// \param WP The warning policy to use for CFG-based warnings, or null if
1089 /// such warnings should not be produced.
1090 /// \param D The declaration corresponding to this function scope, if
1091 /// producing CFG-based warnings.
1092 /// \param BlockType The type of the block expression, if D is a BlockDecl.
1095 Decl *D = nullptr, QualType BlockType = QualType());
1096
1098
1103
1104 void PushCompoundScope(bool IsStmtExpr);
1105 void PopCompoundScope();
1106
1107 /// Determine whether any errors occurred within this function/method/
1108 /// block.
1110
1111 /// Retrieve the current block, if any.
1113
1114 /// Get the innermost lambda or block enclosing the current location, if any.
1115 /// This looks through intervening non-lambda, non-block scopes such as local
1116 /// functions.
1118
1119 /// Retrieve the current lambda scope info, if any.
1120 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1121 /// lambda scope info ignoring all inner capturing scopes that are not
1122 /// lambda scopes.
1124 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1125
1126 /// Retrieve the current generic lambda info, if any.
1128
1129 /// Retrieve the current captured region, if any.
1131
1132 void ActOnComment(SourceRange Comment);
1133
1134 /// Retrieve the parser's current scope.
1135 ///
1136 /// This routine must only be used when it is certain that semantic analysis
1137 /// and the parser are in precisely the same context, which is not the case
1138 /// when, e.g., we are performing any kind of template instantiation.
1139 /// Therefore, the only safe places to use this scope are in the parser
1140 /// itself and in routines directly invoked from the parser and *never* from
1141 /// template substitution or instantiation.
1142 Scope *getCurScope() const { return CurScope; }
1143
1145
1149
1150 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
1151 const FunctionDecl *FD = nullptr);
1153 const PartialDiagnostic &PD,
1154 const FunctionDecl *FD = nullptr) {
1155 return targetDiag(Loc, PD.getDiagID(), FD) << PD;
1156 }
1157
1158 /// Check if the type is allowed to be used for the current target.
1160 ValueDecl *D = nullptr);
1161
1162 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
1163 /// cast. If there is already an implicit cast, merge into the existing one.
1164 /// If isLvalue, the result of the cast is an lvalue.
1167 const CXXCastPath *BasePath = nullptr,
1169
1170 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
1171 /// to the conversion from scalar type ScalarTy to the Boolean type.
1173
1174 /// If \p AllowLambda is true, treat lambda as function.
1175 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
1176
1177 /// Returns a pointer to the innermost enclosing function, or nullptr if the
1178 /// current context is not inside a function. If \p AllowLambda is true,
1179 /// this can return the call operator of an enclosing lambda, otherwise
1180 /// lambdas are skipped when looking for an enclosing function.
1181 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
1182
1183 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1184 /// the method decl for the method being parsed. If we're currently
1185 /// in a 'block', this returns the containing context.
1187
1188 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1189 /// or C function we're in, otherwise return null. If we're currently
1190 /// in a 'block', this returns the containing context.
1192
1193 /// Warn if we're implicitly casting from a _Nullable pointer type to a
1194 /// _Nonnull one.
1196 SourceLocation Loc);
1197
1198 /// Warn when implicitly casting 0 to nullptr.
1199 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
1200
1201 /// Warn when implicitly changing function effects.
1203 SourceLocation Loc);
1204
1205 /// makeUnavailableInSystemHeader - There is an error in the current
1206 /// context. If we're still in a system header, and we can plausibly
1207 /// make the relevant declaration unavailable instead of erroring, do
1208 /// so and return true.
1210 UnavailableAttr::ImplicitReason reason);
1211
1212 /// Retrieve a suitable printing policy for diagnostics.
1216
1217 /// Retrieve a suitable printing policy for diagnostics.
1219 const Preprocessor &PP);
1220
1221 /// Scope actions.
1223
1224 /// Determine whether \param D is function like (function or function
1225 /// template) for parsing.
1227
1228 /// The maximum alignment, same as in llvm::Value. We duplicate them here
1229 /// because that allows us not to duplicate the constants in clang code,
1230 /// which we must to since we can't directly use the llvm constants.
1231 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
1232 ///
1233 /// This is the greatest alignment value supported by load, store, and alloca
1234 /// instructions, and global values.
1235 static const unsigned MaxAlignmentExponent = 32;
1236 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
1237
1238 /// Flag indicating whether or not to collect detailed statistics.
1240
1241 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
1242
1243 /// Stack containing information about each of the nested
1244 /// function, block, and method scopes that are currently active.
1246
1247 /// The index of the first FunctionScope that corresponds to the current
1248 /// context.
1250
1251 /// Track the number of currently active capturing scopes.
1253
1254 llvm::BumpPtrAllocator BumpAlloc;
1255
1256 /// The kind of translation unit we are processing.
1257 ///
1258 /// When we're processing a complete translation unit, Sema will perform
1259 /// end-of-translation-unit semantic tasks (such as creating
1260 /// initializers for tentative definitions in C) once parsing has
1261 /// completed. Modules and precompiled headers perform different kinds of
1262 /// checks.
1264
1265 /// Translation Unit Scope - useful to Objective-C actions that need
1266 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1267 /// For example, user-defined classes, built-in "id" type, etc.
1269
1271 return CurScope->incrementMSManglingNumber();
1272 }
1273
1274 /// Try to recover by turning the given expression into a
1275 /// call. Returns true if recovery was attempted or an error was
1276 /// emitted; this may also leave the ExprResult invalid.
1278 bool ForceComplain = false,
1279 bool (*IsPlausibleResult)(QualType) = nullptr);
1280
1281 // Adds implicit lifetime bound attribute for implicit this to its
1282 // TypeSourceInfo.
1284
1285 /// Figure out if an expression could be turned into a call.
1286 ///
1287 /// Use this when trying to recover from an error where the programmer may
1288 /// have written just the name of a function instead of actually calling it.
1289 ///
1290 /// \param E - The expression to examine.
1291 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1292 /// with no arguments, this parameter is set to the type returned by such a
1293 /// call; otherwise, it is set to an empty QualType.
1294 /// \param OverloadSet - If the expression is an overloaded function
1295 /// name, this parameter is populated with the decls of the various
1296 /// overloads.
1297 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1298 UnresolvedSetImpl &NonTemplateOverloads);
1299
1303
1306
1314
1315 /// A RAII object to enter scope of a compound statement.
1317 public:
1318 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
1319 S.ActOnStartOfCompoundStmt(IsStmtExpr);
1320 }
1321
1322 ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); }
1325
1326 private:
1327 Sema &S;
1328 };
1329
1330 /// An RAII helper that pops function a function scope on exit.
1336 if (Active)
1337 S.PopFunctionScopeInfo();
1338 }
1339 void disable() { Active = false; }
1340 };
1341
1343 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1344 }
1345
1346 /// Worker object for performing CFG-based warnings.
1349
1350 /// Callback to the parser to parse templated functions when needed.
1351 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
1354
1356 LateTemplateParser = LTP;
1357 OpaqueParser = P;
1358 }
1359
1360 /// Callback to the parser to parse a type expressed as a string.
1361 std::function<TypeResult(StringRef, StringRef, SourceLocation)>
1363
1364 /// VAListTagName - The declaration name corresponding to __va_list_tag.
1365 /// This is used as part of a hack to omit that class from ADL results.
1367
1368 /// Is the last error level diagnostic immediate. This is used to determined
1369 /// whether the next info diagnostic should be immediate.
1371
1372 /// Track if we're currently analyzing overflow behavior types in assignment
1373 /// context.
1375
1376 class DelayedDiagnostics;
1377
1379 sema::DelayedDiagnosticPool *SavedPool = nullptr;
1381 };
1384
1385 /// A class which encapsulates the logic for delaying diagnostics
1386 /// during parsing and other processing.
1388 /// The current pool of diagnostics into which delayed
1389 /// diagnostics should go.
1390 sema::DelayedDiagnosticPool *CurPool = nullptr;
1391
1392 public:
1394
1395 /// Adds a delayed diagnostic.
1396 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
1397
1398 /// Determines whether diagnostics should be delayed.
1399 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
1400
1401 /// Returns the current delayed-diagnostics pool.
1402 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
1403
1404 /// Enter a new scope. Access and deprecation diagnostics will be
1405 /// collected in this pool.
1408 state.SavedPool = CurPool;
1409 CurPool = &pool;
1410 return state;
1411 }
1412
1413 /// Leave a delayed-diagnostic state that was previously pushed.
1414 /// Do not emit any of the diagnostics. This is performed as part
1415 /// of the bookkeeping of popping a pool "properly".
1417 CurPool = state.SavedPool;
1418 }
1419
1420 /// Enter a new scope where access and deprecation diagnostics are
1421 /// not delayed.
1424 state.SavedPool = CurPool;
1425 CurPool = nullptr;
1426 return state;
1427 }
1428
1429 /// Undo a previous pushUndelayed().
1431 assert(CurPool == nullptr);
1432 CurPool = state.SavedPool;
1433 }
1435
1439
1440 /// Diagnostics that are emitted only if we discover that the given function
1441 /// must be codegen'ed. Because handling these correctly adds overhead to
1442 /// compilation, this is currently only used for offload languages like CUDA,
1443 /// OpenMP, and SYCL.
1444 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
1445
1446 /// CurContext - This is the current declaration context of parsing.
1448
1450 assert(AMDGPUPtr);
1451 return *AMDGPUPtr;
1452 }
1453
1455 assert(ARMPtr);
1456 return *ARMPtr;
1457 }
1458
1460 assert(AVRPtr);
1461 return *AVRPtr;
1462 }
1463
1465 assert(BPFPtr);
1466 return *BPFPtr;
1467 }
1468
1470 assert(CodeCompletionPtr);
1471 return *CodeCompletionPtr;
1472 }
1473
1475 assert(CUDAPtr);
1476 return *CUDAPtr;
1477 }
1478
1480 assert(DirectXPtr);
1481 return *DirectXPtr;
1482 }
1483
1485 assert(HLSLPtr);
1486 return *HLSLPtr;
1487 }
1488
1490 assert(HexagonPtr);
1491 return *HexagonPtr;
1492 }
1493
1495 assert(LoongArchPtr);
1496 return *LoongArchPtr;
1497 }
1498
1500 assert(M68kPtr);
1501 return *M68kPtr;
1502 }
1503
1505 assert(MIPSPtr);
1506 return *MIPSPtr;
1507 }
1508
1510 assert(MSP430Ptr);
1511 return *MSP430Ptr;
1512 }
1513
1515 assert(NVPTXPtr);
1516 return *NVPTXPtr;
1517 }
1518
1520 assert(ObjCPtr);
1521 return *ObjCPtr;
1522 }
1523
1525 assert(OpenACCPtr);
1526 return *OpenACCPtr;
1527 }
1528
1530 assert(OpenCLPtr);
1531 return *OpenCLPtr;
1532 }
1533
1535 assert(OpenMPPtr && "SemaOpenMP is dead");
1536 return *OpenMPPtr;
1537 }
1538
1540 assert(PPCPtr);
1541 return *PPCPtr;
1542 }
1543
1545 assert(PseudoObjectPtr);
1546 return *PseudoObjectPtr;
1547 }
1548
1550 assert(RISCVPtr);
1551 return *RISCVPtr;
1552 }
1553
1555 assert(SPIRVPtr);
1556 return *SPIRVPtr;
1557 }
1558
1560 assert(SYCLPtr);
1561 return *SYCLPtr;
1562 }
1563
1565 assert(SwiftPtr);
1566 return *SwiftPtr;
1567 }
1568
1570 assert(SystemZPtr);
1571 return *SystemZPtr;
1572 }
1573
1575 assert(WasmPtr);
1576 return *WasmPtr;
1577 }
1578
1580 assert(X86Ptr);
1581 return *X86Ptr;
1582 }
1583
1584 /// Source of additional semantic information.
1586
1587protected:
1588 friend class Parser;
1590 friend class ASTReader;
1591 friend class ASTDeclReader;
1592 friend class ASTWriter;
1593
1594private:
1595 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1596 bool WarnedDarwinSDKInfoMissing = false;
1597
1598 StackExhaustionHandler StackHandler;
1599
1600 Sema(const Sema &) = delete;
1601 void operator=(const Sema &) = delete;
1602
1603 /// The handler for the FileChanged preprocessor events.
1604 ///
1605 /// Used for diagnostics that implement custom semantic analysis for #include
1606 /// directives, like -Wpragma-pack.
1607 sema::SemaPPCallbacks *SemaPPCallbackHandler;
1608
1609 /// The parser's current scope.
1610 ///
1611 /// The parser maintains this state here.
1612 Scope *CurScope;
1613
1614 mutable IdentifierInfo *Ident_super;
1615
1616 std::unique_ptr<SemaAMDGPU> AMDGPUPtr;
1617 std::unique_ptr<SemaARM> ARMPtr;
1618 std::unique_ptr<SemaAVR> AVRPtr;
1619 std::unique_ptr<SemaBPF> BPFPtr;
1620 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1621 std::unique_ptr<SemaCUDA> CUDAPtr;
1622 std::unique_ptr<SemaDirectX> DirectXPtr;
1623 std::unique_ptr<SemaHLSL> HLSLPtr;
1624 std::unique_ptr<SemaHexagon> HexagonPtr;
1625 std::unique_ptr<SemaLoongArch> LoongArchPtr;
1626 std::unique_ptr<SemaM68k> M68kPtr;
1627 std::unique_ptr<SemaMIPS> MIPSPtr;
1628 std::unique_ptr<SemaMSP430> MSP430Ptr;
1629 std::unique_ptr<SemaNVPTX> NVPTXPtr;
1630 std::unique_ptr<SemaObjC> ObjCPtr;
1631 std::unique_ptr<SemaOpenACC> OpenACCPtr;
1632 std::unique_ptr<SemaOpenCL> OpenCLPtr;
1633 std::unique_ptr<SemaOpenMP> OpenMPPtr;
1634 std::unique_ptr<SemaPPC> PPCPtr;
1635 std::unique_ptr<SemaPseudoObject> PseudoObjectPtr;
1636 std::unique_ptr<SemaRISCV> RISCVPtr;
1637 std::unique_ptr<SemaSPIRV> SPIRVPtr;
1638 std::unique_ptr<SemaSYCL> SYCLPtr;
1639 std::unique_ptr<SemaSwift> SwiftPtr;
1640 std::unique_ptr<SemaSystemZ> SystemZPtr;
1641 std::unique_ptr<SemaWasm> WasmPtr;
1642 std::unique_ptr<SemaX86> X86Ptr;
1643
1644 ///@}
1645
1646 //
1647 //
1648 // -------------------------------------------------------------------------
1649 //
1650 //
1651
1652 /// \name API Notes
1653 /// Implementations are in SemaAPINotes.cpp
1654 ///@{
1655
1656public:
1657 /// Map any API notes provided for this declaration to attributes on the
1658 /// declaration.
1659 ///
1660 /// Triggered by declaration-attribute processing.
1661 void ProcessAPINotes(Decl *D);
1662 /// Apply the 'Nullability:' annotation to the specified declaration
1663 void ApplyNullability(Decl *D, NullabilityKind Nullability);
1664 /// Apply the 'Type:' annotation to the specified declaration
1665 void ApplyAPINotesType(Decl *D, StringRef TypeString);
1666
1667 /// Whether APINotes should be gathered for all applicable Swift language
1668 /// versions, without being applied. Leaving clients of the current module
1669 /// to select and apply the correct version.
1671 return APINotes.captureVersionIndependentSwift();
1672 }
1673 ///@}
1674
1675 //
1676 //
1677 // -------------------------------------------------------------------------
1678 //
1679 //
1680
1681 /// \name C++ Access Control
1682 /// Implementations are in SemaAccess.cpp
1683 ///@{
1684
1685public:
1692
1693 /// SetMemberAccessSpecifier - Set the access specifier of a member.
1694 /// Returns true on error (when the previous member decl access specifier
1695 /// is different from the new member decl access specifier).
1696 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1697 NamedDecl *PrevMemberDecl,
1698 AccessSpecifier LexicalAS);
1699
1700 /// Perform access-control checking on a previously-unresolved member
1701 /// access which has now been resolved to a member.
1703 DeclAccessPair FoundDecl);
1705 DeclAccessPair FoundDecl);
1706
1707 /// Checks access to an overloaded operator new or delete.
1709 SourceRange PlacementRange,
1710 CXXRecordDecl *NamingClass,
1711 DeclAccessPair FoundDecl,
1712 bool Diagnose = true);
1713
1714 /// Checks access to a constructor.
1716 DeclAccessPair FoundDecl,
1717 const InitializedEntity &Entity,
1718 bool IsCopyBindingRefToTemp = false);
1719
1720 /// Checks access to a constructor.
1722 DeclAccessPair FoundDecl,
1723 const InitializedEntity &Entity,
1724 const PartialDiagnostic &PDiag);
1726 CXXDestructorDecl *Dtor,
1727 const PartialDiagnostic &PDiag,
1728 QualType objectType = QualType());
1729
1730 /// Checks access to the target of a friend declaration.
1732
1733 /// Checks access to a member.
1735 CXXRecordDecl *NamingClass,
1737
1738 /// Checks implicit access to a member in a structured binding.
1741 CXXRecordDecl *DecomposedClass,
1742 DeclAccessPair Field);
1744 const SourceRange &,
1745 DeclAccessPair FoundDecl);
1746
1747 /// Checks access to an overloaded member operator, including
1748 /// conversion operators.
1750 Expr *ArgExpr,
1751 DeclAccessPair FoundDecl);
1753 ArrayRef<Expr *> ArgExprs,
1754 DeclAccessPair FoundDecl);
1756 DeclAccessPair FoundDecl);
1757
1758 /// Checks access for a hierarchy conversion.
1759 ///
1760 /// \param ForceCheck true if this check should be performed even if access
1761 /// control is disabled; some things rely on this for semantics
1762 /// \param ForceUnprivileged true if this check should proceed as if the
1763 /// context had no special privileges
1765 QualType Derived, const CXXBasePath &Path,
1766 unsigned DiagID, bool ForceCheck = false,
1767 bool ForceUnprivileged = false);
1768
1770 SourceLocation AccessLoc, CXXRecordDecl *Base, CXXRecordDecl *Derived,
1771 const CXXBasePath &Path, unsigned DiagID,
1772 llvm::function_ref<void(PartialDiagnostic &PD)> SetupPDiag,
1773 bool ForceCheck = false, bool ForceUnprivileged = false);
1774
1775 /// Checks access to all the declarations in the given result set.
1776 void CheckLookupAccess(const LookupResult &R);
1777
1778 /// Checks access to Target from the given class. The check will take access
1779 /// specifiers into account, but no member access expressions and such.
1780 ///
1781 /// \param Target the declaration to check if it can be accessed
1782 /// \param NamingClass the class in which the lookup was started.
1783 /// \param BaseType type of the left side of member access expression.
1784 /// \p BaseType and \p NamingClass are used for C++ access control.
1785 /// Depending on the lookup case, they should be set to the following:
1786 /// - lhs.target (member access without a qualifier):
1787 /// \p BaseType and \p NamingClass are both the type of 'lhs'.
1788 /// - lhs.X::target (member access with a qualifier):
1789 /// BaseType is the type of 'lhs', NamingClass is 'X'
1790 /// - X::target (qualified lookup without member access):
1791 /// BaseType is null, NamingClass is 'X'.
1792 /// - target (unqualified lookup).
1793 /// BaseType is null, NamingClass is the parent class of 'target'.
1794 /// \return true if the Target is accessible from the Class, false otherwise.
1795 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1796 QualType BaseType);
1797
1798 /// Is the given member accessible for the purposes of deciding whether to
1799 /// define a special member function as deleted?
1801 DeclAccessPair Found, QualType ObjectType,
1802 SourceLocation Loc,
1803 const PartialDiagnostic &Diag);
1806 QualType ObjectType) {
1807 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1808 SourceLocation(), PDiag());
1809 }
1810
1812 const DependentDiagnostic &DD,
1813 const MultiLevelTemplateArgumentList &TemplateArgs);
1815
1816 ///@}
1817
1818 //
1819 //
1820 // -------------------------------------------------------------------------
1821 //
1822 //
1823
1824 /// \name Attributes
1825 /// Implementations are in SemaAttr.cpp
1826 ///@{
1827
1828public:
1829 /// Controls member pointer representation format under the MS ABI.
1832
1833 bool MSStructPragmaOn; // True when \#pragma ms_struct on
1834
1835 /// Source location for newly created implicit MSInheritanceAttrs
1837
1843
1849
1851 PSK_Reset = 0x0, // #pragma ()
1852 PSK_Set = 0x1, // #pragma (value)
1853 PSK_Push = 0x2, // #pragma (push[, id])
1854 PSK_Pop = 0x4, // #pragma (pop[, id])
1855 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
1856 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1857 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
1858 };
1859
1865
1866 // #pragma pack and align.
1868 public:
1869 // `Native` represents default align mode, which may vary based on the
1870 // platform.
1871 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1872
1873 // #pragma pack info constructor
1874 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1875 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1876 assert(Num == PackNumber && "The pack number has been truncated.");
1877 }
1878
1879 // #pragma align info constructor
1881 : PackAttr(false), AlignMode(M),
1882 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1883
1884 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1885
1887
1888 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1889 // integer encoding for it. This should only be passed to
1890 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
1892 std::uint32_t Encoding{};
1893 if (Info.IsXLStack())
1894 Encoding |= IsXLMask;
1895
1896 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1897
1898 if (Info.IsPackAttr())
1899 Encoding |= PackAttrMask;
1900
1901 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1902
1903 return Encoding;
1904 }
1905
1906 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1907 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1909 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1910 int PackNumber = (Encoding & PackNumMask) >> 4;
1911
1912 if (Encoding & PackAttrMask)
1913 return AlignPackInfo(M, PackNumber, IsXL);
1914
1915 return AlignPackInfo(M, IsXL);
1916 }
1917
1918 bool IsPackAttr() const { return PackAttr; }
1919
1920 bool IsAlignAttr() const { return !PackAttr; }
1921
1922 Mode getAlignMode() const { return AlignMode; }
1923
1924 unsigned getPackNumber() const { return PackNumber; }
1925
1926 bool IsPackSet() const {
1927 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1928 // attriute on a decl.
1929 return PackNumber != UninitPackVal && PackNumber != 0;
1930 }
1931
1932 bool IsXLStack() const { return XLStack; }
1933
1934 bool operator==(const AlignPackInfo &Info) const {
1935 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
1936 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
1937 Info.XLStack);
1938 }
1939
1940 bool operator!=(const AlignPackInfo &Info) const {
1941 return !(*this == Info);
1942 }
1943
1944 private:
1945 /// \brief True if this is a pragma pack attribute,
1946 /// not a pragma align attribute.
1947 bool PackAttr;
1948
1949 /// \brief The alignment mode that is in effect.
1950 Mode AlignMode;
1951
1952 /// \brief The pack number of the stack.
1953 unsigned char PackNumber;
1954
1955 /// \brief True if it is a XL #pragma align/pack stack.
1956 bool XLStack;
1957
1958 /// \brief Uninitialized pack value.
1959 static constexpr unsigned char UninitPackVal = -1;
1960
1961 // Masks to encode and decode an AlignPackInfo.
1962 static constexpr uint32_t IsXLMask{0x0000'0001};
1963 static constexpr uint32_t AlignModeMask{0x0000'0006};
1964 static constexpr uint32_t PackAttrMask{0x00000'0008};
1965 static constexpr uint32_t PackNumMask{0x0000'01F0};
1966 };
1967
1968 template <typename ValueType> struct PragmaStack {
1980
1981 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
1982 llvm::StringRef StackSlotLabel, ValueType Value) {
1983 if (Action == PSK_Reset) {
1985 CurrentPragmaLocation = PragmaLocation;
1986 return;
1987 }
1988 if (Action & PSK_Push)
1989 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
1990 PragmaLocation);
1991 else if (Action & PSK_Pop) {
1992 if (!StackSlotLabel.empty()) {
1993 // If we've got a label, try to find it and jump there.
1994 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
1995 return x.StackSlotLabel == StackSlotLabel;
1996 });
1997 // If we found the label so pop from there.
1998 if (I != Stack.rend()) {
1999 CurrentValue = I->Value;
2000 CurrentPragmaLocation = I->PragmaLocation;
2001 Stack.erase(std::prev(I.base()), Stack.end());
2002 }
2003 } else if (!Stack.empty()) {
2004 // We do not have a label, just pop the last entry.
2005 CurrentValue = Stack.back().Value;
2006 CurrentPragmaLocation = Stack.back().PragmaLocation;
2007 Stack.pop_back();
2008 }
2009 }
2010 if (Action & PSK_Set) {
2012 CurrentPragmaLocation = PragmaLocation;
2013 }
2014 }
2015
2016 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
2017 // method body to restore the stacks on exit, so it works like this:
2018 //
2019 // struct S {
2020 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
2021 // void Method {}
2022 // #pragma <name>(pop, InternalPragmaSlot)
2023 // };
2024 //
2025 // It works even with #pragma vtordisp, although MSVC doesn't support
2026 // #pragma vtordisp(push [, id], n)
2027 // syntax.
2028 //
2029 // Push / pop a named sentinel slot.
2030 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
2031 assert((Action == PSK_Push || Action == PSK_Pop) &&
2032 "Can only push / pop #pragma stack sentinels!");
2033 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
2034 }
2035
2036 // Constructors.
2037 explicit PragmaStack(const ValueType &Default)
2039
2040 bool hasValue() const { return CurrentValue != DefaultValue; }
2041
2043 ValueType DefaultValue; // Value used for PSK_Reset action.
2044 ValueType CurrentValue;
2046 };
2047 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
2048 // we shouldn't do so if they're in a module).
2049
2050 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
2051 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
2052 ///
2053 /// 0: Suppress all vtordisps
2054 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
2055 /// structors
2056 /// 2: Always insert vtordisps to support RTTI on partially constructed
2057 /// objects
2060 // The current #pragma align/pack values and locations at each #include.
2067 // Segment #pragmas.
2072
2073 // #pragma strict_gs_check.
2075
2076 // This stack tracks the current state of Sema.CurFPFeatures.
2079 FPOptionsOverride result;
2080 if (!FpPragmaStack.hasValue()) {
2081 result = FPOptionsOverride();
2082 } else {
2083 result = FpPragmaStack.CurrentValue;
2084 }
2085 return result;
2086 }
2087
2094
2095 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
2096 // Actions should be performed only if we enter / exit a C++ method body.
2098 public:
2099 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
2104
2105 private:
2106 Sema &S;
2107 StringRef SlotLabel;
2108 bool ShouldAct;
2109 };
2110
2111 /// Last section used with #pragma init_seg.
2114
2115 /// Sections used with #pragma alloc_text.
2116 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
2117
2118 /// VisContext - Manages the stack for \#pragma GCC visibility.
2119 void *VisContext; // Really a "PragmaVisStack*"
2120
2121 /// This an attribute introduced by \#pragma clang attribute.
2128
2129 /// A push'd group of PragmaAttributeEntries.
2131 /// The location of the push attribute.
2133 /// The namespace of this push group.
2136 };
2137
2139
2140 /// The declaration that is currently receiving an attribute from the
2141 /// #pragma attribute stack.
2143
2144 /// This represents the last location of a "#pragma clang optimize off"
2145 /// directive if such a directive has not been closed by an "on" yet. If
2146 /// optimizations are currently "on", this is set to an invalid location.
2148
2149 /// Get the location for the currently active "\#pragma clang optimize
2150 /// off". If this location is invalid, then the state of the pragma is "on".
2154
2155 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
2156 /// whether the optimizations in the list passed to the pragma should be
2157 /// turned off or on. This boolean is true by default because command line
2158 /// options are honored when `#pragma optimize("", on)`.
2159 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
2161
2162 /// Set of no-builtin functions listed by \#pragma function.
2164
2165 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
2166 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
2168
2169 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
2171
2172 /// Add gsl::Pointer attribute to std::container::iterator
2173 /// \param ND The declaration that introduces the name
2174 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
2175 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
2176
2177 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
2179
2180 /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
2182
2183 /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
2185
2186 /// Add [[gsl::Pointer]] attributes for std:: types.
2188
2189 LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
2190 StringRef ParamName);
2191 // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
2192 // can be the name of a function parameter, we need to parse the function
2193 // declaration and rest of the parameters before processesing 'X'. Therefore
2194 // do this lazily instead of processing while parsing the annotation itself.
2196
2197 /// Add _Nullable attributes for std:: types.
2199
2200 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
2203 PragmaClangSectionKind SecKind,
2204 StringRef SecName);
2205
2206 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
2208 SourceLocation PragmaLoc);
2209
2210 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
2211 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
2212 StringRef SlotLabel, Expr *Alignment);
2213
2214 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
2215 /// (unless they are value dependent or type dependent). Returns false
2216 /// and emits a diagnostic if one or more of the arguments could not be
2217 /// folded into a constant.
2220
2225
2227 SourceLocation IncludeLoc);
2229
2230 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
2232
2233 /// ActOnPragmaMSComment - Called on well formed
2234 /// \#pragma comment(kind, "arg").
2236 StringRef Arg);
2237
2238 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
2239 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
2240 StringRef Value);
2241
2242 /// Are precise floating point semantics currently enabled?
2244 return !CurFPFeatures.getAllowFPReassociate() &&
2245 !CurFPFeatures.getNoSignedZero() &&
2246 !CurFPFeatures.getAllowReciprocal() &&
2247 !CurFPFeatures.getAllowApproxFunc();
2248 }
2249
2252
2253 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
2254 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
2256
2257 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
2258 /// pointers_to_members(representation method[, general purpose
2259 /// representation]).
2262 SourceLocation PragmaLoc);
2263
2264 /// Called on well formed \#pragma vtordisp().
2265 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
2267
2268 bool UnifySection(StringRef SectionName, int SectionFlags,
2269 NamedDecl *TheDecl);
2270 bool UnifySection(StringRef SectionName, int SectionFlags,
2271 SourceLocation PragmaSectionLocation);
2272
2273 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
2274 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
2275 PragmaMsStackAction Action,
2276 llvm::StringRef StackSlotLabel,
2277 StringLiteral *SegmentName, llvm::StringRef PragmaName);
2278
2279 /// Called on well formed \#pragma section().
2280 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
2281 StringLiteral *SegmentName);
2282
2283 /// Called on well-formed \#pragma init_seg().
2284 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
2285 StringLiteral *SegmentName);
2286
2287 /// Called on well-formed \#pragma alloc_text().
2289 SourceLocation PragmaLocation, StringRef Section,
2290 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
2291 &Functions);
2292
2293 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
2294 /// strict_gs_check.
2296 PragmaMsStackAction Action,
2297 bool Value);
2298
2299 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
2300 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
2301 SourceLocation PragmaLoc);
2302
2304 SourceLocation PragmaLoc,
2307 const IdentifierInfo *Namespace);
2308
2309 /// Called on well-formed '\#pragma clang attribute pop'.
2311 const IdentifierInfo *Namespace);
2312
2313 /// Adds the attributes that have been specified using the
2314 /// '\#pragma clang attribute push' directives to the given declaration.
2315 void AddPragmaAttributes(Scope *S, Decl *D);
2316
2318 llvm::function_ref<void(SourceLocation, PartialDiagnostic)>;
2320 return [this](SourceLocation Loc, PartialDiagnostic PD) {
2321 // This bypasses a lot of the filters in the diag engine, as it's
2322 // to be used to attach notes to diagnostics which have already
2323 // been filtered through.
2324 DiagnosticBuilder Builder(Diags.Report(Loc, PD.getDiagID()));
2325 PD.Emit(Builder);
2326 };
2327 }
2328
2334
2336
2337 /// Called on well formed \#pragma clang optimize.
2338 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
2339
2340 /// #pragma optimize("[optimization-list]", on | off).
2341 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
2342
2343 /// Call on well formed \#pragma function.
2344 void
2346 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
2347
2349 SourceLocation NameLoc,
2350 Scope *curScope);
2351
2352 /// Information from a C++ #pragma export, for a symbol that we
2353 /// haven't seen the declaration for yet.
2358
2359 llvm::DenseMap<IdentifierInfo *, PendingPragmaInfo> PendingExportedNames;
2360
2361 /// ActonPragmaExport - called on well-formed '\#pragma export'.
2362 void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc,
2363 Scope *curScope);
2364
2365 /// Only called on function definitions; if there is a pragma in scope
2366 /// with the effect of a range-based optnone, consider marking the function
2367 /// with attribute optnone.
2369
2370 /// Only called on function definitions; if there is a `#pragma alloc_text`
2371 /// that decides which code section the function should be in, add
2372 /// attribute section to the function.
2374
2375 /// Adds the 'optnone' attribute to the function declaration if there
2376 /// are no conflicts; Loc represents the location causing the 'optnone'
2377 /// attribute to be added (usually because of a pragma).
2379
2380 /// Only called on function definitions; if there is a MSVC #pragma optimize
2381 /// in scope, consider changing the function's attributes based on the
2382 /// optimization list passed to the pragma.
2384
2385 /// Only called on function definitions; if there is a pragma in scope
2386 /// with the effect of a range-based no_builtin, consider marking the function
2387 /// with attribute no_builtin.
2389
2390 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
2391 /// add an appropriate visibility attribute.
2393
2394 /// FreeVisContext - Deallocate and null out VisContext.
2395 void FreeVisContext();
2396
2397 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
2398 void ActOnPragmaVisibility(const IdentifierInfo *VisType,
2399 SourceLocation PragmaLoc);
2400
2401 /// ActOnPragmaFPContract - Called on well formed
2402 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
2403 /// \#pragma clang fp contract
2405
2406 /// Called on well formed
2407 /// \#pragma clang fp reassociate
2408 /// or
2409 /// \#pragma clang fp reciprocal
2411 bool IsEnabled);
2412
2413 /// ActOnPragmaFenvAccess - Called on well formed
2414 /// \#pragma STDC FENV_ACCESS
2415 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
2416
2417 /// ActOnPragmaCXLimitedRange - Called on well formed
2418 /// \#pragma STDC CX_LIMITED_RANGE
2421
2422 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
2425
2426 /// Called to set constant rounding mode for floating point operations.
2427 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
2428
2429 /// Called to set exception behavior for floating point operations.
2431
2432 /// PushNamespaceVisibilityAttr - Note that we've entered a
2433 /// namespace with a visibility attribute.
2434 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
2435 SourceLocation Loc);
2436
2437 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
2438 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
2439 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
2440
2441 /// Handles semantic checking for features that are common to all attributes,
2442 /// such as checking whether a parameter was properly specified, or the
2443 /// correct number of arguments were passed, etc. Returns true if the
2444 /// attribute has been diagnosed.
2445 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
2446 bool SkipArgCountCheck = false);
2447 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
2448 bool SkipArgCountCheck = false);
2449
2450 ///@}
2451
2452 //
2453 //
2454 // -------------------------------------------------------------------------
2455 //
2456 //
2457
2458 /// \name Availability Attribute Handling
2459 /// Implementations are in SemaAvailability.cpp
2460 ///@{
2461
2462public:
2463 /// Issue any -Wunguarded-availability warnings in \c FD
2465
2467
2468 /// Retrieve the current function, if any, that should be analyzed for
2469 /// potential availability violations.
2471
2473 const ObjCInterfaceDecl *UnknownObjCClass,
2474 bool ObjCPropertyAccess,
2475 bool AvoidPartialAvailabilityChecks,
2476 ObjCInterfaceDecl *ClassReceiver);
2477
2479
2480 std::pair<AvailabilityResult, const NamedDecl *>
2481 ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
2482 ObjCInterfaceDecl *ClassReceiver);
2483 ///@}
2484
2485 //
2486 //
2487 // -------------------------------------------------------------------------
2488 //
2489 //
2490
2491 /// \name Bounds Safety
2492 /// Implementations are in SemaBoundsSafety.cpp
2493 ///@{
2494public:
2495 /// Check if applying the specified attribute variant from the "counted by"
2496 /// family of attributes to FieldDecl \p FD is semantically valid. If
2497 /// semantically invalid diagnostics will be emitted explaining the problems.
2498 ///
2499 /// \param FD The FieldDecl to apply the attribute to
2500 /// \param E The count expression on the attribute
2501 /// \param CountInBytes If true the attribute is from the "sized_by" family of
2502 /// attributes. If the false the attribute is from
2503 /// "counted_by" family of attributes.
2504 /// \param OrNull If true the attribute is from the "_or_null" suffixed family
2505 /// of attributes. If false the attribute does not have the
2506 /// suffix.
2507 ///
2508 /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g.
2509 /// \p CountInBytes and \p OrNull both being true indicates the
2510 /// `counted_by_or_null` attribute.
2511 ///
2512 /// \returns false iff semantically valid.
2513 bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
2514 bool OrNull);
2515
2516 /// Perform Bounds Safety Semantic checks for assigning to a `__counted_by` or
2517 /// `__counted_by_or_null` pointer type \param LHSTy.
2518 ///
2519 /// \param LHSTy The type being assigned to. Checks will only be performed if
2520 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2521 /// \param RHSExpr The expression being assigned from.
2522 /// \param Action The type assignment being performed
2523 /// \param Loc The SourceLocation to use for error diagnostics
2524 /// \param Assignee The ValueDecl being assigned. This is used to compute
2525 /// the name of the assignee. If the assignee isn't known this can
2526 /// be set to nullptr.
2527 /// \param ShowFullyQualifiedAssigneeName If set to true when using \p
2528 /// Assignee to compute the name of the assignee use the fully
2529 /// qualified name, otherwise use the unqualified name.
2530 ///
2531 /// \returns True iff no diagnostic where emitted, false otherwise.
2533 QualType LHSTy, Expr *RHSExpr, AssignmentAction Action,
2534 SourceLocation Loc, const ValueDecl *Assignee,
2535 bool ShowFullyQualifiedAssigneeName);
2536
2537 /// Perform Bounds Safety Semantic checks for initializing a Bounds Safety
2538 /// pointer.
2539 ///
2540 /// \param Entity The entity being initialized
2541 /// \param Kind The kind of initialization being performed
2542 /// \param Action The type assignment being performed
2543 /// \param LHSTy The type being assigned to. Checks will only be performed if
2544 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2545 /// \param RHSExpr The expression being used for initialization.
2546 ///
2547 /// \returns True iff no diagnostic where emitted, false otherwise.
2549 const InitializationKind &Kind,
2550 AssignmentAction Action,
2551 QualType LHSType, Expr *RHSExpr);
2552
2553 /// Perform Bounds Safety semantic checks for uses of invalid uses counted_by
2554 /// or counted_by_or_null pointers in \param E.
2555 ///
2556 /// \param E the expression to check
2557 ///
2558 /// \returns True iff no diagnostic where emitted, false otherwise.
2560 ///@}
2561
2562 //
2563 //
2564 // -------------------------------------------------------------------------
2565 //
2566 //
2567
2568 /// \name Casts
2569 /// Implementations are in SemaCast.cpp
2570 ///@{
2571
2572public:
2578
2579 /// ActOnCXXNamedCast - Parse
2580 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
2582 SourceLocation LAngleBracketLoc, Declarator &D,
2583 SourceLocation RAngleBracketLoc,
2584 SourceLocation LParenLoc, Expr *E,
2585 SourceLocation RParenLoc);
2586
2588 TypeSourceInfo *Ty, Expr *E,
2589 SourceRange AngleBrackets, SourceRange Parens);
2590
2592 ExprResult Operand,
2593 SourceLocation RParenLoc);
2594
2596 Expr *Operand, SourceLocation RParenLoc);
2597
2598 // Checks that reinterpret casts don't have undefined behavior.
2599 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2600 bool IsDereference, SourceRange Range);
2601
2602 // Checks that the vector type should be initialized from a scalar
2603 // by splatting the value rather than populating a single element.
2604 // This is the case for AltiVecVector types as well as with
2605 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
2606 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
2607
2608 // Checks if the -faltivec-src-compat=gcc option is specified.
2609 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
2610 // treated the same way as they are when trying to initialize
2611 // these vectors on gcc (an error is emitted).
2613 QualType SrcTy);
2614
2616 SourceLocation RParenLoc, Expr *Op);
2617
2619 SourceLocation LParenLoc,
2620 Expr *CastExpr,
2621 SourceLocation RParenLoc);
2622
2623 ///@}
2624
2625 //
2626 //
2627 // -------------------------------------------------------------------------
2628 //
2629 //
2630
2631 /// \name Extra Semantic Checking
2632 /// Implementations are in SemaChecking.cpp
2633 ///@{
2634
2635public:
2636 /// Used to change context to isConstantEvaluated without pushing a heavy
2637 /// ExpressionEvaluationContextRecord object.
2639
2644
2646 unsigned ByteNo) const;
2647
2649 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
2650 FAPK_Variadic, // values to format are passed as variadic arguments
2651 FAPK_VAList, // values to format are passed in a va_list
2652 FAPK_Elsewhere, // values to format are not passed to this function
2653 };
2654
2655 // Used to grab the relevant information from a FormatAttr and a
2656 // FunctionDeclaration.
2662
2663 /// Given a function and its FormatAttr or FormatMatchesAttr info, attempts to
2664 /// populate the FormatStringInfo parameter with the attribute's correct
2665 /// format_idx and firstDataArg. Returns true when the format fits the
2666 /// function and the FormatStringInfo has been populated.
2667 static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx,
2668 unsigned FirstArg, FormatStringInfo *FSI);
2669 static bool getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
2670 bool HasImplicitThisParam, bool IsVariadic,
2671 FormatStringInfo *FSI);
2672
2673 // Used by C++ template instantiation.
2675
2676 /// ConvertVectorExpr - Handle __builtin_convertvector
2678 SourceLocation BuiltinLoc,
2679 SourceLocation RParenLoc);
2680
2681 static StringRef GetFormatStringTypeName(FormatStringType FST);
2682 static FormatStringType GetFormatStringType(StringRef FormatFlavor);
2683 static FormatStringType GetFormatStringType(const FormatAttr *Format);
2684 static FormatStringType GetFormatStringType(const FormatMatchesAttr *Format);
2685
2686 bool FormatStringHasSArg(const StringLiteral *FExpr);
2687
2688 /// Check for comparisons of floating-point values using == and !=. Issue a
2689 /// warning if the comparison is not likely to do what the programmer
2690 /// intended.
2691 void CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
2692 const Expr *RHS, BinaryOperatorKind Opcode);
2693
2694 /// Register a magic integral constant to be used as a type tag.
2695 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
2696 uint64_t MagicValue, QualType Type,
2697 bool LayoutCompatible, bool MustBeNull);
2698
2701
2705
2707
2708 /// If true, \c Type should be compared with other expression's types for
2709 /// layout-compatibility.
2710 LLVM_PREFERRED_TYPE(bool)
2712 LLVM_PREFERRED_TYPE(bool)
2713 unsigned MustBeNull : 1;
2714 };
2715
2716 /// A pair of ArgumentKind identifier and magic value. This uniquely
2717 /// identifies the magic value.
2718 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
2719
2720 /// Diagnoses the current set of gathered accesses. This happens at the end of
2721 /// each expression evaluation context. Diagnostics are emitted only for
2722 /// accesses gathered in the current evaluation context.
2724
2725 /// This function checks if the expression is in the sef of potentially
2726 /// misaligned members and it is converted to some pointer type T with lower
2727 /// or equal alignment requirements. If so it removes it. This is used when
2728 /// we do not want to diagnose such misaligned access (e.g. in conversions to
2729 /// void*).
2730 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
2731
2732 /// Returns true if `From` is a function or pointer to a function with the
2733 /// `cfi_unchecked_callee` attribute but `To` is a function or pointer to
2734 /// function without this attribute.
2735 bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const;
2736
2737 /// This function calls Action when it determines that E designates a
2738 /// misaligned member due to the packed attribute. This is used to emit
2739 /// local diagnostics like in reference binding.
2741 Expr *E,
2742 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
2743 Action);
2744
2745 enum class AtomicArgumentOrder { API, AST };
2747 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
2748 SourceLocation RParenLoc, MultiExprArg Args,
2751
2752 /// Check to see if a given expression could have '.c_str()' called on it.
2753 bool hasCStrMethod(const Expr *E);
2754
2755 /// Diagnose pointers that are always non-null.
2756 /// \param E the expression containing the pointer
2757 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
2758 /// compared to a null pointer
2759 /// \param IsEqual True when the comparison is equal to a null pointer
2760 /// \param Range Extra SourceRange to highlight in the diagnostic
2763 bool IsEqual, SourceRange Range);
2764
2765 /// CheckParmsForFunctionDef - Check that the parameters of the given
2766 /// function are appropriate for the definition of a function. This
2767 /// takes care of any checks that cannot be performed on the
2768 /// declaration itself, e.g., that the types of each of the function
2769 /// parameters are complete.
2771 bool CheckParameterNames);
2772
2773 /// CheckCastAlign - Implements -Wcast-align, which warns when a
2774 /// pointer cast increases the alignment requirements.
2775 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2776
2777 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
2778 /// to weak/__unsafe_unretained type.
2779 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
2780
2781 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
2782 /// to weak/__unsafe_unretained expression.
2783 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
2784
2785 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2786 /// statement as a \p Body, and it is located on the same line.
2787 ///
2788 /// This helps prevent bugs due to typos, such as:
2789 /// if (condition);
2790 /// do_stuff();
2791 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
2792 unsigned DiagID);
2793
2794 /// Warn if a for/while loop statement \p S, which is followed by
2795 /// \p PossibleBody, has a suspicious null statement as a body.
2796 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
2797
2798 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
2799 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2800 SourceLocation OpLoc);
2801
2802 bool IsLayoutCompatible(QualType T1, QualType T2) const;
2804 const TypeSourceInfo *Derived);
2805
2806 /// CheckFunctionCall - Check a direct function call for various correctness
2807 /// and safety properties not strictly enforced by the C type system.
2808 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2809 const FunctionProtoType *Proto);
2810
2817
2818 /// \param FPOnly restricts the arguments to floating-point types.
2819 std::optional<QualType>
2820 BuiltinVectorMath(CallExpr *TheCall,
2823 bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2824
2825 void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction,
2826 const Expr *ThisArg, ArrayRef<const Expr *> Args);
2827
2828 /// Handles the checks for format strings, non-POD arguments to vararg
2829 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
2830 /// attributes and AArch64 SME attributes.
2831 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2832 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2833 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2834 VariadicCallType CallType);
2835
2836 /// Verify that two format strings (as understood by attribute(format) and
2837 /// attribute(format_matches) are compatible. If they are incompatible,
2838 /// diagnostics are emitted with the assumption that \c
2839 /// AuthoritativeFormatString is correct and
2840 /// \c TestedFormatString is wrong. If \c FunctionCallArg is provided,
2841 /// diagnostics will point to it and a note will refer to \c
2842 /// TestedFormatString or \c AuthoritativeFormatString as appropriate.
2843 bool
2845 const StringLiteral *AuthoritativeFormatString,
2846 const StringLiteral *TestedFormatString,
2847 const Expr *FunctionCallArg = nullptr);
2848
2849 /// Verify that one format string (as understood by attribute(format)) is
2850 /// self-consistent; for instance, that it doesn't have multiple positional
2851 /// arguments referring to the same argument in incompatible ways. Diagnose
2852 /// if it isn't.
2854
2855 /// \brief Enforce the bounds of a TCB
2856 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
2857 /// directly calls other functions in the same TCB as marked by the
2858 /// enforce_tcb and enforce_tcb_leaf attributes.
2859 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2860 const NamedDecl *Callee);
2861
2862 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2863
2864 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2865 /// TheCall is a constant expression.
2866 bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
2867 llvm::APSInt &Result);
2868
2869 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2870 /// TheCall is a constant expression in the range [Low, High].
2871 bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
2872 int High, bool RangeIsError = true);
2873
2874 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
2875 /// TheCall is a constant expression is a multiple of Num..
2876 bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
2877 unsigned Multiple);
2878
2879 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
2880 /// constant expression representing a power of 2.
2881 bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum);
2882
2883 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
2884 /// a constant expression representing an arbitrary byte value shifted left by
2885 /// a multiple of 8 bits.
2886 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
2887 unsigned ArgBits);
2888
2889 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
2890 /// TheCall is a constant expression representing either a shifted byte value,
2891 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
2892 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
2893 /// Arm MVE intrinsics.
2894 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum,
2895 unsigned ArgBits);
2896
2897 /// Checks that a call expression's argument count is at least the desired
2898 /// number. This is useful when doing custom type-checking on a variadic
2899 /// function. Returns true on error.
2900 bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount);
2901
2902 /// Checks that a call expression's argument count is at most the desired
2903 /// number. This is useful when doing custom type-checking on a variadic
2904 /// function. Returns true on error.
2905 bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount);
2906
2907 /// Checks that a call expression's argument count is in the desired range.
2908 /// This is useful when doing custom type-checking on a variadic function.
2909 /// Returns true on error.
2910 bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
2911 unsigned MaxArgCount);
2912
2913 /// Checks that a call expression's argument count is the desired number.
2914 /// This is useful when doing custom type-checking. Returns true on error.
2915 bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount);
2916
2917 /// Returns true if the argument consists of one contiguous run of 1s with any
2918 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
2919 /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
2920 /// since all 1s are not contiguous.
2921 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
2922
2924 bool *ICContext = nullptr,
2925 bool IsListInit = false);
2926
2927 /// Check for overflow behavior type related implicit conversion diagnostics.
2928 /// Returns true if OBT-related diagnostic was issued, false otherwise.
2930 SourceLocation CC);
2931
2932 bool
2937 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr =
2939
2940private:
2941 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
2942 const ArraySubscriptExpr *ASE = nullptr,
2943 bool AllowOnePastEnd = true, bool IndexNegated = false);
2944 void CheckArrayAccess(const Expr *E);
2945
2946 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2947 const FunctionProtoType *Proto);
2948
2949 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2950 /// such as function pointers returned from functions.
2951 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
2952
2953 /// CheckConstructorCall - Check a constructor call for correctness and safety
2954 /// properties not enforced by the C type system.
2955 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
2957 const FunctionProtoType *Proto, SourceLocation Loc);
2958
2959 /// Warn if a pointer or reference argument passed to a function points to an
2960 /// object that is less aligned than the parameter. This can happen when
2961 /// creating a typedef with a lower alignment than the original type and then
2962 /// calling functions defined in terms of the original type.
2963 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
2964 StringRef ParamName, QualType ArgTy, QualType ParamTy);
2965
2966 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
2967
2968 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2969 CallExpr *TheCall);
2970
2971 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2972 CallExpr *TheCall);
2973
2974 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
2975
2976 /// Argument-value fortify checks for libc functions that are not builtins,
2977 /// dispatched by name (e.g. umask). Diagnostics belong to -Wfortify-source.
2978 void checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall);
2979
2980 /// Check the arguments to '__builtin_va_start', '__builtin_ms_va_start',
2981 /// or '__builtin_c23_va_start' for validity. Emit an error and return true
2982 /// on failure; return false on success.
2983 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
2984 bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
2985
2986 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2987 /// friends. This is declared to take (...), so we have to check everything.
2988 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
2989
2990 /// BuiltinSemaBuiltinFPClassification - Handle functions like
2991 /// __builtin_isnan and friends. This is declared to take (...), so we have
2992 /// to check everything.
2993 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
2994 unsigned BuiltinID);
2995
2996 /// Perform semantic analysis for a call to __builtin_complex.
2997 bool BuiltinComplex(CallExpr *TheCall);
2998 bool BuiltinOSLogFormat(CallExpr *TheCall);
2999
3000 /// BuiltinPrefetch - Handle __builtin_prefetch.
3001 /// This is declared to take (const void*, ...) and can take two
3002 /// optional constant int args.
3003 bool BuiltinPrefetch(CallExpr *TheCall);
3004
3005 /// Handle __builtin_alloca_with_align. This is declared
3006 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3007 /// than 8.
3008 bool BuiltinAllocaWithAlign(CallExpr *TheCall);
3009
3010 /// BuiltinArithmeticFence - Handle __arithmetic_fence.
3011 bool BuiltinArithmeticFence(CallExpr *TheCall);
3012
3013 /// BuiltinAssume - Handle __assume (MS Extension).
3014 /// __assume does not evaluate its arguments, and should warn if its argument
3015 /// has side effects.
3016 bool BuiltinAssume(CallExpr *TheCall);
3017
3018 /// Handle __builtin_assume_aligned. This is declared
3019 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3020 bool BuiltinAssumeAligned(CallExpr *TheCall);
3021
3022 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3023 /// This checks that the target supports __builtin_longjmp and
3024 /// that val is a constant 1.
3025 bool BuiltinLongjmp(CallExpr *TheCall);
3026
3027 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3028 /// This checks that the target supports __builtin_setjmp.
3029 bool BuiltinSetjmp(CallExpr *TheCall);
3030
3031 /// We have a call to a function like __sync_fetch_and_add, which is an
3032 /// overloaded function based on the pointer type of its first argument.
3033 /// The main BuildCallExpr routines have already promoted the types of
3034 /// arguments because all of these calls are prototyped as void(...).
3035 ///
3036 /// This function goes through and does final semantic checking for these
3037 /// builtins, as well as generating any warnings.
3038 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
3039
3040 /// BuiltinNontemporalOverloaded - We have a call to
3041 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3042 /// overloaded function based on the pointer type of its last argument.
3043 ///
3044 /// This function goes through and does final semantic checking for these
3045 /// builtins.
3046 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
3047 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
3049
3050 /// \param FPOnly restricts the arguments to floating-point types.
3051 bool BuiltinElementwiseMath(CallExpr *TheCall,
3054 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
3055
3056 bool BuiltinNonDeterministicValue(CallExpr *TheCall);
3057
3058 bool CheckInvalidBuiltinCountedByRef(const Expr *E,
3060 bool BuiltinCountedByRef(CallExpr *TheCall);
3061
3062 // Matrix builtin handling.
3063 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
3064 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
3065 ExprResult CallResult);
3066 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
3067 ExprResult CallResult);
3068
3069 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3070 /// functions) for correct use of format strings.
3071 /// Returns true if a format string has been fully checked.
3072 bool CheckFormatArguments(const FormatAttr *Format,
3073 ArrayRef<const Expr *> Args, bool IsCXXMember,
3074 VariadicCallType CallType, SourceLocation Loc,
3075 SourceRange Range,
3076 llvm::SmallBitVector &CheckedVarArgs);
3077 bool CheckFormatString(const FormatMatchesAttr *Format,
3078 ArrayRef<const Expr *> Args, bool IsCXXMember,
3079 VariadicCallType CallType, SourceLocation Loc,
3080 SourceRange Range,
3081 llvm::SmallBitVector &CheckedVarArgs);
3082 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
3083 FormatArgumentPassingKind FAPK,
3084 StringLiteral *ReferenceFormatString,
3085 unsigned format_idx, unsigned firstDataArg,
3087 SourceLocation Loc, SourceRange range,
3088 llvm::SmallBitVector &CheckedVarArgs);
3089
3090 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
3091
3092 /// Warn when using the wrong abs() function.
3093 void CheckAbsoluteValueFunction(const CallExpr *Call,
3094 const FunctionDecl *FDecl);
3095
3096 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
3097
3098 /// Check for dangerous or invalid arguments to memset().
3099 ///
3100 /// This issues warnings on known problematic, dangerous or unspecified
3101 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3102 /// function calls.
3103 ///
3104 /// \param Call The call expression to diagnose.
3105 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
3106 IdentifierInfo *FnName);
3107
3108 bool CheckSizeofMemaccessArgument(const Expr *SizeOfArg, const Expr *Dest,
3109 IdentifierInfo *FnName);
3110 // Warn if the user has made the 'size' argument to strlcpy or strlcat
3111 // be the size of the source, instead of the destination.
3112 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
3113
3114 // Warn on anti-patterns as the 'size' argument to strncat.
3115 // The correct size argument should look like following:
3116 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3117 void CheckStrncatArguments(const CallExpr *Call,
3118 const IdentifierInfo *FnName);
3119
3120 /// Alerts the user that they are attempting to free a non-malloc'd object.
3121 void CheckFreeArguments(const CallExpr *E);
3122
3123 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
3124 SourceLocation ReturnLoc, bool isObjCMethod = false,
3125 const AttrVec *Attrs = nullptr,
3126 const FunctionDecl *FD = nullptr);
3127
3128 /// Diagnoses "dangerous" implicit conversions within the given
3129 /// expression (which is a full expression). Implements -Wconversion
3130 /// and -Wsign-compare.
3131 ///
3132 /// \param CC the "context" location of the implicit conversion, i.e.
3133 /// the most location of the syntactic entity requiring the implicit
3134 /// conversion
3135 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
3136
3137 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
3138 /// Input argument E is a logical expression.
3140
3141 /// Diagnose when expression is an integer constant expression and its
3142 /// evaluation results in integer overflow
3143 void CheckForIntOverflow(const Expr *E);
3144 void CheckUnsequencedOperations(const Expr *E);
3145
3146 /// Perform semantic checks on a completed expression. This will either
3147 /// be a full-expression or a default argument expression.
3148 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
3149 bool IsConstexpr = false);
3150
3151 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
3152 Expr *Init);
3153
3154 /// A map from magic value to type information.
3155 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
3156 TypeTagForDatatypeMagicValues;
3157
3158 /// Peform checks on a call of a function with argument_with_type_tag
3159 /// or pointer_with_type_tag attributes.
3160 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
3161 const ArrayRef<const Expr *> ExprArgs,
3162 SourceLocation CallSiteLoc);
3163
3164 /// Check if we are taking the address of a packed field
3165 /// as this may be a problem if the pointer value is dereferenced.
3166 void CheckAddressOfPackedMember(Expr *rhs);
3167
3168 /// Helper class that collects misaligned member designations and
3169 /// their location info for delayed diagnostics.
3170 struct MisalignedMember {
3171 Expr *E;
3172 RecordDecl *RD;
3173 ValueDecl *MD;
3174 CharUnits Alignment;
3175
3176 MisalignedMember() : E(), RD(), MD() {}
3177 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
3178 CharUnits Alignment)
3179 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
3180 explicit MisalignedMember(Expr *E)
3181 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
3182
3183 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
3184 };
3185
3186 /// Adds an expression to the set of gathered misaligned members.
3187 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
3188 CharUnits Alignment);
3189 ///@}
3190
3191 //
3192 //
3193 // -------------------------------------------------------------------------
3194 //
3195 //
3196
3197 /// \name C++ Coroutines
3198 /// Implementations are in SemaCoroutine.cpp
3199 ///@{
3200
3201public:
3202 /// The C++ "std::coroutine_traits" template, which is defined in
3203 /// <coroutine_traits>
3205
3207 StringRef Keyword);
3211
3214 UnresolvedLookupExpr *Lookup);
3216 Expr *Awaiter, bool IsImplicit = false);
3218 UnresolvedLookupExpr *Lookup);
3221 bool IsImplicit = false);
3226
3227 // As a clang extension, enforces that a non-coroutine function must be marked
3228 // with [[clang::coro_wrapper]] if it returns a type marked with
3229 // [[clang::coro_return_type]].
3230 // Expects that FD is not a coroutine.
3232 /// Lookup 'coroutine_traits' in std namespace and std::experimental
3233 /// namespace. The namespace found is recorded in Namespace.
3235 SourceLocation FuncLoc);
3236 /// Check that the expression co_await promise.final_suspend() shall not be
3237 /// potentially-throwing.
3238 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
3239
3240 ///@}
3241
3242 //
3243 //
3244 // -------------------------------------------------------------------------
3245 //
3246 //
3247
3248 /// \name C++ Scope Specifiers
3249 /// Implementations are in SemaCXXScopeSpec.cpp
3250 ///@{
3251
3252public:
3253 // Marks SS invalid if it represents an incomplete type.
3255 // Complete an enum decl, maybe without a scope spec.
3257 CXXScopeSpec *SS = nullptr);
3258
3259 /// Compute the DeclContext that is associated with the given type.
3260 ///
3261 /// \param T the type for which we are attempting to find a DeclContext.
3262 ///
3263 /// \returns the declaration context represented by the type T,
3264 /// or NULL if the declaration context cannot be computed (e.g., because it is
3265 /// dependent and not the current instantiation).
3267
3268 /// Compute the DeclContext that is associated with the given
3269 /// scope specifier.
3270 ///
3271 /// \param SS the C++ scope specifier as it appears in the source
3272 ///
3273 /// \param EnteringContext when true, we will be entering the context of
3274 /// this scope specifier, so we can retrieve the declaration context of a
3275 /// class template or class template partial specialization even if it is
3276 /// not the current instantiation.
3277 ///
3278 /// \returns the declaration context represented by the scope specifier @p SS,
3279 /// or NULL if the declaration context cannot be computed (e.g., because it is
3280 /// dependent and not the current instantiation).
3282 bool EnteringContext = false);
3284
3285 /// If the given nested name specifier refers to the current
3286 /// instantiation, return the declaration that corresponds to that
3287 /// current instantiation (C++0x [temp.dep.type]p1).
3288 ///
3289 /// \param NNS a dependent nested name specifier.
3291
3292 /// The parser has parsed a global nested-name-specifier '::'.
3293 ///
3294 /// \param CCLoc The location of the '::'.
3295 ///
3296 /// \param SS The nested-name-specifier, which will be updated in-place
3297 /// to reflect the parsed nested-name-specifier.
3298 ///
3299 /// \returns true if an error occurred, false otherwise.
3301
3302 /// The parser has parsed a '__super' nested-name-specifier.
3303 ///
3304 /// \param SuperLoc The location of the '__super' keyword.
3305 ///
3306 /// \param ColonColonLoc The location of the '::'.
3307 ///
3308 /// \param SS The nested-name-specifier, which will be updated in-place
3309 /// to reflect the parsed nested-name-specifier.
3310 ///
3311 /// \returns true if an error occurred, false otherwise.
3313 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
3314
3315 /// Determines whether the given declaration is an valid acceptable
3316 /// result for name lookup of a nested-name-specifier.
3317 /// \param SD Declaration checked for nested-name-specifier.
3318 /// \param IsExtension If not null and the declaration is accepted as an
3319 /// extension, the pointed variable is assigned true.
3321 bool *CanCorrect = nullptr);
3322
3323 /// If the given nested-name-specifier begins with a bare identifier
3324 /// (e.g., Base::), perform name lookup for that identifier as a
3325 /// nested-name-specifier within the given scope, and return the result of
3326 /// that name lookup.
3328
3329 /// Keeps information about an identifier in a nested-name-spec.
3330 ///
3332 /// The type of the object, if we're parsing nested-name-specifier in
3333 /// a member access expression.
3335
3336 /// The identifier preceding the '::'.
3338
3339 /// The location of the identifier.
3341
3342 /// The location of the '::'.
3344
3345 /// Creates info object for the most typical case.
3347 SourceLocation ColonColonLoc,
3350 CCLoc(ColonColonLoc) {}
3351
3353 SourceLocation ColonColonLoc, QualType ObjectType)
3355 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
3356 };
3357
3358 /// Build a new nested-name-specifier for "identifier::", as described
3359 /// by ActOnCXXNestedNameSpecifier.
3360 ///
3361 /// \param S Scope in which the nested-name-specifier occurs.
3362 /// \param IdInfo Parser information about an identifier in the
3363 /// nested-name-spec.
3364 /// \param EnteringContext If true, enter the context specified by the
3365 /// nested-name-specifier.
3366 /// \param SS Optional nested name specifier preceding the identifier.
3367 /// \param ScopeLookupResult Provides the result of name lookup within the
3368 /// scope of the nested-name-specifier that was computed at template
3369 /// definition time.
3370 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
3371 /// error recovery and what kind of recovery is performed.
3372 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
3373 /// are allowed. The bool value pointed by this parameter is set to
3374 /// 'true' if the identifier is treated as if it was followed by ':',
3375 /// not '::'.
3376 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3377 ///
3378 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
3379 /// that it contains an extra parameter \p ScopeLookupResult, which provides
3380 /// the result of name lookup within the scope of the nested-name-specifier
3381 /// that was computed at template definition time.
3382 ///
3383 /// If ErrorRecoveryLookup is true, then this call is used to improve error
3384 /// recovery. This means that it should not emit diagnostics, it should
3385 /// just return true on failure. It also means it should only return a valid
3386 /// scope if it *knows* that the result is correct. It should not return in a
3387 /// dependent context, for example. Nor will it extend \p SS with the scope
3388 /// specifier.
3389 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3390 bool EnteringContext, CXXScopeSpec &SS,
3391 NamedDecl *ScopeLookupResult,
3392 bool ErrorRecoveryLookup,
3393 bool *IsCorrectedToColon = nullptr,
3394 bool OnlyNamespace = false);
3395
3396 /// The parser has parsed a nested-name-specifier 'identifier::'.
3397 ///
3398 /// \param S The scope in which this nested-name-specifier occurs.
3399 ///
3400 /// \param IdInfo Parser information about an identifier in the
3401 /// nested-name-spec.
3402 ///
3403 /// \param EnteringContext Whether we're entering the context nominated by
3404 /// this nested-name-specifier.
3405 ///
3406 /// \param SS The nested-name-specifier, which is both an input
3407 /// parameter (the nested-name-specifier before this type) and an
3408 /// output parameter (containing the full nested-name-specifier,
3409 /// including this new type).
3410 ///
3411 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
3412 /// are allowed. The bool value pointed by this parameter is set to 'true'
3413 /// if the identifier is treated as if it was followed by ':', not '::'.
3414 ///
3415 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3416 ///
3417 /// \returns true if an error occurred, false otherwise.
3418 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3419 bool EnteringContext, CXXScopeSpec &SS,
3420 bool *IsCorrectedToColon = nullptr,
3421 bool OnlyNamespace = false);
3422
3423 /// The parser has parsed a nested-name-specifier
3424 /// 'template[opt] template-name < template-args >::'.
3425 ///
3426 /// \param S The scope in which this nested-name-specifier occurs.
3427 ///
3428 /// \param SS The nested-name-specifier, which is both an input
3429 /// parameter (the nested-name-specifier before this type) and an
3430 /// output parameter (containing the full nested-name-specifier,
3431 /// including this new type).
3432 ///
3433 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
3434 /// \param TemplateName the template name.
3435 /// \param TemplateNameLoc The location of the template name.
3436 /// \param LAngleLoc The location of the opening angle bracket ('<').
3437 /// \param TemplateArgs The template arguments.
3438 /// \param RAngleLoc The location of the closing angle bracket ('>').
3439 /// \param CCLoc The location of the '::'.
3440 ///
3441 /// \param EnteringContext Whether we're entering the context of the
3442 /// nested-name-specifier.
3443 ///
3444 ///
3445 /// \returns true if an error occurred, false otherwise.
3447 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3448 TemplateTy TemplateName, SourceLocation TemplateNameLoc,
3449 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
3450 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
3451
3453 SourceLocation ColonColonLoc);
3454
3456 const DeclSpec &DS,
3457 SourceLocation ColonColonLoc,
3458 QualType Type);
3459
3460 /// IsInvalidUnlessNestedName - This method is used for error recovery
3461 /// purposes to determine whether the specified identifier is only valid as
3462 /// a nested name specifier, for example a namespace name. It is
3463 /// conservatively correct to always return false from this method.
3464 ///
3465 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
3467 NestedNameSpecInfo &IdInfo,
3468 bool EnteringContext);
3469
3470 /// Given a C++ nested-name-specifier, produce an annotation value
3471 /// that the parser can use later to reconstruct the given
3472 /// nested-name-specifier.
3473 ///
3474 /// \param SS A nested-name-specifier.
3475 ///
3476 /// \returns A pointer containing all of the information in the
3477 /// nested-name-specifier \p SS.
3479
3480 /// Given an annotation pointer for a nested-name-specifier, restore
3481 /// the nested-name-specifier structure.
3482 ///
3483 /// \param Annotation The annotation pointer, produced by
3484 /// \c SaveNestedNameSpecifierAnnotation().
3485 ///
3486 /// \param AnnotationRange The source range corresponding to the annotation.
3487 ///
3488 /// \param SS The nested-name-specifier that will be updated with the contents
3489 /// of the annotation pointer.
3490 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3491 SourceRange AnnotationRange,
3492 CXXScopeSpec &SS);
3493
3494 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3495
3496 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3497 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3498 /// After this method is called, according to [C++ 3.4.3p3], names should be
3499 /// looked up in the declarator-id's scope, until the declarator is parsed and
3500 /// ActOnCXXExitDeclaratorScope is called.
3501 /// The 'SS' should be a non-empty valid CXXScopeSpec.
3503
3504 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3505 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3506 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3507 /// Used to indicate that names should revert to being looked up in the
3508 /// defining scope.
3510
3511 ///@}
3512
3513 //
3514 //
3515 // -------------------------------------------------------------------------
3516 //
3517 //
3518
3519 /// \name Declarations
3520 /// Implementations are in SemaDecl.cpp
3521 ///@{
3522
3523public:
3525
3526 /// The index of the first InventedParameterInfo that refers to the current
3527 /// context.
3529
3530 /// A RAII object to temporarily push a declaration context.
3532 private:
3533 Sema &S;
3534 DeclContext *SavedContext;
3535 ProcessingContextState SavedContextState;
3536 QualType SavedCXXThisTypeOverride;
3537 unsigned SavedFunctionScopesStart;
3538 unsigned SavedInventedParameterInfosStart;
3539
3540 public:
3541 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
3542 : S(S), SavedContext(S.CurContext),
3543 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
3544 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
3545 SavedFunctionScopesStart(S.FunctionScopesStart),
3546 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
3547 assert(ContextToPush && "pushing null context");
3548 S.CurContext = ContextToPush;
3549 if (NewThisContext)
3550 S.CXXThisTypeOverride = QualType();
3551 // Any saved FunctionScopes do not refer to this context.
3552 S.FunctionScopesStart = S.FunctionScopes.size();
3553 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
3554 }
3555
3556 void pop() {
3557 if (!SavedContext)
3558 return;
3559 S.CurContext = SavedContext;
3560 S.DelayedDiagnostics.popUndelayed(SavedContextState);
3561 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
3562 S.FunctionScopesStart = SavedFunctionScopesStart;
3563 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
3564 SavedContext = nullptr;
3565 }
3566
3568 ContextRAII(const ContextRAII &) = delete;
3570 };
3571
3572 void DiagnoseInvalidJumps(Stmt *Body);
3573
3574 /// The function definitions which were renamed as part of typo-correction
3575 /// to match their respective declarations. We want to keep track of them
3576 /// to ensure that we don't emit a "redefinition" error if we encounter a
3577 /// correctly named definition after the renamed definition.
3579
3580 /// A cache of the flags available in enumerations with the flag_enum
3581 /// attribute.
3582 mutable llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
3583
3584 /// A cache of enumerator values for enums checked by -Wassign-enum.
3585 llvm::DenseMap<const EnumDecl *, llvm::SmallVector<llvm::APSInt>>
3587
3588 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
3589 /// declared. Rare. May alias another identifier, declared or undeclared.
3590 ///
3591 /// For aliases, the target identifier is used as a key for eventual
3592 /// processing when the target is declared. For the single-identifier form,
3593 /// the sole identifier is used as the key. Each entry is a `SetVector`
3594 /// (ordered by parse order) of aliases (identified by the alias name) in case
3595 /// of multiple aliases to the same undeclared identifier.
3596 llvm::MapVector<
3598 llvm::SetVector<
3600 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
3602
3603 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
3604 /// \#pragma redefine_extname before declared. Used in Solaris system headers
3605 /// to define functions that occur in multiple standards to call the version
3606 /// in the currently selected standard.
3607 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>
3609
3610 /// Set containing all typedefs that are likely unused.
3613
3617
3618 /// The set of file scoped decls seen so far that have not been used
3619 /// and must warn if not used. Only contains the first declaration.
3621
3625
3626 /// All the tentative definitions encountered in the TU.
3628
3629 /// All the external declarations encoutered and used in the TU.
3631
3632 /// Generally null except when we temporarily switch decl contexts,
3633 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
3635
3636 /// Is the module scope we are in a C++ Header Unit?
3638 return ModuleScopes.empty() ? false
3639 : ModuleScopes.back().Module->isHeaderUnit();
3640 }
3641
3642 /// Get the module owning an entity.
3643 Module *getOwningModule(const Decl *Entity) {
3644 return Entity->getOwningModule();
3645 }
3646
3647 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
3648
3650 /// Returns the TypeDeclType for the given type declaration,
3651 /// as ASTContext::getTypeDeclType would, but
3652 /// performs the required semantic checks for name lookup of said entity.
3653 void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD,
3654 SourceLocation NameLoc);
3655
3656 /// If the identifier refers to a type name within this scope,
3657 /// return the declaration of that type.
3658 ///
3659 /// This routine performs ordinary name lookup of the identifier II
3660 /// within the given scope, with optional C++ scope specifier SS, to
3661 /// determine whether the name refers to a type. If so, returns an
3662 /// opaque pointer (actually a QualType) corresponding to that
3663 /// type. Otherwise, returns NULL.
3665 Scope *S, CXXScopeSpec *SS = nullptr,
3666 bool isClassName = false, bool HasTrailingDot = false,
3667 ParsedType ObjectType = nullptr,
3668 bool IsCtorOrDtorName = false,
3669 bool WantNontrivialTypeSourceInfo = false,
3670 bool IsClassTemplateDeductionContext = true,
3671 ImplicitTypenameContext AllowImplicitTypename =
3673 IdentifierInfo **CorrectedII = nullptr);
3674
3675 /// isTagName() - This method is called *for error recovery purposes only*
3676 /// to determine if the specified name is a valid tag name ("struct foo"). If
3677 /// so, this returns the TST for the tag corresponding to it (TST_enum,
3678 /// TST_union, TST_struct, TST_interface, TST_class). This is used to
3679 /// diagnose cases in C where the user forgot to specify the tag.
3681
3682 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
3683 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
3684 /// then downgrade the missing typename error to a warning.
3685 /// This is needed for MSVC compatibility; Example:
3686 /// @code
3687 /// template<class T> class A {
3688 /// public:
3689 /// typedef int TYPE;
3690 /// };
3691 /// template<class T> class B : public A<T> {
3692 /// public:
3693 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
3694 /// };
3695 /// @endcode
3696 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
3698 Scope *S, CXXScopeSpec *SS,
3699 ParsedType &SuggestedType,
3700 bool IsTemplateName = false);
3701
3702 /// Attempt to behave like MSVC in situations where lookup of an unqualified
3703 /// type name has failed in a dependent context. In these situations, we
3704 /// automatically form a DependentTypeName that will retry lookup in a related
3705 /// scope during instantiation.
3707 SourceLocation NameLoc,
3708 bool IsTemplateTypeArg);
3709
3710 class NameClassification {
3712 union {
3717 };
3718
3719 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
3720
3721 public:
3724
3727
3728 static NameClassification Error() {
3729 return NameClassification(NameClassificationKind::Error);
3730 }
3731
3732 static NameClassification Unknown() {
3733 return NameClassification(NameClassificationKind::Unknown);
3734 }
3735
3736 static NameClassification OverloadSet(ExprResult E) {
3737 NameClassification Result(NameClassificationKind::OverloadSet);
3738 Result.Expr = E;
3739 return Result;
3740 }
3741
3742 static NameClassification NonType(NamedDecl *D) {
3743 NameClassification Result(NameClassificationKind::NonType);
3744 Result.NonTypeDecl = D;
3745 return Result;
3746 }
3747
3748 static NameClassification UndeclaredNonType() {
3749 return NameClassification(NameClassificationKind::UndeclaredNonType);
3750 }
3751
3752 static NameClassification DependentNonType() {
3753 return NameClassification(NameClassificationKind::DependentNonType);
3754 }
3755
3756 static NameClassification TypeTemplate(TemplateName Name) {
3757 NameClassification Result(NameClassificationKind::TypeTemplate);
3758 Result.Template = Name;
3759 return Result;
3760 }
3761
3762 static NameClassification VarTemplate(TemplateName Name) {
3763 NameClassification Result(NameClassificationKind::VarTemplate);
3764 Result.Template = Name;
3765 return Result;
3766 }
3767
3768 static NameClassification FunctionTemplate(TemplateName Name) {
3770 Result.Template = Name;
3771 return Result;
3772 }
3773
3774 static NameClassification Concept(TemplateName Name) {
3775 NameClassification Result(NameClassificationKind::Concept);
3776 Result.Template = Name;
3777 return Result;
3778 }
3779
3780 static NameClassification UndeclaredTemplate(TemplateName Name) {
3782 Result.Template = Name;
3783 return Result;
3784 }
3785
3786 NameClassificationKind getKind() const { return Kind; }
3787
3790 return Expr;
3791 }
3792
3794 assert(Kind == NameClassificationKind::Type);
3795 return Type;
3796 }
3797
3799 assert(Kind == NameClassificationKind::NonType);
3800 return NonTypeDecl;
3801 }
3802
3811
3813 switch (Kind) {
3815 return TNK_Type_template;
3817 return TNK_Function_template;
3819 return TNK_Var_template;
3821 return TNK_Concept_template;
3824 default:
3825 llvm_unreachable("unsupported name classification.");
3826 }
3827 }
3828 };
3829
3830 /// Perform name lookup on the given name, classifying it based on
3831 /// the results of name lookup and the following token.
3832 ///
3833 /// This routine is used by the parser to resolve identifiers and help direct
3834 /// parsing. When the identifier cannot be found, this routine will attempt
3835 /// to correct the typo and classify based on the resulting name.
3836 ///
3837 /// \param S The scope in which we're performing name lookup.
3838 ///
3839 /// \param SS The nested-name-specifier that precedes the name.
3840 ///
3841 /// \param Name The identifier. If typo correction finds an alternative name,
3842 /// this pointer parameter will be updated accordingly.
3843 ///
3844 /// \param NameLoc The location of the identifier.
3845 ///
3846 /// \param NextToken The token following the identifier. Used to help
3847 /// disambiguate the name.
3848 ///
3849 /// \param CCC The correction callback, if typo correction is desired.
3850 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
3851 IdentifierInfo *&Name, SourceLocation NameLoc,
3852 const Token &NextToken,
3853 CorrectionCandidateCallback *CCC = nullptr);
3854
3855 /// Act on the result of classifying a name as an undeclared (ADL-only)
3856 /// non-type declaration.
3858 SourceLocation NameLoc);
3859 /// Act on the result of classifying a name as an undeclared member of a
3860 /// dependent base class.
3862 IdentifierInfo *Name,
3863 SourceLocation NameLoc,
3864 bool IsAddressOfOperand);
3865 /// Act on the result of classifying a name as a specific non-type
3866 /// declaration.
3869 SourceLocation NameLoc,
3870 const Token &NextToken);
3871 /// Act on the result of classifying a name as an overload set.
3873
3874 /// Describes the detailed kind of a template name. Used in diagnostics.
3886
3887 /// Determine whether it's plausible that E was intended to be a
3888 /// template-name.
3890 if (!getLangOpts().CPlusPlus || E.isInvalid())
3891 return false;
3892 Dependent = false;
3893 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
3894 return !DRE->hasExplicitTemplateArgs();
3895 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
3896 return !ME->hasExplicitTemplateArgs();
3897 Dependent = true;
3898 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
3899 return !DSDRE->hasExplicitTemplateArgs();
3900 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
3901 return !DSME->hasExplicitTemplateArgs();
3902 // Any additional cases recognized here should also be handled by
3903 // diagnoseExprIntendedAsTemplateName.
3904 return false;
3905 }
3906
3907 void warnOnReservedIdentifier(const NamedDecl *D);
3909
3910 void ProcessPragmaExport(DeclaratorDecl *newDecl);
3911
3913
3915 MultiTemplateParamsArg TemplateParameterLists);
3916
3917 /// Attempt to fold a variable-sized type to a constant-sized type, returning
3918 /// true if we were successful.
3920 SourceLocation Loc,
3921 unsigned FailedFoldDiagID);
3922
3923 /// Register the given locally-scoped extern "C" declaration so
3924 /// that it can be found later for redeclarations. We include any extern "C"
3925 /// declaration that is not visible in the translation unit here, not just
3926 /// function-scope declarations.
3928
3929 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3930 /// If T is the name of a class, then each of the following shall have a
3931 /// name different from T:
3932 /// - every static data member of class T;
3933 /// - every member function of class T
3934 /// - every member of class T that is itself a type;
3935 /// \returns true if the declaration name violates these rules.
3937
3938 /// Diagnose a declaration whose declarator-id has the given
3939 /// nested-name-specifier.
3940 ///
3941 /// \param SS The nested-name-specifier of the declarator-id.
3942 ///
3943 /// \param DC The declaration context to which the nested-name-specifier
3944 /// resolves.
3945 ///
3946 /// \param Name The name of the entity being declared.
3947 ///
3948 /// \param Loc The location of the name of the entity being declared.
3949 ///
3950 /// \param IsMemberSpecialization Whether we are declaring a member
3951 /// specialization.
3952 ///
3953 /// \param TemplateId The template-id, if any.
3954 ///
3955 /// \returns true if we cannot safely recover from this error, false
3956 /// otherwise.
3959 TemplateIdAnnotation *TemplateId,
3960 bool IsMemberSpecialization);
3961
3963
3964 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
3965
3967 unsigned &IntVal);
3968
3969 /// Diagnose function specifiers on a declaration of an identifier that
3970 /// does not identify a function.
3971 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
3972
3973 /// Return the declaration shadowed by the given typedef \p D, or null
3974 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3976 const LookupResult &R);
3977
3978 /// Return the declaration shadowed by the given variable \p D, or null
3979 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3981
3982 /// Return the declaration shadowed by the given variable \p D, or null
3983 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3985 const LookupResult &R);
3986 /// Diagnose variable or built-in function shadowing. Implements
3987 /// -Wshadow.
3988 ///
3989 /// This method is called whenever a VarDecl is added to a "useful"
3990 /// scope.
3991 ///
3992 /// \param ShadowedDecl the declaration that is shadowed by the given variable
3993 /// \param R the lookup of the name
3994 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
3995 const LookupResult &R);
3996
3997 /// Check -Wshadow without the advantage of a previous lookup.
3998 void CheckShadow(Scope *S, VarDecl *D);
3999
4000 /// Warn if 'E', which is an expression that is about to be modified, refers
4001 /// to a shadowing declaration.
4003
4004 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
4005 /// when these variables are captured by the lambda.
4007
4008 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
4009 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4010 TypedefNameDecl *NewTD);
4013 TypeSourceInfo *TInfo,
4015
4016 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4017 /// declares a typedef-name, either using the 'typedef' type specifier or via
4018 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4022 TypeSourceInfo *TInfo,
4024 MultiTemplateParamsArg TemplateParamLists,
4025 bool &AddToScope,
4027
4028private:
4029 // Perform a check on an AsmLabel to verify its consistency and emit
4030 // diagnostics in case of an error.
4031 void CheckAsmLabel(Scope *S, Expr *AsmLabelExpr, StorageClass SC,
4032 TypeSourceInfo *TInfo, VarDecl *);
4033
4034public:
4035 /// Perform semantic checking on a newly-created variable
4036 /// declaration.
4037 ///
4038 /// This routine performs all of the type-checking required for a
4039 /// variable declaration once it has been built. It is used both to
4040 /// check variables after they have been parsed and their declarators
4041 /// have been translated into a declaration, and to check variables
4042 /// that have been instantiated from a template.
4043 ///
4044 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4045 ///
4046 /// Returns true if the variable declaration is a redeclaration.
4047 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
4048 void CheckVariableDeclarationType(VarDecl *NewVD);
4049 void CheckCompleteVariableDeclaration(VarDecl *VD);
4050
4051 NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4052 TypeSourceInfo *TInfo,
4053 LookupResult &Previous,
4054 MultiTemplateParamsArg TemplateParamLists,
4055 bool &AddToScope);
4056
4057 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4058 /// and if so, check that it's a valid override and remember it.
4059 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
4060
4061 /// Perform semantic checking of a new function declaration.
4062 ///
4063 /// Performs semantic analysis of the new function declaration
4064 /// NewFD. This routine performs all semantic checking that does not
4065 /// require the actual declarator involved in the declaration, and is
4066 /// used both for the declaration of functions as they are parsed
4067 /// (called via ActOnDeclarator) and for the declaration of functions
4068 /// that have been instantiated via C++ template instantiation (called
4069 /// via InstantiateDecl).
4070 ///
4071 /// \param IsMemberSpecialization whether this new function declaration is
4072 /// a member specialization (that replaces any definition provided by the
4073 /// previous declaration).
4074 ///
4075 /// This sets NewFD->isInvalidDecl() to true if there was an error.
4076 ///
4077 /// \returns true if the function declaration is a redeclaration.
4078 bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
4079 LookupResult &Previous,
4080 bool IsMemberSpecialization, bool DeclIsDefn);
4081
4082 /// Checks if the new declaration declared in dependent context must be
4083 /// put in the same redeclaration chain as the specified declaration.
4084 ///
4085 /// \param D Declaration that is checked.
4086 /// \param PrevDecl Previous declaration found with proper lookup method for
4087 /// the same declaration name.
4088 /// \returns True if D must be added to the redeclaration chain which PrevDecl
4089 /// belongs to.
4090 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
4091
4092 /// Determines if we can perform a correct type check for \p D as a
4093 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
4094 /// best-effort check.
4095 ///
4096 /// \param NewD The new declaration.
4097 /// \param OldD The old declaration.
4098 /// \param NewT The portion of the type of the new declaration to check.
4099 /// \param OldT The portion of the type of the old declaration to check.
4100 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
4101 QualType NewT, QualType OldT);
4102 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
4103 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
4104
4105 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
4106 /// containing class. Otherwise it will return implicit SectionAttr if the
4107 /// function is a definition and there is an active value on CodeSegStack
4108 /// (from the current #pragma code-seg value).
4109 ///
4110 /// \param FD Function being declared.
4111 /// \param IsDefinition Whether it is a definition or just a declaration.
4112 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
4113 /// nullptr if no attribute should be added.
4114 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
4115 bool IsDefinition);
4116
4117 /// Common checks for a parameter-declaration that should apply to both
4118 /// function parameters and non-type template parameters.
4119 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
4120
4121 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4122 /// to introduce parameters into function prototype scope.
4123 Decl *ActOnParamDeclarator(Scope *S, Declarator &D,
4124 SourceLocation ExplicitThisLoc = {});
4125
4126 /// Synthesizes a variable for a parameter arising from a
4127 /// typedef.
4128 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
4129 QualType T);
4130 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
4131 SourceLocation NameLoc,
4132 const IdentifierInfo *Name, QualType T,
4133 TypeSourceInfo *TSInfo, StorageClass SC);
4134
4135 /// Emit diagnostics if the initializer or any of its explicit or
4136 /// implicitly-generated subexpressions require copying or
4137 /// default-initializing a type that is or contains a C union type that is
4138 /// non-trivial to copy or default-initialize.
4139 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
4140
4141 // These flags are passed to checkNonTrivialCUnion.
4147
4148 /// Emit diagnostics if a non-trivial C union type or a struct that contains
4149 /// a non-trivial C union is used in an invalid context.
4151 NonTrivialCUnionContext UseContext,
4152 unsigned NonTrivialKind);
4153
4154 /// Certain globally-unique variables might be accidentally duplicated if
4155 /// built into multiple shared libraries with hidden visibility. This can
4156 /// cause problems if the variable is mutable, its initialization is
4157 /// effectful, or its address is taken.
4160
4161 /// AddInitializerToDecl - Adds the initializer Init to the
4162 /// declaration dcl. If DirectInit is true, this is C++ direct
4163 /// initialization rather than copy initialization.
4164 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
4165 void ActOnUninitializedDecl(Decl *dcl);
4166
4167 /// ActOnInitializerError - Given that there was an error parsing an
4168 /// initializer for the given declaration, try to at least re-establish
4169 /// invariants such as whether a variable's type is either dependent or
4170 /// complete.
4171 void ActOnInitializerError(Decl *Dcl);
4172
4173 void ActOnCXXForRangeDecl(Decl *D);
4175 IdentifierInfo *Ident,
4176 ParsedAttributes &Attrs);
4177
4178 /// Check if VD needs to be dllexport/dllimport due to being in a
4179 /// dllexport/import function.
4182
4183 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
4184 /// any semantic actions necessary after any initializer has been attached.
4185 void FinalizeDeclaration(Decl *D);
4187 ArrayRef<Decl *> Group);
4188
4189 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
4190 /// group, performing any necessary semantic checking.
4192
4193 /// Should be called on all declarations that might have attached
4194 /// documentation comments.
4195 void ActOnDocumentableDecl(Decl *D);
4197
4198 enum class FnBodyKind {
4199 /// C++26 [dcl.fct.def.general]p1
4200 /// function-body:
4201 /// ctor-initializer[opt] compound-statement
4202 /// function-try-block
4204 /// = default ;
4206 /// deleted-function-body
4207 ///
4208 /// deleted-function-body:
4209 /// = delete ;
4210 /// = delete ( unevaluated-string ) ;
4212 };
4213
4215 SourceLocation LocAfterDecls);
4217 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
4218 SkipBodyInfo *SkipBody = nullptr);
4220 MultiTemplateParamsArg TemplateParamLists,
4221 SkipBodyInfo *SkipBody = nullptr,
4222 FnBodyKind BodyKind = FnBodyKind::Other);
4224 SkipBodyInfo *SkipBody = nullptr,
4225 FnBodyKind BodyKind = FnBodyKind::Other);
4227
4228 /// Determine whether we can delay parsing the body of a function or
4229 /// function template until it is used, assuming we don't care about emitting
4230 /// code for that function.
4231 ///
4232 /// This will be \c false if we may need the body of the function in the
4233 /// middle of parsing an expression (where it's impractical to switch to
4234 /// parsing a different function), for instance, if it's constexpr in C++11
4235 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
4236 bool canDelayFunctionBody(const Declarator &D);
4237
4238 /// Determine whether we can skip parsing the body of a function
4239 /// definition, assuming we don't care about analyzing its body or emitting
4240 /// code for that function.
4241 ///
4242 /// This will be \c false only if we may need the body of the function in
4243 /// order to parse the rest of the program (for instance, if it is
4244 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
4245 bool canSkipFunctionBody(Decl *D);
4246
4247 /// Given the set of return statements within a function body,
4248 /// compute the variables that are subject to the named return value
4249 /// optimization.
4250 ///
4251 /// Each of the variables that is subject to the named return value
4252 /// optimization will be marked as NRVO variables in the AST, and any
4253 /// return statement that has a marked NRVO variable as its NRVO candidate can
4254 /// use the named return value optimization.
4255 ///
4256 /// This function applies a very simplistic algorithm for NRVO: if every
4257 /// return statement in the scope of a variable has the same NRVO candidate,
4258 /// that candidate is an NRVO variable.
4260
4261 /// Performs semantic analysis at the end of a function body.
4262 ///
4263 /// \param RetainFunctionScopeInfo If \c true, the client is responsible for
4264 /// releasing the associated \p FunctionScopeInfo. This is useful when
4265 /// building e.g. LambdaExprs.
4267 bool IsInstantiation = false,
4268 bool RetainFunctionScopeInfo = false);
4271
4272 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
4273 /// attribute for which parsing is delayed.
4275
4276 /// Diagnose any unused parameters in the given sequence of
4277 /// ParmVarDecl pointers.
4279
4280 /// Diagnose whether the size of parameters or return value of a
4281 /// function or obj-c method definition is pass-by-value and larger than a
4282 /// specified threshold.
4283 void
4285 QualType ReturnTy, NamedDecl *D);
4286
4288 SourceLocation RParenLoc);
4289
4292
4293 void ActOnPopScope(SourceLocation Loc, Scope *S);
4294
4295 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4296 /// no declarator (e.g. "struct foo;") is parsed.
4298 const ParsedAttributesView &DeclAttrs,
4299 RecordDecl *&AnonRecord);
4300
4301 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4302 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4303 /// parameters to cope with template friend declarations.
4305 const ParsedAttributesView &DeclAttrs,
4306 MultiTemplateParamsArg TemplateParams,
4307 bool IsExplicitInstantiation,
4308 RecordDecl *&AnonRecord,
4309 SourceLocation EllipsisLoc = {});
4310
4311 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4312 /// anonymous structure or union. Anonymous unions are a C++ feature
4313 /// (C++ [class.union]) and a C11 feature; anonymous structures
4314 /// are a C11 feature and GNU C++ extension.
4315 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS,
4316 RecordDecl *Record,
4317 const PrintingPolicy &Policy);
4318
4319 /// Called once it is known whether
4320 /// a tag declaration is an anonymous union or struct.
4322
4323 /// Emit diagnostic warnings for placeholder members.
4324 /// We can only do that after the class is fully constructed,
4325 /// as anonymous union/structs can insert placeholders
4326 /// in their parent scope (which might be a Record).
4328
4329 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4330 /// Microsoft C anonymous structure.
4331 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4332 /// Example:
4333 ///
4334 /// struct A { int a; };
4335 /// struct B { struct A; int b; };
4336 ///
4337 /// void foo() {
4338 /// B var;
4339 /// var.a = 3;
4340 /// }
4341 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4342 RecordDecl *Record);
4343
4344 /// Given a non-tag type declaration, returns an enum useful for indicating
4345 /// what kind of non-tag type this is.
4346 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
4347
4348 /// Determine whether a tag with a given kind is acceptable
4349 /// as a redeclaration of the given tag declaration.
4350 ///
4351 /// \returns true if the new tag kind is acceptable, false otherwise.
4353 bool isDefinition, SourceLocation NewTagLoc,
4354 const IdentifierInfo *Name);
4355
4356 /// This is invoked when we see 'struct foo' or 'struct {'. In the
4357 /// former case, Name will be non-null. In the later case, Name will be null.
4358 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is
4359 /// a reference/declaration/definition of a tag.
4360 ///
4361 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
4362 /// trailing-type-specifier) other than one in an alias-declaration.
4363 ///
4364 /// \param SkipBody If non-null, will be set to indicate if the caller should
4365 /// skip the definition of this tag and treat it as if it were a declaration.
4366 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4367 SourceLocation KWLoc, CXXScopeSpec &SS,
4368 IdentifierInfo *Name, SourceLocation NameLoc,
4369 const ParsedAttributesView &Attr, AccessSpecifier AS,
4370 SourceLocation ModulePrivateLoc,
4371 MultiTemplateParamsArg TemplateParameterLists,
4372 bool &OwnedDecl, bool &IsDependent,
4373 SourceLocation ScopedEnumKWLoc,
4374 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
4375 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
4376 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
4377
4378 /// ActOnField - Each field of a C struct/union is passed into this in order
4379 /// to create a FieldDecl object for it.
4380 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
4381 Declarator &D, Expr *BitfieldWidth);
4382
4383 /// HandleField - Analyze a field of a C struct or a C++ data member.
4384 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
4385 Declarator &D, Expr *BitfieldWidth,
4386 InClassInitStyle InitStyle, AccessSpecifier AS);
4387
4388 /// Build a new FieldDecl and check its well-formedness.
4389 ///
4390 /// This routine builds a new FieldDecl given the fields name, type,
4391 /// record, etc. \p PrevDecl should refer to any previous declaration
4392 /// with the same name and in the same scope as the field to be
4393 /// created.
4394 ///
4395 /// \returns a new FieldDecl.
4396 ///
4397 /// \todo The Declarator argument is a hack. It will be removed once
4398 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
4399 TypeSourceInfo *TInfo, RecordDecl *Record,
4400 SourceLocation Loc, bool Mutable,
4401 Expr *BitfieldWidth, InClassInitStyle InitStyle,
4402 SourceLocation TSSL, AccessSpecifier AS,
4403 NamedDecl *PrevDecl, Declarator *D = nullptr);
4404
4406
4407 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
4408 /// class and class extensions. For every class \@interface and class
4409 /// extension \@interface, if the last ivar is a bitfield of any type,
4410 /// then add an implicit `char :0` ivar to the end of that interface.
4411 void ActOnLastBitfield(SourceLocation DeclStart,
4412 SmallVectorImpl<Decl *> &AllIvarDecls);
4413
4414 // This is used for both record definitions and ObjC interface declarations.
4415 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
4416 ArrayRef<Decl *> Fields, SourceLocation LBrac,
4417 SourceLocation RBrac, const ParsedAttributesView &AttrList);
4418
4419 /// ActOnTagStartDefinition - Invoked when we have entered the
4420 /// scope of a tag's definition (e.g., for an enumeration, class,
4421 /// struct, or union).
4422 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
4423
4424 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
4425 /// Differently from C++, actually parse the body and reject / error out
4426 /// in case of a structural mismatch.
4427 bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody);
4428
4430
4431 /// Invoked when we enter a tag definition that we're skipping.
4433
4434 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
4435 /// C++ record definition's base-specifiers clause and are starting its
4436 /// member declarations.
4438 SourceLocation FinalLoc,
4439 bool IsFinalSpelledSealed,
4440 bool IsAbstract,
4441 SourceLocation LBraceLoc);
4442
4443 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
4444 /// the definition of a tag (enumeration, class, struct, or union).
4446 SourceRange BraceRange);
4447
4450
4452
4453 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
4454 /// error parsing the definition of a tag.
4456
4458 EnumConstantDecl *LastEnumConst,
4459 SourceLocation IdLoc, IdentifierInfo *Id,
4460 Expr *val);
4461
4462 /// Check that this is a valid underlying type for an enum declaration.
4464
4465 /// Check whether this is a valid redeclaration of a previous enumeration.
4466 /// \return true if the redeclaration was invalid.
4467 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
4468 QualType EnumUnderlyingTy, bool IsFixed,
4469 const EnumDecl *Prev);
4470
4471 /// Determine whether the body of an anonymous enumeration should be skipped.
4472 /// \param II The name of the first enumerator.
4474 SourceLocation IILoc);
4475
4476 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
4477 SourceLocation IdLoc, IdentifierInfo *Id,
4478 const ParsedAttributesView &Attrs,
4479 SourceLocation EqualLoc, Expr *Val,
4480 SkipBodyInfo *SkipBody = nullptr);
4481 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
4482 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
4483 const ParsedAttributesView &Attr);
4484
4485 /// Set the current declaration context until it gets popped.
4486 void PushDeclContext(Scope *S, DeclContext *DC);
4487 void PopDeclContext();
4488
4489 /// EnterDeclaratorContext - Used when we must lookup names in the context
4490 /// of a declarator's nested name specifier.
4493
4494 /// Enter a template parameter scope, after it's been associated with a
4495 /// particular DeclContext. Causes lookup within the scope to chain through
4496 /// enclosing contexts in the correct order.
4498
4499 /// Push the parameters of D, which must be a function, into scope.
4502
4503 /// Add this decl to the scope shadowed decl chains.
4504 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
4505
4506 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
4507 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
4508 /// true if 'D' belongs to the given declaration context.
4509 ///
4510 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
4511 /// enclosing namespace set of the context, rather than contained
4512 /// directly within it.
4513 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
4514 bool AllowInlineNamespace = false) const;
4515
4516 /// Finds the scope corresponding to the given decl context, if it
4517 /// happens to be an enclosing scope. Otherwise return NULL.
4519
4520 /// Subroutines of ActOnDeclarator().
4522 TypeSourceInfo *TInfo);
4524
4525 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
4527 NamedDecl *New, Decl *Old,
4529
4530 /// CheckAttributesOnDeducedType - Calls Sema functions for attributes that
4531 /// requires the type to be deduced.
4533
4534 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
4535 /// same name and scope as a previous declaration 'Old'. Figure out
4536 /// how to resolve this situation, merging decls or emitting
4537 /// diagnostics as appropriate. If there was an error, set New to be invalid.
4539 LookupResult &OldDecls);
4540
4541 /// CleanupMergedEnum - We have just merged the decl 'New' by making another
4542 /// definition visible.
4543 /// This method performs any necessary cleanup on the parser state to discard
4544 /// child nodes from newly parsed decl we are retiring.
4545 void CleanupMergedEnum(Scope *S, Decl *New);
4546
4547 /// MergeFunctionDecl - We just parsed a function 'New' from
4548 /// declarator D which has the same name and scope as a previous
4549 /// declaration 'Old'. Figure out how to resolve this situation,
4550 /// merging decls or emitting diagnostics as appropriate.
4551 ///
4552 /// In C++, New and Old must be declarations that are not
4553 /// overloaded. Use IsOverload to determine whether New and Old are
4554 /// overloaded, and to select the Old declaration that New should be
4555 /// merged with.
4556 ///
4557 /// Returns true if there was an error, false otherwise.
4559 bool MergeTypeWithOld, bool NewDeclIsDefn);
4560
4561 /// Completes the merge of two function declarations that are
4562 /// known to be compatible.
4563 ///
4564 /// This routine handles the merging of attributes and other
4565 /// properties of function declarations from the old declaration to
4566 /// the new declaration, once we know that New is in fact a
4567 /// redeclaration of Old.
4568 ///
4569 /// \returns false
4571 Scope *S, bool MergeTypeWithOld);
4573
4574 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4575 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4576 /// situation, merging decls or emitting diagnostics as appropriate.
4577 ///
4578 /// Tentative definition rules (C99 6.9.2p2) are checked by
4579 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4580 /// definitions here, since the initializer hasn't been attached.
4582
4583 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4584 /// scope as a previous declaration 'Old'. Figure out how to merge their
4585 /// types, emitting diagnostics as appropriate.
4586 ///
4587 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call
4588 /// back to here in AddInitializerToDecl. We can't check them before the
4589 /// initializer is attached.
4590 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
4591
4592 /// We've just determined that \p Old and \p New both appear to be definitions
4593 /// of the same variable. Either diagnose or fix the problem.
4594 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
4596
4597 /// Filters out lookup results that don't fall within the given scope
4598 /// as determined by isDeclInScope.
4600 bool ConsiderLinkage, bool AllowInlineNamespace);
4601
4602 /// We've determined that \p New is a redeclaration of \p Old. Check that they
4603 /// have compatible owning modules.
4605
4606 /// [module.interface]p6:
4607 /// A redeclaration of an entity X is implicitly exported if X was introduced
4608 /// by an exported declaration; otherwise it shall not be exported.
4610
4611 /// A wrapper function for checking the semantic restrictions of
4612 /// a redeclaration within a module.
4614
4615 /// Check the redefinition in C++20 Modules.
4616 ///
4617 /// [basic.def.odr]p14:
4618 /// For any definable item D with definitions in multiple translation units,
4619 /// - if D is a non-inline non-templated function or variable, or
4620 /// - if the definitions in different translation units do not satisfy the
4621 /// following requirements,
4622 /// the program is ill-formed; a diagnostic is required only if the
4623 /// definable item is attached to a named module and a prior definition is
4624 /// reachable at the point where a later definition occurs.
4625 /// - Each such definition shall not be attached to a named module
4626 /// ([module.unit]).
4627 /// - Each such definition shall consist of the same sequence of tokens, ...
4628 /// ...
4629 ///
4630 /// Return true if the redefinition is not allowed. Return false otherwise.
4631 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
4632
4634
4635 /// If it's a file scoped decl that must warn if not used, keep track
4636 /// of it.
4638
4639 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
4641
4644 DiagReceiverTy DiagReceiver);
4645 void DiagnoseUnusedDecl(const NamedDecl *ND);
4646
4647 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
4648 /// unless they are marked attr(unused).
4649 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
4650
4651 /// If VD is set but not otherwise used, diagnose, for a parameter or a
4652 /// variable.
4653 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
4654
4655 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
4656 /// from S, where a non-field would be declared. This routine copes
4657 /// with the difference between C and C++ scoping rules in structs and
4658 /// unions. For example, the following code is well-formed in C but
4659 /// ill-formed in C++:
4660 /// @code
4661 /// struct S6 {
4662 /// enum { BAR } e;
4663 /// };
4664 ///
4665 /// void test_S6() {
4666 /// struct S6 a;
4667 /// a.e = BAR;
4668 /// }
4669 /// @endcode
4670 /// For the declaration of BAR, this routine will return a different
4671 /// scope. The scope S will be the scope of the unnamed enumeration
4672 /// within S6. In C++, this routine will return the scope associated
4673 /// with S6, because the enumeration's scope is a transparent
4674 /// context but structures can contain non-field names. In C, this
4675 /// routine will return the translation unit scope, since the
4676 /// enumeration's scope is a transparent context and structures cannot
4677 /// contain non-field names.
4679
4681 SourceLocation Loc);
4682
4683 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
4684 /// file scope. lazily create a decl for it. ForRedeclaration is true
4685 /// if we're creating this built-in in anticipation of redeclaring the
4686 /// built-in.
4687 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S,
4688 bool ForRedeclaration, SourceLocation Loc);
4689
4690 /// Get the outermost AttributedType node that sets a calling convention.
4691 /// Valid types should not have multiple attributes with different CCs.
4692 const AttributedType *getCallingConvAttributedType(QualType T) const;
4693
4694 /// GetNameForDeclarator - Determine the full declaration name for the
4695 /// given Declarator.
4697
4698 /// Retrieves the declaration name from a parsed unqualified-id.
4700
4701 /// ParsingInitForAutoVars - a set of declarations with auto types for which
4702 /// we are currently parsing the initializer.
4704
4705 /// Look for a locally scoped extern "C" declaration by the given name.
4707
4710
4711 /// Adjust the \c DeclContext for a function or variable that might be a
4712 /// function-local external declaration.
4714
4716
4717 /// Checks if the variant/multiversion functions are compatible.
4719 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
4720 const PartialDiagnostic &NoProtoDiagID,
4721 const PartialDiagnosticAt &NoteCausedDiagIDAt,
4722 const PartialDiagnosticAt &NoSupportDiagIDAt,
4723 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
4724 bool ConstexprSupported, bool CLinkageMayDiffer);
4725
4726 /// type checking declaration initializers (C99 6.7.8)
4728 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
4729
4732 SourceRange Range, bool DirectInit,
4733 Expr *Init);
4734
4736 Expr *Init);
4737
4739
4740 // Heuristically tells if the function is `get_return_object` member of a
4741 // coroutine promise_type by matching the function name.
4742 static bool CanBeGetReturnObject(const FunctionDecl *FD);
4743 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
4744
4745 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4746 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4748 Scope *S);
4749
4750 /// If this function is a C++ replaceable global allocation function
4751 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
4752 /// adds any function attributes that we know a priori based on the standard.
4753 ///
4754 /// We need to check for duplicate attributes both here and where user-written
4755 /// attributes are applied to declarations.
4757 FunctionDecl *FD);
4758
4759 /// Adds any function attributes that we know a priori based on
4760 /// the declaration of this function.
4761 ///
4762 /// These attributes can apply both to implicitly-declared builtins
4763 /// (like __builtin___printf_chk) or to library-declared functions
4764 /// like NSLog or printf.
4765 ///
4766 /// We need to check for duplicate attributes both here and where user-written
4767 /// attributes are applied to declarations.
4769
4770 /// VerifyBitField - verifies that a bit field expression is an ICE and has
4771 /// the correct width, and that the field type is valid.
4772 /// Returns false on success.
4774 const IdentifierInfo *FieldName, QualType FieldTy,
4775 bool IsMsStruct, Expr *BitWidth);
4776
4777 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
4778 /// enum. If AllowMask is true, then we also allow the complement of a valid
4779 /// value, to be used as a mask.
4780 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
4781 bool AllowMask) const;
4782
4783 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
4784 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
4785 SourceLocation WeakNameLoc);
4786
4787 /// ActOnPragmaRedefineExtname - Called on well formed
4788 /// \#pragma redefine_extname oldname newname.
4790 IdentifierInfo *AliasName,
4791 SourceLocation PragmaLoc,
4792 SourceLocation WeakNameLoc,
4793 SourceLocation AliasNameLoc);
4794
4795 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
4796 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
4797 SourceLocation PragmaLoc,
4798 SourceLocation WeakNameLoc,
4799 SourceLocation AliasNameLoc);
4800
4801 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4804 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4805 OMPDiscarded, // Discarded due to OpenMP hostness
4806 TemplateDiscarded, // Discarded due to uninstantiated templates
4808 };
4809 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4810 bool Final = false);
4811
4812 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4814
4815 /// Function or variable declarations to be checked for whether the deferred
4816 /// diagnostics should be emitted.
4818
4819private:
4820 /// Map of current shadowing declarations to shadowed declarations. Warn if
4821 /// it looks like the user is trying to modify the shadowing declaration.
4822 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
4823
4824 // We need this to handle
4825 //
4826 // typedef struct {
4827 // void *foo() { return 0; }
4828 // } A;
4829 //
4830 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
4831 // for example. If 'A', foo will have external linkage. If we have '*A',
4832 // foo will have no linkage. Since we can't know until we get to the end
4833 // of the typedef, this function finds out if D might have non-external
4834 // linkage. Callers should verify at the end of the TU if it D has external
4835 // linkage or not.
4836 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
4837
4838#include "clang/Sema/AttrIsTypeDependent.inc"
4839
4840 ///@}
4841
4842 //
4843 //
4844 // -------------------------------------------------------------------------
4845 //
4846 //
4847
4848 /// \name Declaration Attribute Handling
4849 /// Implementations are in SemaDeclAttr.cpp
4850 ///@{
4851
4852public:
4853 /// Describes the kind of priority given to an availability attribute.
4854 ///
4855 /// The sum of priorities deteremines the final priority of the attribute.
4856 /// The final priority determines how the attribute will be merged.
4857 /// An attribute with a lower priority will always remove higher priority
4858 /// attributes for the specified platform when it is being applied. An
4859 /// attribute with a higher priority will not be applied if the declaration
4860 /// already has an availability attribute with a lower priority for the
4861 /// specified platform. The final prirority values are not expected to match
4862 /// the values in this enumeration, but instead should be treated as a plain
4863 /// integer value. This enumeration just names the priority weights that are
4864 /// used to calculate that final vaue.
4866 /// The availability attribute was specified explicitly next to the
4867 /// declaration.
4869
4870 /// The availability attribute was applied using '#pragma clang attribute'.
4872
4873 /// The availability attribute for a specific platform was inferred from
4874 /// an availability attribute for another platform.
4876
4877 /// The availability attribute was inferred from an 'anyAppleOS'
4878 /// availability attribute.
4880
4881 /// The availability attribute was inferred from an 'anyAppleOS'
4882 /// availability attribute that was applied using '#pragma clang attribute'.
4883 /// This has the lowest priority.
4885 };
4886
4887 /// Describes the reason a calling convention specification was ignored, used
4888 /// for diagnostics.
4895
4896 /// A helper function to provide Attribute Location for the Attr types
4897 /// AND the ParsedAttr.
4898 template <typename AttrInfo>
4899 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
4900 getAttrLoc(const AttrInfo &AL) {
4901 return AL.getLocation();
4902 }
4904
4905 /// If Expr is a valid integer constant, get the value of the integer
4906 /// expression and return success or failure. May output an error.
4907 ///
4908 /// Negative argument is implicitly converted to unsigned, unless
4909 /// \p StrictlyUnsigned is true.
4910 template <typename AttrInfo>
4911 bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val,
4912 unsigned Idx = UINT_MAX,
4913 bool StrictlyUnsigned = false) {
4914 std::optional<llvm::APSInt> I = llvm::APSInt(32);
4915 if (Expr->isTypeDependent() ||
4917 if (Idx != UINT_MAX)
4918 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
4919 << &AI << Idx << AANT_ArgumentIntegerConstant
4920 << Expr->getSourceRange();
4921 else
4922 Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
4924 return false;
4925 }
4926
4927 if (!I->isIntN(32)) {
4928 Diag(Expr->getExprLoc(), diag::err_ice_too_large)
4929 << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
4930 return false;
4931 }
4932
4933 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
4934 Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
4935 << &AI << /*non-negative*/ 1;
4936 return false;
4937 }
4938
4939 Val = (uint32_t)I->getZExtValue();
4940 return true;
4941 }
4942
4943 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
4944 /// \#pragma weak during processing of other Decls.
4945 /// I couldn't figure out a clean way to generate these in-line, so
4946 /// we store them here and handle separately -- which is a hack.
4947 /// It would be best to refactor this.
4949
4950 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
4952
4956
4957 /// ExtVectorDecls - This is a list all the extended vector types. This allows
4958 /// us to associate a raw vector type with one of the ext_vector type names.
4959 /// This is only necessary for issuing pretty diagnostics.
4961
4962 /// Check if the argument \p E is a ASCII string literal. If not emit an error
4963 /// and return false, otherwise set \p Str to the value of the string literal
4964 /// and return true.
4966 const Expr *E, StringRef &Str,
4967 SourceLocation *ArgLocation = nullptr);
4968
4969 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
4970 /// If not emit an error and return false. If the argument is an identifier it
4971 /// will emit an error with a fixit hint and treat it as if it was a string
4972 /// literal.
4973 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4974 StringRef &Str,
4975 SourceLocation *ArgLocation = nullptr);
4976
4977 /// Determine if type T is a valid subject for a nonnull and similar
4978 /// attributes. Dependent types are considered valid so they can be checked
4979 /// during instantiation time. By default, we look through references (the
4980 /// behavior used by nonnull), but if the second parameter is true, then we
4981 /// treat a reference type as valid.
4982 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4983
4984 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
4985 /// declaration.
4986 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4987 Expr *OE);
4988
4989 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
4990 /// declaration.
4991 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
4992 Expr *ParamExpr);
4993
4994 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4995 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4996
4997 AvailabilityAttr *
4999 const IdentifierInfo *Platform, bool Implicit,
5000 VersionTuple Introduced, VersionTuple Deprecated,
5001 VersionTuple Obsoleted, bool IsUnavailable,
5002 StringRef Message, bool IsStrict, StringRef Replacement,
5003 AvailabilityMergeKind AMK, int Priority,
5004 const IdentifierInfo *IIEnvironment,
5005 const IdentifierInfo *InferredPlatformII = nullptr);
5006
5007 AvailabilityAttr *mergeAndInferAvailabilityAttr(
5008 NamedDecl *D, const AttributeCommonInfo &CI,
5009 const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced,
5010 VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable,
5011 StringRef Message, bool IsStrict, StringRef Replacement,
5012 AvailabilityMergeKind AMK, int Priority,
5013 const IdentifierInfo *IIEnvironment,
5014 const IdentifierInfo *InferredPlatformII);
5015
5016 TypeVisibilityAttr *
5018 TypeVisibilityAttr::VisibilityType Vis);
5019 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5020 VisibilityAttr::VisibilityType Vis);
5022 VisibilityAttr::VisibilityType Type);
5023 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
5024 StringRef Name);
5025
5026 /// Used to implement to perform semantic checking on
5027 /// attribute((section("foo"))) specifiers.
5028 ///
5029 /// In this case, "foo" is passed in to be checked. If the section
5030 /// specifier is invalid, return an Error that indicates the problem.
5031 ///
5032 /// This is a simple quality of implementation feature to catch errors
5033 /// and give good diagnostics in cases when the assembler or code generator
5034 /// would otherwise reject the section specifier.
5035 llvm::Error isValidSectionSpecifier(StringRef Str);
5036 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
5037 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
5038 StringRef Name);
5039
5040 // Check for things we'd like to warn about. Multiversioning issues are
5041 // handled later in the process, once we know how many exist.
5042 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
5043
5044 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
5045 StringRef NewUserDiagnostic);
5046 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
5047 const IdentifierInfo *Format, int FormatIdx,
5048 int FirstArg);
5049 FormatMatchesAttr *mergeFormatMatchesAttr(Decl *D,
5050 const AttributeCommonInfo &CI,
5051 const IdentifierInfo *Format,
5052 int FormatIdx,
5053 StringLiteral *FormatStr);
5054 ModularFormatAttr *mergeModularFormatAttr(Decl *D,
5055 const AttributeCommonInfo &CI,
5056 const IdentifierInfo *ModularImplFn,
5057 StringRef ImplName,
5059
5060 PersonalityAttr *mergePersonalityAttr(Decl *D, FunctionDecl *Routine,
5061 const AttributeCommonInfo &CI);
5062
5063 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
5064 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5065 bool IsPackExpansion);
5067 bool IsPackExpansion);
5068
5069 /// AddAlignValueAttr - Adds an align_value attribute to a particular
5070 /// declaration.
5071 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
5072
5073 /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
5074 Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
5077
5079 bool BestCase,
5080 MSInheritanceModel SemanticSpelling);
5081
5083
5084 /// AddModeAttr - Adds a mode attribute to a particular declaration.
5085 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
5086 const IdentifierInfo *Name, bool InInstantiation = false);
5087 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
5088 const AttributeCommonInfo &CI,
5089 const IdentifierInfo *Ident);
5090 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
5091 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
5092 const AttributeCommonInfo &CI);
5093 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
5094 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
5095 const InternalLinkageAttr &AL);
5096
5097 /// Check validaty of calling convention attribute \p attr. If \p FD
5098 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
5099 /// target. Otherwise, it is specified by \p CFT.
5101 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
5103
5104 /// Checks a regparm attribute, returning true if it is ill-formed and
5105 /// otherwise setting numParams to the appropriate value.
5106 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
5107
5108 /// Create a CUDALaunchBoundsAttr attribute. By default, the function only
5109 /// supports nvptx target architectures and skips MaxBlocks if it is previous
5110 /// to sm_90. Use \p IgnoreArch to skip the architecture check.
5111 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
5112 Expr *MaxThreads,
5113 Expr *MinBlocks, Expr *MaxBlocks,
5114 bool IgnoreArch = false);
5115
5116 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
5117 /// declaration.
5118 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5119 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
5120
5121 /// Add a cluster_dims attribute to a particular declaration.
5122 CUDAClusterDimsAttr *createClusterDimsAttr(const AttributeCommonInfo &CI,
5123 Expr *X, Expr *Y, Expr *Z);
5124 void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X,
5125 Expr *Y, Expr *Z);
5126 /// Add a no_cluster attribute to a particular declaration.
5127 void addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI);
5128
5129 enum class RetainOwnershipKind { NS, CF, OS };
5130
5131 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5132 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
5133
5134 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
5135
5136 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
5137 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
5138 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
5139 const AttributeCommonInfo &CI,
5140 bool BestCase,
5141 MSInheritanceModel Model);
5142
5143 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
5144 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
5145 const EnforceTCBLeafAttr &AL);
5146
5147 /// Helper for delayed processing TransparentUnion or
5148 /// BPFPreserveAccessIndexAttr attribute.
5150 const ParsedAttributesView &AttrList);
5151
5152 // Options for ProcessDeclAttributeList().
5156
5159 Result.IncludeCXX11Attributes = Val;
5160 return Result;
5161 }
5162
5165 Result.IgnoreTypeAttributes = Val;
5166 return Result;
5167 }
5168
5169 // Should C++11 attributes be processed?
5171
5172 // Should any type attributes encountered be ignored?
5173 // If this option is false, a diagnostic will be emitted for any type
5174 // attributes of a kind that does not "slide" from the declaration to
5175 // the decl-specifier-seq.
5177 };
5178
5179 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5180 /// attribute list to the specified decl, ignoring any type attributes.
5182 const ParsedAttributesView &AttrList,
5183 const ProcessDeclAttributeOptions &Options =
5185
5186 /// Annotation attributes are the only attributes allowed after an access
5187 /// specifier.
5189 const ParsedAttributesView &AttrList);
5190
5191 /// checkUnusedDeclAttributes - Given a declarator which is not being
5192 /// used to build a declaration, complain about any decl attributes
5193 /// which might be lying around on it.
5195
5196 void DiagnoseUnknownAttribute(const ParsedAttr &AL);
5197
5198 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5199 /// \#pragma weak needs a non-definition decl and source may not have one.
5201 SourceLocation Loc);
5202
5203 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5204 /// applied to it, possibly with an alias.
5205 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
5206
5207 void ProcessPragmaWeak(Scope *S, Decl *D);
5208 // Decl attributes - this routine is the top level dispatcher.
5209 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
5210
5212
5213 /// Given a set of delayed diagnostics, re-emit them as if they had
5214 /// been delayed in the current context instead of in the given pool.
5215 /// Essentially, this just moves them to the current pool.
5217
5218 /// Check that the type is a plain record with one field being a pointer
5219 /// type and the other field being an integer. This matches the common
5220 /// implementation of std::span or sized_allocation_t in P0901R11.
5221 bool CheckSpanLikeType(const AttributeCommonInfo &CI, const QualType &Ty);
5222
5223 /// Check if IdxExpr is a valid parameter index for a function or
5224 /// instance method D. May output an error.
5225 ///
5226 /// \returns true if IdxExpr is a valid index.
5227 template <typename AttrInfo>
5229 const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
5230 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false,
5231 bool CanIndexVariadicArguments = false) {
5233
5234 // In C++ the implicit 'this' function parameter also counts.
5235 // Parameters are counted from one.
5236 bool HP = hasFunctionProto(D);
5237 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
5238 bool IV = HP && isFunctionOrMethodVariadic(D);
5239 unsigned NumParams =
5240 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
5241
5242 std::optional<llvm::APSInt> IdxInt;
5243 if (IdxExpr->isTypeDependent() ||
5244 !(IdxInt = IdxExpr->getIntegerConstantExpr(Context))) {
5245 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5246 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
5247 << IdxExpr->getSourceRange();
5248 return false;
5249 }
5250
5251 constexpr unsigned Limit = 1 << ParamIdx::IdxBitWidth;
5252 unsigned IdxSource = IdxInt->getLimitedValue(Limit);
5253 if (IdxSource < 1 || IdxSource == Limit ||
5254 ((!IV || !CanIndexVariadicArguments) && IdxSource > NumParams)) {
5255 Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
5256 << &AI << AttrArgNum << IdxExpr->getSourceRange();
5257 return false;
5258 }
5259 if (HasImplicitThisParam && !CanIndexImplicitThis) {
5260 if (IdxSource == 1) {
5261 Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
5262 << &AI << IdxExpr->getSourceRange();
5263 return false;
5264 }
5265 }
5266
5267 Idx = ParamIdx(IdxSource, D);
5268 return true;
5269 }
5270
5271 ///@}
5272
5273 //
5274 //
5275 // -------------------------------------------------------------------------
5276 //
5277 //
5278
5279 /// \name C++ Declarations
5280 /// Implementations are in SemaDeclCXX.cpp
5281 ///@{
5282
5283public:
5285
5286 /// Called before parsing a function declarator belonging to a function
5287 /// declaration.
5289 unsigned TemplateParameterDepth);
5290
5291 /// Called after parsing a function declarator belonging to a function
5292 /// declaration.
5294
5295 // Act on C++ namespaces
5297 SourceLocation NamespaceLoc,
5298 SourceLocation IdentLoc, IdentifierInfo *Ident,
5299 SourceLocation LBrace,
5300 const ParsedAttributesView &AttrList,
5301 UsingDirectiveDecl *&UsingDecl, bool IsNested);
5302
5303 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5304 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5305 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5306
5308
5309 /// Retrieve the special "std" namespace, which may require us to
5310 /// implicitly define the namespace.
5312
5314 EnumDecl *getStdAlignValT() const;
5315
5318 QualType AllocType, SourceLocation);
5319
5321 const IdentifierInfo *MemberOrBase);
5322
5324 /// The '<=>' operator was used in an expression and a builtin operator
5325 /// was selected.
5327 /// A defaulted 'operator<=>' needed the comparison category. This
5328 /// typically only applies to 'std::strong_ordering', due to the implicit
5329 /// fallback return value.
5331 };
5332
5333 /// Lookup the specified comparison category types in the standard
5334 /// library, an check the VarDecls possibly returned by the operator<=>
5335 /// builtins for that type.
5336 ///
5337 /// \return The type of the comparison category type corresponding to the
5338 /// specified Kind, or a null type if an error occurs
5340 SourceLocation Loc,
5342
5343 /// Tests whether Ty is an instance of std::initializer_list and, if
5344 /// it is and Element is not NULL, assigns the element type to Element.
5345 bool isStdInitializerList(QualType Ty, QualType *Element);
5346
5347 /// Tests whether Ty is an instance of std::type_identity and, if
5348 /// it is and TypeArgument is not NULL, assigns the element type to Element.
5349 /// If MalformedDecl is not null, and type_identity was ruled out due to being
5350 /// incorrectly structured despite having the correct name, the faulty Decl
5351 /// will be assigned to MalformedDecl.
5352 bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument,
5353 const Decl **MalformedDecl = nullptr);
5354
5355 /// Looks for the std::initializer_list template and instantiates it
5356 /// with Element, or emits an error if it's not found.
5357 ///
5358 /// \returns The instantiated template, or null on error.
5360
5361 /// Looks for the std::type_identity template and instantiates it
5362 /// with Type, or returns a null type if type_identity has not been declared
5363 ///
5364 /// \returns The instantiated template, or null if std::type_identity is not
5365 /// declared
5367
5368 /// Determine whether Ctor is an initializer-list constructor, as
5369 /// defined in [dcl.init.list]p2.
5370 bool isInitListConstructor(const FunctionDecl *Ctor);
5371
5372 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5373 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5374 SourceLocation IdentLoc,
5375 IdentifierInfo *NamespcName,
5376 const ParsedAttributesView &AttrList);
5377
5379
5380 Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc,
5381 SourceLocation AliasLoc, IdentifierInfo *Alias,
5382 CXXScopeSpec &SS, SourceLocation IdentLoc,
5383 IdentifierInfo *Ident);
5384
5385 /// Remove decls we can't actually see from a lookup being used to declare
5386 /// shadow using decls.
5387 ///
5388 /// \param S - The scope of the potential shadow decl
5389 /// \param Previous - The lookup of a potential shadow decl's name.
5390 void FilterUsingLookup(Scope *S, LookupResult &lookup);
5391
5392 /// Hides a using shadow declaration. This is required by the current
5393 /// using-decl implementation when a resolvable using declaration in a
5394 /// class is followed by a declaration which would hide or override
5395 /// one or more of the using decl's targets; for example:
5396 ///
5397 /// struct Base { void foo(int); };
5398 /// struct Derived : Base {
5399 /// using Base::foo;
5400 /// void foo(int);
5401 /// };
5402 ///
5403 /// The governing language is C++03 [namespace.udecl]p12:
5404 ///
5405 /// When a using-declaration brings names from a base class into a
5406 /// derived class scope, member functions in the derived class
5407 /// override and/or hide member functions with the same name and
5408 /// parameter types in a base class (rather than conflicting).
5409 ///
5410 /// There are two ways to implement this:
5411 /// (1) optimistically create shadow decls when they're not hidden
5412 /// by existing declarations, or
5413 /// (2) don't create any shadow decls (or at least don't make them
5414 /// visible) until we've fully parsed/instantiated the class.
5415 /// The problem with (1) is that we might have to retroactively remove
5416 /// a shadow decl, which requires several O(n) operations because the
5417 /// decl structures are (very reasonably) not designed for removal.
5418 /// (2) avoids this but is very fiddly and phase-dependent.
5419 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5420
5421 /// Determines whether to create a using shadow decl for a particular
5422 /// decl, given the set of decls existing prior to this using lookup.
5424 const LookupResult &PreviousDecls,
5425 UsingShadowDecl *&PrevShadow);
5426
5427 /// Builds a shadow declaration corresponding to a 'using' declaration.
5430 UsingShadowDecl *PrevDecl);
5431
5432 /// Checks that the given using declaration is not an invalid
5433 /// redeclaration. Note that this is checking only for the using decl
5434 /// itself, not for any ill-formedness among the UsingShadowDecls.
5436 bool HasTypenameKeyword,
5437 const CXXScopeSpec &SS,
5438 SourceLocation NameLoc,
5439 const LookupResult &Previous);
5440
5441 /// Checks that the given nested-name qualifier used in a using decl
5442 /// in the current context is appropriately related to the current
5443 /// scope. If an error is found, diagnoses it and returns true.
5444 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's
5445 /// the result of that lookup. UD is likewise nullptr, except when we have an
5446 /// already-populated UsingDecl whose shadow decls contain the same
5447 /// information (i.e. we're instantiating a UsingDecl with non-dependent
5448 /// scope).
5449 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5450 const CXXScopeSpec &SS,
5451 const DeclarationNameInfo &NameInfo,
5452 SourceLocation NameLoc,
5453 const LookupResult *R = nullptr,
5454 const UsingDecl *UD = nullptr);
5455
5456 /// Builds a using declaration.
5457 ///
5458 /// \param IsInstantiation - Whether this call arises from an
5459 /// instantiation of an unresolved using declaration. We treat
5460 /// the lookup differently for these declarations.
5462 SourceLocation UsingLoc,
5463 bool HasTypenameKeyword,
5464 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5465 DeclarationNameInfo NameInfo,
5466 SourceLocation EllipsisLoc,
5467 const ParsedAttributesView &AttrList,
5468 bool IsInstantiation, bool IsUsingIfExists);
5470 SourceLocation UsingLoc,
5471 SourceLocation EnumLoc,
5472 SourceLocation NameLoc,
5473 TypeSourceInfo *EnumType, EnumDecl *ED);
5474 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5475 ArrayRef<NamedDecl *> Expansions);
5476
5477 /// Additional checks for a using declaration referring to a constructor name.
5479
5480 /// Given a derived-class using shadow declaration for a constructor and the
5481 /// correspnding base class constructor, find or create the implicit
5482 /// synthesized derived class constructor to use for this initialization.
5485 ConstructorUsingShadowDecl *DerivedShadow);
5486
5488 SourceLocation UsingLoc,
5489 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5490 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5491 const ParsedAttributesView &AttrList);
5493 SourceLocation UsingLoc,
5494 SourceLocation EnumLoc, SourceRange TyLoc,
5495 const IdentifierInfo &II, ParsedType Ty,
5496 const CXXScopeSpec &SS);
5498 MultiTemplateParamsArg TemplateParams,
5499 SourceLocation UsingLoc, UnqualifiedId &Name,
5500 const ParsedAttributesView &AttrList,
5501 TypeResult Type, Decl *DeclFromDeclSpec);
5502
5503 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5504 /// including handling of its default argument expressions.
5505 ///
5506 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5508 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5510 bool HadMultipleCandidates, bool IsListInitialization,
5511 bool IsStdInitListInitialization, bool RequiresZeroInit,
5512 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5513
5514 /// Build a CXXConstructExpr whose constructor has already been resolved if
5515 /// it denotes an inherited constructor.
5517 SourceLocation ConstructLoc, QualType DeclInitType,
5518 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5519 bool HadMultipleCandidates, bool IsListInitialization,
5520 bool IsStdInitListInitialization, bool RequiresZeroInit,
5521 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5522
5523 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5524 // the constructor can be elidable?
5526 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5527 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5528 bool HadMultipleCandidates, bool IsListInitialization,
5529 bool IsStdInitListInitialization, bool RequiresZeroInit,
5530 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5531
5533 SourceLocation InitLoc);
5534
5535 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5536 /// constructed variable.
5537 void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit);
5538
5539 /// Helper class that collects exception specifications for
5540 /// implicitly-declared special member functions.
5542 // Pointer to allow copying
5543 Sema *Self;
5544 // We order exception specifications thus:
5545 // noexcept is the most restrictive, but is only used in C++11.
5546 // throw() comes next.
5547 // Then a throw(collected exceptions)
5548 // Finally no specification, which is expressed as noexcept(false).
5549 // throw(...) is used instead if any called function uses it.
5550 ExceptionSpecificationType ComputedEST;
5551 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5552 SmallVector<QualType, 4> Exceptions;
5553
5554 void ClearExceptions() {
5555 ExceptionsSeen.clear();
5556 Exceptions.clear();
5557 }
5558
5559 public:
5561 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5562 if (!Self.getLangOpts().CPlusPlus11)
5563 ComputedEST = EST_DynamicNone;
5564 }
5565
5566 /// Get the computed exception specification type.
5568 assert(!isComputedNoexcept(ComputedEST) &&
5569 "noexcept(expr) should not be a possible result");
5570 return ComputedEST;
5571 }
5572
5573 /// The number of exceptions in the exception specification.
5574 unsigned size() const { return Exceptions.size(); }
5575
5576 /// The set of exceptions in the exception specification.
5577 const QualType *data() const { return Exceptions.data(); }
5578
5579 /// Integrate another called method into the collected data.
5580 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5581
5582 /// Integrate an invoked expression into the collected data.
5583 void CalledExpr(Expr *E) { CalledStmt(E); }
5584
5585 /// Integrate an invoked statement into the collected data.
5586 void CalledStmt(Stmt *S);
5587
5588 /// Overwrite an EPI's exception specification with this
5589 /// computed exception specification.
5592 ESI.Type = getExceptionSpecType();
5593 if (ESI.Type == EST_Dynamic) {
5594 ESI.Exceptions = Exceptions;
5595 } else if (ESI.Type == EST_None) {
5596 /// C++11 [except.spec]p14:
5597 /// The exception-specification is noexcept(false) if the set of
5598 /// potential exceptions of the special member function contains "any"
5599 ESI.Type = EST_NoexceptFalse;
5600 ESI.NoexceptExpr =
5601 Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get();
5602 }
5603 return ESI;
5604 }
5605 };
5606
5607 /// Evaluate the implicit exception specification for a defaulted
5608 /// special member function.
5610
5611 /// Check the given exception-specification and update the
5612 /// exception specification information with the results.
5613 void checkExceptionSpecification(bool IsTopLevel,
5615 ArrayRef<ParsedType> DynamicExceptions,
5616 ArrayRef<SourceRange> DynamicExceptionRanges,
5617 Expr *NoexceptExpr,
5618 SmallVectorImpl<QualType> &Exceptions,
5620
5621 /// Add an exception-specification to the given member or friend function
5622 /// (or function template). The exception-specification was parsed
5623 /// after the function itself was declared.
5625 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
5626 ArrayRef<ParsedType> DynamicExceptions,
5627 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr);
5628
5629 class InheritedConstructorInfo;
5630
5631 /// Determine if a special member function should have a deleted
5632 /// definition when it is defaulted.
5634 InheritedConstructorInfo *ICI = nullptr,
5635 bool Diagnose = false);
5636
5637 /// Produce notes explaining why a defaulted function was defined as deleted.
5639
5640 /// Declare the implicit default constructor for the given class.
5641 ///
5642 /// \param ClassDecl The class declaration into which the implicit
5643 /// default constructor will be added.
5644 ///
5645 /// \returns The implicitly-declared default constructor.
5648
5649 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5650 /// defining this constructor as the default constructor.
5653
5654 /// Declare the implicit destructor for the given class.
5655 ///
5656 /// \param ClassDecl The class declaration into which the implicit
5657 /// destructor will be added.
5658 ///
5659 /// \returns The implicitly-declared destructor.
5661
5662 /// DefineImplicitDestructor - Checks for feasibility of
5663 /// defining this destructor as the default destructor.
5664 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5666
5667 /// Build an exception spec for destructors that don't have one.
5668 ///
5669 /// C++11 says that user-defined destructors with no exception spec get one
5670 /// that looks as if the destructor was implicitly declared.
5672
5673 /// Define the specified inheriting constructor.
5676
5677 /// Declare the implicit copy constructor for the given class.
5678 ///
5679 /// \param ClassDecl The class declaration into which the implicit
5680 /// copy constructor will be added.
5681 ///
5682 /// \returns The implicitly-declared copy constructor.
5684
5685 /// DefineImplicitCopyConstructor - Checks for feasibility of
5686 /// defining this constructor as the copy constructor.
5687 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5689
5690 /// Declare the implicit move constructor for the given class.
5691 ///
5692 /// \param ClassDecl The Class declaration into which the implicit
5693 /// move constructor will be added.
5694 ///
5695 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5696 /// declared.
5698
5699 /// DefineImplicitMoveConstructor - Checks for feasibility of
5700 /// defining this constructor as the move constructor.
5701 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5703
5704 /// Declare the implicit copy assignment operator for the given class.
5705 ///
5706 /// \param ClassDecl The class declaration into which the implicit
5707 /// copy assignment operator will be added.
5708 ///
5709 /// \returns The implicitly-declared copy assignment operator.
5711
5712 /// Defines an implicitly-declared copy assignment operator.
5713 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5714 CXXMethodDecl *MethodDecl);
5715
5716 /// Declare the implicit move assignment operator for the given class.
5717 ///
5718 /// \param ClassDecl The Class declaration into which the implicit
5719 /// move assignment operator will be added.
5720 ///
5721 /// \returns The implicitly-declared move assignment operator, or NULL if it
5722 /// wasn't declared.
5724
5725 /// Defines an implicitly-declared move assignment operator.
5726 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5727 CXXMethodDecl *MethodDecl);
5728
5729 /// Check a completed declaration of an implicit special member.
5731
5732 /// Determine whether the given function is an implicitly-deleted
5733 /// special member function.
5735
5736 /// Check whether 'this' shows up in the type of a static member
5737 /// function after the (naturally empty) cv-qualifier-seq would be.
5738 ///
5739 /// \returns true if an error occurred.
5741
5742 /// Whether this' shows up in the exception specification of a static
5743 /// member function.
5745
5746 /// Check whether 'this' shows up in the attributes of the given
5747 /// static member function.
5748 ///
5749 /// \returns true if an error occurred.
5751
5753 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI);
5754
5756
5757 /// Given a constructor and the set of arguments provided for the
5758 /// constructor, convert the arguments and add any required default arguments
5759 /// to form a proper call to this constructor.
5760 ///
5761 /// \returns true if an error occurred, false otherwise.
5763 QualType DeclInitType, MultiExprArg ArgsPtr,
5764 SourceLocation Loc,
5765 SmallVectorImpl<Expr *> &ConvertedArgs,
5766 bool AllowExplicit = false,
5767 bool IsListInitialization = false);
5768
5769 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5770 /// initializer for the declaration 'Dcl'.
5771 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5772 /// static data member of class X, names should be looked up in the scope of
5773 /// class X.
5775
5776 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5777 /// initializer for the declaration 'Dcl'.
5778 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5779
5780 /// Define the "body" of the conversion from a lambda object to a
5781 /// function pointer.
5782 ///
5783 /// This routine doesn't actually define a sensible body; rather, it fills
5784 /// in the initialization expression needed to copy the lambda object into
5785 /// the block, and IR generation actually generates the real body of the
5786 /// block pointer conversion.
5787 void
5789 CXXConversionDecl *Conv);
5790
5791 /// Define the "body" of the conversion from a lambda object to a
5792 /// block pointer.
5793 ///
5794 /// This routine doesn't actually define a sensible body; rather, it fills
5795 /// in the initialization expression needed to copy the lambda object into
5796 /// the block, and IR generation actually generates the real body of the
5797 /// block pointer conversion.
5799 CXXConversionDecl *Conv);
5800
5801 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5802 /// linkage specification, including the language and (if present)
5803 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
5804 /// language string literal. LBraceLoc, if valid, provides the location of
5805 /// the '{' brace. Otherwise, this linkage specification does not
5806 /// have any braces.
5808 Expr *LangStr, SourceLocation LBraceLoc);
5809
5810 /// ActOnFinishLinkageSpecification - Complete the definition of
5811 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
5812 /// valid, it's the position of the closing '}' brace in a linkage
5813 /// specification that uses braces.
5815 SourceLocation RBraceLoc);
5816
5817 //===--------------------------------------------------------------------===//
5818 // C++ Classes
5819 //
5820
5821 /// Get the class that is directly named by the current context. This is the
5822 /// class for which an unqualified-id in this scope could name a constructor
5823 /// or destructor.
5824 ///
5825 /// If the scope specifier denotes a class, this will be that class.
5826 /// If the scope specifier is empty, this will be the class whose
5827 /// member-specification we are currently within. Otherwise, there
5828 /// is no such class.
5830
5831 /// isCurrentClassName - Determine whether the identifier II is the
5832 /// name of the class type currently being defined. In the case of
5833 /// nested classes, this will only return true if II is the name of
5834 /// the innermost class.
5835 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5836 const CXXScopeSpec *SS = nullptr);
5837
5838 /// Determine whether the identifier II is a typo for the name of
5839 /// the class type currently being defined. If so, update it to the identifier
5840 /// that should have been used.
5842
5843 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
5845 SourceLocation ColonLoc,
5846 const ParsedAttributesView &Attrs);
5847
5848 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
5849 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
5850 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
5851 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
5852 /// present (but parsing it has been deferred).
5853 NamedDecl *
5855 MultiTemplateParamsArg TemplateParameterLists,
5856 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5857 InClassInitStyle InitStyle);
5858
5859 /// Enter a new C++ default initializer scope. After calling this, the
5860 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
5861 /// parsing or instantiating the initializer failed.
5863
5864 /// This is invoked after parsing an in-class initializer for a
5865 /// non-static C++ class member, and after instantiating an in-class
5866 /// initializer in a class template. Such actions are deferred until the class
5867 /// is complete.
5869 SourceLocation EqualLoc,
5871
5872 /// Handle a C++ member initializer using parentheses syntax.
5874 ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS,
5875 IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy,
5876 const DeclSpec &DS, SourceLocation IdLoc,
5877 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
5878 SourceLocation RParenLoc, SourceLocation EllipsisLoc);
5879
5880 /// Handle a C++ member initializer using braced-init-list syntax.
5881 MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S,
5882 CXXScopeSpec &SS,
5883 IdentifierInfo *MemberOrBase,
5884 ParsedType TemplateTypeTy,
5885 const DeclSpec &DS, SourceLocation IdLoc,
5886 Expr *InitList, SourceLocation EllipsisLoc);
5887
5888 /// Handle a C++ member initializer.
5889 MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S,
5890 CXXScopeSpec &SS,
5891 IdentifierInfo *MemberOrBase,
5892 ParsedType TemplateTypeTy,
5893 const DeclSpec &DS, SourceLocation IdLoc,
5894 Expr *Init, SourceLocation EllipsisLoc);
5895
5897 SourceLocation IdLoc);
5898
5900 TypeSourceInfo *BaseTInfo, Expr *Init,
5901 CXXRecordDecl *ClassDecl,
5902 SourceLocation EllipsisLoc);
5903
5905 CXXRecordDecl *ClassDecl);
5906
5909
5911 ArrayRef<CXXCtorInitializer *> Initializers = {});
5912
5913 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5914 /// mark all the non-trivial destructors of its members and bases as
5915 /// referenced.
5916 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5917 CXXRecordDecl *Record);
5918
5919 /// Mark destructors of virtual bases of this class referenced. In the Itanium
5920 /// C++ ABI, this is done when emitting a destructor for any non-abstract
5921 /// class. In the Microsoft C++ ABI, this is done any time a class's
5922 /// destructor is referenced.
5924 SourceLocation Location, CXXRecordDecl *ClassDecl,
5925 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases =
5926 nullptr);
5927
5928 /// Do semantic checks to allow the complete destructor variant to be emitted
5929 /// when the destructor is defined in another translation unit. In the Itanium
5930 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
5931 /// can be emitted in separate TUs. To emit the complete variant, run a subset
5932 /// of the checks performed when emitting a regular destructor.
5933 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
5934 CXXDestructorDecl *Dtor);
5935
5936 /// The list of classes whose vtables have been used within
5937 /// this translation unit, and the source locations at which the
5938 /// first use occurred.
5939 typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse;
5940
5941 /// The list of vtables that are required but have not yet been
5942 /// materialized.
5944
5945 /// The set of classes whose vtables have been used within
5946 /// this translation unit, and a bit that will be true if the vtable is
5947 /// required to be emitted (otherwise, it should be emitted only if needed
5948 /// by code generation).
5949 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5950
5951 /// Load any externally-stored vtable uses.
5953
5954 /// Note that the vtable for the given class was used at the
5955 /// given location.
5957 bool DefinitionRequired = false);
5958
5959 /// Mark the exception specifications of all virtual member functions
5960 /// in the given class as needed.
5962 const CXXRecordDecl *RD);
5963
5964 /// MarkVirtualMembersReferenced - Will mark all members of the given
5965 /// CXXRecordDecl referenced.
5967 bool ConstexprOnly = false);
5968
5969 /// Define all of the vtables that have been used in this
5970 /// translation unit and reference any virtual members used by those
5971 /// vtables.
5972 ///
5973 /// \returns true if any work was done, false otherwise.
5974 bool DefineUsedVTables();
5975
5976 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5977 /// special functions, such as the default constructor, copy
5978 /// constructor, or destructor, to the given C++ class (C++
5979 /// [special]p1). This routine can only be executed just before the
5980 /// definition of the class is complete.
5982
5983 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5984 void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc,
5986 bool AnyErrors);
5987
5988 /// Check class-level dllimport/dllexport attribute. The caller must
5989 /// ensure that referenceDLLExportedClassMethods is called some point later
5990 /// when all outer classes of Class are complete.
5993
5995
5996 /// Perform propagation of DLL attributes from a derived class to a
5997 /// templated base class for MS compatibility.
5999 CXXRecordDecl *Class, Attr *ClassAttr,
6000 ClassTemplateSpecializationDecl *BaseTemplateSpec,
6001 SourceLocation BaseLoc);
6002
6003 /// Perform semantic checks on a class definition that has been
6004 /// completing, introducing implicitly-declared members, checking for
6005 /// abstract types, etc.
6006 ///
6007 /// \param S The scope in which the class was parsed. Null if we didn't just
6008 /// parse a class definition.
6009 /// \param Record The completed class.
6011
6012 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6013 /// conditions that are needed for the attribute to have an effect.
6015
6016 /// Check that VTable Pointer authentication is only being set on the first
6017 /// first instantiation of the vtable
6019
6021 Decl *TagDecl, SourceLocation LBrac,
6022 SourceLocation RBrac,
6023 const ParsedAttributesView &AttrList);
6024
6025 /// Perform any semantic analysis which needs to be delayed until all
6026 /// pending class member declarations have been parsed.
6029
6030 /// This is used to implement the constant expression evaluation part of the
6031 /// attribute enable_if extension. There is nothing in standard C++ which
6032 /// would require reentering parameters.
6035 llvm::function_ref<Scope *()> EnterScope);
6037
6038 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6039 /// parsing a top-level (non-nested) C++ class, and we are now
6040 /// parsing those parts of the given Method declaration that could
6041 /// not be parsed earlier (C++ [class.mem]p2), such as default
6042 /// arguments. This action should enter the scope of the given
6043 /// Method declaration as if we had just parsed the qualified method
6044 /// name. However, it should not bring the parameters into scope;
6045 /// that will be performed by ActOnDelayedCXXMethodParameter.
6047 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6049
6050 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6051 /// processing the delayed method declaration for Method. The method
6052 /// declaration is now considered finished. There may be a separate
6053 /// ActOnStartOfFunctionDef action later (not necessarily
6054 /// immediately!) for this method, if it was also defined inside the
6055 /// class body.
6058
6060
6061 bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
6062 StringEvaluationContext EvalContext,
6063 bool ErrorOnInvalidMessage);
6064 bool EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
6065 StringEvaluationContext EvalContext,
6066 bool ErrorOnInvalidMessage);
6067
6069 Expr *AssertExpr, Expr *AssertMessageExpr,
6070 SourceLocation RParenLoc);
6072 Expr *AssertExpr, Expr *AssertMessageExpr,
6073 SourceLocation RParenLoc, bool Failed);
6074
6075 /// Try to print more useful information about a failed static_assert
6076 /// with expression \E
6077 void DiagnoseStaticAssertDetails(const Expr *E);
6078
6079 /// If E represents a built-in type trait, or a known standard type trait,
6080 /// try to print more information about why the type type-trait failed.
6081 /// This assumes we already evaluated the expression to a false boolean value.
6082 void DiagnoseTypeTraitDetails(const Expr *E);
6083
6084 /// Handle a friend type declaration. This works in tandem with
6085 /// ActOnTag.
6086 ///
6087 /// Notes on friend class templates:
6088 ///
6089 /// We generally treat friend class declarations as if they were
6090 /// declaring a class. So, for example, the elaborated type specifier
6091 /// in a friend declaration is required to obey the restrictions of a
6092 /// class-head (i.e. no typedefs in the scope chain), template
6093 /// parameters are required to match up with simple template-ids, &c.
6094 /// However, unlike when declaring a template specialization, it's
6095 /// okay to refer to a template specialization without an empty
6096 /// template parameter declaration, e.g.
6097 /// friend class A<T>::B<unsigned>;
6098 /// We permit this as a special case; if there are any template
6099 /// parameters present at all, require proper matching, i.e.
6100 /// template <> template <class T> friend class A<int>::B;
6101 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6102 MultiTemplateParamsArg TemplateParams,
6103 SourceLocation EllipsisLoc);
6105 MultiTemplateParamsArg TemplateParams);
6106
6107 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6108 /// the well-formedness of the constructor declarator @p D with type @p
6109 /// R. If there are any errors in the declarator, this routine will
6110 /// emit diagnostics and set the invalid bit to true. In any case, the type
6111 /// will be updated to reflect a well-formed type for the constructor and
6112 /// returned.
6114 StorageClass &SC);
6115
6116 /// CheckConstructor - Checks a fully-formed constructor for
6117 /// well-formedness, issuing any diagnostics required. Returns true if
6118 /// the constructor declarator is invalid.
6120
6121 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6122 /// the well-formednes of the destructor declarator @p D with type @p
6123 /// R. If there are any errors in the declarator, this routine will
6124 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6125 /// will be updated to reflect a well-formed type for the destructor and
6126 /// returned.
6128 StorageClass &SC);
6129
6130 /// CheckDestructor - Checks a fully-formed destructor definition for
6131 /// well-formedness, issuing any diagnostics required. Returns true
6132 /// on error.
6134
6135 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6136 /// well-formednes of the conversion function declarator @p D with
6137 /// type @p R. If there are any errors in the declarator, this routine
6138 /// will emit diagnostics and return true. Otherwise, it will return
6139 /// false. Either way, the type @p R will be updated to reflect a
6140 /// well-formed type for the conversion operator.
6142
6143 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6144 /// the declaration of the given C++ conversion function. This routine
6145 /// is responsible for recording the conversion function in the C++
6146 /// class, if possible.
6148
6149 /// Check the validity of a declarator that we parsed for a deduction-guide.
6150 /// These aren't actually declarators in the grammar, so we need to check that
6151 /// the user didn't specify any pieces that are not part of the
6152 /// deduction-guide grammar. Return true on invalid deduction-guide.
6154 StorageClass &SC);
6155
6157
6160 SourceLocation DefaultLoc);
6162
6163 /// Kinds of defaulted comparison operator functions.
6164 enum class DefaultedComparisonKind : unsigned char {
6165 /// This is not a defaultable comparison operator.
6167 /// This is an operator== that should be implemented as a series of
6168 /// subobject comparisons.
6170 /// This is an operator<=> that should be implemented as a series of
6171 /// subobject comparisons.
6173 /// This is an operator!= that should be implemented as a rewrite in terms
6174 /// of a == comparison.
6176 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
6177 /// terms of a <=> comparison.
6179 };
6180
6184 FunctionDecl *Spaceship);
6187
6189 QualType R, bool IsLambda,
6190 DeclContext *DC = nullptr);
6192 DeclarationName Name, QualType R);
6194
6195 //===--------------------------------------------------------------------===//
6196 // C++ Derived Classes
6197 //
6198
6199 /// Check the validity of a C++ base class specifier.
6200 ///
6201 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
6202 /// and returns NULL otherwise.
6204 SourceRange SpecifierRange, bool Virtual,
6205 AccessSpecifier Access,
6206 TypeSourceInfo *TInfo,
6207 SourceLocation EllipsisLoc);
6208
6209 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
6210 /// one entry in the base class list of a class specifier, for
6211 /// example:
6212 /// class foo : public bar, virtual private baz {
6213 /// 'public bar' and 'virtual private baz' are each base-specifiers.
6214 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
6215 const ParsedAttributesView &Attrs, bool Virtual,
6216 AccessSpecifier Access, ParsedType basetype,
6217 SourceLocation BaseLoc,
6218 SourceLocation EllipsisLoc);
6219
6220 /// Performs the actual work of attaching the given base class
6221 /// specifiers to a C++ class.
6224
6225 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
6226 /// class, after checking whether there are any duplicate base
6227 /// classes.
6228 void ActOnBaseSpecifiers(Decl *ClassDecl,
6230
6231 /// Determine whether the type \p Derived is a C++ class that is
6232 /// derived from the type \p Base.
6233 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6235 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6239 CXXBasePaths &Paths);
6240
6241 // FIXME: I don't like this name.
6242 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6243
6245 SourceLocation Loc, SourceRange Range,
6246 CXXCastPath *BasePath = nullptr,
6247 bool IgnoreAccess = false);
6248
6249 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
6250 /// conversion (where Derived and Base are class types) is
6251 /// well-formed, meaning that the conversion is unambiguous (and
6252 /// that all of the base classes are accessible). Returns true
6253 /// and emits a diagnostic if the code is ill-formed, returns false
6254 /// otherwise. Loc is the location where this routine should point to
6255 /// if there is an error, and Range is the source range to highlight
6256 /// if there is an error.
6257 ///
6258 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
6259 /// diagnostic for the respective type of error will be suppressed, but the
6260 /// check for ill-formed code will still be performed.
6262 unsigned InaccessibleBaseID,
6263 unsigned AmbiguousBaseConvID,
6264 SourceLocation Loc, SourceRange Range,
6265 DeclarationName Name, CXXCastPath *BasePath,
6266 bool IgnoreAccess = false);
6267
6268 /// Builds a string representing ambiguous paths from a
6269 /// specific derived class to different subobjects of the same base
6270 /// class.
6271 ///
6272 /// This function builds a string that can be used in error messages
6273 /// to show the different paths that one can take through the
6274 /// inheritance hierarchy to go from the derived class to different
6275 /// subobjects of a base class. The result looks something like this:
6276 /// @code
6277 /// struct D -> struct B -> struct A
6278 /// struct D -> struct C -> struct A
6279 /// @endcode
6280 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6281
6283 const CXXMethodDecl *Old);
6284
6285 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6286 /// covariant, according to C++ [class.virtual]p5.
6288 const CXXMethodDecl *Old);
6289
6290 // Check that the overriding method has no explicit object parameter.
6292 const CXXMethodDecl *Old);
6293
6294 /// Mark the given method pure.
6295 ///
6296 /// \param Method the method to be marked pure.
6297 ///
6298 /// \param InitRange the source range that covers the "0" initializer.
6300
6301 /// CheckOverrideControl - Check C++11 override control semantics.
6303
6304 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6305 /// not used in the declaration of an overriding method.
6307
6308 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
6309 /// function overrides a virtual member function marked 'final', according to
6310 /// C++11 [class.virtual]p4.
6312 const CXXMethodDecl *Old);
6313
6324
6325 struct TypeDiagnoser;
6326
6329 TypeDiagnoser &Diagnoser);
6330 template <typename... Ts>
6331 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6332 const Ts &...Args) {
6333 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6334 return RequireNonAbstractType(Loc, T, Diagnoser);
6335 }
6336
6337 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6338
6339 //===--------------------------------------------------------------------===//
6340 // C++ Overloaded Operators [C++ 13.5]
6341 //
6342
6343 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
6344 /// of this overloaded operator is well-formed. If so, returns false;
6345 /// otherwise, emits appropriate diagnostics and returns true.
6347
6348 /// CheckLiteralOperatorDeclaration - Check whether the declaration
6349 /// of this literal operator function is well-formed. If so, returns
6350 /// false; otherwise, emits appropriate diagnostics and returns true.
6352
6353 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
6354 /// found in an explicit(bool) specifier.
6356
6357 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
6358 /// Returns true if the explicit specifier is now resolved.
6360
6361 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6362 /// C++ if/switch/while/for statement.
6363 /// e.g: "if (int x = f()) {...}"
6365
6366 // Emitting members of dllexported classes is delayed until the class
6367 // (including field initializers) is fully parsed.
6370
6371 /// Merge the exception specifications of two variable declarations.
6372 ///
6373 /// This is called when there's a redeclaration of a VarDecl. The function
6374 /// checks if the redeclaration might have an exception specification and
6375 /// validates compatibility and merges the specs if necessary.
6377
6378 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
6379 /// function, once we already know that they have the same
6380 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
6381 /// error, false otherwise.
6383
6384 /// Helpers for dealing with blocks and functions.
6386
6387 /// CheckExtraCXXDefaultArguments - Check for any extra default
6388 /// arguments in the declarator, which is not a function declaration
6389 /// or definition and therefore is not permitted to have default
6390 /// arguments. This routine should be invoked for every declarator
6391 /// that is not a function declaration or definition.
6393
6397
6398 /// Perform semantic analysis for the variable declaration that
6399 /// occurs within a C++ catch clause, returning the newly-created
6400 /// variable.
6402 SourceLocation StartLoc,
6403 SourceLocation IdLoc,
6404 const IdentifierInfo *Id);
6405
6406 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6407 /// handler.
6409
6411
6412 /// Handle a friend tag declaration where the scope specifier was
6413 /// templated.
6415 unsigned TagSpec, SourceLocation TagLoc,
6416 CXXScopeSpec &SS, IdentifierInfo *Name,
6417 SourceLocation NameLoc,
6418 SourceLocation EllipsisLoc,
6420 MultiTemplateParamsArg TempParamLists);
6421
6423 SourceLocation DeclStart, Declarator &D,
6424 Expr *BitfieldWidth,
6425 InClassInitStyle InitStyle,
6426 AccessSpecifier AS,
6427 const ParsedAttr &MSPropertyAttr);
6428
6429 /// Diagnose why the specified class does not have a trivial special member of
6430 /// the given kind.
6433
6434 /// Determine whether a defaulted or deleted special member function is
6435 /// trivial, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6436 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6440 bool Diagnose = false);
6441
6442 /// For a defaulted function, the kind of defaulted function that it is.
6444 LLVM_PREFERRED_TYPE(CXXSpecialMemberKind)
6445 unsigned SpecialMember : 8;
6446 unsigned Comparison : 8;
6447
6448 public:
6450 : SpecialMember(llvm::to_underlying(CXXSpecialMemberKind::Invalid)),
6451 Comparison(llvm::to_underlying(DefaultedComparisonKind::None)) {}
6453 : SpecialMember(llvm::to_underlying(CSM)),
6454 Comparison(llvm::to_underlying(DefaultedComparisonKind::None)) {}
6456 : SpecialMember(llvm::to_underlying(CXXSpecialMemberKind::Invalid)),
6457 Comparison(llvm::to_underlying(Comp)) {}
6458
6459 bool isSpecialMember() const {
6460 return static_cast<CXXSpecialMemberKind>(SpecialMember) !=
6462 }
6463 bool isComparison() const {
6464 return static_cast<DefaultedComparisonKind>(Comparison) !=
6466 }
6467
6468 explicit operator bool() const {
6469 return isSpecialMember() || isComparison();
6470 }
6471
6473 return static_cast<CXXSpecialMemberKind>(SpecialMember);
6474 }
6476 return static_cast<DefaultedComparisonKind>(Comparison);
6477 }
6478
6479 /// Get the index of this function kind for use in diagnostics.
6480 unsigned getDiagnosticIndex() const {
6481 static_assert(llvm::to_underlying(CXXSpecialMemberKind::Invalid) >
6482 llvm::to_underlying(CXXSpecialMemberKind::Destructor),
6483 "invalid should have highest index");
6484 static_assert((unsigned)DefaultedComparisonKind::None == 0,
6485 "none should be equal to zero");
6486 return SpecialMember + Comparison;
6487 }
6488 };
6489
6490 /// Determine the kind of defaulting that would be done for a given function.
6491 ///
6492 /// If the function is both a default constructor and a copy / move
6493 /// constructor (due to having a default argument for the first parameter),
6494 /// this picks CXXSpecialMemberKind::DefaultConstructor.
6495 ///
6496 /// FIXME: Check that case is properly handled by all callers.
6497 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
6498
6499 /// Handle a C++11 empty-declaration and attribute-declaration.
6501 SourceLocation SemiLoc);
6502
6504 /// Diagnose issues that are non-constant or that are extensions.
6506 /// Identify whether this function satisfies the formal rules for constexpr
6507 /// functions in the current lanugage mode (with no extensions).
6509 };
6510
6511 // Check whether a function declaration satisfies the requirements of a
6512 // constexpr function definition or a constexpr constructor definition. If so,
6513 // return true. If not, produce appropriate diagnostics (unless asked not to
6514 // by Kind) and return false.
6515 //
6516 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
6518 CheckConstexprKind Kind);
6519
6520 /// Diagnose methods which overload virtual methods in a base class
6521 /// without overriding any.
6523
6524 /// Check if a method overloads virtual methods in a base class without
6525 /// overriding any.
6526 void
6528 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6529 void
6531 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6532
6533 /// ActOnParamDefaultArgument - Check whether the default argument
6534 /// provided for a function parameter is well-formed. If so, attach it
6535 /// to the parameter declaration.
6536 void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
6537 Expr *defarg);
6538
6539 /// ActOnParamUnparsedDefaultArgument - We've seen a default
6540 /// argument for a function parameter, but we can't parse it yet
6541 /// because we're inside a class definition. Note that this default
6542 /// argument will be parsed later.
6544 SourceLocation ArgLoc);
6545
6546 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
6547 /// the default argument for the parameter param failed.
6549 Expr *DefaultArg);
6551 SourceLocation EqualLoc);
6552 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6553 SourceLocation EqualLoc);
6554
6555 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
6556 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc,
6557 StringLiteral *Message = nullptr);
6558 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
6559
6560 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
6561 StringLiteral *DeletedMessage = nullptr);
6565
6566 NamedDecl *
6568 MultiTemplateParamsArg TemplateParamLists);
6571 RecordDecl *ClassDecl,
6572 const IdentifierInfo *Name);
6573
6575 SourceLocation Loc);
6577
6578 /// Stack containing information needed when in C++2a an 'auto' is encountered
6579 /// in a function declaration parameter type specifier in order to invent a
6580 /// corresponding template parameter in the enclosing abbreviated function
6581 /// template. This information is also present in LambdaScopeInfo, stored in
6582 /// the FunctionScopes stack.
6584
6585 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
6586 std::unique_ptr<CXXFieldCollector> FieldCollector;
6587
6589 /// Set containing all declared private fields that are not used.
6591
6593
6594 /// PureVirtualClassDiagSet - a set of class declarations which we have
6595 /// emitted a list of pure virtual functions. Used to prevent emitting the
6596 /// same list more than once.
6597 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
6598
6602
6603 /// All the delegating constructors seen so far in the file, used for
6604 /// cycle detection at the end of the TU.
6606
6607 /// The C++ "std" namespace, where the standard library resides.
6609
6610 /// The C++ "std::initializer_list" template, which is defined in
6611 /// <initializer_list>.
6613
6614 /// The C++ "std::type_identity" template, which is defined in
6615 /// <type_traits>.
6617
6618 // Contains the locations of the beginning of unparsed default
6619 // argument locations.
6620 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
6621
6622 /// UndefinedInternals - all the used, undefined objects which require a
6623 /// definition in this translation unit.
6624 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
6625
6626 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMemberKind>
6628
6629 /// The C++ special members which we are currently in the process of
6630 /// declaring. If this process recursively triggers the declaration of the
6631 /// same special member, we should act as if it is not yet declared.
6633
6635
6636 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
6637
6640 ParsingClassDepth++;
6642 }
6644 ParsingClassDepth--;
6646 }
6647
6649 CXXScopeSpec &SS,
6650 ParsedType TemplateTypeTy,
6651 IdentifierInfo *MemberOrBase);
6652
6653private:
6654 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
6655 QualType ResultTy,
6656 ArrayRef<QualType> Args);
6657 // Helper for ActOnFields to check for all function pointer members.
6658 bool EntirelyFunctionPointers(const RecordDecl *Record);
6659
6660 // A cache representing if we've fully checked the various comparison category
6661 // types stored in ASTContext. The bit-index corresponds to the integer value
6662 // of a ComparisonCategoryType enumerator.
6663 llvm::SmallBitVector FullyCheckedComparisonCategories;
6664
6665 /// Check if there is a field shadowing.
6666 void CheckShadowInheritedFields(const SourceLocation &Loc,
6667 DeclarationName FieldName,
6668 const CXXRecordDecl *RD,
6669 bool DeclIsField = true);
6670
6671 ///@}
6672
6673 //
6674 //
6675 // -------------------------------------------------------------------------
6676 //
6677 //
6678
6679 /// \name C++ Exception Specifications
6680 /// Implementations are in SemaExceptionSpec.cpp
6681 ///@{
6682
6683public:
6684 /// All the overriding functions seen during a class definition
6685 /// that had their exception spec checks delayed, plus the overridden
6686 /// function.
6689
6690 /// All the function redeclarations seen during a class definition that had
6691 /// their exception spec checks delayed, plus the prior declaration they
6692 /// should be checked against. Except during error recovery, the new decl
6693 /// should always be a friend declaration, as that's the only valid way to
6694 /// redeclare a special member before its class is complete.
6697
6698 /// Determine if we're in a case where we need to (incorrectly) eagerly
6699 /// parse an exception specification to work around a libstdc++ bug.
6701
6702 /// Check the given noexcept-specifier, convert its expression, and compute
6703 /// the appropriate ExceptionSpecificationType.
6704 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6706
6707 CanThrowResult canThrow(const Stmt *E);
6708 /// Determine whether the callee of a particular function call can throw.
6709 /// E, D and Loc are all optional.
6710 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
6713 const FunctionProtoType *FPT);
6716
6717 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
6718 /// exception specification. Incomplete types, or pointers to incomplete types
6719 /// other than void are not allowed.
6720 ///
6721 /// \param[in,out] T The exception type. This will be decayed to a pointer
6722 /// type
6723 /// when the input is an array or a function type.
6725
6726 /// CheckDistantExceptionSpec - Check if the given type is a pointer or
6727 /// pointer to member to a function with an exception specification. This
6728 /// means that it is invalid to add another level of indirection.
6731
6732 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
6733 /// exception specifications. Exception specifications are equivalent if
6734 /// they allow exactly the same set of exception types. It does not matter how
6735 /// that is achieved. See C++ [except.spec]p2.
6737 SourceLocation OldLoc,
6738 const FunctionProtoType *New,
6739 SourceLocation NewLoc);
6741 const PartialDiagnostic &NoteID,
6742 const FunctionProtoType *Old,
6743 SourceLocation OldLoc,
6744 const FunctionProtoType *New,
6745 SourceLocation NewLoc);
6746 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
6747
6748 /// CheckExceptionSpecSubset - Check whether the second function type's
6749 /// exception specification is a subset (or equivalent) of the first function
6750 /// type. This is used by override and pointer assignment checks.
6752 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
6753 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
6754 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
6755 SourceLocation SuperLoc, const FunctionProtoType *Subset,
6756 bool SkipSubsetFirstParameter, SourceLocation SubLoc);
6757
6758 /// CheckParamExceptionSpec - Check if the parameter and return types of the
6759 /// two functions have equivalent exception specs. This is part of the
6760 /// assignment and override compatibility check. We do not check the
6761 /// parameters of parameter function pointers recursively, as no sane
6762 /// programmer would even be able to write such a function type.
6764 const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID,
6765 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
6766 SourceLocation TargetLoc, const FunctionProtoType *Source,
6767 bool SkipSourceFirstParameter, SourceLocation SourceLoc);
6768
6769 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6770
6771 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6772 /// spec is a subset of base spec.
6774 const CXXMethodDecl *Old);
6775
6776 ///@}
6777
6778 //
6779 //
6780 // -------------------------------------------------------------------------
6781 //
6782 //
6783
6784 /// \name Expressions
6785 /// Implementations are in SemaExpr.cpp
6786 ///@{
6787
6788public:
6789 /// Describes how the expressions currently being parsed are
6790 /// evaluated at run-time, if at all.
6792 /// The current expression and its subexpressions occur within an
6793 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
6794 /// \c sizeof, where the type of the expression may be significant but
6795 /// no code will be generated to evaluate the value of the expression at
6796 /// run time.
6798
6799 /// The current expression occurs within a braced-init-list within
6800 /// an unevaluated operand. This is mostly like a regular unevaluated
6801 /// context, except that we still instantiate constexpr functions that are
6802 /// referenced here so that we can perform narrowing checks correctly.
6804
6805 /// The current expression occurs within a discarded statement.
6806 /// This behaves largely similarly to an unevaluated operand in preventing
6807 /// definitions from being required, but not in other ways.
6809
6810 /// The current expression occurs within an unevaluated
6811 /// operand that unconditionally permits abstract references to
6812 /// fields, such as a SIZE operator in MS-style inline assembly.
6814
6815 /// The current context is "potentially evaluated" in C++11 terms,
6816 /// but the expression is evaluated at compile-time (like the values of
6817 /// cases in a switch statement).
6819
6820 /// In addition of being constant evaluated, the current expression
6821 /// occurs in an immediate function context - either a consteval function
6822 /// or a consteval if statement.
6824
6825 /// The current expression is potentially evaluated at run time,
6826 /// which means that code may be generated to evaluate the value of the
6827 /// expression at run time.
6829
6830 /// The current expression is potentially evaluated, but any
6831 /// declarations referenced inside that expression are only used if
6832 /// in fact the current expression is used.
6833 ///
6834 /// This value is used when parsing default function arguments, for which
6835 /// we would like to provide diagnostics (e.g., passing non-POD arguments
6836 /// through varargs) but do not want to mark declarations as "referenced"
6837 /// until the default argument is used.
6839 };
6840
6841 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
6842 /// to a variable (constant) that may or may not be odr-used in this Expr, and
6843 /// we won't know until all lvalue-to-rvalue and discarded value conversions
6844 /// have been applied to all subexpressions of the enclosing full expression.
6845 /// This is cleared at the end of each full expression.
6848
6849 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
6850
6851 /// Data structure used to record current or nested
6852 /// expression evaluation contexts.
6854 /// The expression evaluation context.
6856
6857 /// Whether the enclosing context needed a cleanup.
6859
6860 /// The number of active cleanup objects when we entered
6861 /// this expression evaluation context.
6863
6865
6866 /// The lambdas that are present within this context, if it
6867 /// is indeed an unevaluated context.
6869
6870 /// The declaration that provides context for lambda expressions
6871 /// and block literals if the normal declaration context does not
6872 /// suffice, e.g., in a default function argument.
6874
6875 /// Declaration for initializer if one is currently being
6876 /// parsed. Used when an expression has a possibly unreachable
6877 /// diagnostic to reference the declaration as a whole.
6879
6880 /// If we are processing a decltype type, a set of call expressions
6881 /// for which we have deferred checking the completeness of the return type.
6883
6884 /// If we are processing a decltype type, a set of temporary binding
6885 /// expressions for which we have deferred checking the destructor.
6887
6889
6890 /// Expressions appearing as the LHS of a volatile assignment in this
6891 /// context. We produce a warning for these when popping the context if
6892 /// they are not discarded-value expressions nor unevaluated operands.
6894
6895 /// Set of candidates for starting an immediate invocation.
6898
6899 /// Set of DeclRefExprs referencing a consteval function when used in a
6900 /// context not already known to be immediately invoked.
6902
6903 /// P2718R0 - Lifetime extension in range-based for loops.
6904 /// MaterializeTemporaryExprs in for-range-init expressions which need to
6905 /// extend lifetime. Add MaterializeTemporaryExpr* if the value of
6906 /// InLifetimeExtendingContext is true.
6908
6909 /// Small set of gathered accesses to potentially misaligned members
6910 /// due to the packed attribute.
6912
6913 /// \brief Describes whether we are in an expression constext which we have
6914 /// to handle differently.
6922
6923 // A context can be nested in both a discarded statement context and
6924 // an immediate function context, so they need to be tracked independently.
6928
6930
6931 // We are in a constant context, but we also allow
6932 // non constant expressions, for example for array bounds (which may be
6933 // VLAs).
6935
6936 /// Whether we are currently in a context in which all temporaries must be
6937 /// lifetime-extended, even if they're not bound to a reference (for
6938 /// example, in a for-range initializer).
6940
6941 /// Whether evaluating an expression for a switch case label.
6942 bool IsCaseExpr = false;
6943
6944 /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
6946
6947 // When evaluating immediate functions in the initializer of a default
6948 // argument or default member initializer, this is the declaration whose
6949 // default initializer is being evaluated and the location of the call
6950 // or constructor definition.
6954 : Loc(Loc), Decl(Decl), Context(Context) {
6955 assert(Decl && Context && "invalid initialization context");
6956 }
6957
6959 ValueDecl *Decl = nullptr;
6961 };
6962 std::optional<InitializationContext> DelayedDefaultInitializationContext;
6963
6974
6980
6987
6992
6997 // C++23 [expr.const]p14:
6998 // An expression or conversion is in an immediate function
6999 // context if it is potentially evaluated and either:
7000 // * its innermost enclosing non-block scope is a function
7001 // parameter scope of an immediate function, or
7002 // * its enclosing statement is enclosed by the compound-
7003 // statement of a consteval if statement.
7006 }
7007
7015 };
7016
7018 assert(!ExprEvalContexts.empty() &&
7019 "Must be in an expression evaluation context");
7020 return ExprEvalContexts.back();
7021 }
7022
7024 assert(!ExprEvalContexts.empty() &&
7025 "Must be in an expression evaluation context");
7026 return ExprEvalContexts.back();
7027 }
7028
7030 assert(ExprEvalContexts.size() >= 2 &&
7031 "Must be in an expression evaluation context");
7032 return ExprEvalContexts[ExprEvalContexts.size() - 2];
7033 }
7034
7036 return const_cast<Sema *>(this)->parentEvaluationContext();
7037 }
7038
7043
7044 /// Increment when we find a reference; decrement when we find an ignored
7045 /// assignment. Ultimately the value is 0 if every reference is an ignored
7046 /// assignment.
7047 ///
7048 /// Uses canonical VarDecl as key so in-class decls and out-of-class defs of
7049 /// static data members get tracked as a single entry.
7050 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
7051
7052 /// Used to control the generation of ExprWithCleanups.
7054
7055 /// ExprCleanupObjects - This is the stack of objects requiring
7056 /// cleanup that are created by the current full expression.
7058
7059 /// Determine whether the use of this declaration is valid, without
7060 /// emitting diagnostics.
7061 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
7062 // A version of DiagnoseUseOfDecl that should be used if overload resolution
7063 // has been used to find this declaration, which means we don't have to bother
7064 // checking the trailing requires clause.
7066 return DiagnoseUseOfDecl(
7067 D, Loc, /*UnknownObjCClass=*/nullptr, /*ObjCPropertyAccess=*/false,
7068 /*AvoidPartialAvailabilityChecks=*/false, /*ClassReceiver=*/nullptr,
7069 /*SkipTrailingRequiresClause=*/true);
7070 }
7071
7072 /// Determine whether the use of this declaration is valid, and
7073 /// emit any corresponding diagnostics.
7074 ///
7075 /// This routine diagnoses various problems with referencing
7076 /// declarations that can occur when using a declaration. For example,
7077 /// it might warn if a deprecated or unavailable declaration is being
7078 /// used, or produce an error (and return true) if a C++0x deleted
7079 /// function is being used.
7080 ///
7081 /// \returns true if there was an error (this declaration cannot be
7082 /// referenced), false otherwise.
7084 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
7085 bool ObjCPropertyAccess = false,
7086 bool AvoidPartialAvailabilityChecks = false,
7087 ObjCInterfaceDecl *ClassReceiver = nullptr,
7088 bool SkipTrailingRequiresClause = false);
7089
7090 /// Emit a note explaining that this function is deleted.
7092
7093 /// DiagnoseSentinelCalls - This routine checks whether a call or
7094 /// message-send is to a declaration with the sentinel attribute, and
7095 /// if so, it checks that the requirements of the sentinel are
7096 /// satisfied.
7098 ArrayRef<Expr *> Args);
7099
7101 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
7104
7106 ExpressionEvaluationContext NewContext, FunctionDecl *FD);
7107
7110 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
7114
7116
7120
7121 /// Check whether E, which is either a discarded-value expression or an
7122 /// unevaluated operand, is a simple-assignment to a volatlie-qualified
7123 /// lvalue, and if so, remove it from the list of volatile-qualified
7124 /// assignments that we are going to warn are deprecated.
7126
7128
7129 // Functions for marking a declaration referenced. These functions also
7130 // contain the relevant logic for marking if a reference to a function or
7131 // variable is an odr-use (in the C++11 sense). There are separate variants
7132 // for expressions referring to a decl; these exist because odr-use marking
7133 // needs to be delayed for some constant variables when we build one of the
7134 // named expressions.
7135 //
7136 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
7137 // should usually be true. This only needs to be set to false if the lack of
7138 // odr-use cannot be determined from the current context (for instance,
7139 // because the name denotes a virtual function and was written without an
7140 // explicit nested-name-specifier).
7141 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
7142
7143 /// Mark a function referenced, and check whether it is odr-used
7144 /// (C++ [basic.def.odr]p2, C99 6.9p3)
7146 bool MightBeOdrUse = true);
7147
7148 /// Mark a variable referenced, and check whether it is odr-used
7149 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
7150 /// used directly for normal expressions referring to VarDecl.
7152
7153 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
7154 ///
7155 /// Note, this may change the dependence of the DeclRefExpr, and so needs to
7156 /// be handled with care if the DeclRefExpr is not newly-created.
7157 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
7158
7159 /// Perform reference-marking and odr-use handling for a MemberExpr.
7161
7162 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
7165 unsigned CapturingScopeIndex);
7166
7168 void CleanupVarDeclMarking();
7169
7170 /// Try to capture the given variable.
7171 ///
7172 /// \param Var The variable to capture.
7173 ///
7174 /// \param Loc The location at which the capture occurs.
7175 ///
7176 /// \param Kind The kind of capture, which may be implicit (for either a
7177 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
7178 ///
7179 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
7180 /// an explicit lambda capture.
7181 ///
7182 /// \param BuildAndDiagnose Whether we are actually supposed to add the
7183 /// captures or diagnose errors. If false, this routine merely check whether
7184 /// the capture can occur without performing the capture itself or complaining
7185 /// if the variable cannot be captured.
7186 ///
7187 /// \param CaptureType Will be set to the type of the field used to capture
7188 /// this variable in the innermost block or lambda. Only valid when the
7189 /// variable can be captured.
7190 ///
7191 /// \param DeclRefType Will be set to the type of a reference to the capture
7192 /// from within the current scope. Only valid when the variable can be
7193 /// captured.
7194 ///
7195 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
7196 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
7197 /// This is useful when enclosing lambdas must speculatively capture
7198 /// variables that may or may not be used in certain specializations of
7199 /// a nested generic lambda.
7200 ///
7201 /// \returns true if an error occurred (i.e., the variable cannot be
7202 /// captured) and false if the capture succeeded.
7204 TryCaptureKind Kind, SourceLocation EllipsisLoc,
7205 bool BuildAndDiagnose, QualType &CaptureType,
7206 QualType &DeclRefType,
7207 const unsigned *const FunctionScopeIndexToStopAt);
7208
7209 /// Try to capture the given variable.
7212 SourceLocation EllipsisLoc = SourceLocation());
7213
7214 /// Checks if the variable must be captured.
7216
7217 /// Given a variable, determine the type that a reference to that
7218 /// variable will have in the given scope.
7220
7221 /// Mark all of the declarations referenced within a particular AST node as
7222 /// referenced. Used when template instantiation instantiates a non-dependent
7223 /// type -- entities referenced by the type are now referenced.
7225
7226 /// Mark any declarations that appear within this expression or any
7227 /// potentially-evaluated subexpressions as "referenced".
7228 ///
7229 /// \param SkipLocalVariables If true, don't mark local variables as
7230 /// 'referenced'.
7231 /// \param StopAt Subexpressions that we shouldn't recurse into.
7233 bool SkipLocalVariables = false,
7234 ArrayRef<const Expr *> StopAt = {});
7235
7236 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
7237 /// conversion.
7238 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
7239
7240 /// Conditionally issue a diagnostic based on the statements's reachability
7241 /// analysis.
7242 ///
7243 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
7244 /// the function body is parsed, and then do a basic reachability analysis to
7245 /// determine if the statement is reachable. If it is unreachable, the
7246 /// diagnostic will not be emitted.
7247 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7248 const PartialDiagnostic &PD);
7249
7250 /// Conditionally issue a diagnostic based on the current
7251 /// evaluation context.
7252 ///
7253 /// \param Statement If Statement is non-null, delay reporting the
7254 /// diagnostic until the function body is parsed, and then do a basic
7255 /// reachability analysis to determine if the statement is reachable.
7256 /// If it is unreachable, the diagnostic will not be emitted.
7257 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
7258 const PartialDiagnostic &PD);
7259 /// Similar, but diagnostic is only produced if all the specified statements
7260 /// are reachable.
7261 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7262 const PartialDiagnostic &PD);
7263
7264 // Primary Expressions.
7265 SourceRange getExprRange(Expr *E) const;
7266
7267 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
7268 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
7269 bool HasTrailingLParen, bool IsAddressOfOperand,
7270 CorrectionCandidateCallback *CCC = nullptr,
7271 bool IsInlineAsmIdentifier = false);
7272
7273 /// Decomposes the given name into a DeclarationNameInfo, its location, and
7274 /// possibly a list of template arguments.
7275 ///
7276 /// If this produces template arguments, it is permitted to call
7277 /// DecomposeTemplateName.
7278 ///
7279 /// This actually loses a lot of source location information for
7280 /// non-standard name kinds; we should consider preserving that in
7281 /// some way.
7282 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
7283 TemplateArgumentListInfo &Buffer,
7284 DeclarationNameInfo &NameInfo,
7285 const TemplateArgumentListInfo *&TemplateArgs);
7286
7287 /// Diagnose a lookup that found results in an enclosing class during error
7288 /// recovery. This usually indicates that the results were found in a
7289 /// dependent base class that could not be searched as part of a template
7290 /// definition. Always issues a diagnostic (though this may be only a warning
7291 /// in MS compatibility mode).
7292 ///
7293 /// Return \c true if the error is unrecoverable, or \c false if the caller
7294 /// should attempt to recover using these lookup results.
7295 bool DiagnoseDependentMemberLookup(const LookupResult &R);
7296
7297 /// Diagnose an empty lookup.
7298 ///
7299 /// \return false if new lookup candidates were found
7300 bool
7301 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
7302 CorrectionCandidateCallback &CCC,
7303 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
7304 ArrayRef<Expr *> Args = {},
7305 DeclContext *LookupCtx = nullptr);
7306
7307 /// If \p D cannot be odr-used in the current expression evaluation context,
7308 /// return a reason explaining why. Otherwise, return NOUR_None.
7310
7311 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7312 SourceLocation Loc,
7313 const CXXScopeSpec *SS = nullptr);
7314 DeclRefExpr *
7315 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7316 const DeclarationNameInfo &NameInfo,
7317 const CXXScopeSpec *SS = nullptr,
7318 NamedDecl *FoundD = nullptr,
7319 SourceLocation TemplateKWLoc = SourceLocation(),
7320 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7321
7322 /// BuildDeclRefExpr - Build an expression that references a
7323 /// declaration that does not require a closure capture.
7324 DeclRefExpr *
7325 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7326 const DeclarationNameInfo &NameInfo,
7327 NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr,
7328 SourceLocation TemplateKWLoc = SourceLocation(),
7329 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7330
7331 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R,
7332 bool HasTrailingLParen);
7333
7334 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
7335 /// declaration name, generally during template instantiation.
7336 /// There's a large number of things which don't need to be done along
7337 /// this path.
7339 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
7340 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
7341
7342 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R,
7343 bool NeedsADL,
7344 bool AcceptInvalidDecl = false);
7345
7346 /// Complete semantic analysis for a reference to the given declaration.
7348 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
7349 NamedDecl *FoundD = nullptr,
7350 const TemplateArgumentListInfo *TemplateArgs = nullptr,
7351 bool AcceptInvalidDecl = false);
7352
7353 // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens,
7354 // where Tokens representing function local predefined macros (such as
7355 // __FUNCTION__) are replaced (expanded) with string-literal Tokens.
7356 std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks);
7357
7358 ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK);
7359 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
7360 ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val);
7361
7362 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero);
7363
7364 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
7366 Scope *UDLScope = nullptr);
7367 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
7368 ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R,
7369 MultiExprArg Val);
7370 ExprResult ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
7371 unsigned NumUserSpecifiedExprs,
7372 SourceLocation InitLoc,
7373 SourceLocation LParenLoc,
7374 SourceLocation RParenLoc);
7375
7376 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
7377 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle
7378 /// string concatenation ([C99 5.1.1.2, translation phase #6]), so it may come
7379 /// from multiple tokens. However, the common case is that StringToks points
7380 /// to one string.
7381 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
7382 Scope *UDLScope = nullptr);
7383
7384 ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks);
7385
7386 /// ControllingExprOrType is either an opaque pointer coming out of a
7387 /// ParsedType or an Expr *. FIXME: it'd be better to split this interface
7388 /// into two so we don't take a void *, but that's awkward because one of
7389 /// the operands is either a ParsedType or an Expr *, which doesn't lend
7390 /// itself to generic code very well.
7391 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
7392 SourceLocation DefaultLoc,
7393 SourceLocation RParenLoc,
7394 bool PredicateIsExpr,
7395 void *ControllingExprOrType,
7396 ArrayRef<ParsedType> ArgTypes,
7397 ArrayRef<Expr *> ArgExprs);
7398 /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME:
7399 /// it'd be better to split this interface into two so we don't take a
7400 /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that
7401 /// isn't a trivial change.
7402 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
7403 SourceLocation DefaultLoc,
7404 SourceLocation RParenLoc,
7405 bool PredicateIsExpr,
7406 void *ControllingExprOrType,
7407 ArrayRef<TypeSourceInfo *> Types,
7408 ArrayRef<Expr *> Exprs);
7409
7410 // Binary/Unary Operators. 'Tok' is the token for the operator.
7411 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
7412 Expr *InputExpr, bool IsAfterAmp = false);
7413 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
7414 Expr *Input, bool IsAfterAmp = false);
7415
7416 /// Unary Operators. 'Tok' is the token for the operator.
7417 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
7418 Expr *Input, bool IsAfterAmp = false);
7419
7420 /// Determine whether the given expression is a qualified member
7421 /// access expression, of a form that could be turned into a pointer to member
7422 /// with the address-of operator.
7423 bool isQualifiedMemberAccess(Expr *E);
7424 bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
7425 const Expr *Op,
7426 const CXXMethodDecl *MD);
7427
7428 /// CheckAddressOfOperand - The operand of & must be either a function
7429 /// designator or an lvalue designating an object. If it is an lvalue, the
7430 /// object cannot be declared with storage class register or be a bit field.
7431 /// Note: The usual conversions are *not* applied to the operand of the &
7432 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7433 /// In C++, the operand might be an overloaded function name, in which case
7434 /// we allow the '&' but retain the overloaded-function type.
7435 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
7436
7437 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
7438 /// _Alignas(type-name) .
7439 /// [dcl.align] An alignment-specifier of the form
7440 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
7441 ///
7442 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
7443 /// _Alignas(_Alignof(type-name)).
7444 bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
7445 SourceLocation OpLoc, SourceRange R);
7446 bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
7447 SourceLocation OpLoc, SourceRange R);
7448
7449 /// Build a sizeof or alignof expression given a type operand.
7450 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
7451 SourceLocation OpLoc,
7452 UnaryExprOrTypeTrait ExprKind,
7453 SourceRange R);
7454
7455 /// Build a sizeof or alignof expression given an expression
7456 /// operand.
7457 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
7458 UnaryExprOrTypeTrait ExprKind);
7459
7460 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
7461 /// expr and the same for @c alignof and @c __alignof
7462 /// Note that the ArgRange is invalid if isType is false.
7463 ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
7464 UnaryExprOrTypeTrait ExprKind,
7465 bool IsType, void *TyOrEx,
7466 SourceRange ArgRange);
7467
7468 /// Check for operands with placeholder types and complain if found.
7469 /// Returns ExprError() if there was an error and no recovery was possible.
7471 bool CheckVecStepExpr(Expr *E);
7472
7473 /// Check the constraints on expression operands to unary type expression
7474 /// and type traits.
7475 ///
7476 /// Completes any types necessary and validates the constraints on the operand
7477 /// expression. The logic mostly mirrors the type-based overload, but may
7478 /// modify the expression as it completes the type for that expression through
7479 /// template instantiation, etc.
7481
7482 /// Check the constraints on operands to unary expression and type
7483 /// traits.
7484 ///
7485 /// This will complete any types necessary, and validate the various
7486 /// constraints on those operands.
7487 ///
7488 /// The UsualUnaryConversions() function is *not* called by this routine.
7489 /// C99 6.3.2.1p[2-4] all state:
7490 /// Except when it is the operand of the sizeof operator ...
7491 ///
7492 /// C++ [expr.sizeof]p4
7493 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
7494 /// standard conversions are not applied to the operand of sizeof.
7495 ///
7496 /// This policy is followed for all of the unary trait expressions.
7497 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
7498 SourceRange ExprRange,
7499 UnaryExprOrTypeTrait ExprKind,
7500 StringRef KWName);
7501
7502 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
7503 tok::TokenKind Kind, Expr *Input);
7504
7505 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
7506 MultiExprArg ArgExprs,
7507 SourceLocation RLoc);
7508 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
7509 Expr *Idx, SourceLocation RLoc);
7510
7511 ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx,
7512 SourceLocation RBLoc);
7513
7514 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
7515 Expr *ColumnIdx,
7516 SourceLocation RBLoc);
7517
7518 /// ConvertArgumentsForCall - Converts the arguments specified in
7519 /// Args/NumArgs to the parameter types of the function FDecl with
7520 /// function prototype Proto. Call is the call expression itself, and
7521 /// Fn is the function expression. For a C++ member function, this
7522 /// routine does not attempt to convert the object argument. Returns
7523 /// true if the call is ill-formed.
7524 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl,
7525 const FunctionProtoType *Proto,
7526 ArrayRef<Expr *> Args, SourceLocation RParenLoc,
7527 bool ExecConfig = false);
7528
7529 /// CheckStaticArrayArgument - If the given argument corresponds to a static
7530 /// array parameter, check that it is non-null, and that if it is formed by
7531 /// array-to-pointer decay, the underlying array is sufficiently large.
7532 ///
7533 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of
7534 /// the array type derivation, then for each call to the function, the value
7535 /// of the corresponding actual argument shall provide access to the first
7536 /// element of an array with at least as many elements as specified by the
7537 /// size expression.
7538 void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param,
7539 const Expr *ArgExpr);
7540
7541 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
7542 /// This provides the location of the left/right parens and a list of comma
7543 /// locations.
7544 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7545 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7546 Expr *ExecConfig = nullptr);
7547
7548 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7549 /// This provides the location of the left/right parens and a list of comma
7550 /// locations.
7551 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7552 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7553 Expr *ExecConfig = nullptr,
7554 bool IsExecConfig = false,
7555 bool AllowRecovery = false);
7556
7557 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7558 // with the specified CallArgs
7559 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7560 MultiExprArg CallArgs);
7561
7563
7564 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7565 /// i.e. an expression not of \p OverloadTy. The expression should
7566 /// unary-convert to an expression of function-pointer or
7567 /// block-pointer type.
7568 ///
7569 /// \param NDecl the declaration being called, if available
7571 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
7572 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
7573 Expr *Config = nullptr, bool IsExecConfig = false,
7574 ADLCallKind UsesADL = ADLCallKind::NotADL);
7575
7577 ParsedType &Ty, SourceLocation RParenLoc,
7578 Expr *CastExpr);
7579
7580 /// Prepares for a scalar cast, performing all the necessary stages
7581 /// except the final cast and returning the kind required.
7583
7584 /// Build an altivec or OpenCL literal.
7586 SourceLocation RParenLoc, Expr *E,
7587 TypeSourceInfo *TInfo);
7588
7589 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7590 /// the ParenListExpr into a sequence of comma binary operators.
7592
7594 SourceLocation RParenLoc, Expr *InitExpr);
7595
7597 TypeSourceInfo *TInfo,
7598 SourceLocation RParenLoc,
7599 Expr *LiteralExpr);
7600
7601 ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7602 SourceLocation RBraceLoc);
7603
7604 ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7605 SourceLocation RBraceLoc, bool IsExplicit);
7606
7607 /// Binary Operators. 'Tok' is the token for the operator.
7609 Expr *LHSExpr, Expr *RHSExpr);
7611 Expr *LHSExpr, Expr *RHSExpr,
7612 bool ForFoldExpression = false);
7613
7614 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7615 /// operator @p Opc at location @c TokLoc. This routine only supports
7616 /// built-in operations; ActOnBinOp handles overloaded operators.
7618 Expr *LHSExpr, Expr *RHSExpr,
7619 bool ForFoldExpression = false);
7621 UnresolvedSetImpl &Functions);
7622
7623 /// Look for instances where it is likely the comma operator is confused with
7624 /// another operator. There is an explicit list of acceptable expressions for
7625 /// the left hand side of the comma operator, otherwise emit a warning.
7626 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
7627
7628 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7629 /// in the case of a the GNU conditional expr extension.
7631 SourceLocation ColonLoc, Expr *CondExpr,
7632 Expr *LHSExpr, Expr *RHSExpr);
7633
7634 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
7636 LabelDecl *TheDecl);
7637
7638 void ActOnStartStmtExpr();
7639 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
7640 SourceLocation RPLoc);
7642 SourceLocation RPLoc, unsigned TemplateDepth);
7643 // Handle the final expression in a statement expression.
7645 void ActOnStmtExprError();
7646
7647 /// __builtin_offsetof(type, a.b[123][456].c)
7649 TypeSourceInfo *TInfo,
7650 const Designation &Desig,
7651 SourceLocation RParenLoc);
7654 ParsedType ParsedArgTy,
7655 const Designation &Desig,
7656 SourceLocation RParenLoc);
7657
7658 // __builtin_choose_expr(constExpr, expr1, expr2)
7659 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr,
7660 Expr *LHSExpr, Expr *RHSExpr,
7661 SourceLocation RPLoc);
7662
7663 // __builtin_va_arg(expr, type)
7665 SourceLocation RPLoc);
7667 TypeSourceInfo *TInfo, SourceLocation RPLoc);
7668
7669 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(),
7670 // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location()
7672 SourceLocation BuiltinLoc,
7673 SourceLocation RPLoc);
7674
7675 // #embed
7677 StringLiteral *BinaryData, StringRef FileName);
7678
7679 // Build a potentially resolved SourceLocExpr.
7681 SourceLocation BuiltinLoc, SourceLocation RPLoc,
7682 DeclContext *ParentContext);
7683
7684 // __null
7686
7687 bool CheckCaseExpression(Expr *E);
7688
7689 //===------------------------- "Block" Extension ------------------------===//
7690
7691 /// ActOnBlockStart - This callback is invoked when a block literal is
7692 /// started.
7693 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
7694
7695 /// ActOnBlockArguments - This callback allows processing of block arguments.
7696 /// If there are no arguments, this is still invoked.
7697 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
7698 Scope *CurScope);
7699
7700 /// ActOnBlockError - If there is an error parsing a block, this callback
7701 /// is invoked to pop the information about the block from the action impl.
7702 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
7703
7704 /// ActOnBlockStmtExpr - This is called when the body of a block statement
7705 /// literal was successfully completed. ^(int x){...}
7707 Scope *CurScope);
7708
7709 //===---------------------------- Clang Extensions ----------------------===//
7710
7711 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7712 /// provided arguments.
7713 ///
7714 /// __builtin_convertvector( value, dst type )
7715 ///
7717 SourceLocation BuiltinLoc,
7718 SourceLocation RParenLoc);
7719
7720 //===---------------------------- OpenCL Features -----------------------===//
7721
7722 /// Parse a __builtin_astype expression.
7723 ///
7724 /// __builtin_astype( value, dst type )
7725 ///
7726 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7727 SourceLocation BuiltinLoc,
7728 SourceLocation RParenLoc);
7729
7730 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7732 SourceLocation BuiltinLoc,
7733 SourceLocation RParenLoc);
7734
7735 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
7737 ArrayRef<Expr *> SubExprs,
7738 QualType T = QualType());
7739
7740 /// Cast a base object to a member's actual type.
7741 ///
7742 /// There are two relevant checks:
7743 ///
7744 /// C++ [class.access.base]p7:
7745 ///
7746 /// If a class member access operator [...] is used to access a non-static
7747 /// data member or non-static member function, the reference is ill-formed
7748 /// if the left operand [...] cannot be implicitly converted to a pointer to
7749 /// the naming class of the right operand.
7750 ///
7751 /// C++ [expr.ref]p7:
7752 ///
7753 /// If E2 is a non-static data member or a non-static member function, the
7754 /// program is ill-formed if the class of which E2 is directly a member is
7755 /// an ambiguous base (11.8) of the naming class (11.9.3) of E2.
7756 ///
7757 /// Note that the latter check does not consider access; the access of the
7758 /// "real" base class is checked as appropriate when checking the access of
7759 /// the member name.
7761 NestedNameSpecifier Qualifier,
7762 NamedDecl *FoundDecl,
7763 NamedDecl *Member);
7764
7765 /// CheckCallReturnType - Checks that a call expression's return type is
7766 /// complete. Returns true on failure. The location passed in is the location
7767 /// that best represents the call.
7768 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7769 CallExpr *CE, FunctionDecl *FD);
7770
7771 /// Emit a warning for all pending noderef expressions that we recorded.
7773
7775
7776 /// Instantiate or parse a C++ default argument expression as necessary.
7777 /// Return true on error.
7779 ParmVarDecl *Param, Expr *Init = nullptr,
7780 bool SkipImmediateInvocations = true);
7781
7782 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
7783 /// the default expr if needed.
7785 ParmVarDecl *Param, Expr *Init = nullptr);
7786
7787 /// Wrap the expression in a ConstantExpr if it is a potential immediate
7788 /// invocation.
7790
7792
7793 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
7794 bool IsInvalidSMECallConversion(QualType FromType, QualType ToType);
7795
7796 /// Abstract base class used for diagnosing integer constant
7797 /// expression violations.
7799 public:
7801
7803
7804 virtual SemaDiagnosticBuilder
7805 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
7807 SourceLocation Loc) = 0;
7810 };
7811
7812 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7813 /// and reports the appropriate diagnostics. Returns false on success.
7814 /// Can optionally return the value of the expression.
7817 VerifyICEDiagnoser &Diagnoser,
7821 unsigned DiagID,
7824 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr,
7828 AllowFoldKind CanFold = AllowFoldKind::No) {
7829 return VerifyIntegerConstantExpression(E, nullptr, CanFold);
7830 }
7831
7832 /// DiagnoseAssignmentAsCondition - Given that an expression is
7833 /// being used as a boolean condition, warn if it's an assignment.
7835
7836 /// Redundant parentheses over an equality comparison can indicate
7837 /// that the user intended an assignment used as condition.
7839
7841 public:
7843 FullExprArg(Sema &actions) : E(nullptr) {}
7844
7845 ExprResult release() { return E; }
7846
7847 Expr *get() const { return E; }
7848
7849 Expr *operator->() { return E; }
7850
7851 private:
7852 // FIXME: No need to make the entire Sema class a friend when it's just
7853 // Sema::MakeFullExpr that needs access to the constructor below.
7854 friend class Sema;
7855
7856 explicit FullExprArg(Expr *expr) : E(expr) {}
7857
7858 Expr *E;
7859 };
7860
7862 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
7863 }
7865 return FullExprArg(
7866 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
7867 }
7869 ExprResult FE =
7870 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
7871 /*DiscardedValue*/ true);
7872 return FullExprArg(FE.get());
7873 }
7874
7875 class ConditionResult {
7876 Decl *ConditionVar;
7877 ExprResult Condition;
7878 bool Invalid;
7879 std::optional<bool> KnownValue;
7880
7881 friend class Sema;
7882 ConditionResult(Sema &S, Decl *ConditionVar, ExprResult Condition,
7883 bool IsConstexpr)
7884 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
7885 if (IsConstexpr && Condition.get()) {
7886 if (std::optional<llvm::APSInt> Val =
7887 Condition.get()->getIntegerConstantExpr(S.Context)) {
7888 KnownValue = !!(*Val);
7889 }
7890 }
7891 }
7892 explicit ConditionResult(bool Invalid)
7893 : ConditionVar(nullptr), Condition(Invalid), Invalid(Invalid),
7894 KnownValue(std::nullopt) {}
7895
7896 public:
7897 ConditionResult() : ConditionResult(false) {}
7898 bool isInvalid() const { return Invalid; }
7899 std::pair<VarDecl *, Expr *> get() const {
7900 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
7901 Condition.get());
7902 }
7903 std::optional<bool> getKnownValue() const { return KnownValue; }
7904 };
7906
7907 /// CheckBooleanCondition - Diagnose problems involving the use of
7908 /// the given expression as a boolean condition (e.g. in an if
7909 /// statement). Also performs the standard function and array
7910 /// decays, possibly changing the input variable.
7911 ///
7912 /// \param Loc - A location associated with the condition, e.g. the
7913 /// 'if' keyword.
7914 /// \return true iff there were any errors
7916 bool IsConstexpr = false);
7917
7918 enum class ConditionKind {
7919 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
7920 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
7921 Switch ///< An integral condition for a 'switch' statement.
7922 };
7923
7924 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
7925 ConditionKind CK, bool MissingOK = false);
7926
7927 QualType CheckConditionalOperands( // C99 6.5.15
7929 ExprObjectKind &OK, SourceLocation QuestionLoc);
7930
7931 /// Emit a specialized diagnostic when one expression is a null pointer
7932 /// constant and the other is not a pointer. Returns true if a diagnostic is
7933 /// emitted.
7934 bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7935 SourceLocation QuestionLoc);
7936
7937 /// type checking for vector binary operators.
7939 SourceLocation Loc, bool IsCompAssign,
7940 bool AllowBothBool, bool AllowBoolConversion,
7941 bool AllowBoolOperation, bool ReportInvalid);
7942
7943 /// Return a signed ext_vector_type that is of identical size and number of
7944 /// elements. For floating point vectors, return an integer type of identical
7945 /// size and number of elements. In the non ext_vector_type case, search from
7946 /// the largest type to the smallest type to avoid cases where long long ==
7947 /// long, where long gets picked over long long.
7950
7951 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7952 /// operates on extended vector types. Instead of producing an IntTy result,
7953 /// like a scalar comparison, a vector comparison produces a vector of integer
7954 /// types.
7956 SourceLocation Loc,
7957 BinaryOperatorKind Opc);
7959 SourceLocation Loc,
7960 BinaryOperatorKind Opc);
7962 SourceLocation Loc,
7963 BinaryOperatorKind Opc);
7965 SourceLocation Loc,
7966 BinaryOperatorKind Opc);
7967 // type checking for sizeless vector binary operators.
7969 SourceLocation Loc, bool IsCompAssign,
7970 ArithConvKind OperationKind);
7971
7972 /// Type checking for matrix binary operators.
7974 SourceLocation Loc,
7975 bool IsCompAssign);
7977 SourceLocation Loc, bool IsCompAssign);
7978
7979 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from
7980 /// the first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE
7981 /// VLST) allowed?
7982 ///
7983 /// This will also return false if the two given types do not make sense from
7984 /// the perspective of SVE bitcasts.
7985 bool isValidSveBitcast(QualType srcType, QualType destType);
7986
7987 /// Are the two types matrix types and do they have the same dimensions i.e.
7988 /// do they have the same number of rows and the same number of columns?
7990
7991 bool areVectorTypesSameSize(QualType srcType, QualType destType);
7992
7993 /// Are the two types lax-compatible vector types? That is, given
7994 /// that one of them is a vector, do they have equal storage sizes,
7995 /// where the storage size is the number of elements times the element
7996 /// size?
7997 ///
7998 /// This will also return false if either of the types is neither a
7999 /// vector nor a real type.
8000 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
8001
8002 /// Is this a legal conversion between two types, one of which is
8003 /// known to be a vector type?
8004 bool isLaxVectorConversion(QualType srcType, QualType destType);
8005
8006 // This returns true if at least one of the types is an altivec vector.
8007 bool anyAltivecTypes(QualType srcType, QualType destType);
8008
8009 // type checking C++ declaration initializers (C++ [dcl.init]).
8010
8011 /// Check a cast of an unknown-any type. We intentionally only
8012 /// trigger this for C-style casts.
8015 ExprValueKind &VK, CXXCastPath &Path);
8016
8017 /// Force an expression with unknown-type to an expression of the
8018 /// given type.
8020
8021 /// Type-check an expression that's being passed to an
8022 /// __unknown_anytype parameter.
8024 QualType &paramType);
8025
8026 // CheckMatrixCast - Check type constraints for matrix casts.
8027 // We allow casting between matrixes of the same dimensions i.e. when they
8028 // have the same number of rows and column. Returns true if the cast is
8029 // invalid.
8030 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8031 CastKind &Kind);
8032
8033 // CheckVectorCast - check type constraints for vectors.
8034 // Since vectors are an extension, there are no C standard reference for this.
8035 // We allow casting between vectors and integer datatypes of the same size.
8036 // returns true if the cast is invalid
8037 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8038 CastKind &Kind);
8039
8040 /// Prepare `SplattedExpr` for a vector splat operation, adding
8041 /// implicit casts if necessary.
8042 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
8043
8044 /// Prepare `SplattedExpr` for a matrix splat operation, adding
8045 /// implicit casts if necessary.
8046 ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr);
8047
8048 // CheckExtVectorCast - check type constraints for extended vectors.
8049 // Since vectors are an extension, there are no C standard reference for this.
8050 // We allow casting between vectors and integer datatypes of the same size,
8051 // or vectors and the element type of that vector.
8052 // returns the cast expr
8054 CastKind &Kind);
8055
8057 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
8058 }
8059
8060 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2), converts
8061 // functions and arrays to their respective pointers (C99 6.3.2.1), and
8062 // promotes floating-piont types according to the language semantics.
8064
8065 // UsualUnaryFPConversions - promotes floating-point types according to the
8066 // current language semantics.
8068
8069 /// CallExprUnaryConversions - a special case of an unary conversion
8070 /// performed on a function designator of a call expression.
8072
8073 // DefaultFunctionArrayConversion - converts functions and arrays
8074 // to their respective pointers (C99 6.3.2.1).
8076
8077 // DefaultFunctionArrayLvalueConversion - converts functions and
8078 // arrays to their respective pointers and performs the
8079 // lvalue-to-rvalue conversion.
8081 bool Diagnose = true);
8082
8083 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8084 // the operand. This function is a no-op if the operand has a function type
8085 // or an array type.
8087
8088 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8089 // do not have a prototype. Integer promotions are performed on each
8090 // argument, and arguments that have type float are promoted to double.
8092
8094 const FunctionProtoType *Proto,
8095 Expr *Fn);
8096
8097 /// Determine the degree of POD-ness for an expression.
8098 /// Incomplete types are considered POD, since this check can be performed
8099 /// when we're in an unevaluated context.
8101
8102 /// Check to see if the given expression is a valid argument to a variadic
8103 /// function, issuing a diagnostic if not.
8104 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8105
8106 /// GatherArgumentsForCall - Collector argument expressions for various
8107 /// form of call prototypes.
8109 SourceLocation CallLoc, FunctionDecl *FDecl,
8110 const FunctionProtoType *Proto, unsigned FirstParam,
8113 bool AllowExplicit = false, bool IsListInitialization = false);
8114
8115 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8116 // will create a runtime trap if the resulting type is not a POD type.
8118 FunctionDecl *FDecl);
8119
8120 // Check that the usual arithmetic conversions can be performed on this pair
8121 // of expressions that might be of enumeration type.
8123 ArithConvKind ACK);
8124
8125 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8126 // operands and then handles various conversions that are common to binary
8127 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8128 // routine returns the first non-arithmetic type found. The client is
8129 // responsible for emitting appropriate error diagnostics.
8131 SourceLocation Loc, ArithConvKind ACK);
8132
8134 switch (ConvTy) {
8135 default:
8136 return false;
8140 return true;
8141 }
8142 llvm_unreachable("impossible");
8143 }
8144
8145 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8146 /// assignment conversion type specified by ConvTy. This returns true if the
8147 /// conversion was invalid or false if the conversion was accepted.
8149 QualType DstType, QualType SrcType,
8150 Expr *SrcExpr, AssignmentAction Action,
8151 bool *Complained = nullptr);
8152
8153 /// CheckAssignmentConstraints - Perform type checking for assignment,
8154 /// argument passing, variable initialization, and function return values.
8155 /// C99 6.5.16.
8157 QualType LHSType,
8158 QualType RHSType);
8159
8160 /// Check assignment constraints and optionally prepare for a conversion of
8161 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8162 /// is true.
8164 ExprResult &RHS, CastKind &Kind,
8165 bool ConvertRHS = true);
8166
8167 /// Check assignment constraints for an assignment of RHS to LHSType.
8168 ///
8169 /// \param LHSType The destination type for the assignment.
8170 /// \param RHS The source expression for the assignment.
8171 /// \param Diagnose If \c true, diagnostics may be produced when checking
8172 /// for assignability. If a diagnostic is produced, \p RHS will be
8173 /// set to ExprError(). Note that this function may still return
8174 /// without producing a diagnostic, even for an invalid assignment.
8175 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
8176 /// in an audited Core Foundation API and does not need to be checked
8177 /// for ARC retain issues.
8178 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
8179 /// conversions necessary to perform the assignment. If \c false,
8180 /// \p Diagnose must also be \c false.
8182 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
8183 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
8184
8185 // If the lhs type is a transparent union, check whether we
8186 // can initialize the transparent union with the given expression.
8188 ExprResult &RHS);
8189
8190 /// the following "Check" methods will return a valid/converted QualType
8191 /// or a null QualType (indicating an error diagnostic was issued).
8192
8193 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8195 ExprResult &RHS);
8196
8197 /// Diagnose cases where a scalar was implicitly converted to a vector and
8198 /// diagnose the underlying types. Otherwise, diagnose the error
8199 /// as invalid vector logical operands for non-C++ cases.
8201 ExprResult &RHS);
8202
8204 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8205 BinaryOperatorKind Opc);
8206 QualType CheckRemainderOperands( // C99 6.5.5
8207 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8208 bool IsCompAssign = false);
8209 QualType CheckAdditionOperands( // C99 6.5.6
8210 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8211 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8213 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8214 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8215 QualType CheckShiftOperands( // C99 6.5.7
8216 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8217 BinaryOperatorKind Opc, bool IsCompAssign = false);
8219 QualType CheckCompareOperands( // C99 6.5.8/9
8220 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8221 BinaryOperatorKind Opc);
8222 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8223 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8224 BinaryOperatorKind Opc);
8225 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8226 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8227 BinaryOperatorKind Opc);
8228 // CheckAssignmentOperands is used for both simple and compound assignment.
8229 // For simple assignment, pass both expressions and a null converted type.
8230 // For compound assignment, pass both expressions and the converted type.
8231 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8232 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
8233 BinaryOperatorKind Opc);
8234
8235 /// To be used for checking whether the arguments being passed to
8236 /// function exceeds the number of parameters expected for it.
8237 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
8238 bool PartialOverloading = false) {
8239 // We check whether we're just after a comma in code-completion.
8240 if (NumArgs > 0 && PartialOverloading)
8241 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
8242 return NumArgs > NumParams;
8243 }
8244
8245 /// Whether the AST is currently being rebuilt to correct immediate
8246 /// invocations. Immediate invocation candidates and references to consteval
8247 /// functions aren't tracked when this is set.
8249
8255
8256 /// Determines whether we are currently in a context that
8257 /// is not evaluated as per C++ [expr] p5.
8260 }
8261
8265
8269
8273
8280
8281 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8283 assert(!ExprEvalContexts.empty() &&
8284 "Must be in an expression evaluation context");
8285 for (const auto &Ctx : llvm::reverse(ExprEvalContexts)) {
8287 Ctx.DelayedDefaultInitializationContext)
8288 return Ctx.DelayedDefaultInitializationContext;
8289 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8290 Ctx.isUnevaluated())
8291 break;
8292 }
8293 return std::nullopt;
8294 }
8295
8296 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8298 assert(!ExprEvalContexts.empty() &&
8299 "Must be in an expression evaluation context");
8300 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
8301 for (auto &Ctx : llvm::reverse(ExprEvalContexts)) {
8303 !Ctx.DelayedDefaultInitializationContext && Res)
8304 break;
8305 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8306 Ctx.isUnevaluated())
8307 break;
8308 Res = Ctx.DelayedDefaultInitializationContext;
8309 }
8310 return Res;
8311 }
8312
8316
8317 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
8318 /// SelfAssigned when inside a CXXMethodDecl.
8319 const FieldDecl *
8321
8323
8324 template <typename... Ts>
8326 const Ts &...Args) {
8327 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8328 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
8329 }
8330
8331 template <typename... Ts>
8332 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
8333 const Ts &...Args) {
8334 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8336 }
8337
8338 /// Abstract class used to diagnose incomplete types.
8341
8342 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
8343 virtual ~TypeDiagnoser() {}
8344 };
8345
8346 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
8347 protected:
8348 unsigned DiagID;
8349 std::tuple<const Ts &...> Args;
8350
8351 template <std::size_t... Is>
8353 std::index_sequence<Is...>) const {
8354 // Apply all tuple elements to the builder in order.
8355 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
8356 (void)Dummy;
8357 }
8358
8359 public:
8360 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8361 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
8362 assert(DiagID != 0 && "no diagnostic for type diagnoser");
8363 }
8364
8365 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8366 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
8367 emit(DB, std::index_sequence_for<Ts...>());
8368 DB << T;
8369 }
8370 };
8371
8372 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
8373 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
8374 /// For example, a diagnostic with no other parameters would generally have
8375 /// the form "...%select{incomplete|sizeless}0 type %1...".
8376 template <typename... Ts>
8378 public:
8379 SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8380 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
8381
8382 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8383 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
8384 this->emit(DB, std::index_sequence_for<Ts...>());
8385 DB << T->isSizelessType() << T;
8386 }
8387 };
8388
8389 /// Check an argument list for placeholders that we won't try to
8390 /// handle later.
8392
8393 /// The C++ "std::source_location::__impl" struct, defined in
8394 /// <source_location>.
8396
8397 /// A stack of expression evaluation contexts.
8399
8400 // Set of failed immediate invocations to avoid double diagnosing.
8402
8403 /// List of SourceLocations where 'self' is implicitly retained inside a
8404 /// block.
8407
8408 /// Do an explicit extend of the given block pointer if we're in ARC.
8410
8411 std::vector<std::pair<QualType, unsigned>> ExcessPrecisionNotSatisfied;
8414
8415private:
8416 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
8417
8418 /// Methods for marking which expressions involve dereferencing a pointer
8419 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
8420 /// they are parsed, meaning that a noderef pointer may not be accessed. For
8421 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
8422 /// `*p`, but need to check that `address of` is called on it. This requires
8423 /// keeping a container of all pending expressions and checking if the address
8424 /// of them are eventually taken.
8425 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
8426 void CheckAddressOfNoDeref(const Expr *E);
8427
8428 ///@}
8429
8430 //
8431 //
8432 // -------------------------------------------------------------------------
8433 //
8434 //
8435
8436 /// \name C++ Expressions
8437 /// Implementations are in SemaExprCXX.cpp
8438 ///@{
8439
8440public:
8441 /// The C++ "std::bad_alloc" class, which is defined by the C++
8442 /// standard library.
8444
8445 /// The C++ "std::align_val_t" enum class, which is defined by the C++
8446 /// standard library.
8448
8449 /// The C++ "type_info" declaration, which is defined in <typeinfo>.
8451
8452 /// A flag to remember whether the implicit forms of operator new and delete
8453 /// have been declared.
8455
8456 /// Delete-expressions to be analyzed at the end of translation unit
8457 ///
8458 /// This list contains class members, and locations of delete-expressions
8459 /// that could not be proven as to whether they mismatch with new-expression
8460 /// used in initializer of the field.
8461 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
8462
8463 /// Handle the result of the special case name lookup for inheriting
8464 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
8465 /// constructor names in member using declarations, even if 'X' is not the
8466 /// name of the corresponding type.
8468 SourceLocation NameLoc,
8469 const IdentifierInfo &Name);
8470
8472 SourceLocation NameLoc, Scope *S,
8473 CXXScopeSpec &SS, bool EnteringContext);
8475 Scope *S, CXXScopeSpec &SS,
8476 ParsedType ObjectType, bool EnteringContext);
8477
8479 ParsedType ObjectType);
8480
8481 /// Build a C++ typeid expression with a type operand.
8482 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8483 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8484
8485 /// Build a C++ typeid expression with an expression operand.
8486 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8487 Expr *Operand, SourceLocation RParenLoc);
8488
8489 /// ActOnCXXTypeid - Parse typeid( something ).
8491 bool isType, void *TyOrExpr,
8492 SourceLocation RParenLoc);
8493
8494 /// Build a Microsoft __uuidof expression with a type operand.
8495 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8496 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8497
8498 /// Build a Microsoft __uuidof expression with an expression operand.
8499 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8500 Expr *Operand, SourceLocation RParenLoc);
8501
8502 /// ActOnCXXUuidof - Parse __uuidof( something ).
8504 bool isType, void *TyOrExpr,
8505 SourceLocation RParenLoc);
8506
8507 //// ActOnCXXThis - Parse 'this' pointer.
8509
8510 /// Check whether the type of 'this' is valid in the current context.
8512
8513 /// Build a CXXThisExpr and mark it referenced in the current context.
8514 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
8516
8517 /// Try to retrieve the type of the 'this' pointer.
8518 ///
8519 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
8521
8522 /// When non-NULL, the C++ 'this' expression is allowed despite the
8523 /// current context not being a non-static member function. In such cases,
8524 /// this provides the type used for 'this'.
8526
8527 /// RAII object used to temporarily allow the C++ 'this' expression
8528 /// to be used, with the given qualifiers on the current class type.
8530 Sema &S;
8531 QualType OldCXXThisTypeOverride;
8532 bool Enabled;
8533
8534 public:
8535 /// Introduce a new scope where 'this' may be allowed (when enabled),
8536 /// using the given declaration (which is either a class template or a
8537 /// class) along with the given qualifiers.
8538 /// along with the qualifiers placed on '*this'.
8539 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
8540 bool Enabled = true);
8541
8545 };
8546
8547 /// Make sure the value of 'this' is actually available in the current
8548 /// context, if it is a potentially evaluated context.
8549 ///
8550 /// \param Loc The location at which the capture of 'this' occurs.
8551 ///
8552 /// \param Explicit Whether 'this' is explicitly captured in a lambda
8553 /// capture list.
8554 ///
8555 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
8556 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
8557 /// This is useful when enclosing lambdas must speculatively capture
8558 /// 'this' that may or may not be used in certain specializations of
8559 /// a nested generic lambda (depending on whether the name resolves to
8560 /// a non-static member function or a static function).
8561 /// \return returns 'true' if failed, 'false' if success.
8563 SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true,
8564 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
8565 bool ByCopy = false);
8566
8567 /// Determine whether the given type is the type of *this that is used
8568 /// outside of the body of a member function for a type that is currently
8569 /// being defined.
8571
8572 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
8574
8575 /// Build a boolean-typed literal expression.
8577
8578 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
8580
8581 //// ActOnCXXThrow - Parse throw expressions.
8584 bool IsThrownVarInScope);
8585
8586 /// CheckCXXThrowOperand - Validate the operand of a throw.
8587 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
8588
8589 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
8590 /// Can be interpreted either as function-style casting ("int(x)")
8591 /// or class type construction ("ClassType(x,y,z)")
8592 /// or creation of a value-initialized type ("int()").
8594 SourceLocation LParenOrBraceLoc,
8595 MultiExprArg Exprs,
8596 SourceLocation RParenOrBraceLoc,
8597 bool ListInitialization);
8598
8600 SourceLocation LParenLoc,
8601 MultiExprArg Exprs,
8602 SourceLocation RParenLoc,
8603 bool ListInitialization);
8604
8605 /// Parsed a C++ 'new' expression (C++ 5.3.4).
8606 ///
8607 /// E.g.:
8608 /// @code new (memory) int[size][4] @endcode
8609 /// or
8610 /// @code ::new Foo(23, "hello") @endcode
8611 ///
8612 /// \param StartLoc The first location of the expression.
8613 /// \param UseGlobal True if 'new' was prefixed with '::'.
8614 /// \param PlacementLParen Opening paren of the placement arguments.
8615 /// \param PlacementArgs Placement new arguments.
8616 /// \param PlacementRParen Closing paren of the placement arguments.
8617 /// \param TypeIdParens If the type is in parens, the source range.
8618 /// \param D The type to be allocated, as well as array dimensions.
8619 /// \param Initializer The initializing expression or initializer-list, or
8620 /// null if there is none.
8621 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
8622 SourceLocation PlacementLParen,
8623 MultiExprArg PlacementArgs,
8624 SourceLocation PlacementRParen,
8625 SourceRange TypeIdParens, Declarator &D,
8626 Expr *Initializer);
8628 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
8629 MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
8630 SourceRange TypeIdParens, QualType AllocType,
8631 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
8632 SourceRange DirectInitRange, Expr *Initializer);
8633
8634 /// Determine whether \p FD is an aligned allocation or deallocation
8635 /// function that is unavailable.
8637
8638 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
8639 /// function that is unavailable.
8641 SourceLocation Loc);
8642
8643 /// Checks that a type is suitable as the allocated type
8644 /// in a new-expression.
8645 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
8646 SourceRange R);
8647
8648 /// Finds the overloads of operator new and delete that are appropriate
8649 /// for the allocation.
8651 SourceLocation StartLoc, SourceRange Range,
8653 QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP,
8654 MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew,
8655 FunctionDecl *&OperatorDelete, bool Diagnose = true);
8656
8657 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
8658 /// delete. These are:
8659 /// @code
8660 /// // C++03:
8661 /// void* operator new(std::size_t) throw(std::bad_alloc);
8662 /// void* operator new[](std::size_t) throw(std::bad_alloc);
8663 /// void operator delete(void *) throw();
8664 /// void operator delete[](void *) throw();
8665 /// // C++11:
8666 /// void* operator new(std::size_t);
8667 /// void* operator new[](std::size_t);
8668 /// void operator delete(void *) noexcept;
8669 /// void operator delete[](void *) noexcept;
8670 /// // C++1y:
8671 /// void* operator new(std::size_t);
8672 /// void* operator new[](std::size_t);
8673 /// void operator delete(void *) noexcept;
8674 /// void operator delete[](void *) noexcept;
8675 /// void operator delete(void *, std::size_t) noexcept;
8676 /// void operator delete[](void *, std::size_t) noexcept;
8677 /// @endcode
8678 /// Note that the placement and nothrow forms of new are *not* implicitly
8679 /// declared. Their use requires including <new>.
8682 ArrayRef<QualType> Params);
8683
8685 DeclarationName Name, FunctionDecl *&Operator,
8687 bool Diagnose = true);
8690 DeclarationName Name,
8691 bool Diagnose = true);
8693 CXXRecordDecl *RD,
8694 bool Diagnose,
8695 bool LookForGlobal,
8696 DeclarationName Name);
8697
8698 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
8699 /// @code ::delete ptr; @endcode
8700 /// or
8701 /// @code delete [] ptr; @endcode
8702 ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
8703 bool ArrayForm, Expr *Operand);
8705 bool IsDelete, bool CallCanBeVirtual,
8706 bool WarnOnNonAbstractTypes,
8707 SourceLocation DtorLoc);
8708
8710 Expr *Operand, SourceLocation RParen);
8712 SourceLocation RParen);
8713
8715 SourceLocation OpLoc,
8716 tok::TokenKind OpKind,
8717 ParsedType &ObjectType,
8718 bool &MayBePseudoDestructor);
8719
8721 Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8722 const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc,
8723 SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType);
8724
8726 Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8727 CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc,
8728 SourceLocation TildeLoc, UnqualifiedId &SecondTypeName);
8729
8731 SourceLocation OpLoc,
8732 tok::TokenKind OpKind,
8733 SourceLocation TildeLoc,
8734 const DeclSpec &DS);
8735
8736 /// MaybeCreateExprWithCleanups - If the current full-expression
8737 /// requires any cleanups, surround it with a ExprWithCleanups node.
8738 /// Otherwise, just returns the passed-in expression.
8742
8743 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
8744 return ActOnFinishFullExpr(
8745 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
8746 }
8748 bool DiscardedValue, bool IsConstexpr = false,
8749 bool IsTemplateArgument = false);
8751
8752 /// Process the expression contained within a decltype. For such expressions,
8753 /// certain semantic checks on temporaries are delayed until this point, and
8754 /// are omitted for the 'topmost' call in the decltype expression. If the
8755 /// topmost call bound a temporary, strip that temporary off the expression.
8757
8758 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
8759 bool IsUDSuffix);
8760
8762
8763 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
8764 SourceLocation StmtLoc,
8765 ConditionKind CK);
8766
8767 /// Check the use of the given variable as a C++ condition in an if,
8768 /// while, do-while, or switch statement.
8770 SourceLocation StmtLoc, ConditionKind CK);
8771
8772 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8773 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
8774
8775 /// Helper function to determine whether this is the (deprecated) C++
8776 /// conversion from a string literal to a pointer to non-const char or
8777 /// non-const wchar_t (for narrow and wide string literals,
8778 /// respectively).
8780
8781 /// PerformImplicitConversion - Perform an implicit conversion of the
8782 /// expression From to the type ToType using the pre-computed implicit
8783 /// conversion sequence ICS. Returns the converted
8784 /// expression. Action is the kind of conversion we're performing,
8785 /// used in the error message.
8787 Expr *From, QualType ToType, const ImplicitConversionSequence &ICS,
8788 AssignmentAction Action,
8790
8791 /// PerformImplicitConversion - Perform an implicit conversion of the
8792 /// expression From to the type ToType by following the standard
8793 /// conversion sequence SCS. Returns the converted
8794 /// expression. Flavor is the context in which we're performing this
8795 /// conversion, for use in error messages.
8797 const StandardConversionSequence &SCS,
8798 AssignmentAction Action,
8800
8801 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
8802
8803 /// Parsed one of the type trait support pseudo-functions.
8806 SourceLocation RParenLoc);
8809 SourceLocation RParenLoc);
8810
8811 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
8812 /// pseudo-functions.
8814 ParsedType LhsTy, Expr *DimExpr,
8815 SourceLocation RParen);
8816
8818 TypeSourceInfo *TSInfo, Expr *DimExpr,
8819 SourceLocation RParen);
8820
8821 /// ActOnExpressionTrait - Parsed one of the unary type trait support
8822 /// pseudo-functions.
8824 Expr *Queried, SourceLocation RParen);
8825
8827 Expr *Queried, SourceLocation RParen);
8828
8831 bool isIndirect);
8833 ExprResult &RHS,
8834 SourceLocation QuestionLoc);
8835
8836 //// Determines if a type is trivially relocatable
8837 /// according to the C++26 rules.
8838 // FIXME: This is in Sema because it requires
8839 // overload resolution, can we move to ASTContext?
8842
8843 /// Check the operands of ?: under C++ semantics.
8844 ///
8845 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
8846 /// extension. In this case, LHS == Cond. (But they're not aliases.)
8847 ///
8848 /// This function also implements GCC's vector extension and the
8849 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
8850 /// permit the use of a?b:c where the type of a is that of a integer vector
8851 /// with the same number of elements and size as the vectors of b and c. If
8852 /// one of either b or c is a scalar it is implicitly converted to match the
8853 /// type of the vector. Otherwise the expression is ill-formed. If both b and
8854 /// c are scalars, then b and c are checked and converted to the type of a if
8855 /// possible.
8856 ///
8857 /// The expressions are evaluated differently for GCC's and OpenCL's
8858 /// extensions. For the GCC extension, the ?: operator is evaluated as
8859 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
8860 /// For the OpenCL extensions, the ?: operator is evaluated as
8861 /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
8862 /// most-significant-bit-set(a[n]) ? b[n] : c[n]).
8864 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK,
8865 ExprObjectKind &OK, SourceLocation questionLoc);
8866
8867 /// Find a merged pointer type and convert the two expressions to it.
8868 ///
8869 /// This finds the composite pointer type for \p E1 and \p E2 according to
8870 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
8871 /// it. It does not emit diagnostics (FIXME: that's not true if \p
8872 /// ConvertArgs is \c true).
8873 ///
8874 /// \param Loc The location of the operator requiring these two expressions to
8875 /// be converted to the composite pointer type.
8876 ///
8877 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target
8878 /// type.
8880 bool ConvertArgs = true);
8882 ExprResult &E2, bool ConvertArgs = true) {
8883 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8884 QualType Composite =
8885 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
8886 E1 = E1Tmp;
8887 E2 = E2Tmp;
8888 return Composite;
8889 }
8890
8891 /// MaybeBindToTemporary - If the passed in expression has a record type with
8892 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
8893 /// it simply returns the passed in expression.
8895
8896 /// IgnoredValueConversions - Given that an expression's result is
8897 /// syntactically ignored, perform any conversions that are
8898 /// required.
8900
8902
8905 const DeclarationNameInfo &TargetNameInfo);
8906
8908 SourceLocation KeywordLoc,
8909 bool IsIfExists, CXXScopeSpec &SS,
8910 UnqualifiedId &Name);
8911
8914 ArrayRef<ParmVarDecl *> LocalParameters,
8915 Scope *BodyScope);
8919 CXXScopeSpec &SS,
8920 SourceLocation NameLoc,
8921 const IdentifierInfo *TypeName,
8922 TemplateIdAnnotation *TemplateId);
8924 SourceLocation NoexceptLoc);
8926 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8927 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8930 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8934 bool IsSatisfied, SourceLocation NoexceptLoc,
8941 BuildNestedRequirement(StringRef InvalidConstraintEntity,
8942 const ASTConstraintSatisfaction &Satisfaction);
8945 SourceLocation LParenLoc,
8946 ArrayRef<ParmVarDecl *> LocalParameters,
8947 SourceLocation RParenLoc,
8949 SourceLocation ClosingBraceLoc);
8950
8951private:
8952 ExprResult BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
8953 bool IsDelete);
8954
8955 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
8956 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
8957 bool DeleteWasArrayForm);
8958
8959 ///@}
8960
8961 //
8962 //
8963 // -------------------------------------------------------------------------
8964 //
8965 //
8966
8967 /// \name Member Access Expressions
8968 /// Implementations are in SemaExprMember.cpp
8969 ///@{
8970
8971public:
8972 /// Check whether an expression might be an implicit class member access.
8974 bool IsAddressOfOperand);
8975
8976 /// Builds an expression which might be an implicit member expression.
8978 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
8979 const TemplateArgumentListInfo *TemplateArgs, const Scope *S);
8980
8981 /// Builds an implicit member access expression. The current context
8982 /// is known to be an instance method, and the given unqualified lookup
8983 /// set is known to contain only instance members, at least one of which
8984 /// is from an appropriate type.
8986 BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8987 LookupResult &R,
8988 const TemplateArgumentListInfo *TemplateArgs,
8989 bool IsDefiniteInstance, const Scope *S);
8990
8992 Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc,
8993 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8994 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
8995 const TemplateArgumentListInfo *TemplateArgs);
8996
8997 /// The main callback when the parser finds something like
8998 /// expression . [nested-name-specifier] identifier
8999 /// expression -> [nested-name-specifier] identifier
9000 /// where 'identifier' encompasses a fairly broad spectrum of
9001 /// possibilities, including destructor and operator references.
9002 ///
9003 /// \param OpKind either tok::arrow or tok::period
9004 /// \param ObjCImpDecl the current Objective-C \@implementation
9005 /// decl; this is an ugly hack around the fact that Objective-C
9006 /// \@implementations aren't properly put in the context chain
9008 tok::TokenKind OpKind, CXXScopeSpec &SS,
9009 SourceLocation TemplateKWLoc,
9010 UnqualifiedId &Member, Decl *ObjCImpDecl);
9011
9012 MemberExpr *
9013 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
9014 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
9015 ValueDecl *Member, DeclAccessPair FoundDecl,
9016 bool HadMultipleCandidates,
9017 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
9019 const TemplateArgumentListInfo *TemplateArgs = nullptr);
9020
9021 // Check whether the declarations we found through a nested-name
9022 // specifier in a member expression are actually members of the base
9023 // type. The restriction here is:
9024 //
9025 // C++ [expr.ref]p2:
9026 // ... In these cases, the id-expression shall name a
9027 // member of the class or of one of its base classes.
9028 //
9029 // So it's perfectly legitimate for the nested-name specifier to name
9030 // an unrelated class, and for us to find an overload set including
9031 // decls from classes which are not superclasses, as long as the decl
9032 // we actually pick through overload resolution is from a superclass.
9033 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
9034 const CXXScopeSpec &SS,
9035 const LookupResult &R);
9036
9037 // This struct is for use by ActOnMemberAccess to allow
9038 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
9039 // changing the access operator from a '.' to a '->' (to see if that is the
9040 // change needed to fix an error about an unknown member, e.g. when the class
9041 // defines a custom operator->).
9047
9049 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
9050 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9051 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9052 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
9053 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9054
9057 bool IsArrow, const CXXScopeSpec &SS,
9058 SourceLocation TemplateKWLoc,
9059 NamedDecl *FirstQualifierInScope, LookupResult &R,
9060 const TemplateArgumentListInfo *TemplateArgs,
9061 const Scope *S, bool SuppressQualifierCheck = false,
9062 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9063
9064 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
9065 SourceLocation OpLoc,
9066 const CXXScopeSpec &SS, FieldDecl *Field,
9067 DeclAccessPair FoundDecl,
9068 const DeclarationNameInfo &MemberNameInfo);
9069
9070 /// Perform conversions on the LHS of a member access expression.
9072
9074 const CXXScopeSpec &SS, SourceLocation nameLoc,
9075 IndirectFieldDecl *indirectField,
9076 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
9077 Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation());
9078
9079private:
9080 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
9081
9082 ///@}
9083
9084 //
9085 //
9086 // -------------------------------------------------------------------------
9087 //
9088 //
9089
9090 /// \name Initializers
9091 /// Implementations are in SemaInit.cpp
9092 ///@{
9093
9094public:
9095 /// Stack of types that correspond to the parameter entities that are
9096 /// currently being copy-initialized. Can be empty.
9098
9099 llvm::DenseMap<unsigned, CXXDeductionGuideDecl *>
9101
9102 bool IsStringInit(Expr *Init, const ArrayType *AT);
9103
9104 /// Determine whether we can perform aggregate initialization for the purposes
9105 /// of overload resolution.
9107 const InitializedEntity &Entity, InitListExpr *From);
9108
9110 SourceLocation EqualOrColonLoc,
9111 bool GNUSyntax, ExprResult Init);
9112
9113 /// Check that the lifetime of the initializer (and its subobjects) is
9114 /// sufficient for initializing the entity, and perform lifetime extension
9115 /// (when permitted) if not.
9117
9120 bool BoundToLvalueReference);
9121
9122 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9123 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9124 /// we don't have xvalues there.
9126
9130
9134 SourceLocation EqualLoc, ExprResult Init,
9135 bool TopLevelOfInitList = false,
9136 bool AllowExplicit = false);
9137
9139 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
9140 const InitializationKind &Kind, MultiExprArg Init);
9141
9142 ///@}
9143
9144 //
9145 //
9146 // -------------------------------------------------------------------------
9147 //
9148 //
9149
9150 /// \name C++ Lambda Expressions
9151 /// Implementations are in SemaLambda.cpp
9152 ///@{
9153
9154public:
9155 /// Create a new lambda closure type.
9157 TypeSourceInfo *Info,
9158 unsigned LambdaDependencyKind,
9159 LambdaCaptureDefault CaptureDefault);
9160
9161 /// Number lambda for linkage purposes if necessary.
9163 std::optional<CXXRecordDecl::LambdaNumbering>
9164 NumberingOverride = std::nullopt);
9165
9166 /// Endow the lambda scope info with the relevant properties.
9167 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
9168 SourceRange IntroducerRange,
9169 LambdaCaptureDefault CaptureDefault,
9170 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
9171 bool Mutable);
9172
9175
9177 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
9178 TemplateParameterList *TemplateParams);
9179
9180 void
9182 SourceLocation CallOperatorLoc,
9183 const AssociatedConstraint &TrailingRequiresClause,
9184 TypeSourceInfo *MethodTyInfo,
9185 ConstexprSpecKind ConstexprKind, StorageClass SC,
9187 bool HasExplicitResultType);
9188
9189 /// Returns true if the explicit object parameter was invalid.
9191 SourceLocation CallLoc);
9192
9193 /// Perform initialization analysis of the init-capture and perform
9194 /// any implicit conversions such as an lvalue-to-rvalue conversion if
9195 /// not being used to initialize a reference.
9197 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
9198 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
9200 Loc, ByRef, EllipsisLoc, std::nullopt, Id,
9202 }
9204 SourceLocation EllipsisLoc,
9205 UnsignedOrNone NumExpansions,
9206 IdentifierInfo *Id,
9207 bool DirectInit, Expr *&Init);
9208
9209 /// Create a dummy variable within the declcontext of the lambda's
9210 /// call operator, for name lookup purposes for a lambda init capture.
9211 ///
9212 /// CodeGen handles emission of lambda captures, ignoring these dummy
9213 /// variables appropriately.
9215 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
9216 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
9217
9218 /// Add an init-capture to a lambda scope.
9219 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef);
9220
9221 /// Note that we have finished the explicit captures for the
9222 /// given lambda.
9224
9225 /// Deduce a block or lambda's return type based on the return
9226 /// statements present in the body.
9228
9229 /// Once the Lambdas capture are known, we can start to create the closure,
9230 /// call operator method, and keep track of the captures.
9231 /// We do the capture lookup here, but they are not actually captured until
9232 /// after we know what the qualifiers of the call operator are.
9234 Scope *CurContext);
9235
9236 /// This is called after parsing the explicit template parameter list
9237 /// on a lambda (if it exists) in C++2a.
9239 SourceLocation LAngleLoc,
9240 ArrayRef<NamedDecl *> TParams,
9241 SourceLocation RAngleLoc,
9242 ExprResult RequiresClause);
9243
9245 SourceLocation MutableLoc);
9246
9248 Scope *LambdaScope,
9250
9251 /// ActOnStartOfLambdaDefinition - This is called just before we start
9252 /// parsing the body of a lambda; it analyzes the explicit captures and
9253 /// arguments, and sets up various data-structures for the body of the
9254 /// lambda.
9256 Declarator &ParamInfo, const DeclSpec &DS);
9257
9258 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
9259 /// is invoked to pop the information about the lambda.
9260 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
9261 bool IsInstantiation = false);
9262
9263 /// ActOnLambdaExpr - This is called when the body of a lambda expression
9264 /// was successfully completed.
9266
9267 /// Does copying/destroying the captured variable have side effects?
9268 bool CaptureHasSideEffects(const sema::Capture &From);
9269
9270 /// Diagnose if an explicit lambda capture is unused. Returns true if a
9271 /// diagnostic is emitted.
9272 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
9273 SourceRange FixItRange,
9274 const sema::Capture &From);
9275
9276 /// Build a FieldDecl suitable to hold the given capture.
9278
9279 /// Initialize the given capture with a suitable expression.
9281 SourceLocation ImplicitCaptureLoc,
9282 bool IsOpenMPMapping = false);
9283
9284 /// Complete a lambda-expression having processed and attached the
9285 /// lambda body.
9287
9288 /// Get the return type to use for a lambda's conversion function(s) to
9289 /// function pointer type, given the type of the call operator.
9290 QualType
9292 CallingConv CC);
9293
9295 SourceLocation ConvLocation,
9296 CXXConversionDecl *Conv, Expr *Src);
9297
9299 : private FunctionScopeRAII {
9300 public:
9302 Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
9304 bool ShouldAddDeclsFromParentScope = true);
9305 };
9306
9307 /// Compute the mangling number context for a lambda expression or
9308 /// block literal. Also return the extra mangling decl if any.
9309 ///
9310 /// \param DC - The DeclContext containing the lambda expression or
9311 /// block literal.
9312 std::tuple<MangleNumberingContext *, Decl *>
9314
9315 ///@}
9316
9317 //
9318 //
9319 // -------------------------------------------------------------------------
9320 //
9321 //
9322
9323 /// \name Name Lookup
9324 ///
9325 /// These routines provide name lookup that is used during semantic
9326 /// analysis to resolve the various kinds of names (identifiers,
9327 /// overloaded operator names, constructor names, etc.) into zero or
9328 /// more declarations within a particular scope. The major entry
9329 /// points are LookupName, which performs unqualified name lookup,
9330 /// and LookupQualifiedName, which performs qualified name lookup.
9331 ///
9332 /// All name lookup is performed based on some specific criteria,
9333 /// which specify what names will be visible to name lookup and how
9334 /// far name lookup should work. These criteria are important both
9335 /// for capturing language semantics (certain lookups will ignore
9336 /// certain names, for example) and for performance, since name
9337 /// lookup is often a bottleneck in the compilation of C++. Name
9338 /// lookup criteria is specified via the LookupCriteria enumeration.
9339 ///
9340 /// The results of name lookup can vary based on the kind of name
9341 /// lookup performed, the current language, and the translation
9342 /// unit. In C, for example, name lookup will either return nothing
9343 /// (no entity found) or a single declaration. In C++, name lookup
9344 /// can additionally refer to a set of overloaded functions or
9345 /// result in an ambiguity. All of the possible results of name
9346 /// lookup are captured by the LookupResult class, which provides
9347 /// the ability to distinguish among them.
9348 ///
9349 /// Implementations are in SemaLookup.cpp
9350 ///@{
9351
9352public:
9353 /// Tracks whether we are in a context where typo correction is
9354 /// disabled.
9356
9357 /// The number of typos corrected by CorrectTypo.
9359
9360 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9361 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9362
9363 /// A cache containing identifiers for which typo correction failed and
9364 /// their locations, so that repeated attempts to correct an identifier in a
9365 /// given location are ignored if typo correction already failed for it.
9367
9368 /// SpecialMemberOverloadResult - The overloading result for a special member
9369 /// function.
9370 ///
9371 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
9372 /// integer are used to determine whether overload resolution succeeded.
9374 public:
9376
9377 private:
9378 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
9379
9380 public:
9383 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
9384
9385 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
9386 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
9387
9388 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
9389 void setKind(Kind K) { Pair.setInt(K); }
9390 };
9391
9392 class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode,
9394 public:
9395 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
9396 : FastFoldingSetNode(ID) {}
9397 };
9398
9399 /// A cache of special member function overload resolution results
9400 /// for C++ records.
9401 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
9402
9404
9405 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
9406 // TODO: make this is a typesafe union.
9409
9410 /// Describes the kind of name lookup to perform.
9412 /// Ordinary name lookup, which finds ordinary names (functions,
9413 /// variables, typedefs, etc.) in C and most kinds of names
9414 /// (functions, variables, members, types, etc.) in C++.
9416 /// Tag name lookup, which finds the names of enums, classes,
9417 /// structs, and unions.
9419 /// Label name lookup.
9421 /// Member name lookup, which finds the names of
9422 /// class/struct/union members.
9424 /// Look up of an operator name (e.g., operator+) for use with
9425 /// operator overloading. This lookup is similar to ordinary name
9426 /// lookup, but will ignore any declarations that are class members.
9428 /// Look up a name following ~ in a destructor name. This is an ordinary
9429 /// lookup, but prefers tags to typedefs.
9431 /// Look up of a name that precedes the '::' scope resolution
9432 /// operator in C++. This lookup completely ignores operator, object,
9433 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
9435 /// Look up a namespace name within a C++ using directive or
9436 /// namespace alias definition, ignoring non-namespace names (C++
9437 /// [basic.lookup.udir]p1).
9439 /// Look up all declarations in a scope with the given name,
9440 /// including resolved using declarations. This is appropriate
9441 /// for checking redeclarations for a using declaration.
9443 /// Look up an ordinary name that is going to be redeclared as a
9444 /// name with linkage. This lookup ignores any declarations that
9445 /// are outside of the current scope unless they have linkage. See
9446 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
9448 /// Look up a friend of a local class. This lookup does not look
9449 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
9451 /// Look up the name of an Objective-C protocol.
9453 /// Look up implicit 'self' parameter of an objective-c method.
9455 /// Look up the name of an OpenMP user-defined reduction operation.
9457 /// Look up the name of an OpenMP user-defined mapper.
9459 /// Look up any declaration with any name.
9461 };
9462
9463 /// The possible outcomes of name lookup for a literal operator.
9465 /// The lookup resulted in an error.
9467 /// The lookup found no match but no diagnostic was issued.
9469 /// The lookup found a single 'cooked' literal operator, which
9470 /// expects a normal literal to be built and passed to it.
9472 /// The lookup found a single 'raw' literal operator, which expects
9473 /// a string literal containing the spelling of the literal token.
9475 /// The lookup found an overload set of literal operator templates,
9476 /// which expect the characters of the spelling of the literal token to be
9477 /// passed as a non-type template argument pack.
9479 /// The lookup found an overload set of literal operator templates,
9480 /// which expect the character type and characters of the spelling of the
9481 /// string literal token to be passed as template arguments.
9483 };
9484
9485 SpecialMemberOverloadResult
9487 bool VolatileArg, bool RValueThis, bool ConstThis,
9488 bool VolatileThis);
9489
9491
9492 /// Look up a name, looking for a single declaration. Return
9493 /// null if the results were absent, ambiguous, or overloaded.
9494 ///
9495 /// It is preferable to use the elaborated form and explicitly handle
9496 /// ambiguity and overloaded.
9498 Scope *S, DeclarationName Name, SourceLocation Loc,
9499 LookupNameKind NameKind,
9501
9502 /// Lookup a builtin function, when name lookup would otherwise
9503 /// fail.
9504 bool LookupBuiltin(LookupResult &R);
9505 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
9506
9507 /// Perform unqualified name lookup starting from a given
9508 /// scope.
9509 ///
9510 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
9511 /// used to find names within the current scope. For example, 'x' in
9512 /// @code
9513 /// int x;
9514 /// int f() {
9515 /// return x; // unqualified name look finds 'x' in the global scope
9516 /// }
9517 /// @endcode
9518 ///
9519 /// Different lookup criteria can find different names. For example, a
9520 /// particular scope can have both a struct and a function of the same
9521 /// name, and each can be found by certain lookup criteria. For more
9522 /// information about lookup criteria, see the documentation for the
9523 /// class LookupCriteria.
9524 ///
9525 /// @param S The scope from which unqualified name lookup will
9526 /// begin. If the lookup criteria permits, name lookup may also search
9527 /// in the parent scopes.
9528 ///
9529 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
9530 /// look up and the lookup kind), and is updated with the results of lookup
9531 /// including zero or more declarations and possibly additional information
9532 /// used to diagnose ambiguities.
9533 ///
9534 /// @returns \c true if lookup succeeded and false otherwise.
9535 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
9536 bool ForceNoCPlusPlus = false);
9537
9538 /// Perform qualified name lookup into a given context.
9539 ///
9540 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
9541 /// names when the context of those names is explicit specified, e.g.,
9542 /// "std::vector" or "x->member", or as part of unqualified name lookup.
9543 ///
9544 /// Different lookup criteria can find different names. For example, a
9545 /// particular scope can have both a struct and a function of the same
9546 /// name, and each can be found by certain lookup criteria. For more
9547 /// information about lookup criteria, see the documentation for the
9548 /// class LookupCriteria.
9549 ///
9550 /// \param R captures both the lookup criteria and any lookup results found.
9551 ///
9552 /// \param LookupCtx The context in which qualified name lookup will
9553 /// search. If the lookup criteria permits, name lookup may also search
9554 /// in the parent contexts or (for C++ classes) base classes.
9555 ///
9556 /// \param InUnqualifiedLookup true if this is qualified name lookup that
9557 /// occurs as part of unqualified name lookup.
9558 ///
9559 /// \returns true if lookup succeeded, false if it failed.
9560 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9561 bool InUnqualifiedLookup = false);
9562
9563 /// Performs qualified name lookup or special type of lookup for
9564 /// "__super::" scope specifier.
9565 ///
9566 /// This routine is a convenience overload meant to be called from contexts
9567 /// that need to perform a qualified name lookup with an optional C++ scope
9568 /// specifier that might require special kind of lookup.
9569 ///
9570 /// \param R captures both the lookup criteria and any lookup results found.
9571 ///
9572 /// \param LookupCtx The context in which qualified name lookup will
9573 /// search.
9574 ///
9575 /// \param SS An optional C++ scope-specifier.
9576 ///
9577 /// \returns true if lookup succeeded, false if it failed.
9578 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9579 CXXScopeSpec &SS);
9580
9581 /// Performs name lookup for a name that was parsed in the
9582 /// source code, and may contain a C++ scope specifier.
9583 ///
9584 /// This routine is a convenience routine meant to be called from
9585 /// contexts that receive a name and an optional C++ scope specifier
9586 /// (e.g., "N::M::x"). It will then perform either qualified or
9587 /// unqualified name lookup (with LookupQualifiedName or LookupName,
9588 /// respectively) on the given name and return those results. It will
9589 /// perform a special type of lookup for "__super::" scope specifier.
9590 ///
9591 /// @param S The scope from which unqualified name lookup will
9592 /// begin.
9593 ///
9594 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
9595 ///
9596 /// @param EnteringContext Indicates whether we are going to enter the
9597 /// context of the scope-specifier SS (if present).
9598 ///
9599 /// @returns True if any decls were found (but possibly ambiguous)
9601 QualType ObjectType, bool AllowBuiltinCreation = false,
9602 bool EnteringContext = false);
9603
9604 /// Perform qualified name lookup into all base classes of the given
9605 /// class.
9606 ///
9607 /// \param R captures both the lookup criteria and any lookup results found.
9608 ///
9609 /// \param Class The context in which qualified name lookup will
9610 /// search. Name lookup will search in all base classes merging the results.
9611 ///
9612 /// @returns True if any decls were found (but possibly ambiguous)
9614
9616 UnresolvedSetImpl &Functions);
9617
9618 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
9619 /// If GnuLabelLoc is a valid source location, then this is a definition
9620 /// of an __label__ label name, otherwise it is a normal label definition
9621 /// or use.
9623 SourceLocation GnuLabelLoc = SourceLocation());
9624
9625 /// Perform a name lookup for a label with the specified name; this does not
9626 /// create a new label if the lookup fails.
9628
9629 /// Look up the constructors for the given class.
9631
9632 /// Look up the default constructor for the given class.
9634
9635 /// Look up the copying constructor for the given class.
9637 unsigned Quals);
9638
9639 /// Look up the copying assignment operator for the given class.
9641 bool RValueThis, unsigned ThisQuals);
9642
9643 /// Look up the moving constructor for the given class.
9645 unsigned Quals);
9646
9647 /// Look up the moving assignment operator for the given class.
9649 bool RValueThis, unsigned ThisQuals);
9650
9651 /// Look for the destructor of the given class.
9652 ///
9653 /// During semantic analysis, this routine should be used in lieu of
9654 /// CXXRecordDecl::getDestructor().
9655 ///
9656 /// \returns The destructor for this class.
9658
9659 /// Force the declaration of any implicitly-declared members of this
9660 /// class.
9662
9663 /// Make a merged definition of an existing hidden definition \p ND
9664 /// visible at the specified location.
9666
9667 /// Check ODR hashes for C/ObjC when merging types from modules.
9668 /// Differently from C++, actually parse the body and reject in case
9669 /// of a mismatch.
9670 template <typename T,
9671 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
9673 if (Duplicate->getODRHash() != Previous->getODRHash())
9674 return false;
9675
9676 // Make the previous decl visible.
9678 return true;
9679 }
9680
9681 /// Get the set of additional modules that should be checked during
9682 /// name lookup. A module and its imports become visible when instanting a
9683 /// template defined within it.
9684 llvm::DenseSet<Module *> &getLookupModules();
9685
9686 bool hasVisibleMergedDefinition(const NamedDecl *Def);
9688
9689 /// Determine if the template parameter \p D has a visible default argument.
9690 bool
9692 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9693 /// Determine if the template parameter \p D has a reachable default argument.
9695 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9696 /// Determine if the template parameter \p D has a reachable default argument.
9700
9701 /// Determine if there is a visible declaration of \p D that is an explicit
9702 /// specialization declaration for a specialization of a template. (For a
9703 /// member specialization, use hasVisibleMemberSpecialization.)
9705 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9706 /// Determine if there is a reachable declaration of \p D that is an explicit
9707 /// specialization declaration for a specialization of a template. (For a
9708 /// member specialization, use hasReachableMemberSpecialization.)
9710 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9711
9712 /// Determine if there is a visible declaration of \p D that is a member
9713 /// specialization declaration (as opposed to an instantiated declaration).
9715 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9716 /// Determine if there is a reachable declaration of \p D that is a member
9717 /// specialization declaration (as opposed to an instantiated declaration).
9719 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9720
9721 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
9722
9723 /// Determine whether any declaration of an entity is visible.
9724 bool
9726 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9727 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
9728 }
9729
9732 /// Determine whether any declaration of an entity is reachable.
9733 bool
9735 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9736 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
9737 }
9739 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9740
9741 void diagnoseTypo(const TypoCorrection &Correction,
9742 const PartialDiagnostic &TypoDiag,
9743 bool ErrorRecovery = true);
9744
9745 /// Diagnose a successfully-corrected typo. Separated from the correction
9746 /// itself to allow external validation of the result, etc.
9747 ///
9748 /// \param Correction The result of performing typo correction.
9749 /// \param TypoDiag The diagnostic to produce. This will have the corrected
9750 /// string added to it (and usually also a fixit).
9751 /// \param PrevNote A note to use when indicating the location of the entity
9752 /// to which we are correcting. Will have the correction string added
9753 /// to it.
9754 /// \param ErrorRecovery If \c true (the default), the caller is going to
9755 /// recover from the typo as if the corrected string had been typed.
9756 /// In this case, \c PDiag must be an error, and we will attach a fixit
9757 /// to it.
9758 void diagnoseTypo(const TypoCorrection &Correction,
9759 const PartialDiagnostic &TypoDiag,
9760 const PartialDiagnostic &PrevNote,
9761 bool ErrorRecovery = true);
9762
9763 /// Find the associated classes and namespaces for
9764 /// argument-dependent lookup for a call with the given set of
9765 /// arguments.
9766 ///
9767 /// This routine computes the sets of associated classes and associated
9768 /// namespaces searched by argument-dependent lookup
9769 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
9771 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
9772 AssociatedNamespaceSet &AssociatedNamespaces,
9773 AssociatedClassSet &AssociatedClasses);
9774
9775 /// Produce a diagnostic describing the ambiguity that resulted
9776 /// from name lookup.
9777 ///
9778 /// \param Result The result of the ambiguous lookup to be diagnosed.
9780
9781 /// LookupLiteralOperator - Determine which literal operator should be used
9782 /// for a user-defined literal, per C++11 [lex.ext].
9783 ///
9784 /// Normal overload resolution is not used to select which literal operator to
9785 /// call for a user-defined literal. Look up the provided literal operator
9786 /// name, and filter the results to the appropriate set for the given argument
9787 /// types.
9790 bool AllowRaw, bool AllowTemplate,
9791 bool AllowStringTemplate, bool DiagnoseMissing,
9792 StringLiteral *StringLit = nullptr);
9793
9795 ArrayRef<Expr *> Args, ADLResult &Functions);
9796
9797 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
9799 bool IncludeGlobalScope = true,
9800 bool LoadExternal = true);
9801 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
9803 bool IncludeGlobalScope = true,
9804 bool IncludeDependentBases = false,
9805 bool LoadExternal = true);
9806
9807 /// Try to "correct" a typo in the source code by finding
9808 /// visible declarations whose names are similar to the name that was
9809 /// present in the source code.
9810 ///
9811 /// \param TypoName the \c DeclarationNameInfo structure that contains
9812 /// the name that was present in the source code along with its location.
9813 ///
9814 /// \param LookupKind the name-lookup criteria used to search for the name.
9815 ///
9816 /// \param S the scope in which name lookup occurs.
9817 ///
9818 /// \param SS the nested-name-specifier that precedes the name we're
9819 /// looking for, if present.
9820 ///
9821 /// \param CCC A CorrectionCandidateCallback object that provides further
9822 /// validation of typo correction candidates. It also provides flags for
9823 /// determining the set of keywords permitted.
9824 ///
9825 /// \param MemberContext if non-NULL, the context in which to look for
9826 /// a member access expression.
9827 ///
9828 /// \param EnteringContext whether we're entering the context described by
9829 /// the nested-name-specifier SS.
9830 ///
9831 /// \param OPT when non-NULL, the search for visible declarations will
9832 /// also walk the protocols in the qualified interfaces of \p OPT.
9833 ///
9834 /// \returns a \c TypoCorrection containing the corrected name if the typo
9835 /// along with information such as the \c NamedDecl where the corrected name
9836 /// was declared, and any additional \c NestedNameSpecifier needed to access
9837 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
9839 Sema::LookupNameKind LookupKind, Scope *S,
9841 CorrectTypoKind Mode,
9842 DeclContext *MemberContext = nullptr,
9843 bool EnteringContext = false,
9844 const ObjCObjectPointerType *OPT = nullptr,
9845 bool RecordFailure = true);
9846
9847 /// Kinds of missing import. Note, the values of these enumerators correspond
9848 /// to %select values in diagnostics.
9856
9857 /// Diagnose that the specified declaration needs to be visible but
9858 /// isn't, and suggest a module import that would resolve the problem.
9860 MissingImportKind MIK, bool Recover = true);
9862 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
9863 MissingImportKind MIK, bool Recover);
9864
9865 /// Called on #pragma clang __debug dump II
9867
9868 /// Called on #pragma clang __debug dump E
9869 void ActOnPragmaDump(Expr *E);
9870
9871private:
9872 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
9873 //
9874 // The boolean value will be true to indicate that the namespace was loaded
9875 // from an AST/PCH file, or false otherwise.
9876 llvm::MapVector<NamespaceDecl *, bool> KnownNamespaces;
9877
9878 /// Whether we have already loaded known namespaces from an extenal
9879 /// source.
9880 bool LoadedExternalKnownNamespaces;
9881
9882 bool CppLookupName(LookupResult &R, Scope *S);
9883
9884 /// Determine if we could use all the declarations in the module.
9885 bool isUsableModule(const Module *M);
9886
9887 /// Helper for CorrectTypo used to create and populate a new
9888 /// TypoCorrectionConsumer. Returns nullptr if typo correction should be
9889 /// skipped entirely.
9890 std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(
9891 const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind,
9893 DeclContext *MemberContext, bool EnteringContext,
9894 const ObjCObjectPointerType *OPT, bool ErrorRecovery);
9895
9896 /// Cache for module units which is usable for current module.
9897 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
9898
9899 /// Record the typo correction failure and return an empty correction.
9900 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
9901 bool RecordFailure = true) {
9902 if (RecordFailure)
9903 TypoCorrectionFailures[Typo].insert(TypoLoc);
9904 return TypoCorrection();
9905 }
9906
9907 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
9908
9909 /// Determine whether two declarations should be linked together, given that
9910 /// the old declaration might not be visible and the new declaration might
9911 /// not have external linkage.
9912 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
9913 const NamedDecl *New) {
9914 if (isVisible(Old))
9915 return true;
9916 // See comment in below overload for why it's safe to compute the linkage
9917 // of the new declaration here.
9918 if (New->isExternallyDeclarable()) {
9919 assert(Old->isExternallyDeclarable() &&
9920 "should not have found a non-externally-declarable previous decl");
9921 return true;
9922 }
9923 return false;
9924 }
9925 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
9926
9927 ///@}
9928
9929 //
9930 //
9931 // -------------------------------------------------------------------------
9932 //
9933 //
9934
9935 /// \name Modules
9936 /// Implementations are in SemaModule.cpp
9937 ///@{
9938
9939public:
9940 /// Get the module unit whose scope we are currently within.
9942 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
9943 }
9944
9945 /// Is the module scope we are an implementation unit?
9947 if (ModuleScopes.empty())
9948 return false;
9949 const Module *M = ModuleScopes.back().Module;
9951 }
9952
9953 // When loading a non-modular PCH files, this is used to restore module
9954 // visibility.
9956 VisibleModules.setVisible(Mod, ImportLoc);
9957 }
9958
9959 enum class ModuleDeclKind {
9960 Interface, ///< 'export module X;'
9961 Implementation, ///< 'module X;'
9962 PartitionInterface, ///< 'export module X:Y;'
9963 PartitionImplementation, ///< 'module X:Y;'
9964 };
9965
9966 /// An enumeration to represent the transition of states in parsing module
9967 /// fragments and imports. If we are not parsing a C++20 TU, or we find
9968 /// an error in state transition, the state is set to NotACXX20Module.
9970 FirstDecl, ///< Parsing the first decl in a TU.
9971 GlobalFragment, ///< after 'module;' but before 'module X;'
9972 ImportAllowed, ///< after 'module X;' but before any non-import decl.
9973 ImportFinished, ///< after any non-import decl.
9974 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
9975 ///< non-import decl.
9976 PrivateFragmentImportFinished, ///< after 'module :private;' but a
9977 ///< non-import decl has already been seen.
9978 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
9979 };
9980
9981 /// The parser has processed a module-declaration that begins the definition
9982 /// of a module interface or implementation.
9984 SourceLocation ModuleLoc, ModuleDeclKind MDK,
9985 ModuleIdPath Path, ModuleIdPath Partition,
9986 ModuleImportState &ImportState,
9987 bool SeenNoTrivialPPDirective);
9988
9989 /// The parser has processed a global-module-fragment declaration that begins
9990 /// the definition of the global module fragment of the current module unit.
9991 /// \param ModuleLoc The location of the 'module' keyword.
9993
9994 /// The parser has processed a private-module-fragment declaration that begins
9995 /// the definition of the private module fragment of the current module unit.
9996 /// \param ModuleLoc The location of the 'module' keyword.
9997 /// \param PrivateLoc The location of the 'private' keyword.
9999 SourceLocation PrivateLoc);
10000
10001 /// The parser has processed a module import declaration.
10002 ///
10003 /// \param StartLoc The location of the first token in the declaration. This
10004 /// could be the location of an '@', 'export', or 'import'.
10005 /// \param ExportLoc The location of the 'export' keyword, if any.
10006 /// \param ImportLoc The location of the 'import' keyword.
10007 /// \param Path The module toplevel name as an access path.
10008 /// \param IsPartition If the name is for a partition.
10010 SourceLocation ExportLoc,
10011 SourceLocation ImportLoc, ModuleIdPath Path,
10012 bool IsPartition = false);
10014 SourceLocation ExportLoc,
10015 SourceLocation ImportLoc, Module *M,
10016 ModuleIdPath Path = {});
10017
10018 /// The parser has processed a module import translated from a
10019 /// #include or similar preprocessing directive.
10020 void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10021 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10022
10023 /// The parsed has entered a submodule.
10024 void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
10025 /// The parser has left a submodule.
10026 void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
10027
10028 /// Create an implicit import of the given module at the given
10029 /// source location, for error recovery, if possible.
10030 ///
10031 /// This routine is typically used when an entity found by name lookup
10032 /// is actually hidden within a module that we know about but the user
10033 /// has forgotten to import.
10034 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
10035 Module *Mod);
10036
10037 /// We have parsed the start of an export declaration, including the '{'
10038 /// (if present).
10039 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
10040 SourceLocation LBraceLoc);
10041
10042 /// Complete the definition of an export declaration.
10043 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
10044 SourceLocation RBraceLoc);
10045
10046private:
10047 /// The parser has begun a translation unit to be compiled as a C++20
10048 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
10049 void HandleStartOfHeaderUnit();
10050
10051 struct ModuleScope {
10052 SourceLocation BeginLoc;
10053 clang::Module *Module = nullptr;
10054 VisibleModuleSet OuterVisibleModules;
10055 };
10056 /// The modules we're currently parsing.
10057 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
10058
10059 /// For an interface unit, this is the implicitly imported interface unit.
10060 clang::Module *ThePrimaryInterface = nullptr;
10061
10062 /// The explicit global module fragment of the current translation unit.
10063 /// The explicit Global Module Fragment, as specified in C++
10064 /// [module.global.frag].
10065 clang::Module *TheGlobalModuleFragment = nullptr;
10066
10067 /// The implicit global module fragments of the current translation unit.
10068 ///
10069 /// The contents in the implicit global module fragment can't be discarded.
10070 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
10071
10072 /// Namespace definitions that we will export when they finish.
10073 llvm::SmallPtrSet<const NamespaceDecl *, 8> DeferredExportedNamespaces;
10074
10075 /// In a C++ standard module, inline declarations require a definition to be
10076 /// present at the end of a definition domain. This set holds the decls to
10077 /// be checked at the end of the TU.
10078 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
10079
10080 /// Helper function to judge if we are in module purview.
10081 /// Return false if we are not in a module.
10082 bool isCurrentModulePurview() const;
10083
10084 /// Enter the scope of the explicit global module fragment.
10085 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
10086 /// Leave the scope of the explicit global module fragment.
10087 void PopGlobalModuleFragment();
10088
10089 /// Enter the scope of an implicit global module fragment.
10090 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
10091 /// Leave the scope of an implicit global module fragment.
10092 void PopImplicitGlobalModuleFragment();
10093
10094 VisibleModuleSet VisibleModules;
10095
10096 /// Whether we had imported any named modules.
10097 bool HadImportedNamedModules = false;
10098 /// The set of instantiations we need to check if they references TU-local
10099 /// entity from TUs. This only makes sense if we imported any named modules.
10100 llvm::SmallVector<std::pair<FunctionDecl *, SourceLocation>>
10101 PendingCheckReferenceForTULocal;
10102 /// Implement [basic.link]p18, which requires that we can't use TU-local
10103 /// entities from other TUs (ignoring header units).
10104 void checkReferenceToTULocalFromOtherTU(FunctionDecl *FD,
10105 SourceLocation PointOfInstantiation);
10106 /// Implement [basic.link]p17, which diagnose for non TU local exposure in
10107 /// module interface or module partition.
10108 void checkExposure(const TranslationUnitDecl *TU);
10109
10110 ///@}
10111
10112 //
10113 //
10114 // -------------------------------------------------------------------------
10115 //
10116 //
10117
10118 /// \name C++ Overloading
10119 /// Implementations are in SemaOverload.cpp
10120 ///@{
10121
10122public:
10123 /// Whether deferrable diagnostics should be deferred.
10124 bool DeferDiags = false;
10125
10126 /// RAII class to control scope of DeferDiags.
10128 Sema &S;
10129 bool SavedDeferDiags = false;
10130
10131 public:
10133 : S(S), SavedDeferDiags(S.DeferDiags) {
10134 S.DeferDiags = SavedDeferDiags || DeferDiags;
10135 }
10136 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
10139 };
10140
10141 /// Flag indicating if Sema is building a recovery call expression.
10142 ///
10143 /// This flag is used to avoid building recovery call expressions
10144 /// if Sema is already doing so, which would cause infinite recursions.
10146
10147 /// Determine whether the given New declaration is an overload of the
10148 /// declarations in Old. This routine returns OverloadKind::Match or
10149 /// OverloadKind::NonFunction if New and Old cannot be overloaded, e.g., if
10150 /// New has the same signature as some function in Old (C++ 1.3.10) or if the
10151 /// Old declarations aren't functions (or function templates) at all. When it
10152 /// does return OverloadKind::Match or OverloadKind::NonFunction, MatchedDecl
10153 /// will point to the decl that New cannot be overloaded with. This decl may
10154 /// be a UsingShadowDecl on top of the underlying declaration.
10155 ///
10156 /// Example: Given the following input:
10157 ///
10158 /// void f(int, float); // #1
10159 /// void f(int, int); // #2
10160 /// int f(int, int); // #3
10161 ///
10162 /// When we process #1, there is no previous declaration of "f", so IsOverload
10163 /// will not be used.
10164 ///
10165 /// When we process #2, Old contains only the FunctionDecl for #1. By
10166 /// comparing the parameter types, we see that #1 and #2 are overloaded (since
10167 /// they have different signatures), so this routine returns
10168 /// OverloadKind::Overload; MatchedDecl is unchanged.
10169 ///
10170 /// When we process #3, Old is an overload set containing #1 and #2. We
10171 /// compare the signatures of #3 to #1 (they're overloaded, so we do nothing)
10172 /// and then #3 to #2. Since the signatures of #3 and #2 are identical (return
10173 /// types of functions are not part of the signature), IsOverload returns
10174 /// OverloadKind::Match and MatchedDecl will be set to point to the
10175 /// FunctionDecl for #2.
10176 ///
10177 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a
10178 /// class by a using declaration. The rules for whether to hide shadow
10179 /// declarations ignore some properties which otherwise figure into a function
10180 /// template's signature.
10182 const LookupResult &OldDecls, NamedDecl *&OldDecl,
10183 bool UseMemberUsingDeclRules);
10185 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10186
10187 // Checks whether MD constitutes an override the base class method BaseMD.
10188 // When checking for overrides, the object object members are ignored.
10189 bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
10190 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10191
10192 enum class AllowedExplicit {
10193 /// Allow no explicit functions to be used.
10195 /// Allow explicit conversion functions but not explicit constructors.
10197 /// Allow both explicit conversion functions and explicit constructors.
10199 };
10200
10202 Expr *From, QualType ToType, bool SuppressUserConversions,
10203 AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle,
10204 bool AllowObjCWritebackConversion);
10205
10206 /// PerformImplicitConversion - Perform an implicit conversion of the
10207 /// expression From to the type ToType. Returns the
10208 /// converted expression. Flavor is the kind of conversion we're
10209 /// performing, used in the error message. If @p AllowExplicit,
10210 /// explicit user-defined conversions are permitted.
10212 AssignmentAction Action,
10213 bool AllowExplicit = false);
10214
10215 /// IsIntegralPromotion - Determines whether the conversion from the
10216 /// expression From (whose potentially-adjusted type is FromType) to
10217 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
10218 /// sets PromotedType to the promoted type.
10219 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
10220
10221 /// IsFloatingPointPromotion - Determines whether the conversion from
10222 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
10223 /// returns true and sets PromotedType to the promoted type.
10224 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
10225
10226 /// Determine if a conversion is a complex promotion.
10227 ///
10228 /// A complex promotion is defined as a complex -> complex conversion
10229 /// where the conversion between the underlying real types is a
10230 /// floating-point or integral promotion.
10231 bool IsComplexPromotion(QualType FromType, QualType ToType);
10232
10233 /// IsOverflowBehaviorTypePromotion - Determines whether the conversion from
10234 /// FromType to ToType involves an OverflowBehaviorType FromType being
10235 /// promoted to an OverflowBehaviorType ToType which has a larger bitwidth.
10236 /// If so, returns true and sets FromType to ToType.
10237 bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType);
10238
10239 /// IsOverflowBehaviorTypeConversion - Determines whether the conversion from
10240 /// FromType to ToType necessarily involves both an OverflowBehaviorType and
10241 /// a non-OverflowBehaviorType. If so, returns true and sets FromType to
10242 /// ToType.
10243 bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType);
10244
10245 /// IsPointerConversion - Determines whether the conversion of the
10246 /// expression From, which has the (possibly adjusted) type FromType,
10247 /// can be converted to the type ToType via a pointer conversion (C++
10248 /// 4.10). If so, returns true and places the converted type (that
10249 /// might differ from ToType in its cv-qualifiers at some level) into
10250 /// ConvertedType.
10251 ///
10252 /// This routine also supports conversions to and from block pointers
10253 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
10254 /// pointers to interfaces. FIXME: Once we've determined the
10255 /// appropriate overloading rules for Objective-C, we may want to
10256 /// split the Objective-C checks into a different routine; however,
10257 /// GCC seems to consider all of these conversions to be pointer
10258 /// conversions, so for now they live here. IncompatibleObjC will be
10259 /// set if the conversion is an allowed Objective-C conversion that
10260 /// should result in a warning.
10261 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
10262 bool InOverloadResolution, QualType &ConvertedType,
10263 bool &IncompatibleObjC);
10264
10265 /// isObjCPointerConversion - Determines whether this is an
10266 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
10267 /// with the same arguments and return values.
10268 bool isObjCPointerConversion(QualType FromType, QualType ToType,
10269 QualType &ConvertedType, bool &IncompatibleObjC);
10270 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
10271 QualType &ConvertedType);
10272
10273 /// FunctionParamTypesAreEqual - This routine checks two function proto types
10274 /// for equality of their parameter types. Caller has already checked that
10275 /// they have same number of parameters. If the parameters are different,
10276 /// ArgPos will have the parameter index of the first different parameter.
10277 /// If `Reversed` is true, the parameters of `NewType` will be compared in
10278 /// reverse order. That's useful if one of the functions is being used as a
10279 /// C++20 synthesized operator overload with a reversed parameter order.
10282 unsigned *ArgPos = nullptr,
10283 bool Reversed = false);
10284
10286 const FunctionProtoType *NewType,
10287 unsigned *ArgPos = nullptr,
10288 bool Reversed = false);
10289
10290 bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
10291 const FunctionDecl *NewFunction,
10292 unsigned *ArgPos = nullptr,
10293 bool Reversed = false);
10294
10295 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
10296 /// function types. Catches different number of parameter, mismatch in
10297 /// parameter types, and different return types.
10299 QualType ToType);
10300
10301 /// CheckPointerConversion - Check the pointer conversion from the
10302 /// expression From to the type ToType. This routine checks for
10303 /// ambiguous or inaccessible derived-to-base pointer
10304 /// conversions for which IsPointerConversion has already returned
10305 /// true. It returns true and produces a diagnostic if there was an
10306 /// error, or returns false otherwise.
10307 bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind,
10308 CXXCastPath &BasePath, bool IgnoreBaseAccess,
10309 bool Diagnose = true);
10310
10311 /// IsMemberPointerConversion - Determines whether the conversion of the
10312 /// expression From, which has the (possibly adjusted) type FromType, can be
10313 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
10314 /// If so, returns true and places the converted type (that might differ from
10315 /// ToType in its cv-qualifiers at some level) into ConvertedType.
10316 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
10317 bool InOverloadResolution,
10318 QualType &ConvertedType);
10319
10329 /// CheckMemberPointerConversion - Check the member pointer conversion from
10330 /// the expression From to the type ToType. This routine checks for ambiguous
10331 /// or virtual or inaccessible base-to-derived member pointer conversions for
10332 /// which IsMemberPointerConversion has already returned true. It produces a
10333 // diagnostic if there was an error.
10335 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
10336 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
10337 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction);
10338
10339 /// IsQualificationConversion - Determines whether the conversion from
10340 /// an rvalue of type FromType to ToType is a qualification conversion
10341 /// (C++ 4.4).
10342 ///
10343 /// \param ObjCLifetimeConversion Output parameter that will be set to
10344 /// indicate when the qualification conversion involves a change in the
10345 /// Objective-C object lifetime.
10346 bool IsQualificationConversion(QualType FromType, QualType ToType,
10347 bool CStyle, bool &ObjCLifetimeConversion);
10348
10349 /// Determine whether the conversion from FromType to ToType is a valid
10350 /// conversion of ExtInfo/ExtProtoInfo on the nested function type.
10351 /// More precisely, this method checks whether FromType can be transformed
10352 /// into an exact match for ToType, by transforming its extended function
10353 /// type information in legal manner (e.g. by strictly stripping "noreturn"
10354 /// or "noexcept", or by stripping "noescape" for arguments).
10355 bool IsFunctionConversion(QualType FromType, QualType ToType) const;
10356
10357 /// Same as `IsFunctionConversion`, but if this would return true, it sets
10358 /// `ResultTy` to `ToType`.
10359 bool TryFunctionConversion(QualType FromType, QualType ToType,
10360 QualType &ResultTy) const;
10361
10364 DeclarationName Name,
10365 OverloadCandidateSet &CandidateSet,
10366 FunctionDecl *Fn, MultiExprArg Args,
10367 bool IsMember = false);
10368
10370 FunctionDecl *Fun);
10372 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
10374
10375 /// PerformContextuallyConvertToBool - Perform a contextual conversion
10376 /// of the expression From to bool (C++0x [conv]p3).
10378
10379 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
10380 /// conversion of the expression From to an Objective-C pointer type.
10381 /// Returns a valid but null ExprResult if no conversion sequence exists.
10383
10385 CCEKind CCE,
10386 NamedDecl *Dest = nullptr);
10387
10389 llvm::APSInt &Value, CCEKind CCE);
10391 APValue &Value, CCEKind CCE,
10392 NamedDecl *Dest = nullptr);
10393
10394 /// EvaluateConvertedConstantExpression - Evaluate an Expression
10395 /// That is a converted constant expression
10396 /// (which was built with BuildConvertedConstantExpression)
10399 CCEKind CCE, bool RequireInt,
10400 const APValue &PreNarrowingValue);
10401
10402 /// Abstract base class used to perform a contextual implicit
10403 /// conversion from an expression to any type passing a filter.
10405 public:
10408
10412
10413 /// Determine whether the specified type is a valid destination type
10414 /// for this conversion.
10415 virtual bool match(QualType T) = 0;
10416
10417 /// Emits a diagnostic complaining that the expression does not have
10418 /// integral or enumeration type.
10420 QualType T) = 0;
10421
10422 /// Emits a diagnostic when the expression has incomplete class type.
10423 virtual SemaDiagnosticBuilder
10425
10426 /// Emits a diagnostic when the only matching conversion function
10427 /// is explicit.
10429 SourceLocation Loc,
10430 QualType T,
10431 QualType ConvTy) = 0;
10432
10433 /// Emits a note for the explicit conversion function.
10434 virtual SemaDiagnosticBuilder
10436
10437 /// Emits a diagnostic when there are multiple possible conversion
10438 /// functions.
10440 QualType T) = 0;
10441
10442 /// Emits a note for one of the candidate conversions.
10443 virtual SemaDiagnosticBuilder
10445
10446 /// Emits a diagnostic when we picked a conversion function
10447 /// (for cases when we are not allowed to pick a conversion function).
10449 SourceLocation Loc,
10450 QualType T,
10451 QualType ConvTy) = 0;
10452
10454 };
10455
10457 bool AllowScopedEnumerations;
10458
10459 public:
10460 ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress,
10461 bool SuppressConversion)
10463 AllowScopedEnumerations(AllowScopedEnumerations) {}
10464
10465 /// Match an integral or (possibly scoped) enumeration type.
10466 bool match(QualType T) override;
10467
10469 QualType T) override {
10470 return diagnoseNotInt(S, Loc, T);
10471 }
10472
10473 /// Emits a diagnostic complaining that the expression does not have
10474 /// integral or enumeration type.
10476 QualType T) = 0;
10477 };
10478
10479 /// Perform a contextual implicit conversion.
10482 ContextualImplicitConverter &Converter);
10483
10484 /// ReferenceCompareResult - Expresses the result of comparing two
10485 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10486 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10488 /// Ref_Incompatible - The two types are incompatible, so direct
10489 /// reference binding is not possible.
10491 /// Ref_Related - The two types are reference-related, which means
10492 /// that their unqualified forms (T1 and T2) are either the same
10493 /// or T1 is a base class of T2.
10495 /// Ref_Compatible - The two types are reference-compatible.
10497 };
10498
10499 // Fake up a scoped enumeration that still contextually converts to bool.
10501 /// The conversions that would be performed on an lvalue of type T2 when
10502 /// binding a reference of type T1 to it, as determined when evaluating
10503 /// whether T1 is reference-compatible with T2.
10514 };
10516
10517 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
10518 /// determine whether they are reference-compatible,
10519 /// reference-related, or incompatible, for use in C++ initialization by
10520 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
10521 /// type, and the first type (T1) is the pointee type of the reference
10522 /// type being initialized.
10525 ReferenceConversions *Conv = nullptr);
10526
10527 /// AddOverloadCandidate - Adds the given function to the set of
10528 /// candidate functions, using the given function call arguments. If
10529 /// @p SuppressUserConversions, then don't allow user-defined
10530 /// conversions via constructors or conversion operators.
10531 ///
10532 /// \param PartialOverloading true if we are performing "partial" overloading
10533 /// based on an incomplete set of function arguments. This feature is used by
10534 /// code completion.
10537 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10538 bool PartialOverloading = false, bool AllowExplicit = true,
10539 bool AllowExplicitConversion = false,
10540 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10541 ConversionSequenceList EarlyConversions = {},
10543 bool AggregateCandidateDeduction = false, bool StrictPackMatch = false);
10544
10545 /// Add all of the function declarations in the given function set to
10546 /// the overload candidate set.
10548 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10549 OverloadCandidateSet &CandidateSet,
10550 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
10551 bool SuppressUserConversions = false, bool PartialOverloading = false,
10552 bool FirstArgumentIsBase = false);
10553
10554 /// AddMethodCandidate - Adds a named decl (which is some kind of
10555 /// method) as a method candidate to the given overload set.
10556 void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
10557 Expr::Classification ObjectClassification,
10558 ArrayRef<Expr *> Args,
10559 OverloadCandidateSet &CandidateSet,
10560 bool SuppressUserConversion = false,
10561 OverloadCandidateParamOrder PO = {});
10562
10563 /// AddMethodCandidate - Adds the given C++ member function to the set
10564 /// of candidate functions, using the given function call arguments
10565 /// and the object argument (@c Object). For example, in a call
10566 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
10567 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
10568 /// allow user-defined conversions via constructors or conversion
10569 /// operators.
10570 void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
10571 CXXRecordDecl *ActingContext, QualType ObjectType,
10572 Expr::Classification ObjectClassification,
10573 ArrayRef<Expr *> Args,
10574 OverloadCandidateSet &CandidateSet,
10575 bool SuppressUserConversions = false,
10576 bool PartialOverloading = false,
10577 ConversionSequenceList EarlyConversions = {},
10579 bool StrictPackMatch = false);
10580
10581 /// Add a C++ member function template as a candidate to the candidate
10582 /// set, using template argument deduction to produce an appropriate member
10583 /// function template specialization.
10585 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
10586 CXXRecordDecl *ActingContext,
10587 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
10588 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
10589 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10590 bool PartialOverloading = false, OverloadCandidateParamOrder PO = {});
10591
10592 /// Add a C++ function template specialization as a candidate
10593 /// in the candidate set, using template argument deduction to produce
10594 /// an appropriate function template specialization.
10596 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10597 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
10598 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10599 bool PartialOverloading = false, bool AllowExplicit = true,
10600 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10602 bool AggregateCandidateDeduction = false);
10603
10605 /// Do not consider any user-defined conversions when constructing the
10606 /// initializing sequence.
10608
10609 /// Before constructing the initializing sequence, we check whether the
10610 /// parameter type and argument type contain any user defined conversions.
10611 /// If so, do not initialize them. This effectively bypasses some undesired
10612 /// instantiation before checking constaints, which might otherwise result
10613 /// in non-SFINAE errors e.g. recursive constraints.
10615
10622 };
10623
10624 /// Check that implicit conversion sequences can be formed for each argument
10625 /// whose corresponding parameter has a non-dependent type, per DR1391's
10626 /// [temp.deduct.call]p10.
10629 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
10631 CheckNonDependentConversionsFlag UserConversionFlag,
10632 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
10633 Expr::Classification ObjectClassification = {},
10634 OverloadCandidateParamOrder PO = {});
10635
10636 /// AddConversionCandidate - Add a C++ conversion function as a
10637 /// candidate in the candidate set (C++ [over.match.conv],
10638 /// C++ [over.match.copy]). From is the expression we're converting from,
10639 /// and ToType is the type that we're eventually trying to convert to
10640 /// (which may or may not be the same type as the type that the
10641 /// conversion function produces).
10643 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
10644 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10645 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10646 bool AllowExplicit, bool AllowResultConversion = true,
10647 bool StrictPackMatch = false);
10648
10649 /// Adds a conversion function template specialization
10650 /// candidate to the overload set, using template argument deduction
10651 /// to deduce the template arguments of the conversion function
10652 /// template from the type that we are converting to (C++
10653 /// [temp.deduct.conv]).
10655 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10656 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10657 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10658 bool AllowExplicit, bool AllowResultConversion = true);
10659
10660 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
10661 /// converts the given @c Object to a function pointer via the
10662 /// conversion function @c Conversion, and then attempts to call it
10663 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
10664 /// the type of function that we'll eventually be calling.
10665 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
10666 DeclAccessPair FoundDecl,
10667 CXXRecordDecl *ActingContext,
10668 const FunctionProtoType *Proto, Expr *Object,
10669 ArrayRef<Expr *> Args,
10670 OverloadCandidateSet &CandidateSet);
10671
10672 /// Add all of the non-member operator function declarations in the given
10673 /// function set to the overload candidate set.
10675 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10676 OverloadCandidateSet &CandidateSet,
10677 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10678
10679 /// Add overload candidates for overloaded operators that are
10680 /// member functions.
10681 ///
10682 /// Add the overloaded operator candidates that are member functions
10683 /// for the operator Op that was used in an operator expression such
10684 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
10685 /// CandidateSet will store the added overload candidates. (C++
10686 /// [over.match.oper]).
10688 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10689 OverloadCandidateSet &CandidateSet,
10691
10692 /// AddBuiltinCandidate - Add a candidate for a built-in
10693 /// operator. ResultTy and ParamTys are the result and parameter types
10694 /// of the built-in candidate, respectively. Args and NumArgs are the
10695 /// arguments being passed to the candidate. IsAssignmentOperator
10696 /// should be true when this built-in candidate is an assignment
10697 /// operator. NumContextualBoolArguments is the number of arguments
10698 /// (at the beginning of the argument list) that will be contextually
10699 /// converted to bool.
10700 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
10701 OverloadCandidateSet &CandidateSet,
10702 bool IsAssignmentOperator = false,
10703 unsigned NumContextualBoolArguments = 0);
10704
10705 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
10706 /// operator overloads to the candidate set (C++ [over.built]), based
10707 /// on the operator @p Op and the arguments given. For example, if the
10708 /// operator is a binary '+', this routine might add "int
10709 /// operator+(int, int)" to cover integer addition.
10711 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10712 OverloadCandidateSet &CandidateSet);
10713
10714 /// Add function candidates found via argument-dependent lookup
10715 /// to the set of overloading candidates.
10716 ///
10717 /// This routine performs argument-dependent name lookup based on the
10718 /// given function name (which may also be an operator name) and adds
10719 /// all of the overload candidates found by ADL to the overload
10720 /// candidate set (C++ [basic.lookup.argdep]).
10722 DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args,
10723 TemplateArgumentListInfo *ExplicitTemplateArgs,
10724 OverloadCandidateSet &CandidateSet, bool PartialOverloading = false);
10725
10726 /// Check the enable_if expressions on the given function. Returns the first
10727 /// failing attribute, or NULL if they were all successful.
10728 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
10729 ArrayRef<Expr *> Args,
10730 bool MissingImplicitThis = false);
10731
10732 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10733 /// non-ArgDependent DiagnoseIfAttrs.
10734 ///
10735 /// Argument-dependent diagnose_if attributes should be checked each time a
10736 /// function is used as a direct callee of a function call.
10737 ///
10738 /// Returns true if any errors were emitted.
10739 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
10740 const Expr *ThisArg,
10741 ArrayRef<const Expr *> Args,
10742 SourceLocation Loc);
10743
10744 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10745 /// ArgDependent DiagnoseIfAttrs.
10746 ///
10747 /// Argument-independent diagnose_if attributes should be checked on every use
10748 /// of a function.
10749 ///
10750 /// Returns true if any errors were emitted.
10751 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
10752 SourceLocation Loc);
10753
10754 /// Determine if \p A and \p B are equivalent internal linkage declarations
10755 /// from different modules, and thus an ambiguity error can be downgraded to
10756 /// an extension warning.
10757 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10758 const NamedDecl *B);
10760 SourceLocation Loc, const NamedDecl *D,
10761 ArrayRef<const NamedDecl *> Equiv);
10762
10763 // Emit as a 'note' the specific overload candidate
10765 const NamedDecl *Found, const FunctionDecl *Fn,
10767 QualType DestType = QualType(), bool TakingAddress = false);
10768
10769 // Emit as a series of 'note's all template and non-templates identified by
10770 // the expression Expr
10771 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
10772 bool TakingAddress = false);
10773
10774 /// Returns whether the given function's address can be taken or not,
10775 /// optionally emitting a diagnostic if the address can't be taken.
10776 ///
10777 /// Returns false if taking the address of the function is illegal.
10778 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10779 bool Complain = false,
10780 SourceLocation Loc = SourceLocation());
10781
10782 // [PossiblyAFunctionType] --> [Return]
10783 // NonFunctionType --> NonFunctionType
10784 // R (A) --> R(A)
10785 // R (*)(A) --> R (A)
10786 // R (&)(A) --> R (A)
10787 // R (S::*)(A) --> R (A)
10788 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
10789
10790 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10791 /// an overloaded function (C++ [over.over]), where @p From is an
10792 /// expression with overloaded function type and @p ToType is the type
10793 /// we're trying to resolve to. For example:
10794 ///
10795 /// @code
10796 /// int f(double);
10797 /// int f(int);
10798 ///
10799 /// int (*pfd)(double) = f; // selects f(double)
10800 /// @endcode
10801 ///
10802 /// This routine returns the resulting FunctionDecl if it could be
10803 /// resolved, and NULL otherwise. When @p Complain is true, this
10804 /// routine will emit diagnostics if there is an error.
10805 FunctionDecl *
10806 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
10807 bool Complain, DeclAccessPair &Found,
10808 bool *pHadMultipleCandidates = nullptr);
10809
10810 /// Given an expression that refers to an overloaded function, try to
10811 /// resolve that function to a single function that can have its address
10812 /// taken. This will modify `Pair` iff it returns non-null.
10813 ///
10814 /// This routine can only succeed if from all of the candidates in the
10815 /// overload set for SrcExpr that can have their addresses taken, there is one
10816 /// candidate that is more constrained than the rest.
10817 FunctionDecl *
10818 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
10819
10820 /// Given an overloaded function, tries to turn it into a non-overloaded
10821 /// function reference using resolveAddressOfSingleOverloadCandidate. This
10822 /// will perform access checks, diagnose the use of the resultant decl, and,
10823 /// if requested, potentially perform a function-to-pointer decay.
10824 ///
10825 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
10826 /// Otherwise, returns true. This may emit diagnostics and return true.
10828 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
10829
10830 /// Given an expression that refers to an overloaded function, try to
10831 /// resolve that overloaded function expression down to a single function.
10832 ///
10833 /// This routine can only resolve template-ids that refer to a single function
10834 /// template, where that template-id refers to a single template whose
10835 /// template arguments are either provided by the template-id or have
10836 /// defaults, as described in C++0x [temp.arg.explicit]p3.
10837 ///
10838 /// If no template-ids are found, no diagnostics are emitted and NULL is
10839 /// returned.
10841 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
10842 TemplateSpecCandidateSet *FailedTSC = nullptr,
10843 bool ForTypeDeduction = false);
10844
10845 // Resolve and fix an overloaded expression that can be resolved
10846 // because it identifies a single function template specialization.
10847 //
10848 // Last three arguments should only be supplied if Complain = true
10849 //
10850 // Return true if it was logically possible to so resolve the
10851 // expression, regardless of whether or not it succeeded. Always
10852 // returns true if 'complain' is set.
10854 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
10855 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
10856 QualType DestTypeForComplaining = QualType(),
10857 unsigned DiagIDForComplaining = 0);
10858
10859 /// Add the overload candidates named by callee and/or found by argument
10860 /// dependent lookup to the given overload set.
10861 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10862 ArrayRef<Expr *> Args,
10863 OverloadCandidateSet &CandidateSet,
10864 bool PartialOverloading = false);
10865
10866 /// Add the call candidates from the given set of lookup results to the given
10867 /// overload set. Non-function lookup results are ignored.
10869 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
10870 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
10871
10872 // An enum used to represent the different possible results of building a
10873 // range-based for loop.
10879
10880 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
10881 /// given LookupResult is non-empty, it is assumed to describe a member which
10882 /// will be invoked. Otherwise, the function will be found via argument
10883 /// dependent lookup.
10884 /// CallExpr is set to a valid expression and FRS_Success returned on success,
10885 /// otherwise CallExpr is set to ExprError() and some non-success value
10886 /// is returned.
10888 SourceLocation RangeLoc,
10889 const DeclarationNameInfo &NameInfo,
10890 LookupResult &MemberLookup,
10891 OverloadCandidateSet *CandidateSet,
10892 Expr *Range, ExprResult *CallExpr);
10893
10894 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10895 /// (which eventually refers to the declaration Func) and the call
10896 /// arguments Args/NumArgs, attempt to resolve the function call down
10897 /// to a specific function. If overload resolution succeeds, returns
10898 /// the call expression produced by overload resolution.
10899 /// Otherwise, emits diagnostics and returns ExprError.
10901 Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
10902 MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig,
10903 bool AllowTypoCorrection = true, bool CalleesAddressIsTaken = false);
10904
10905 /// Constructs and populates an OverloadedCandidateSet from
10906 /// the given function.
10907 /// \returns true when an the ExprResult output parameter has been set.
10909 MultiExprArg Args, SourceLocation RParenLoc,
10910 OverloadCandidateSet *CandidateSet,
10912
10916 const UnresolvedSetImpl &Fns,
10917 bool PerformADL = true);
10918
10919 /// Create a unary operation that may resolve to an overloaded
10920 /// operator.
10921 ///
10922 /// \param OpLoc The location of the operator itself (e.g., '*').
10923 ///
10924 /// \param Opc The UnaryOperatorKind that describes this operator.
10925 ///
10926 /// \param Fns The set of non-member functions that will be
10927 /// considered by overload resolution. The caller needs to build this
10928 /// set based on the context using, e.g.,
10929 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10930 /// set should not contain any member functions; those will be added
10931 /// by CreateOverloadedUnaryOp().
10932 ///
10933 /// \param Input The input argument.
10936 const UnresolvedSetImpl &Fns, Expr *input,
10937 bool RequiresADL = true);
10938
10939 /// Perform lookup for an overloaded binary operator.
10942 const UnresolvedSetImpl &Fns,
10943 ArrayRef<Expr *> Args, bool RequiresADL = true);
10944
10945 /// Create a binary operation that may resolve to an overloaded
10946 /// operator.
10947 ///
10948 /// \param OpLoc The location of the operator itself (e.g., '+').
10949 ///
10950 /// \param Opc The BinaryOperatorKind that describes this operator.
10951 ///
10952 /// \param Fns The set of non-member functions that will be
10953 /// considered by overload resolution. The caller needs to build this
10954 /// set based on the context using, e.g.,
10955 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10956 /// set should not contain any member functions; those will be added
10957 /// by CreateOverloadedBinOp().
10958 ///
10959 /// \param LHS Left-hand argument.
10960 /// \param RHS Right-hand argument.
10961 /// \param PerformADL Whether to consider operator candidates found by ADL.
10962 /// \param AllowRewrittenCandidates Whether to consider candidates found by
10963 /// C++20 operator rewrites.
10964 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
10965 /// the function in question. Such a function is never a candidate in
10966 /// our overload resolution. This also enables synthesizing a three-way
10967 /// comparison from < and == as described in C++20 [class.spaceship]p1.
10969 const UnresolvedSetImpl &Fns, Expr *LHS,
10970 Expr *RHS, bool RequiresADL = true,
10971 bool AllowRewrittenCandidates = true,
10972 FunctionDecl *DefaultedFn = nullptr);
10974 const UnresolvedSetImpl &Fns,
10975 Expr *LHS, Expr *RHS,
10976 FunctionDecl *DefaultedFn);
10977
10979 SourceLocation RLoc, Expr *Base,
10980 MultiExprArg Args);
10981
10982 /// BuildCallToMemberFunction - Build a call to a member
10983 /// function. MemExpr is the expression that refers to the member
10984 /// function (and includes the object parameter), Args/NumArgs are the
10985 /// arguments to the function call (not including the object
10986 /// parameter). The caller needs to validate that the member
10987 /// expression refers to a non-static member function or an overloaded
10988 /// member function.
10990 Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args,
10991 SourceLocation RParenLoc, Expr *ExecConfig = nullptr,
10992 bool IsExecConfig = false, bool AllowRecovery = false);
10993
10994 /// BuildCallToObjectOfClassType - Build a call to an object of class
10995 /// type (C++ [over.call.object]), which can end up invoking an
10996 /// overloaded function call operator (@c operator()) or performing a
10997 /// user-defined conversion on the object argument.
10999 SourceLocation LParenLoc,
11000 MultiExprArg Args,
11001 SourceLocation RParenLoc);
11002
11003 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11004 /// (if one exists), where @c Base is an expression of class type and
11005 /// @c Member is the name of the member we're trying to find.
11007 SourceLocation OpLoc,
11008 bool *NoArrowOperatorFound = nullptr);
11009
11012 bool HadMultipleCandidates);
11013
11014 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call
11015 /// to a literal operator described by the provided lookup results.
11018 SourceLocation LitEndLoc,
11019 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
11020
11021 /// FixOverloadedFunctionReference - E is an expression that refers to
11022 /// a C++ overloaded function (possibly with some parentheses and
11023 /// perhaps a '&' around it). We have resolved the overloaded function
11024 /// to the function declaration Fn, so patch up the expression E to
11025 /// refer (possibly indirectly) to Fn. Returns the new expr.
11027 FunctionDecl *Fn);
11029 DeclAccessPair FoundDecl,
11030 FunctionDecl *Fn);
11031
11032 /// - Returns a selector which best matches given argument list or
11033 /// nullptr if none could be found
11035 bool IsInstance,
11037
11038 ///@}
11039
11040 //
11041 //
11042 // -------------------------------------------------------------------------
11043 //
11044 //
11045
11046 /// \name Statements
11047 /// Implementations are in SemaStmt.cpp
11048 ///@{
11049
11050public:
11051 /// Stack of active SEH __finally scopes. Can be empty.
11053
11054 /// Stack of '_Defer' statements that are currently being parsed, as well
11055 /// as the locations of their '_Defer' keywords. Can be empty.
11057
11058 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
11060
11062 bool HasLeadingEmptyMacro = false);
11063
11065 SourceLocation EndLoc);
11067
11068 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
11069 /// whose result is unused, warn.
11070 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
11071
11072 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
11076 ArrayRef<Stmt *> Elts, bool isStmtExpr);
11077
11079
11082 SourceLocation DotDotDotLoc, ExprResult RHS,
11083 SourceLocation ColonLoc);
11084
11085 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
11086 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
11087
11089 SourceLocation ColonLoc, Stmt *SubStmt,
11090 Scope *CurScope);
11092 SourceLocation ColonLoc, Stmt *SubStmt);
11093
11095 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
11097 Stmt *SubStmt);
11098
11099 /// Check whether the given statement can have musttail applied to it,
11100 /// issuing a diagnostic and returning false if not. In the success case,
11101 /// the statement is rewritten to remove implicit nodes from the return
11102 /// value.
11103 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11104
11106 SourceLocation LParenLoc, Stmt *InitStmt,
11108 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11110 SourceLocation LParenLoc, Stmt *InitStmt,
11112 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11113
11115
11117 SourceLocation LParenLoc, Stmt *InitStmt,
11119 SourceLocation RParenLoc);
11121 Stmt *Body);
11122
11123 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11124 /// integer not in the range of enum values.
11125 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11126 Expr *SrcExpr);
11127
11130 Stmt *Body);
11132 SourceLocation WhileLoc, SourceLocation CondLParen,
11133 Expr *Cond, SourceLocation CondRParen);
11134
11136 Stmt *First, ConditionResult Second,
11137 FullExprArg Third, SourceLocation RParenLoc,
11138 Stmt *Body);
11139
11140 /// In an Objective C collection iteration statement:
11141 /// for (x in y)
11142 /// x can be an arbitrary l-value expression. Bind it up as a
11143 /// full-expression.
11145
11147 /// Initial building of a for-range statement.
11149 /// Instantiation or recovery rebuild of a for-range statement. Don't
11150 /// attempt any typo-correction.
11152 /// Determining whether a for-range statement could be built. Avoid any
11153 /// unnecessary or irreversible actions.
11155 };
11156
11157 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
11158 ///
11159 /// C++11 [stmt.ranged]:
11160 /// A range-based for statement is equivalent to
11161 ///
11162 /// {
11163 /// auto && __range = range-init;
11164 /// for ( auto __begin = begin-expr,
11165 /// __end = end-expr;
11166 /// __begin != __end;
11167 /// ++__begin ) {
11168 /// for-range-declaration = *__begin;
11169 /// statement
11170 /// }
11171 /// }
11172 ///
11173 /// The body of the loop is not available yet, since it cannot be analysed
11174 /// until we have determined the type of the for-range-declaration.
11176 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc,
11177 Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection,
11178 SourceLocation RParenLoc, BuildForRangeKind Kind,
11179 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11180
11181 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
11182 StmtResult BuildCXXForRangeStmt(
11183 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
11184 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
11185 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
11186 BuildForRangeKind Kind,
11187 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11188
11189 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
11190 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
11191 /// body cannot be performed until after the type of the range variable is
11192 /// determined.
11193 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
11194
11195 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
11196 LabelDecl *TheDecl);
11197 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
11198 SourceLocation StarLoc, Expr *DestExp);
11199 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope,
11200 LabelDecl *Label, SourceLocation LabelLoc);
11201 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope,
11202 LabelDecl *Label, SourceLocation LabelLoc);
11203
11204 void ActOnStartOfDeferStmt(SourceLocation DeferLoc, Scope *CurScope);
11205 void ActOnDeferStmtError(Scope *CurScope);
11206 StmtResult ActOnEndOfDeferStmt(Stmt *Body, Scope *CurScope);
11207
11210
11213
11214 bool isMoveEligible() const { return S != None; };
11216 };
11218
11219 /// Determine whether the given expression might be move-eligible or
11220 /// copy-elidable in either a (co_)return statement or throw expression,
11221 /// without considering function return type, if applicable.
11222 ///
11223 /// \param E The expression being returned from the function or block,
11224 /// being thrown, or being co_returned from a coroutine. This expression
11225 /// might be modified by the implementation.
11226 ///
11227 /// \param Mode Overrides detection of current language mode
11228 /// and uses the rules for C++23.
11229 ///
11230 /// \returns An aggregate which contains the Candidate and isMoveEligible
11231 /// and isCopyElidable methods. If Candidate is non-null, it means
11232 /// isMoveEligible() would be true under the most permissive language
11233 /// standard.
11234 NamedReturnInfo getNamedReturnInfo(
11236
11237 /// Determine whether the given NRVO candidate variable is move-eligible or
11238 /// copy-elidable, without considering function return type.
11239 ///
11240 /// \param VD The NRVO candidate variable.
11241 ///
11242 /// \returns An aggregate which contains the Candidate and isMoveEligible
11243 /// and isCopyElidable methods. If Candidate is non-null, it means
11244 /// isMoveEligible() would be true under the most permissive language
11245 /// standard.
11246 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
11247
11248 /// Updates given NamedReturnInfo's move-eligible and
11249 /// copy-elidable statuses, considering the function
11250 /// return type criteria as applicable to return statements.
11251 ///
11252 /// \param Info The NamedReturnInfo object to update.
11253 ///
11254 /// \param ReturnType This is the return type of the function.
11255 /// \returns The copy elision candidate, in case the initial return expression
11256 /// was copy elidable, or nullptr otherwise.
11257 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
11258 QualType ReturnType);
11259
11260 /// Perform the initialization of a potentially-movable value, which
11261 /// is the result of return value.
11262 ///
11263 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
11264 /// treat returned lvalues as rvalues in certain cases (to prefer move
11265 /// construction), then falls back to treating them as lvalues if that failed.
11268 const NamedReturnInfo &NRInfo, Expr *Value,
11269 bool SupressSimplerImplicitMoves = false);
11270
11272
11273 /// Deduce the return type for a function from a returned expression, per
11274 /// C++1y [dcl.spec.auto]p6.
11276 SourceLocation ReturnLoc, Expr *RetExpr,
11277 const AutoType *AT);
11278
11279 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11280 Scope *CurScope);
11281 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11282 bool AllowRecovery = false);
11283
11284 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
11285 /// for capturing scopes.
11287 NamedReturnInfo &NRInfo,
11288 bool SupressSimplerImplicitMoves);
11289
11290 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
11291 /// and creates a proper catch handler from them.
11293 Stmt *HandlerBlock);
11294
11295 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
11296 /// handlers and creates a try statement from them.
11298 ArrayRef<Stmt *> Handlers);
11299
11300 void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry);
11301
11302 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
11303 SourceLocation TryLoc, Stmt *TryBlock,
11304 Stmt *Handler);
11306 Stmt *Block);
11311
11313 bool IsIfExists,
11314 NestedNameSpecifierLoc QualifierLoc,
11315 DeclarationNameInfo NameInfo,
11316 Stmt *Nested);
11318 bool IsIfExists, CXXScopeSpec &SS,
11319 UnqualifiedId &Name, Stmt *Nested);
11320
11321 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11322 CapturedRegionKind Kind, unsigned NumParams);
11323 typedef std::pair<StringRef, QualType> CapturedParamNameType;
11324 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11325 CapturedRegionKind Kind,
11327 unsigned OpenMPCaptureLevel = 0);
11331 SourceLocation Loc,
11332 unsigned NumParams);
11333
11334private:
11335 /// Check whether the given statement can have musttail applied to it,
11336 /// issuing a diagnostic and returning false if not.
11337 bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11338
11339 ///@}
11340
11341 //
11342 //
11343 // -------------------------------------------------------------------------
11344 //
11345 //
11346
11347 /// \name `inline asm` Statement
11348 /// Implementations are in SemaStmtAsm.cpp
11349 ///@{
11350
11351public:
11352 ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel);
11353 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
11354 bool IsVolatile, unsigned NumOutputs,
11355 unsigned NumInputs, IdentifierInfo **Names,
11356 MultiExprArg Constraints, MultiExprArg Exprs,
11357 Expr *AsmString, MultiExprArg Clobbers,
11358 unsigned NumLabels, SourceLocation RParenLoc);
11359
11361 llvm::InlineAsmIdentifierInfo &Info);
11363 SourceLocation TemplateKWLoc,
11364 UnqualifiedId &Id,
11365 bool IsUnevaluatedContext);
11366 bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset,
11367 SourceLocation AsmLoc);
11369 SourceLocation AsmLoc);
11371 ArrayRef<Token> AsmToks, StringRef AsmString,
11372 unsigned NumOutputs, unsigned NumInputs,
11373 ArrayRef<StringRef> Constraints,
11374 ArrayRef<StringRef> Clobbers,
11375 ArrayRef<Expr *> Exprs, SourceLocation EndLoc);
11376 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
11377 SourceLocation Location, bool AlwaysCreate);
11378
11379 ///@}
11380
11381 //
11382 //
11383 // -------------------------------------------------------------------------
11384 //
11385 //
11386
11387 /// \name Statement Attribute Handling
11388 /// Implementations are in SemaStmtAttr.cpp
11389 ///@{
11390
11391public:
11392 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11393 const AttributeCommonInfo &A);
11394 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11395 const AttributeCommonInfo &A);
11396
11397 CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E);
11399
11400 /// Process the attributes before creating an attributed statement. Returns
11401 /// the semantic attributes that have been processed.
11402 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
11404
11406 SourceRange Range);
11408 const IdentifierInfo *AttrName,
11409 SourceRange Range);
11410
11411 ///@}
11412
11413 //
11414 //
11415 // -------------------------------------------------------------------------
11416 //
11417 //
11418
11419 /// \name C++ Templates
11420 /// Implementations are in SemaTemplate.cpp
11421 ///@{
11422
11423public:
11424 // Saves the current floating-point pragma stack and clear it in this Sema.
11426 public:
11428 : S(S), SavedStack(std::move(S.FpPragmaStack)) {
11429 S.FpPragmaStack.Stack.clear();
11430 }
11431 ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); }
11434
11435 private:
11436 Sema &S;
11438 };
11439
11441 CurFPFeatures = FPO;
11442 FpPragmaStack.CurrentValue = FPO.getChangesFrom(FPOptions(LangOpts));
11443 }
11444
11450
11455
11456 typedef llvm::MapVector<const FunctionDecl *,
11457 std::unique_ptr<LateParsedTemplate>>
11460
11461 /// Determine the number of levels of enclosing template parameters. This is
11462 /// only usable while parsing. Note that this does not include dependent
11463 /// contexts in which no template parameters have yet been declared, such as
11464 /// in a terse function template or generic lambda before the first 'auto' is
11465 /// encountered.
11466 unsigned getTemplateDepth(Scope *S) const;
11467
11469 bool AllowFunctionTemplates = true,
11470 bool AllowDependent = true);
11472 bool AllowFunctionTemplates = true,
11473 bool AllowDependent = true,
11474 bool AllowNonTemplateFunctions = false);
11475 /// Try to interpret the lookup result D as a template-name.
11476 ///
11477 /// \param D A declaration found by name lookup.
11478 /// \param AllowFunctionTemplates Whether function templates should be
11479 /// considered valid results.
11480 /// \param AllowDependent Whether unresolved using declarations (that might
11481 /// name templates) should be considered valid results.
11483 bool AllowFunctionTemplates = true,
11484 bool AllowDependent = true);
11485
11487 /// Whether and why a template name is required in this lookup.
11489 public:
11490 /// Template name is required if TemplateKWLoc is valid.
11492 : TemplateKW(TemplateKWLoc) {}
11493 /// Template name is unconditionally required.
11495
11497 return TemplateKW.value_or(SourceLocation());
11498 }
11499 bool hasTemplateKeyword() const {
11500 return getTemplateKeywordLoc().isValid();
11501 }
11502 bool isRequired() const { return TemplateKW != SourceLocation(); }
11503 explicit operator bool() const { return isRequired(); }
11504
11505 private:
11506 std::optional<SourceLocation> TemplateKW;
11507 };
11508
11510 /// This is not assumed to be a template name.
11512 /// This is assumed to be a template name because lookup found nothing.
11514 /// This is assumed to be a template name because lookup found one or more
11515 /// functions (but no function templates).
11517 };
11518
11519 bool
11521 QualType ObjectType, bool EnteringContext,
11522 RequiredTemplateKind RequiredTemplate = SourceLocation(),
11523 AssumedTemplateKind *ATK = nullptr,
11524 bool AllowTypoCorrection = true);
11525
11527 bool hasTemplateKeyword,
11528 const UnqualifiedId &Name,
11529 ParsedType ObjectType, bool EnteringContext,
11531 bool &MemberOfUnknownSpecialization,
11532 bool AllowTypoCorrection = true);
11533
11534 /// Try to resolve an undeclared template name as a type template.
11535 ///
11536 /// Sets II to the identifier corresponding to the template name, and updates
11537 /// Name to a corresponding (typo-corrected) type template name and TNK to
11538 /// the corresponding kind, if possible.
11540 TemplateNameKind &TNK,
11541 SourceLocation NameLoc,
11542 IdentifierInfo *&II);
11543
11544 /// Determine whether a particular identifier might be the name in a C++1z
11545 /// deduction-guide declaration.
11546 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
11547 SourceLocation NameLoc, CXXScopeSpec &SS,
11548 ParsedTemplateTy *Template = nullptr);
11549
11551 SourceLocation IILoc, Scope *S,
11552 const CXXScopeSpec *SS,
11553 TemplateTy &SuggestedTemplate,
11554 TemplateNameKind &SuggestedKind);
11555
11556 /// Determine whether we would be unable to instantiate this template (because
11557 /// it either has no definition, or is in the process of being instantiated).
11559 SourceLocation PointOfInstantiation, NamedDecl *Instantiation,
11560 bool InstantiatedFromMember, const NamedDecl *Pattern,
11561 const NamedDecl *PatternDef, TemplateSpecializationKind TSK,
11562 bool Complain = true, bool *Unreachable = nullptr);
11563
11564 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
11565 /// that the template parameter 'PrevDecl' is being shadowed by a new
11566 /// declaration at location Loc. Returns true to indicate that this is
11567 /// an error, and false otherwise.
11568 ///
11569 /// \param Loc The location of the declaration that shadows a template
11570 /// parameter.
11571 ///
11572 /// \param PrevDecl The template parameter that the declaration shadows.
11573 ///
11574 /// \param SupportedForCompatibility Whether to issue the diagnostic as
11575 /// a warning for compatibility with older versions of clang.
11576 /// Ignored when MSVC compatibility is enabled.
11578 bool SupportedForCompatibility = false);
11579
11580 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
11581 /// the parameter D to reference the templated declaration and return a
11582 /// pointer to the template declaration. Otherwise, do nothing to D and return
11583 /// null.
11585
11586 /// ActOnTypeParameter - Called when a C++ template type parameter
11587 /// (e.g., "typename T") has been parsed. Typename specifies whether
11588 /// the keyword "typename" was used to declare the type parameter
11589 /// (otherwise, "class" was used), and KeyLoc is the location of the
11590 /// "class" or "typename" keyword. ParamName is the name of the
11591 /// parameter (NULL indicates an unnamed template parameter) and
11592 /// ParamNameLoc is the location of the parameter name (if any).
11593 /// If the type parameter has a default argument, it will be added
11594 /// later via ActOnTypeParameterDefault.
11596 SourceLocation EllipsisLoc,
11597 SourceLocation KeyLoc,
11598 IdentifierInfo *ParamName,
11599 SourceLocation ParamNameLoc, unsigned Depth,
11600 unsigned Position, SourceLocation EqualLoc,
11601 ParsedType DefaultArg, bool HasTypeConstraint);
11602
11604
11605 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
11607 TemplateTypeParmDecl *ConstrainedParameter,
11608 SourceLocation EllipsisLoc);
11609 bool BuildTypeConstraint(const CXXScopeSpec &SS,
11611 TemplateTypeParmDecl *ConstrainedParameter,
11612 SourceLocation EllipsisLoc,
11613 bool AllowUnexpandedPack);
11614
11615 /// Attach a type-constraint to a template parameter.
11616 /// \returns true if an error occurred. This can happen if the
11617 /// immediately-declared constraint could not be formed (e.g. incorrect number
11618 /// of arguments for the named concept).
11620 DeclarationNameInfo NameInfo,
11621 TemplateDecl *NamedConcept, NamedDecl *FoundDecl,
11622 const TemplateArgumentListInfo *TemplateArgs,
11623 TemplateTypeParmDecl *ConstrainedParameter,
11624 SourceLocation EllipsisLoc);
11625
11627 NonTypeTemplateParmDecl *NewConstrainedParm,
11628 NonTypeTemplateParmDecl *OrigConstrainedParm,
11629 SourceLocation EllipsisLoc);
11630
11631 /// Require the given type to be a structural type, and diagnose if it is not.
11632 ///
11633 /// \return \c true if an error was produced.
11635
11636 /// Check that the type of a non-type template parameter is
11637 /// well-formed.
11638 ///
11639 /// \returns the (possibly-promoted) parameter type if valid;
11640 /// otherwise, produces a diagnostic and returns a NULL type.
11642 SourceLocation Loc);
11644
11646 unsigned Depth, unsigned Position,
11647 SourceLocation EqualLoc,
11648 Expr *DefaultArg);
11649
11650 /// ActOnTemplateTemplateParameter - Called when a C++ template template
11651 /// parameter (e.g. T in template <template <typename> class T> class array)
11652 /// has been parsed. S is the current scope.
11654 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind,
11655 bool TypenameKeyword, TemplateParameterList *Params,
11656 SourceLocation EllipsisLoc, IdentifierInfo *ParamName,
11657 SourceLocation ParamNameLoc, unsigned Depth, unsigned Position,
11658 SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg);
11659
11660 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
11661 /// constrained by RequiresClause, that contains the template parameters in
11662 /// Params.
11664 unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc,
11665 SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params,
11666 SourceLocation RAngleLoc, Expr *RequiresClause);
11667
11668 /// The context in which we are checking a template parameter list.
11670 // For this context, Class, Variable, TypeAlias, and non-pack Template
11671 // Template Parameters are treated uniformly.
11673
11680 };
11681
11682 /// Checks the validity of a template parameter list, possibly
11683 /// considering the template parameter list from a previous
11684 /// declaration.
11685 ///
11686 /// If an "old" template parameter list is provided, it must be
11687 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
11688 /// template parameter list.
11689 ///
11690 /// \param NewParams Template parameter list for a new template
11691 /// declaration. This template parameter list will be updated with any
11692 /// default arguments that are carried through from the previous
11693 /// template parameter list.
11694 ///
11695 /// \param OldParams If provided, template parameter list from a
11696 /// previous declaration of the same template. Default template
11697 /// arguments will be merged from the old template parameter list to
11698 /// the new template parameter list.
11699 ///
11700 /// \param TPC Describes the context in which we are checking the given
11701 /// template parameter list.
11702 ///
11703 /// \param SkipBody If we might have already made a prior merged definition
11704 /// of this template visible, the corresponding body-skipping information.
11705 /// Default argument redefinition is not an error when skipping such a body,
11706 /// because (under the ODR) we can assume the default arguments are the same
11707 /// as the prior merged definition.
11708 ///
11709 /// \returns true if an error occurred, false otherwise.
11711 TemplateParameterList *OldParams,
11713 SkipBodyInfo *SkipBody = nullptr);
11714
11715 /// Match the given template parameter lists to the given scope
11716 /// specifier, returning the template parameter list that applies to the
11717 /// name.
11718 ///
11719 /// \param DeclStartLoc the start of the declaration that has a scope
11720 /// specifier or a template parameter list.
11721 ///
11722 /// \param DeclLoc The location of the declaration itself.
11723 ///
11724 /// \param SS the scope specifier that will be matched to the given template
11725 /// parameter lists. This scope specifier precedes a qualified name that is
11726 /// being declared.
11727 ///
11728 /// \param TemplateId The template-id following the scope specifier, if there
11729 /// is one. Used to check for a missing 'template<>'.
11730 ///
11731 /// \param ParamLists the template parameter lists, from the outermost to the
11732 /// innermost template parameter lists.
11733 ///
11734 /// \param IsFriend Whether to apply the slightly different rules for
11735 /// matching template parameters to scope specifiers in friend
11736 /// declarations.
11737 ///
11738 /// \param IsMemberSpecialization will be set true if the scope specifier
11739 /// denotes a fully-specialized type, and therefore this is a declaration of
11740 /// a member specialization.
11741 ///
11742 /// \returns the template parameter list, if any, that corresponds to the
11743 /// name that is preceded by the scope specifier @p SS. This template
11744 /// parameter list may have template parameters (if we're declaring a
11745 /// template) or may have no template parameters (if we're declaring a
11746 /// template specialization), or may be NULL (if what we're declaring isn't
11747 /// itself a template).
11749 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
11750 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
11751 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
11752 bool &IsMemberSpecialization, bool &Invalid,
11753 bool SuppressDiagnostic = false);
11754
11755 /// Returns the template parameter list with all default template argument
11756 /// information.
11758
11760 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11761 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
11762 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
11763 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
11764 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
11765 TemplateParameterList **OuterTemplateParamLists,
11766 bool IsMemberSpecialization, SkipBodyInfo *SkipBody = nullptr);
11767
11768 /// Translates template arguments as provided by the parser
11769 /// into template arguments used by semantic analysis.
11772
11773 /// Convert a parsed type into a parsed template argument. This is mostly
11774 /// trivial, except that we may have parsed a C++17 deduced class template
11775 /// specialization type, in which case we should form a template template
11776 /// argument instead of a type template argument.
11778
11780
11783 SourceLocation TemplateLoc,
11784 TemplateArgumentListInfo &TemplateArgs,
11785 Scope *Scope, bool ForNestedNameSpecifier);
11786
11788 ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
11789 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
11790 SourceLocation TemplateKWLoc, TemplateTy Template,
11791 const IdentifierInfo *TemplateII,
11792 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11793 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
11794 bool IsCtorOrDtorName = false, bool IsClassName = false,
11795 ImplicitTypenameContext AllowImplicitTypename =
11797
11798 /// Parsed an elaborated-type-specifier that refers to a template-id,
11799 /// such as \c class T::template apply<U>.
11801 TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc,
11802 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD,
11803 SourceLocation TemplateLoc, SourceLocation LAngleLoc,
11804 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc);
11805
11808 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
11810
11811 /// Get the specialization of the given variable template corresponding to
11812 /// the specified argument list, or a null-but-valid result if the arguments
11813 /// are dependent.
11815 SourceLocation TemplateLoc,
11816 SourceLocation TemplateNameLoc,
11817 const TemplateArgumentListInfo &TemplateArgs,
11818 bool SetWrittenArgs);
11819
11820 /// Form a reference to the specialization of the given variable template
11821 /// corresponding to the specified argument list, or a null-but-valid result
11822 /// if the arguments are dependent.
11824 const DeclarationNameInfo &NameInfo,
11826 SourceLocation TemplateLoc,
11827 const TemplateArgumentListInfo *TemplateArgs);
11828
11830 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
11832 const TemplateArgumentListInfo *TemplateArgs);
11833
11835 CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11836 const DeclarationNameInfo &ConceptNameInfo,
11837 NamedDecl *FoundDecl, TemplateDecl *NamedConcept,
11838 const TemplateArgumentListInfo *TemplateArgs,
11839 bool DoCheckConstraintSatisfaction = true);
11840
11843 bool TemplateKeyword, TemplateDecl *TD,
11844 SourceLocation Loc);
11845
11847 SourceLocation TemplateKWLoc, LookupResult &R,
11848 bool RequiresADL,
11849 const TemplateArgumentListInfo *TemplateArgs);
11850
11851 // We actually only call this from template instantiation.
11854 const DeclarationNameInfo &NameInfo,
11855 const TemplateArgumentListInfo *TemplateArgs,
11856 bool IsAddressOfOperand);
11857
11859 return Pack.pack_size() - 1 - *ArgPackSubstIndex;
11860 }
11861
11864 Arg = Arg.pack_elements()[*ArgPackSubstIndex];
11865 if (Arg.isPackExpansion())
11866 Arg = Arg.getPackExpansionPattern();
11867 return Arg;
11868 }
11869
11871 BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
11872 QualType ParamType, SourceLocation loc,
11873 TemplateArgument Replacement,
11874 UnsignedOrNone PackIndex, bool Final);
11875
11876 /// Form a template name from a name that is syntactically required to name a
11877 /// template, either due to use of the 'template' keyword or because a name in
11878 /// this syntactic context is assumed to name a template (C++
11879 /// [temp.names]p2-4).
11880 ///
11881 /// This action forms a template name given the name of the template and its
11882 /// optional scope specifier. This is used when the 'template' keyword is used
11883 /// or when the parsing context unambiguously treats a following '<' as
11884 /// introducing a template argument list. Note that this may produce a
11885 /// non-dependent template name if we can perform the lookup now and identify
11886 /// the named template.
11887 ///
11888 /// For example, given "x.MetaFun::template apply", the scope specifier
11889 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
11890 /// of the "template" keyword, and "apply" is the \p Name.
11892 SourceLocation TemplateKWLoc,
11893 const UnqualifiedId &Name,
11894 ParsedType ObjectType,
11895 bool EnteringContext, TemplateTy &Template,
11896 bool AllowInjectedClassName = false);
11897
11899 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11900 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
11902 MultiTemplateParamsArg TemplateParameterLists,
11903 SkipBodyInfo *SkipBody = nullptr);
11904
11905 /// Check the non-type template arguments of a class template
11906 /// partial specialization according to C++ [temp.class.spec]p9.
11907 ///
11908 /// \param TemplateNameLoc the location of the template name.
11909 /// \param PrimaryTemplate the template parameters of the primary class
11910 /// template.
11911 /// \param NumExplicit the number of explicitly-specified template arguments.
11912 /// \param TemplateArgs the template arguments of the class template
11913 /// partial specialization.
11914 ///
11915 /// \returns \c true if there was an error, \c false otherwise.
11917 TemplateDecl *PrimaryTemplate,
11918 unsigned NumExplicitArgs,
11924
11926 MultiTemplateParamsArg TemplateParameterLists,
11927 Declarator &D);
11928
11929 /// Diagnose cases where we have an explicit template specialization
11930 /// before/after an explicit template instantiation, producing diagnostics
11931 /// for those cases where they are required and determining whether the
11932 /// new specialization/instantiation will have any effect.
11933 ///
11934 /// \param NewLoc the location of the new explicit specialization or
11935 /// instantiation.
11936 ///
11937 /// \param NewTSK the kind of the new explicit specialization or
11938 /// instantiation.
11939 ///
11940 /// \param PrevDecl the previous declaration of the entity.
11941 ///
11942 /// \param PrevTSK the kind of the old explicit specialization or
11943 /// instantiatin.
11944 ///
11945 /// \param PrevPointOfInstantiation if valid, indicates where the previous
11946 /// declaration was instantiated (either implicitly or explicitly).
11947 ///
11948 /// \param HasNoEffect will be set to true to indicate that the new
11949 /// specialization or instantiation has no effect and should be ignored.
11950 ///
11951 /// \returns true if there was an error that should prevent the introduction
11952 /// of the new declaration into the AST, false otherwise.
11954 SourceLocation NewLoc,
11955 TemplateSpecializationKind ActOnExplicitInstantiationNewTSK,
11956 NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK,
11957 SourceLocation PrevPtOfInstantiation, bool &SuppressNew);
11958
11959 /// Perform semantic analysis for the given dependent function
11960 /// template specialization.
11961 ///
11962 /// The only possible way to get a dependent function template specialization
11963 /// is with a friend declaration, like so:
11964 ///
11965 /// \code
11966 /// template <class T> void foo(T);
11967 /// template <class T> class A {
11968 /// friend void foo<>(T);
11969 /// };
11970 /// \endcode
11971 ///
11972 /// There really isn't any useful analysis we can do here, so we
11973 /// just store the information.
11975 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
11977
11978 /// Perform semantic analysis for the given function template
11979 /// specialization.
11980 ///
11981 /// This routine performs all of the semantic analysis required for an
11982 /// explicit function template specialization. On successful completion,
11983 /// the function declaration \p FD will become a function template
11984 /// specialization.
11985 ///
11986 /// \param FD the function declaration, which will be updated to become a
11987 /// function template specialization.
11988 ///
11989 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
11990 /// if any. Note that this may be valid info even when 0 arguments are
11991 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
11992 /// as it anyway contains info on the angle brackets locations.
11993 ///
11994 /// \param Previous the set of declarations that may be specialized by
11995 /// this function specialization.
11996 ///
11997 /// \param QualifiedFriend whether this is a lookup for a qualified friend
11998 /// declaration with no explicit template argument list that might be
11999 /// befriending a function template specialization.
12001 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
12002 LookupResult &Previous, bool QualifiedFriend = false);
12003
12004 /// Perform semantic analysis for the given non-template member
12005 /// specialization.
12006 ///
12007 /// This routine performs all of the semantic analysis required for an
12008 /// explicit member function specialization. On successful completion,
12009 /// the function declaration \p FD will become a member function
12010 /// specialization.
12011 ///
12012 /// \param Member the member declaration, which will be updated to become a
12013 /// specialization.
12014 ///
12015 /// \param Previous the set of declarations, one of which may be specialized
12016 /// by this function specialization; the set will be modified to contain the
12017 /// redeclared member.
12020
12021 // Explicit instantiation of a class template specialization
12023 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
12024 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
12025 TemplateTy Template, SourceLocation TemplateNameLoc,
12026 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
12027 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
12028
12029 // Explicit instantiation of a member class of a class template.
12031 SourceLocation TemplateLoc,
12032 unsigned TagSpec, SourceLocation KWLoc,
12033 CXXScopeSpec &SS, IdentifierInfo *Name,
12034 SourceLocation NameLoc,
12035 const ParsedAttributesView &Attr);
12036
12038 SourceLocation TemplateLoc,
12039 Declarator &D);
12040
12041 /// If the given template parameter has a default template
12042 /// argument, substitute into that default template argument and
12043 /// return the corresponding template argument.
12045 TemplateDecl *Template, SourceLocation TemplateKWLoc,
12046 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
12047 ArrayRef<TemplateArgument> SugaredConverted,
12048 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
12049
12050 /// Returns the top most location responsible for the definition of \p N.
12051 /// If \p N is a a template specialization, this is the location
12052 /// of the top of the instantiation stack.
12053 /// Otherwise, the location of \p N is returned.
12055
12056 /// Specifies the context in which a particular template
12057 /// argument is being checked.
12059 /// The template argument was specified in the code or was
12060 /// instantiated with some deduced template arguments.
12062
12063 /// The template argument was deduced via template argument
12064 /// deduction.
12066
12067 /// The template argument was deduced from an array bound
12068 /// via template argument deduction.
12070 };
12071
12079
12080 /// The checked, converted argument will be added to the
12081 /// end of these vectors.
12083
12084 /// The check is being performed in the context of partial ordering.
12086
12087 /// If true, assume these template arguments are
12088 /// the injected template arguments for a template template parameter.
12089 /// This will relax the requirement that all its possible uses are valid:
12090 /// TTP checking is loose, and assumes that invalid uses will be diagnosed
12091 /// during instantiation.
12093
12094 /// Is set to true when, in the context of TTP matching, a pack parameter
12095 /// matches non-pack arguments.
12096 bool StrictPackMatch = false;
12097 };
12098
12099 /// Check that the given template argument corresponds to the given
12100 /// template parameter.
12101 ///
12102 /// \param Param The template parameter against which the argument will be
12103 /// checked.
12104 ///
12105 /// \param Arg The template argument, which may be updated due to conversions.
12106 ///
12107 /// \param Template The template in which the template argument resides.
12108 ///
12109 /// \param TemplateLoc The location of the template name for the template
12110 /// whose argument list we're matching.
12111 ///
12112 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
12113 /// the template argument list.
12114 ///
12115 /// \param ArgumentPackIndex The index into the argument pack where this
12116 /// argument will be placed. Only valid if the parameter is a parameter pack.
12117 ///
12118 /// \param CTAK Describes how we arrived at this particular template argument:
12119 /// explicitly written, deduced, etc.
12120 ///
12121 /// \returns true on error, false otherwise.
12123 NamedDecl *Template, SourceLocation TemplateLoc,
12124 SourceLocation RAngleLoc,
12125 unsigned ArgumentPackIndex,
12128
12129 /// Check that the given template arguments can be provided to
12130 /// the given template, converting the arguments along the way.
12131 ///
12132 /// \param Template The template to which the template arguments are being
12133 /// provided.
12134 ///
12135 /// \param TemplateLoc The location of the template name in the source.
12136 ///
12137 /// \param TemplateArgs The list of template arguments. If the template is
12138 /// a template template parameter, this function may extend the set of
12139 /// template arguments to also include substituted, defaulted template
12140 /// arguments.
12141 ///
12142 /// \param PartialTemplateArgs True if the list of template arguments is
12143 /// intentionally partial, e.g., because we're checking just the initial
12144 /// set of template arguments.
12145 ///
12146 /// \param Converted Will receive the converted, canonicalized template
12147 /// arguments.
12148 ///
12149 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
12150 /// contain the converted forms of the template arguments as written.
12151 /// Otherwise, \p TemplateArgs will not be modified.
12152 ///
12153 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
12154 /// receive true if the cause for the error is the associated constraints of
12155 /// the template not being satisfied by the template arguments.
12156 ///
12157 /// \param DefaultArgs any default arguments from template specialization
12158 /// deduction.
12159 ///
12160 /// \returns true if an error occurred, false otherwise.
12162 SourceLocation TemplateLoc,
12163 TemplateArgumentListInfo &TemplateArgs,
12164 const DefaultArguments &DefaultArgs,
12165 bool PartialTemplateArgs,
12167 bool UpdateArgsWithConversions = true,
12168 bool *ConstraintsNotSatisfied = nullptr);
12169
12172 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
12173 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
12174 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions = true,
12175 bool *ConstraintsNotSatisfied = nullptr);
12176
12179 SmallVectorImpl<TemplateArgument> &SugaredConverted,
12180 SmallVectorImpl<TemplateArgument> &CanonicalConverted);
12181
12182 /// Check a template argument against its corresponding
12183 /// template type parameter.
12184 ///
12185 /// This routine implements the semantics of C++ [temp.arg.type]. It
12186 /// returns true if an error occurred, and false otherwise.
12188
12189 /// Check a template argument against its corresponding
12190 /// non-type template parameter.
12191 ///
12192 /// This routine implements the semantics of C++ [temp.arg.nontype].
12193 /// If an error occurred, it returns ExprError(); otherwise, it
12194 /// returns the converted template argument. \p ParamType is the
12195 /// type of the non-type template parameter after it has been instantiated.
12197 QualType InstantiatedParamType, Expr *Arg,
12198 TemplateArgument &SugaredConverted,
12199 TemplateArgument &CanonicalConverted,
12200 bool StrictCheck,
12202
12203 /// Check a template argument against its corresponding
12204 /// template template parameter.
12205 ///
12206 /// This routine implements the semantics of C++ [temp.arg.template].
12207 /// It returns true if an error occurred, and false otherwise.
12209 TemplateParameterList *Params,
12211 bool PartialOrdering,
12212 bool *StrictPackMatch);
12213
12216 const TemplateArgumentLoc &Arg);
12217
12219 std::optional<SourceRange> ParamRange = {});
12221
12222 /// Given a non-type template argument that refers to a
12223 /// declaration and the type of its corresponding non-type template
12224 /// parameter, produce an expression that properly refers to that
12225 /// declaration.
12226 /// FIXME: This is used in some contexts where the resulting expression
12227 /// doesn't need to live too long. It would be useful if this function
12228 /// could return a temporary expression.
12230 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc);
12233 SourceLocation Loc);
12234
12235 /// Enumeration describing how template parameter lists are compared
12236 /// for equality.
12238 /// We are matching the template parameter lists of two templates
12239 /// that might be redeclarations.
12240 ///
12241 /// \code
12242 /// template<typename T> struct X;
12243 /// template<typename T> struct X;
12244 /// \endcode
12246
12247 /// We are matching the template parameter lists of two template
12248 /// template parameters as part of matching the template parameter lists
12249 /// of two templates that might be redeclarations.
12250 ///
12251 /// \code
12252 /// template<template<int I> class TT> struct X;
12253 /// template<template<int Value> class Other> struct X;
12254 /// \endcode
12256
12257 /// We are determining whether the template-parameters are equivalent
12258 /// according to C++ [temp.over.link]/6. This comparison does not consider
12259 /// constraints.
12260 ///
12261 /// \code
12262 /// template<C1 T> void f(T);
12263 /// template<C2 T> void f(T);
12264 /// \endcode
12266 };
12267
12268 // A struct to represent the 'new' declaration, which is either itself just
12269 // the named decl, or the important information we need about it in order to
12270 // do constraint comparisons.
12272 const NamedDecl *ND = nullptr;
12273 const DeclContext *DC = nullptr;
12274 const DeclContext *LexicalDC = nullptr;
12275 SourceLocation Loc;
12276
12277 public:
12280 const DeclContext *LexicalDeclCtx,
12281 SourceLocation Loc)
12282
12283 : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) {
12284 assert(DC && LexicalDC &&
12285 "Constructor only for cases where we have the information to put "
12286 "in here");
12287 }
12288
12289 // If this was constructed with no information, we cannot do substitution
12290 // for constraint comparison, so make sure we can check that.
12291 bool isInvalid() const { return !ND && !DC; }
12292
12293 const NamedDecl *getDecl() const { return ND; }
12294
12295 bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; }
12296
12298 return ND ? ND->getLexicalDeclContext() : LexicalDC;
12299 }
12300
12302 return ND ? ND->getDeclContext() : DC;
12303 }
12304
12305 SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; }
12306 };
12307
12308 /// Determine whether the given template parameter lists are
12309 /// equivalent.
12310 ///
12311 /// \param New The new template parameter list, typically written in the
12312 /// source code as part of a new template declaration.
12313 ///
12314 /// \param Old The old template parameter list, typically found via
12315 /// name lookup of the template declared with this template parameter
12316 /// list.
12317 ///
12318 /// \param Complain If true, this routine will produce a diagnostic if
12319 /// the template parameter lists are not equivalent.
12320 ///
12321 /// \param Kind describes how we are to match the template parameter lists.
12322 ///
12323 /// \param TemplateArgLoc If this source location is valid, then we
12324 /// are actually checking the template parameter list of a template
12325 /// argument (New) against the template parameter list of its
12326 /// corresponding template template parameter (Old). We produce
12327 /// slightly different diagnostics in this scenario.
12328 ///
12329 /// \returns True if the template parameter lists are equal, false
12330 /// otherwise.
12332 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
12333 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
12335 SourceLocation TemplateArgLoc = SourceLocation());
12336
12338 TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
12340 SourceLocation TemplateArgLoc = SourceLocation()) {
12341 return TemplateParameterListsAreEqual(nullptr, New, nullptr, Old, Complain,
12342 Kind, TemplateArgLoc);
12343 }
12344
12345 /// Check whether a template can be declared within this scope.
12346 ///
12347 /// If the template declaration is valid in this scope, returns
12348 /// false. Otherwise, issues a diagnostic and returns true.
12349 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
12350
12351 /// Called when the parser has parsed a C++ typename
12352 /// specifier, e.g., "typename T::type".
12353 ///
12354 /// \param S The scope in which this typename type occurs.
12355 /// \param TypenameLoc the location of the 'typename' keyword
12356 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12357 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
12358 /// \param IdLoc the location of the identifier.
12359 /// \param IsImplicitTypename context where T::type refers to a type.
12361 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
12362 const IdentifierInfo &II, SourceLocation IdLoc,
12364
12365 /// Called when the parser has parsed a C++ typename
12366 /// specifier that ends in a template-id, e.g.,
12367 /// "typename MetaFun::template apply<T1, T2>".
12368 ///
12369 /// \param S The scope in which this typename type occurs.
12370 /// \param TypenameLoc the location of the 'typename' keyword
12371 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12372 /// \param TemplateLoc the location of the 'template' keyword, if any.
12373 /// \param TemplateName The template name.
12374 /// \param TemplateII The identifier used to name the template.
12375 /// \param TemplateIILoc The location of the template name.
12376 /// \param LAngleLoc The location of the opening angle bracket ('<').
12377 /// \param TemplateArgs The template arguments.
12378 /// \param RAngleLoc The location of the closing angle bracket ('>').
12380 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
12381 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
12382 TemplateTy TemplateName, const IdentifierInfo *TemplateII,
12383 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
12384 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc);
12385
12387 SourceLocation KeywordLoc,
12388 NestedNameSpecifierLoc QualifierLoc,
12389 const IdentifierInfo &II, SourceLocation IILoc,
12390 TypeSourceInfo **TSI, bool DeducedTSTContext);
12391
12393 SourceLocation KeywordLoc,
12394 NestedNameSpecifierLoc QualifierLoc,
12395 const IdentifierInfo &II, SourceLocation IILoc,
12396 bool DeducedTSTContext = true);
12397
12398 /// Rebuilds a type within the context of the current instantiation.
12399 ///
12400 /// The type \p T is part of the type of an out-of-line member definition of
12401 /// a class template (or class template partial specialization) that was
12402 /// parsed and constructed before we entered the scope of the class template
12403 /// (or partial specialization thereof). This routine will rebuild that type
12404 /// now that we have entered the declarator's scope, which may produce
12405 /// different canonical types, e.g.,
12406 ///
12407 /// \code
12408 /// template<typename T>
12409 /// struct X {
12410 /// typedef T* pointer;
12411 /// pointer data();
12412 /// };
12413 ///
12414 /// template<typename T>
12415 /// typename X<T>::pointer X<T>::data() { ... }
12416 /// \endcode
12417 ///
12418 /// Here, the type "typename X<T>::pointer" will be created as a
12419 /// DependentNameType, since we do not know that we can look into X<T> when we
12420 /// parsed the type. This function will rebuild the type, performing the
12421 /// lookup of "pointer" in X<T> and returning an ElaboratedType whose
12422 /// canonical type is the same as the canonical type of T*, allowing the
12423 /// return types of the out-of-line definition and the declaration to match.
12425 SourceLocation Loc,
12426 DeclarationName Name);
12428
12430
12431 /// Rebuild the template parameters now that we know we're in a current
12432 /// instantiation.
12433 bool
12435
12436 /// Produces a formatted string that describes the binding of
12437 /// template parameters to template arguments.
12438 std::string
12440 const TemplateArgumentList &Args);
12441
12442 std::string
12444 const TemplateArgument *Args,
12445 unsigned NumArgs);
12446
12450
12451 /// ActOnDependentIdExpression - Handle a dependent id-expression that
12452 /// was just parsed. This is only possible with an explicit scope
12453 /// specifier naming a dependent type.
12455 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
12456 const DeclarationNameInfo &NameInfo, bool isAddressOfOperand,
12457 const TemplateArgumentListInfo *TemplateArgs);
12458
12461 SourceLocation TemplateKWLoc,
12462 const DeclarationNameInfo &NameInfo,
12463 const TemplateArgumentListInfo *TemplateArgs);
12464
12465 // Calculates whether the expression Constraint depends on an enclosing
12466 // template, for the purposes of [temp.friend] p9.
12467 // TemplateDepth is the 'depth' of the friend function, which is used to
12468 // compare whether a declaration reference is referring to a containing
12469 // template, or just the current friend function. A 'lower' TemplateDepth in
12470 // the AST refers to a 'containing' template. As the constraint is
12471 // uninstantiated, this is relative to the 'top' of the TU.
12472 bool
12474 unsigned TemplateDepth,
12475 const Expr *Constraint);
12476
12477 /// Find the failed Boolean condition within a given Boolean
12478 /// constant expression, and describe it with a string.
12479 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
12480
12482
12484 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
12485 const IdentifierInfo *Name, SourceLocation NameLoc);
12486
12488 Expr *ConstraintExpr,
12489 const ParsedAttributesView &Attrs);
12490
12492 bool &AddToScope);
12494
12495 TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12496 const CXXScopeSpec &SS,
12497 const IdentifierInfo *Name,
12498 SourceLocation TagLoc, SourceLocation NameLoc);
12499
12501 CachedTokens &Toks);
12504
12505 /// We've found a use of a templated declaration that would trigger an
12506 /// implicit instantiation. Check that any relevant explicit specializations
12507 /// and partial specializations are visible/reachable, and diagnose if not.
12510
12511 ///@}
12512
12513 //
12514 //
12515 // -------------------------------------------------------------------------
12516 //
12517 //
12518
12519 /// \name C++ Template Argument Deduction
12520 /// Implementations are in SemaTemplateDeduction.cpp
12521 ///@{
12522
12523public:
12524 class SFINAETrap;
12525
12528 : S(S), Prev(std::exchange(S.CurrentSFINAEContext, Cur)) {}
12529
12530 protected:
12532 ~SFINAEContextBase() { S.CurrentSFINAEContext = Prev; }
12535
12536 private:
12537 SFINAETrap *Prev;
12538 };
12539
12543
12544 /// RAII class used to determine whether SFINAE has
12545 /// trapped any errors that occur during template argument
12546 /// deduction.
12547 class SFINAETrap : SFINAEContextBase {
12548 bool HasErrorOcurred = false;
12549 bool WithAccessChecking = false;
12550 bool PrevLastDiagnosticIgnored =
12551 S.getDiagnostics().isLastDiagnosticIgnored();
12552 sema::TemplateDeductionInfo *DeductionInfo = nullptr;
12553
12554 SFINAETrap(Sema &S, sema::TemplateDeductionInfo *Info,
12555 bool WithAccessChecking)
12556 : SFINAEContextBase(S, this), WithAccessChecking(WithAccessChecking),
12557 DeductionInfo(Info) {}
12558
12559 public:
12560 /// \param WithAccessChecking If true, discard all diagnostics (from the
12561 /// immediate context) instead of adding them to the currently active
12562 /// \ref TemplateDeductionInfo.
12563 explicit SFINAETrap(Sema &S, bool WithAccessChecking = false)
12564 : SFINAETrap(S, /*Info=*/nullptr, WithAccessChecking) {}
12565
12567 : SFINAETrap(S, &Info, /*WithAccessChecking=*/false) {}
12568
12570 S.getDiagnostics().setLastDiagnosticIgnored(PrevLastDiagnosticIgnored);
12571 }
12572
12573 SFINAETrap(const SFINAETrap &) = delete;
12574 SFINAETrap &operator=(const SFINAETrap &) = delete;
12575
12577 return DeductionInfo;
12578 }
12579
12580 /// Determine whether any SFINAE errors have been trapped.
12581 bool hasErrorOccurred() const { return HasErrorOcurred; }
12582 void setErrorOccurred() { HasErrorOcurred = true; }
12583
12584 bool withAccessChecking() const { return WithAccessChecking; }
12585 };
12586
12587 /// RAII class used to indicate that we are performing provisional
12588 /// semantic analysis to determine the validity of a construct, so
12589 /// typo-correction and diagnostics in the immediate context (not within
12590 /// implicitly-instantiated templates) should be suppressed.
12592 Sema &SemaRef;
12593 // FIXME: Using a SFINAETrap for this is a hack.
12594 SFINAETrap Trap;
12595 bool PrevDisableTypoCorrection;
12596
12597 public:
12598 explicit TentativeAnalysisScope(Sema &SemaRef)
12599 : SemaRef(SemaRef), Trap(SemaRef, /*ForValidityCheck=*/true),
12600 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
12601 SemaRef.DisableTypoCorrection = true;
12602 }
12604 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
12605 }
12606
12609 };
12610
12611 /// For each declaration that involved template argument deduction, the
12612 /// set of diagnostics that were suppressed during that template argument
12613 /// deduction.
12614 ///
12615 /// FIXME: Serialize this structure to the AST file.
12616 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1>>
12619
12620 /// Compare types for equality with respect to possibly compatible
12621 /// function types (noreturn adjustment, implicit calling conventions). If any
12622 /// of parameter and argument is not a function, just perform type comparison.
12623 ///
12624 /// \param P the template parameter type.
12625 ///
12626 /// \param A the argument type.
12628
12629 /// Allocate a TemplateArgumentLoc where all locations have
12630 /// been initialized to the given location.
12631 ///
12632 /// \param Arg The template argument we are producing template argument
12633 /// location information for.
12634 ///
12635 /// \param NTTPType For a declaration template argument, the type of
12636 /// the non-type template parameter that corresponds to this template
12637 /// argument. Can be null if no type sugar is available to add to the
12638 /// type from the template argument.
12639 ///
12640 /// \param Loc The source location to use for the resulting template
12641 /// argument.
12643 QualType NTTPType,
12644 SourceLocation Loc);
12645
12646 /// Get a template argument mapping the given template parameter to itself,
12647 /// e.g. for X in \c template<int X>, this would return an expression template
12648 /// argument referencing X.
12650 SourceLocation Location);
12651
12652 /// Adjust the type \p ArgFunctionType to match the calling convention,
12653 /// noreturn, and optionally the exception specification of \p FunctionType.
12654 /// Deduction often wants to ignore these properties when matching function
12655 /// types.
12657 bool AdjustExceptionSpec = false);
12658
12661 ArrayRef<TemplateArgument> TemplateArgs,
12663
12666 ArrayRef<TemplateArgument> TemplateArgs,
12668
12669 /// Deduce the template arguments of the given template from \p FromType.
12670 /// Used to implement the IsDeducible constraint for alias CTAD per C++
12671 /// [over.match.class.deduct]p4.
12672 ///
12673 /// It only supports class or type alias templates.
12677
12682 bool NumberOfArgumentsMustMatch);
12683
12684 /// Substitute the explicitly-provided template arguments into the
12685 /// given function template according to C++ [temp.arg.explicit].
12686 ///
12687 /// \param FunctionTemplate the function template into which the explicit
12688 /// template arguments will be substituted.
12689 ///
12690 /// \param ExplicitTemplateArgs the explicitly-specified template
12691 /// arguments.
12692 ///
12693 /// \param Deduced the deduced template arguments, which will be populated
12694 /// with the converted and checked explicit template arguments.
12695 ///
12696 /// \param ParamTypes will be populated with the instantiated function
12697 /// parameters.
12698 ///
12699 /// \param FunctionType if non-NULL, the result type of the function template
12700 /// will also be instantiated and the pointed-to value will be updated with
12701 /// the instantiated function type.
12702 ///
12703 /// \param Info if substitution fails for any reason, this object will be
12704 /// populated with more information about the failure.
12705 ///
12706 /// \returns TemplateDeductionResult::Success if substitution was successful,
12707 /// or some failure condition.
12710 TemplateArgumentListInfo &ExplicitTemplateArgs,
12714
12715 /// brief A function argument from which we performed template argument
12716 // deduction for a call.
12729
12730 /// Finish template argument deduction for a function template,
12731 /// checking the deduced template arguments for completeness and forming
12732 /// the function template specialization.
12733 ///
12734 /// \param OriginalCallArgs If non-NULL, the original call arguments against
12735 /// which the deduced argument types should be compared.
12736 /// \param CheckNonDependent Callback before substituting into the declaration
12737 /// with the deduced template arguments.
12738 /// \param OnlyInitializeNonUserDefinedConversions is used as a workaround for
12739 /// some breakages introduced by CWG2369, where non-user-defined conversions
12740 /// are checked first before the constraints.
12744 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
12746 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
12747 bool PartialOverloading, bool PartialOrdering,
12748 bool ForOverloadSetAddressResolution,
12749 llvm::function_ref<bool(bool)> CheckNonDependent =
12750 [](bool /*OnlyInitializeNonUserDefinedConversions*/) {
12751 return false;
12752 });
12753
12754 /// Perform template argument deduction from a function call
12755 /// (C++ [temp.deduct.call]).
12756 ///
12757 /// \param FunctionTemplate the function template for which we are performing
12758 /// template argument deduction.
12759 ///
12760 /// \param ExplicitTemplateArgs the explicit template arguments provided
12761 /// for this call.
12762 ///
12763 /// \param Args the function call arguments
12764 ///
12765 /// \param Specialization if template argument deduction was successful,
12766 /// this will be set to the function template specialization produced by
12767 /// template argument deduction.
12768 ///
12769 /// \param Info the argument will be updated to provide additional information
12770 /// about template argument deduction.
12771 ///
12772 /// \param CheckNonDependent A callback to invoke to check conversions for
12773 /// non-dependent parameters, between deduction and substitution, per DR1391.
12774 /// If this returns true, substitution will be skipped and we return
12775 /// TemplateDeductionResult::NonDependentConversionFailure. The callback is
12776 /// passed the parameter types (after substituting explicit template
12777 /// arguments).
12778 ///
12779 /// \returns the result of template argument deduction.
12782 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12784 bool PartialOverloading, bool AggregateDeductionCandidate,
12785 bool PartialOrdering, QualType ObjectType,
12786 Expr::Classification ObjectClassification,
12787 bool ForOverloadSetAddressResolution,
12788 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent);
12789
12790 /// Deduce template arguments when taking the address of a function
12791 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
12792 /// a template.
12793 ///
12794 /// \param FunctionTemplate the function template for which we are performing
12795 /// template argument deduction.
12796 ///
12797 /// \param ExplicitTemplateArgs the explicitly-specified template
12798 /// arguments.
12799 ///
12800 /// \param ArgFunctionType the function type that will be used as the
12801 /// "argument" type (A) when performing template argument deduction from the
12802 /// function template's function type. This type may be NULL, if there is no
12803 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
12804 ///
12805 /// \param Specialization if template argument deduction was successful,
12806 /// this will be set to the function template specialization produced by
12807 /// template argument deduction.
12808 ///
12809 /// \param Info the argument will be updated to provide additional information
12810 /// about template argument deduction.
12811 ///
12812 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12813 /// the address of a function template per [temp.deduct.funcaddr] and
12814 /// [over.over]. If \c false, we are looking up a function template
12815 /// specialization based on its signature, per [temp.deduct.decl].
12816 ///
12817 /// \returns the result of template argument deduction.
12820 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
12822 bool IsAddressOfFunction = false);
12823
12824 /// Deduce template arguments for a templated conversion
12825 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
12826 /// conversion function template specialization.
12829 Expr::Classification ObjectClassification, QualType ToType,
12831
12832 /// Deduce template arguments for a function template when there is
12833 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
12834 ///
12835 /// \param FunctionTemplate the function template for which we are performing
12836 /// template argument deduction.
12837 ///
12838 /// \param ExplicitTemplateArgs the explicitly-specified template
12839 /// arguments.
12840 ///
12841 /// \param Specialization if template argument deduction was successful,
12842 /// this will be set to the function template specialization produced by
12843 /// template argument deduction.
12844 ///
12845 /// \param Info the argument will be updated to provide additional information
12846 /// about template argument deduction.
12847 ///
12848 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12849 /// the address of a function template in a context where we do not have a
12850 /// target type, per [over.over]. If \c false, we are looking up a function
12851 /// template specialization based on its signature, which only happens when
12852 /// deducing a function parameter type from an argument that is a template-id
12853 /// naming a function template specialization.
12854 ///
12855 /// \returns the result of template argument deduction.
12858 TemplateArgumentListInfo *ExplicitTemplateArgs,
12861 bool IsAddressOfFunction = false);
12862
12863 /// Substitute Replacement for \p auto in \p TypeWithAuto
12864 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
12865 /// Substitute Replacement for auto in TypeWithAuto
12867 QualType Replacement);
12868
12869 // Substitute auto in TypeWithAuto for a Dependent auto type
12871
12872 // Substitute auto in TypeWithAuto for a Dependent auto type
12875
12876 /// Completely replace the \c auto in \p TypeWithAuto by
12877 /// \p Replacement. This does not retain any \c auto type sugar.
12878 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
12880 QualType Replacement);
12881
12882 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
12883 ///
12884 /// Note that this is done even if the initializer is dependent. (This is
12885 /// necessary to support partial ordering of templates using 'auto'.)
12886 /// A dependent type will be produced when deducing from a dependent type.
12887 ///
12888 /// \param Type the type pattern using the auto type-specifier.
12889 /// \param Init the initializer for the variable whose type is to be deduced.
12890 /// \param Result if type deduction was successful, this will be set to the
12891 /// deduced type.
12892 /// \param Info the argument will be updated to provide additional information
12893 /// about template argument deduction.
12894 /// \param DependentDeduction Set if we should permit deduction in
12895 /// dependent cases. This is necessary for template partial ordering
12896 /// with 'auto' template parameters. The template parameter depth to be
12897 /// used should be specified in the 'Info' parameter.
12898 /// \param IgnoreConstraints Set if we should not fail if the deduced type
12899 /// does not satisfy the type-constraint in the auto
12900 /// type.
12904 bool DependentDeduction = false,
12905 bool IgnoreConstraints = false,
12906 TemplateSpecCandidateSet *FailedTSC = nullptr);
12907 void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init);
12909 bool Diagnose = true);
12910
12912 SourceLocation Loc);
12913
12914 /// Returns the more specialized class template partial specialization
12915 /// according to the rules of partial ordering of class template partial
12916 /// specializations (C++ [temp.class.order]).
12917 ///
12918 /// \param PS1 the first class template partial specialization
12919 ///
12920 /// \param PS2 the second class template partial specialization
12921 ///
12922 /// \returns the more specialized class template partial specialization. If
12923 /// neither partial specialization is more specialized, returns NULL.
12928
12931
12935
12938
12940 TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
12941 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
12942 bool PartialOrdering, bool *StrictPackMatch);
12943
12944 /// Mark which template parameters are used in a given expression.
12945 ///
12946 /// \param E the expression from which template parameters will be deduced.
12947 ///
12948 /// \param Used a bit vector whose elements will be set to \c true
12949 /// to indicate when the corresponding template parameter will be
12950 /// deduced.
12951 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
12952 unsigned Depth, llvm::SmallBitVector &Used);
12953
12954 /// Mark which template parameters are named in a given expression.
12955 ///
12956 /// Unlike MarkUsedTemplateParameters, this excludes parameter that
12957 /// are used but not directly named by an expression - i.e. it excludes
12958 /// any template parameter that denotes the type of a referenced NTTP.
12959 ///
12960 /// \param Used a bit vector whose elements will be set to \c true
12961 /// to indicate when the corresponding template parameter will be
12962 /// deduced.
12964 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used);
12965
12966 /// Mark which template parameters can be deduced from a given
12967 /// template argument list.
12968 ///
12969 /// \param TemplateArgs the template argument list from which template
12970 /// parameters will be deduced.
12971 ///
12972 /// \param Used a bit vector whose elements will be set to \c true
12973 /// to indicate when the corresponding template parameter will be
12974 /// deduced.
12975 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
12976 bool OnlyDeduced, unsigned Depth,
12977 llvm::SmallBitVector &Used);
12978
12980 unsigned Depth, llvm::SmallBitVector &Used);
12981
12983 unsigned Depth, llvm::SmallBitVector &Used);
12984
12985 void
12990
12991 /// Marks all of the template parameters that will be deduced by a
12992 /// call to the given function template.
12993 static void
12996 llvm::SmallBitVector &Deduced);
12997
12998 /// Returns the more specialized function template according
12999 /// to the rules of function template partial ordering (C++
13000 /// [temp.func.order]).
13001 ///
13002 /// \param FT1 the first function template
13003 ///
13004 /// \param FT2 the second function template
13005 ///
13006 /// \param TPOC the context in which we are performing partial ordering of
13007 /// function templates.
13008 ///
13009 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
13010 /// only when \c TPOC is \c TPOC_Call. Does not include the object argument
13011 /// when calling a member function.
13012 ///
13013 /// \param RawObj1Ty The type of the object parameter of FT1 if a member
13014 /// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function
13015 /// template from a member function
13016 ///
13017 /// \param RawObj2Ty The type of the object parameter of FT2 if a member
13018 /// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function
13019 /// template from a member function
13020 ///
13021 /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
13022 /// candidate with a reversed parameter order. In this case, the corresponding
13023 /// P/A pairs between FT1 and FT2 are reversed.
13024 ///
13025 /// \returns the more specialized function template. If neither
13026 /// template is more specialized, returns NULL.
13029 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
13030 QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false,
13031 bool PartialOverloading = false);
13032
13033 /// Retrieve the most specialized of the given function template
13034 /// specializations.
13035 ///
13036 /// \param SpecBegin the start iterator of the function template
13037 /// specializations that we will be comparing.
13038 ///
13039 /// \param SpecEnd the end iterator of the function template
13040 /// specializations, paired with \p SpecBegin.
13041 ///
13042 /// \param Loc the location where the ambiguity or no-specializations
13043 /// diagnostic should occur.
13044 ///
13045 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
13046 /// no matching candidates.
13047 ///
13048 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
13049 /// occurs.
13050 ///
13051 /// \param CandidateDiag partial diagnostic used for each function template
13052 /// specialization that is a candidate in the ambiguous ordering. One
13053 /// parameter in this diagnostic should be unbound, which will correspond to
13054 /// the string describing the template arguments for the function template
13055 /// specialization.
13056 ///
13057 /// \returns the most specialized function template specialization, if
13058 /// found. Otherwise, returns SpecEnd.
13059 UnresolvedSetIterator
13060 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
13061 TemplateSpecCandidateSet &FailedCandidates,
13062 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
13063 const PartialDiagnostic &AmbigDiag,
13064 const PartialDiagnostic &CandidateDiag,
13065 bool Complain = true, QualType TargetType = QualType());
13066
13067 /// Returns the more constrained function according to the rules of
13068 /// partial ordering by constraints (C++ [temp.constr.order]).
13069 ///
13070 /// \param FD1 the first function
13071 ///
13072 /// \param FD2 the second function
13073 ///
13074 /// \returns the more constrained function. If neither function is
13075 /// more constrained, returns NULL.
13076 FunctionDecl *getMoreConstrainedFunction(FunctionDecl *FD1,
13077 FunctionDecl *FD2);
13078
13079 ///@}
13080
13081 //
13082 //
13083 // -------------------------------------------------------------------------
13084 //
13085 //
13086
13087 /// \name C++ Template Deduction Guide
13088 /// Implementations are in SemaTemplateDeductionGuide.cpp
13089 ///@{
13090
13091 /// Declare implicit deduction guides for a class template if we've
13092 /// not already done so.
13093 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
13094 SourceLocation Loc);
13095
13096 CXXDeductionGuideDecl *DeclareAggregateDeductionGuideFromInitList(
13097 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
13098 SourceLocation Loc);
13099
13100 ///@}
13101
13102 //
13103 //
13104 // -------------------------------------------------------------------------
13105 //
13106 //
13107
13108 /// \name C++ Template Instantiation
13109 /// Implementations are in SemaTemplateInstantiate.cpp
13110 ///@{
13111
13112public:
13113 /// A helper class for building up ExtParameterInfos.
13116 bool HasInteresting = false;
13117
13118 public:
13119 /// Set the ExtParameterInfo for the parameter at the given index,
13120 ///
13122 assert(Infos.size() <= index);
13123 Infos.resize(index);
13124 Infos.push_back(info);
13125
13126 if (!HasInteresting)
13127 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
13128 }
13129
13130 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
13131 /// ExtParameterInfo array we've built up.
13133 getPointerOrNull(unsigned numParams) {
13134 if (!HasInteresting)
13135 return nullptr;
13136 Infos.resize(numParams);
13137 return Infos.data();
13138 }
13139 };
13140
13141 /// The current instantiation scope used to store local
13142 /// variables.
13144
13145 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
13147
13148 /// A mapping from parameters with unparsed default arguments to the
13149 /// set of instantiations of each parameter.
13150 ///
13151 /// This mapping is a temporary data structure used when parsing
13152 /// nested class templates or nested classes of class templates,
13153 /// where we might end up instantiating an inner class before the
13154 /// default arguments of its methods have been parsed.
13156
13157 using InstantiatingSpecializationsKey = llvm::PointerIntPair<Decl *, 2>;
13158
13165
13167 : S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
13168 auto [_, Created] = S.InstantiatingSpecializations.insert(Key);
13169 if (!Created)
13170 Key = {};
13171 }
13172
13174 if (Key.getOpaqueValue()) {
13175 [[maybe_unused]] bool Erased =
13176 S.InstantiatingSpecializations.erase(Key);
13177 assert(Erased);
13178 }
13179 }
13180
13183
13184 operator bool() const { return Key.getOpaqueValue() == nullptr; }
13185
13186 private:
13187 Sema &S;
13189 };
13190
13191 /// A context in which code is being synthesized (where a source location
13192 /// alone is not sufficient to identify the context). This covers template
13193 /// instantiation and various forms of implicitly-generated functions.
13195 /// The kind of template instantiation we are performing
13197 /// We are instantiating a template declaration. The entity is
13198 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
13200
13201 /// We are instantiating a default argument for a template
13202 /// parameter. The Entity is the template parameter whose argument is
13203 /// being instantiated, the Template is the template, and the
13204 /// TemplateArgs/NumTemplateArguments provide the template arguments as
13205 /// specified.
13207
13208 /// We are instantiating a default argument for a function.
13209 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
13210 /// provides the template arguments as specified.
13212
13213 /// We are substituting explicit template arguments provided for
13214 /// a function template. The entity is a FunctionTemplateDecl.
13216
13217 /// We are substituting template argument determined as part of
13218 /// template argument deduction for either a class template
13219 /// partial specialization or a function template. The
13220 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
13221 /// a TemplateDecl.
13223
13224 /// We are substituting into a lambda expression.
13226
13227 /// We are substituting prior template arguments into a new
13228 /// template parameter. The template parameter itself is either a
13229 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
13231
13232 /// We are checking the validity of a default template argument that
13233 /// has been used when naming a template-id.
13235
13236 /// We are computing the exception specification for a defaulted special
13237 /// member function.
13239
13240 /// We are instantiating the exception specification for a function
13241 /// template which was deferred until it was needed.
13243
13244 /// We are instantiating a requirement of a requires expression.
13246
13247 /// We are checking the satisfaction of a nested requirement of a requires
13248 /// expression.
13250
13251 /// We are declaring an implicit special member function.
13253
13254 /// We are declaring an implicit 'operator==' for a defaulted
13255 /// 'operator<=>'.
13257
13258 /// We are defining a synthesized function (such as a defaulted special
13259 /// member).
13261
13262 // We are checking the constraints associated with a constrained entity or
13263 // the constraint expression of a concept. This includes the checks that
13264 // atomic constraints have the type 'bool' and that they can be constant
13265 // evaluated.
13267
13268 // We are substituting template arguments into a constraint expression.
13270
13271 // Instantiating a Requires Expression parameter clause.
13273
13274 // We are substituting into the parameter mapping of an atomic constraint
13275 // during normalization.
13277
13278 /// We are rewriting a comparison operator in terms of an operator<=>.
13280
13281 /// We are initializing a structured binding.
13283
13284 /// We are marking a class as __dllexport.
13286
13287 /// We are building an implied call from __builtin_dump_struct. The
13288 /// arguments are in CallArgs.
13290
13291 /// Added for Template instantiation observation.
13292 /// Memoization means we are _not_ instantiating a template because
13293 /// it is already instantiated (but we entered a context where we
13294 /// would have had to if it was not already instantiated).
13296
13297 /// We are building deduction guides for a class.
13299
13300 /// We are instantiating a type alias template declaration.
13302
13303 /// We are performing partial ordering for template template parameters.
13305
13306 /// We are performing name lookup for a function template or variable
13307 /// template named 'sycl_kernel_launch'.
13309
13310 /// We are performing overload resolution for a call to a function
13311 /// template or variable template named 'sycl_kernel_launch'.
13313 } Kind;
13314
13315 /// Whether we're substituting into constraints.
13317
13318 /// Whether we're substituting into the parameter mapping of a constraint.
13320
13321 /// The point of instantiation or synthesis within the source code.
13323
13324 /// The entity that is being synthesized.
13326
13327 /// The template (or partial specialization) in which we are
13328 /// performing the instantiation, for substitutions of prior template
13329 /// arguments.
13331
13332 union {
13333 /// The list of template arguments we are substituting, if they
13334 /// are not part of the entity.
13336
13337 /// The list of argument expressions in a synthesized call.
13338 const Expr *const *CallArgs;
13339 };
13340
13341 // FIXME: Wrap this union around more members, or perhaps store the
13342 // kind-specific members in the RAII object owning the context.
13343 union {
13344 /// The number of template arguments in TemplateArgs.
13346
13347 /// The number of expressions in CallArgs.
13348 unsigned NumCallArgs;
13349
13350 /// The special member being declared or defined.
13352 };
13353
13358
13359 /// The source range that covers the construct that cause
13360 /// the instantiation, e.g., the template-id that causes a class
13361 /// template instantiation.
13363
13368
13369 /// Determines whether this template is an actual instantiation
13370 /// that should be counted toward the maximum instantiation depth.
13371 bool isInstantiationRecord() const;
13372 };
13373
13374 /// A stack object to be created when performing template
13375 /// instantiation.
13376 ///
13377 /// Construction of an object of type \c InstantiatingTemplate
13378 /// pushes the current instantiation onto the stack of active
13379 /// instantiations. If the size of this stack exceeds the maximum
13380 /// number of recursive template instantiations, construction
13381 /// produces an error and evaluates true.
13382 ///
13383 /// Destruction of this object will pop the named instantiation off
13384 /// the stack.
13386 /// Note that we are instantiating a class template,
13387 /// function template, variable template, alias template,
13388 /// or a member thereof.
13389 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13390 Decl *Entity,
13391 SourceRange InstantiationRange = SourceRange());
13392
13394 /// Note that we are instantiating an exception specification
13395 /// of a function template.
13396 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13398 SourceRange InstantiationRange = SourceRange());
13399
13400 /// Note that we are instantiating a type alias template declaration.
13401 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13402 TypeAliasTemplateDecl *Entity,
13403 ArrayRef<TemplateArgument> TemplateArgs,
13404 SourceRange InstantiationRange = SourceRange());
13405
13406 /// Note that we are instantiating a default argument in a
13407 /// template-id.
13408 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13410 ArrayRef<TemplateArgument> TemplateArgs,
13411 SourceRange InstantiationRange = SourceRange());
13412
13413 /// Note that we are substituting either explicitly-specified or
13414 /// deduced template arguments during function template argument deduction.
13415 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13417 ArrayRef<TemplateArgument> TemplateArgs,
13419 SourceRange InstantiationRange = SourceRange());
13420
13421 /// Note that we are instantiating as part of template
13422 /// argument deduction for a class template declaration.
13423 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13425 ArrayRef<TemplateArgument> TemplateArgs,
13426 SourceRange InstantiationRange = SourceRange());
13427
13428 /// Note that we are instantiating as part of template
13429 /// argument deduction for a class template partial
13430 /// specialization.
13431 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13433 ArrayRef<TemplateArgument> TemplateArgs,
13434 SourceRange InstantiationRange = SourceRange());
13435
13436 /// Note that we are instantiating as part of template
13437 /// argument deduction for a variable template partial
13438 /// specialization.
13439 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13441 ArrayRef<TemplateArgument> TemplateArgs,
13442 SourceRange InstantiationRange = SourceRange());
13443
13444 /// Note that we are instantiating a default argument for a function
13445 /// parameter.
13446 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13447 ParmVarDecl *Param,
13448 ArrayRef<TemplateArgument> TemplateArgs,
13449 SourceRange InstantiationRange = SourceRange());
13450
13451 /// Note that we are substituting prior template arguments into a
13452 /// non-type parameter.
13453 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13455 ArrayRef<TemplateArgument> TemplateArgs,
13456 SourceRange InstantiationRange);
13457
13458 /// Note that we are substituting prior template arguments into a
13459 /// template template parameter.
13460 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13462 ArrayRef<TemplateArgument> TemplateArgs,
13463 SourceRange InstantiationRange);
13464
13465 /// Note that we are checking the default template argument
13466 /// against the template parameter for a given template-id.
13467 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13469 ArrayRef<TemplateArgument> TemplateArgs,
13470 SourceRange InstantiationRange);
13471
13473 /// \brief Note that we are checking the constraints associated with some
13474 /// constrained entity (a concept declaration or a template with associated
13475 /// constraints).
13476 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13478 ArrayRef<TemplateArgument> TemplateArgs,
13479 SourceRange InstantiationRange);
13480
13482 /// \brief Note that we are checking a constraint expression associated
13483 /// with a template declaration or as part of the satisfaction check of a
13484 /// concept.
13485 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13487 SourceRange InstantiationRange);
13488
13490 /// \brief Note that we are subtituting into the parameter mapping of an
13491 /// atomic constraint during constraint normalization.
13492 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13494 SourceRange InstantiationRange);
13495
13496 /// \brief Note that we are substituting template arguments into a part of
13497 /// a requirement of a requires expression.
13498 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13500 SourceRange InstantiationRange = SourceRange());
13501
13502 /// \brief Note that we are checking the satisfaction of the constraint
13503 /// expression inside of a nested requirement.
13504 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13506 SourceRange InstantiationRange = SourceRange());
13507
13508 /// \brief Note that we are checking a requires clause.
13509 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13510 const RequiresExpr *E,
13511 SourceRange InstantiationRange);
13512
13514 /// \brief Note that we are building deduction guides.
13515 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13517 SourceRange InstantiationRange = SourceRange());
13518
13520 /// \brief Note that we are partial ordering template template parameters.
13521 InstantiatingTemplate(Sema &SemaRef, SourceLocation ArgLoc,
13523 SourceRange InstantiationRange = SourceRange());
13524
13525 /// Note that we have finished instantiating this template.
13526 void Clear();
13527
13529
13530 /// Determines whether we have exceeded the maximum
13531 /// recursive template instantiations.
13532 bool isInvalid() const { return Invalid; }
13533
13534 private:
13535 Sema &SemaRef;
13536 bool Invalid;
13537
13540 SourceLocation PointOfInstantiation,
13541 SourceRange InstantiationRange, Decl *Entity,
13542 NamedDecl *Template = nullptr,
13543 ArrayRef<TemplateArgument> TemplateArgs = {});
13544
13546
13547 InstantiatingTemplate &operator=(const InstantiatingTemplate &) = delete;
13548 };
13549
13550 bool SubstTemplateArgument(const TemplateArgumentLoc &Input,
13551 const MultiLevelTemplateArgumentList &TemplateArgs,
13552 TemplateArgumentLoc &Output,
13553 SourceLocation Loc = {},
13554 const DeclarationName &Entity = {});
13555 bool
13556 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
13557 const MultiLevelTemplateArgumentList &TemplateArgs,
13558 TemplateArgumentListInfo &Outputs);
13559
13560 /// Substitute concept template arguments in the constraint expression
13561 /// of a concept-id. This is used to implement [temp.constr.normal].
13563 SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE,
13564 const Expr *ConstraintExpr,
13565 const MultiLevelTemplateArgumentList &MLTAL);
13566
13568 ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,
13569 const MultiLevelTemplateArgumentList &TemplateArgs,
13570 TemplateArgumentListInfo &Out);
13571
13572 /// Retrieve the template argument list(s) that should be used to
13573 /// instantiate the definition of the given declaration.
13574 ///
13575 /// \param ND the declaration for which we are computing template
13576 /// instantiation arguments.
13577 ///
13578 /// \param DC In the event we don't HAVE a declaration yet, we instead provide
13579 /// the decl context where it will be created. In this case, the `Innermost`
13580 /// should likely be provided. If ND is non-null, this is ignored.
13581 ///
13582 /// \param Innermost if non-NULL, specifies a template argument list for the
13583 /// template declaration passed as ND.
13584 ///
13585 /// \param RelativeToPrimary true if we should get the template
13586 /// arguments relative to the primary template, even when we're
13587 /// dealing with a specialization. This is only relevant for function
13588 /// template specializations.
13589 ///
13590 /// \param Pattern If non-NULL, indicates the pattern from which we will be
13591 /// instantiating the definition of the given declaration, \p ND. This is
13592 /// used to determine the proper set of template instantiation arguments for
13593 /// friend function template specializations.
13594 ///
13595 /// \param ForConstraintInstantiation when collecting arguments,
13596 /// ForConstraintInstantiation indicates we should continue looking when
13597 /// encountering a lambda generic call operator, and continue looking for
13598 /// arguments on an enclosing class template.
13599 ///
13600 /// \param SkipForSpecialization when specified, any template specializations
13601 /// in a traversal would be ignored.
13602 ///
13603 /// \param ForDefaultArgumentSubstitution indicates we should continue looking
13604 /// when encountering a specialized member function template, rather than
13605 /// returning immediately.
13606 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
13607 const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
13608 std::optional<ArrayRef<TemplateArgument>> Innermost = std::nullopt,
13609 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr,
13610 bool ForConstraintInstantiation = false,
13611 bool SkipForSpecialization = false,
13612 bool ForDefaultArgumentSubstitution = false);
13613
13614 /// RAII object to handle the state changes required to synthesize
13615 /// a function body.
13617 Sema &S;
13618 Sema::ContextRAII SavedContext;
13619 bool PushedCodeSynthesisContext = false;
13620
13621 public:
13623 : S(S), SavedContext(S, DC) {
13624 auto *FD = dyn_cast<FunctionDecl>(DC);
13625 S.PushFunctionScope();
13626 S.PushExpressionEvaluationContextForFunction(
13628 if (FD)
13629 FD->setWillHaveBody(true);
13630 else
13631 assert(isa<ObjCMethodDecl>(DC));
13632 }
13633
13635 assert(!PushedCodeSynthesisContext);
13636
13639 Ctx.PointOfInstantiation = UseLoc;
13640 Ctx.Entity = cast<Decl>(S.CurContext);
13641 S.pushCodeSynthesisContext(Ctx);
13642
13643 PushedCodeSynthesisContext = true;
13644 }
13645
13647 if (PushedCodeSynthesisContext)
13648 S.popCodeSynthesisContext();
13649 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
13650 FD->setWillHaveBody(false);
13651 S.CheckImmediateEscalatingFunctionDefinition(FD, S.getCurFunction());
13652 }
13653 S.PopExpressionEvaluationContext();
13654 S.PopFunctionScopeInfo();
13655 }
13656
13660 };
13661
13662 /// RAII object to ensure that a code synthesis context is popped on scope
13663 /// exit.
13665 Sema &S;
13666
13667 public:
13669 : S(S) {
13670 S.pushCodeSynthesisContext(Ctx);
13671 }
13672
13673 ~ScopedCodeSynthesisContext() { S.popCodeSynthesisContext(); }
13677 };
13678
13679 /// List of active code synthesis contexts.
13680 ///
13681 /// This vector is treated as a stack. As synthesis of one entity requires
13682 /// synthesis of another, additional contexts are pushed onto the stack.
13684
13685 /// Specializations whose definitions are currently being instantiated.
13686 llvm::DenseSet<InstantiatingSpecializationsKey> InstantiatingSpecializations;
13687
13688 /// Non-dependent types used in templates that have already been instantiated
13689 /// by some template instantiation.
13690 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
13691
13692 /// Extra modules inspected when performing a lookup during a template
13693 /// instantiation. Computed lazily.
13695
13696 /// Cache of additional modules that should be used for name lookup
13697 /// within the current template instantiation. Computed lazily; use
13698 /// getLookupModules() to get a complete set.
13699 llvm::DenseSet<Module *> LookupModulesCache;
13700
13701 /// Map from the most recent declaration of a namespace to the most
13702 /// recent visible declaration of that namespace.
13703 llvm::DenseMap<NamedDecl *, NamedDecl *> VisibleNamespaceCache;
13704
13706
13707 /// The number of \p CodeSynthesisContexts that are not template
13708 /// instantiations and, therefore, should not be counted as part of the
13709 /// instantiation depth.
13710 ///
13711 /// When the instantiation depth reaches the user-configurable limit
13712 /// \p LangOptions::InstantiationDepth we will abort instantiation.
13713 // FIXME: Should we have a similar limit for other forms of synthesis?
13715
13716 /// The depth of the context stack at the point when the most recent
13717 /// error or warning was produced.
13718 ///
13719 /// This value is used to suppress printing of redundant context stacks
13720 /// when there are multiple errors or warnings in the same instantiation.
13721 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
13723
13724 /// The template instantiation callbacks to trace or track
13725 /// instantiations (objects can be chained).
13726 ///
13727 /// This callbacks is used to print, trace or track template
13728 /// instantiations as they are being constructed.
13729 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
13731
13732 /// The current index into pack expansion arguments that will be
13733 /// used for substitution of parameter packs.
13734 ///
13735 /// The pack expansion index will be none to indicate that parameter packs
13736 /// should be instantiated as themselves. Otherwise, the index specifies
13737 /// which argument within the parameter pack will be used for substitution.
13739
13740 /// RAII object used to change the argument pack substitution index
13741 /// within a \c Sema object.
13742 ///
13743 /// See \c ArgPackSubstIndex for more information.
13745 Sema &Self;
13746 UnsignedOrNone OldSubstIndex;
13747
13748 public:
13750 : Self(Self),
13751 OldSubstIndex(std::exchange(Self.ArgPackSubstIndex, NewSubstIndex)) {}
13752
13753 ~ArgPackSubstIndexRAII() { Self.ArgPackSubstIndex = OldSubstIndex; }
13756 };
13757
13760
13771 /// Prints the current instantiation stack through a series of
13772 /// notes.
13777
13778 /// Returns a pointer to the current SFINAE context, if any.
13779 [[nodiscard]] SFINAETrap *getSFINAEContext() const {
13780 return CurrentSFINAEContext;
13781 }
13782 [[nodiscard]] bool isSFINAEContext() const {
13783 return CurrentSFINAEContext != nullptr;
13784 }
13785
13786 /// Perform substitution on the type T with a given set of template
13787 /// arguments.
13788 ///
13789 /// This routine substitutes the given template arguments into the
13790 /// type T and produces the instantiated type.
13791 ///
13792 /// \param T the type into which the template arguments will be
13793 /// substituted. If this type is not dependent, it will be returned
13794 /// immediately.
13795 ///
13796 /// \param Args the template arguments that will be
13797 /// substituted for the top-level template parameters within T.
13798 ///
13799 /// \param Loc the location in the source code where this substitution
13800 /// is being performed. It will typically be the location of the
13801 /// declarator (if we're instantiating the type of some declaration)
13802 /// or the location of the type in the source code (if, e.g., we're
13803 /// instantiating the type of a cast expression).
13804 ///
13805 /// \param Entity the name of the entity associated with a declaration
13806 /// being instantiated (if any). May be empty to indicate that there
13807 /// is no such entity (if, e.g., this is a type that occurs as part of
13808 /// a cast expression) or that the entity has no name (e.g., an
13809 /// unnamed function parameter).
13810 ///
13811 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
13812 /// acceptable as the top level type of the result.
13813 ///
13814 /// \param IsIncompleteSubstitution If provided, the pointee will be set
13815 /// whenever substitution would perform a replacement with a null or
13816 /// non-existent template argument.
13817 ///
13818 /// \returns If the instantiation succeeds, the instantiated
13819 /// type. Otherwise, produces diagnostics and returns a NULL type.
13821 const MultiLevelTemplateArgumentList &TemplateArgs,
13822 SourceLocation Loc, DeclarationName Entity,
13823 bool AllowDeducedTST = false);
13824
13826 const MultiLevelTemplateArgumentList &TemplateArgs,
13827 SourceLocation Loc, DeclarationName Entity,
13828 bool *IsIncompleteSubstitution = nullptr);
13829
13831 const MultiLevelTemplateArgumentList &TemplateArgs,
13832 SourceLocation Loc, DeclarationName Entity);
13833
13834 /// A form of SubstType intended specifically for instantiating the
13835 /// type of a FunctionDecl. Its purpose is solely to force the
13836 /// instantiation of default-argument expressions and to avoid
13837 /// instantiating an exception-specification.
13839 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
13840 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
13841 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
13843 const MultiLevelTemplateArgumentList &Args);
13846 SmallVectorImpl<QualType> &ExceptionStorage,
13847 const MultiLevelTemplateArgumentList &Args);
13848 ParmVarDecl *
13850 const MultiLevelTemplateArgumentList &TemplateArgs,
13851 int indexAdjustment, UnsignedOrNone NumExpansions,
13852 bool ExpectParameterPack, bool EvaluateConstraints = true);
13853
13854 /// Substitute the given template arguments into the given set of
13855 /// parameters, producing the set of parameter types that would be generated
13856 /// from such a substitution.
13858 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
13859 const MultiLevelTemplateArgumentList &TemplateArgs,
13860 SmallVectorImpl<QualType> &ParamTypes,
13862 ExtParameterInfoBuilder &ParamInfos);
13863
13864 /// Substitute the given template arguments into the default argument.
13866 const MultiLevelTemplateArgumentList &TemplateArgs,
13867 bool ForCallExpr = false);
13869 const MultiLevelTemplateArgumentList &TemplateArgs);
13870 /// Substitute an expression as if it is a address-of-operand, which makes it
13871 /// act like a CXXIdExpression rather than an attempt to call.
13873 const MultiLevelTemplateArgumentList &TemplateArgs);
13874
13875 // A RAII type used by the TemplateDeclInstantiator and TemplateInstantiator
13876 // to disable constraint evaluation, then restore the state.
13877 template <typename InstTy> struct ConstraintEvalRAII {
13878 InstTy &TI;
13880
13882 : TI(TI), OldValue(TI.getEvaluateConstraints()) {
13883 TI.setEvaluateConstraints(false);
13884 }
13885 ~ConstraintEvalRAII() { TI.setEvaluateConstraints(OldValue); }
13888 };
13889
13890 // Must be used instead of SubstExpr at 'constraint checking' time.
13893 const MultiLevelTemplateArgumentList &TemplateArgs);
13894 // Unlike the above, this does not evaluate constraints.
13896 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs);
13897
13898 /// Substitute the given template arguments into a list of
13899 /// expressions, expanding pack expansions if required.
13900 ///
13901 /// \param Exprs The list of expressions to substitute into.
13902 ///
13903 /// \param IsCall Whether this is some form of call, in which case
13904 /// default arguments will be dropped.
13905 ///
13906 /// \param TemplateArgs The set of template arguments to substitute.
13907 ///
13908 /// \param Outputs Will receive all of the substituted arguments.
13909 ///
13910 /// \returns true if an error occurred, false otherwise.
13911 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
13912 const MultiLevelTemplateArgumentList &TemplateArgs,
13913 SmallVectorImpl<Expr *> &Outputs);
13914
13916 const MultiLevelTemplateArgumentList &TemplateArgs);
13917
13920 bool CXXDirectInit);
13921
13922 /// Perform substitution on the base class specifiers of the
13923 /// given class template specialization.
13924 ///
13925 /// Produces a diagnostic and returns true on error, returns false and
13926 /// attaches the instantiated base classes to the class template
13927 /// specialization if successful.
13928 bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13929 const MultiLevelTemplateArgumentList &TemplateArgs);
13930
13931 /// Instantiate the definition of a class from a given pattern.
13932 ///
13933 /// \param PointOfInstantiation The point of instantiation within the
13934 /// source code.
13935 ///
13936 /// \param Instantiation is the declaration whose definition is being
13937 /// instantiated. This will be either a class template specialization
13938 /// or a member class of a class template specialization.
13939 ///
13940 /// \param Pattern is the pattern from which the instantiation
13941 /// occurs. This will be either the declaration of a class template or
13942 /// the declaration of a member class of a class template.
13943 ///
13944 /// \param TemplateArgs The template arguments to be substituted into
13945 /// the pattern.
13946 ///
13947 /// \param TSK the kind of implicit or explicit instantiation to perform.
13948 ///
13949 /// \param Complain whether to complain if the class cannot be instantiated
13950 /// due to the lack of a definition.
13951 ///
13952 /// \returns true if an error occurred, false otherwise.
13953 bool InstantiateClass(SourceLocation PointOfInstantiation,
13954 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13955 const MultiLevelTemplateArgumentList &TemplateArgs,
13956 TemplateSpecializationKind TSK, bool Complain = true);
13957
13958private:
13959 bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
13960 CXXRecordDecl *Instantiation,
13961 CXXRecordDecl *Pattern,
13962 const MultiLevelTemplateArgumentList &TemplateArgs,
13963 TemplateSpecializationKind TSK, bool Complain);
13964
13965public:
13966 /// Instantiate the definition of an enum from a given pattern.
13967 ///
13968 /// \param PointOfInstantiation The point of instantiation within the
13969 /// source code.
13970 /// \param Instantiation is the declaration whose definition is being
13971 /// instantiated. This will be a member enumeration of a class
13972 /// temploid specialization, or a local enumeration within a
13973 /// function temploid specialization.
13974 /// \param Pattern The templated declaration from which the instantiation
13975 /// occurs.
13976 /// \param TemplateArgs The template arguments to be substituted into
13977 /// the pattern.
13978 /// \param TSK The kind of implicit or explicit instantiation to perform.
13979 ///
13980 /// \return \c true if an error occurred, \c false otherwise.
13981 bool InstantiateEnum(SourceLocation PointOfInstantiation,
13982 EnumDecl *Instantiation, EnumDecl *Pattern,
13983 const MultiLevelTemplateArgumentList &TemplateArgs,
13985
13986 /// Instantiate the definition of a field from the given pattern.
13987 ///
13988 /// \param PointOfInstantiation The point of instantiation within the
13989 /// source code.
13990 /// \param Instantiation is the declaration whose definition is being
13991 /// instantiated. This will be a class of a class temploid
13992 /// specialization, or a local enumeration within a function temploid
13993 /// specialization.
13994 /// \param Pattern The templated declaration from which the instantiation
13995 /// occurs.
13996 /// \param TemplateArgs The template arguments to be substituted into
13997 /// the pattern.
13998 ///
13999 /// \return \c true if an error occurred, \c false otherwise.
14001 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
14002 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
14003
14005 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
14006
14008 SourceLocation PointOfInstantiation,
14009 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14010 TemplateSpecializationKind TSK, bool Complain,
14011 bool PrimaryStrictPackMatch);
14012
14013 /// Instantiates the definitions of all of the member
14014 /// of the given class, which is an instantiation of a class template
14015 /// or a member class of a template.
14016 void
14017 InstantiateClassMembers(SourceLocation PointOfInstantiation,
14018 CXXRecordDecl *Instantiation,
14019 const MultiLevelTemplateArgumentList &TemplateArgs,
14021
14022 /// Instantiate the definitions of all of the members of the
14023 /// given class template specialization, which was named as part of an
14024 /// explicit instantiation.
14026 SourceLocation PointOfInstantiation,
14027 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14029
14032 const MultiLevelTemplateArgumentList &TemplateArgs);
14033
14034 /// Do template substitution on declaration name info.
14037 const MultiLevelTemplateArgumentList &TemplateArgs);
14039 SubstTemplateName(SourceLocation TemplateKWLoc,
14040 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
14041 SourceLocation NameLoc,
14042 const MultiLevelTemplateArgumentList &TemplateArgs);
14043
14045 const MultiLevelTemplateArgumentList &TemplateArgs,
14046 bool EvaluateConstraint);
14047
14048 /// Determine whether we are currently performing template instantiation.
14051 }
14052
14053 /// Determine whether we are currently performing constraint substitution.
14055 return !CodeSynthesisContexts.empty() &&
14056 CodeSynthesisContexts.back().InConstraintSubstitution;
14057 }
14058
14060 return !CodeSynthesisContexts.empty() &&
14061 CodeSynthesisContexts.back().InParameterMappingSubstitution &&
14063 }
14064
14065 using EntityPrinter = llvm::function_ref<void(llvm::raw_ostream &)>;
14066
14067 /// \brief create a Requirement::SubstitutionDiagnostic with only a
14068 /// SubstitutedEntity and DiagLoc using ASTContext's allocator.
14071
14072 ///@}
14073
14074 //
14075 //
14076 // -------------------------------------------------------------------------
14077 //
14078 //
14079
14080 /// \name C++ Template Declaration Instantiation
14081 /// Implementations are in SemaTemplateInstantiateDecl.cpp
14082 ///@{
14083
14084public:
14085 /// An entity for which implicit template instantiation is required.
14086 ///
14087 /// The source location associated with the declaration is the first place in
14088 /// the source code where the declaration was "used". It is not necessarily
14089 /// the point of instantiation (which will be either before or after the
14090 /// namespace-scope declaration that triggered this implicit instantiation),
14091 /// However, it is the location that diagnostics should generally refer to,
14092 /// because users will need to know what code triggered the instantiation.
14093 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
14094
14095 /// The queue of implicit template instantiations that are required
14096 /// but have not yet been performed.
14097 std::deque<PendingImplicitInstantiation> PendingInstantiations;
14098
14099 /// Queue of implicit template instantiations that cannot be performed
14100 /// eagerly.
14102
14106
14107 /// The queue of implicit template instantiations that are required
14108 /// and must be performed within the current local scope.
14109 ///
14110 /// This queue is only used for member functions of local classes in
14111 /// templates, which must be instantiated in the same scope as their
14112 /// enclosing function, so that they can reference function-local
14113 /// types, static variables, enumerators, etc.
14114 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
14115
14117 public:
14119 : S(S), AtEndOfTU(AtEndOfTU) {
14120 SavedPendingLocalImplicitInstantiations.swap(
14121 S.PendingLocalImplicitInstantiations);
14122 }
14123
14124 void perform() {
14125 S.PerformPendingInstantiations(/*LocalOnly=*/true,
14126 /*AtEndOfTU=*/AtEndOfTU);
14127 }
14128
14130 assert(S.PendingLocalImplicitInstantiations.empty() &&
14131 "there shouldn't be any pending local implicit instantiations");
14132 SavedPendingLocalImplicitInstantiations.swap(
14133 S.PendingLocalImplicitInstantiations);
14134 }
14135
14139
14140 private:
14141 Sema &S;
14142 bool AtEndOfTU;
14143 std::deque<PendingImplicitInstantiation>
14144 SavedPendingLocalImplicitInstantiations;
14145 };
14146
14147 /// Records and restores the CurFPFeatures state on entry/exit of compound
14148 /// statements.
14150 public:
14155 FPOptionsOverride getOverrides() { return OldOverrides; }
14156
14157 private:
14158 Sema &S;
14159 FPOptions OldFPFeaturesState;
14160 FPOptionsOverride OldOverrides;
14161 LangOptions::FPEvalMethodKind OldEvalMethod;
14162 SourceLocation OldFPPragmaLocation;
14163 };
14164
14166 public:
14167 GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
14168 : S(S), Enabled(Enabled), AtEndOfTU(AtEndOfTU) {
14169 if (!Enabled)
14170 return;
14171
14172 S.SavedPendingInstantiations.emplace_back();
14173 S.SavedPendingInstantiations.back().swap(S.PendingInstantiations);
14174
14175 S.SavedVTableUses.emplace_back();
14176 S.SavedVTableUses.back().swap(S.VTableUses);
14177 }
14178
14179 void perform() {
14180 if (Enabled) {
14181 S.DefineUsedVTables();
14182 S.PerformPendingInstantiations(/*LocalOnly=*/false,
14183 /*AtEndOfTU=*/AtEndOfTU);
14184 }
14185 }
14186
14188 if (!Enabled)
14189 return;
14190
14191 // Restore the set of pending vtables.
14192 assert(S.VTableUses.empty() &&
14193 "VTableUses should be empty before it is discarded.");
14194 S.VTableUses.swap(S.SavedVTableUses.back());
14195 S.SavedVTableUses.pop_back();
14196
14197 // Restore the set of pending implicit instantiations.
14198 if ((S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) &&
14199 AtEndOfTU) {
14200 assert(S.PendingInstantiations.empty() &&
14201 "PendingInstantiations should be empty before it is discarded.");
14202 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
14203 S.SavedPendingInstantiations.pop_back();
14204 } else {
14205 // Template instantiations in the PCH may be delayed until the TU.
14206 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
14207 S.PendingInstantiations.insert(
14208 S.PendingInstantiations.end(),
14209 S.SavedPendingInstantiations.back().begin(),
14210 S.SavedPendingInstantiations.back().end());
14211 S.SavedPendingInstantiations.pop_back();
14212 }
14213 }
14214
14216 delete;
14219
14220 private:
14221 Sema &S;
14222 bool Enabled;
14223 bool AtEndOfTU;
14224 };
14225
14227 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES);
14228
14239
14240 /// Recheck instantiated thread-safety attributes that could not be validated
14241 /// on the dependent pattern declaration.
14242 bool checkInstantiatedThreadSafetyAttrs(const Decl *D, const Attr *A);
14243
14244 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
14245 const Decl *Pattern, Decl *Inst,
14246 LateInstantiatedAttrVec *LateAttrs = nullptr,
14247 LocalInstantiationScope *OuterMostScope = nullptr);
14248
14249 /// Update instantiation attributes after template was late parsed.
14250 ///
14251 /// Some attributes are evaluated based on the body of template. If it is
14252 /// late parsed, such attributes cannot be evaluated when declaration is
14253 /// instantiated. This function is used to update instantiation attributes
14254 /// when template definition is ready.
14255 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
14256
14257 void
14259 const Decl *Pattern, Decl *Inst,
14260 LateInstantiatedAttrVec *LateAttrs = nullptr,
14261 LocalInstantiationScope *OuterMostScope = nullptr);
14262
14264 bool IsCopy = false);
14265
14267 ParmVarDecl *Param);
14268 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
14270
14271 /// Instantiate (or find existing instantiation of) a function template with a
14272 /// given set of template arguments.
14273 ///
14274 /// Usually this should not be used, and template argument deduction should be
14275 /// used in its place.
14278 SourceLocation Loc,
14281
14282 /// Instantiate the definition of the given function from its
14283 /// template.
14284 ///
14285 /// \param PointOfInstantiation the point at which the instantiation was
14286 /// required. Note that this is not precisely a "point of instantiation"
14287 /// for the function, but it's close.
14288 ///
14289 /// \param Function the already-instantiated declaration of a
14290 /// function template specialization or member function of a class template
14291 /// specialization.
14292 ///
14293 /// \param Recursive if true, recursively instantiates any functions that
14294 /// are required by this instantiation.
14295 ///
14296 /// \param DefinitionRequired if true, then we are performing an explicit
14297 /// instantiation where the body of the function is required. Complain if
14298 /// there is no such body.
14299 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
14301 bool Recursive = false,
14302 bool DefinitionRequired = false,
14303 bool AtEndOfTU = false);
14306 const TemplateArgumentList *PartialSpecArgs,
14308 SourceLocation PointOfInstantiation,
14309 LateInstantiatedAttrVec *LateAttrs = nullptr,
14310 LocalInstantiationScope *StartingScope = nullptr);
14311
14312 /// Instantiates a variable template specialization by completing it
14313 /// with appropriate type information and initializer.
14315 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
14316 const MultiLevelTemplateArgumentList &TemplateArgs);
14317
14318 /// BuildVariableInstantiation - Used after a new variable has been created.
14319 /// Sets basic variable data and decides whether to postpone the
14320 /// variable instantiation.
14321 void
14323 const MultiLevelTemplateArgumentList &TemplateArgs,
14324 LateInstantiatedAttrVec *LateAttrs,
14325 DeclContext *Owner,
14326 LocalInstantiationScope *StartingScope,
14327 bool InstantiatingVarTemplate = false,
14328 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
14329
14330 /// Instantiate the initializer of a variable.
14332 VarDecl *Var, VarDecl *OldVar,
14333 const MultiLevelTemplateArgumentList &TemplateArgs);
14334
14335 /// Instantiate the definition of the given variable from its
14336 /// template.
14337 ///
14338 /// \param PointOfInstantiation the point at which the instantiation was
14339 /// required. Note that this is not precisely a "point of instantiation"
14340 /// for the variable, but it's close.
14341 ///
14342 /// \param Var the already-instantiated declaration of a templated variable.
14343 ///
14344 /// \param Recursive if true, recursively instantiates any functions that
14345 /// are required by this instantiation.
14346 ///
14347 /// \param DefinitionRequired if true, then we are performing an explicit
14348 /// instantiation where a definition of the variable is required. Complain
14349 /// if there is no such definition.
14350 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
14351 VarDecl *Var, bool Recursive = false,
14352 bool DefinitionRequired = false,
14353 bool AtEndOfTU = false);
14354
14357 const MultiLevelTemplateArgumentList &TemplateArgs);
14358
14359 /// Find the instantiation of the given declaration within the
14360 /// current instantiation.
14361 ///
14362 /// This routine is intended to be used when \p D is a declaration
14363 /// referenced from within a template, that needs to mapped into the
14364 /// corresponding declaration within an instantiation. For example,
14365 /// given:
14366 ///
14367 /// \code
14368 /// template<typename T>
14369 /// struct X {
14370 /// enum Kind {
14371 /// KnownValue = sizeof(T)
14372 /// };
14373 ///
14374 /// bool getKind() const { return KnownValue; }
14375 /// };
14376 ///
14377 /// template struct X<int>;
14378 /// \endcode
14379 ///
14380 /// In the instantiation of X<int>::getKind(), we need to map the \p
14381 /// EnumConstantDecl for \p KnownValue (which refers to
14382 /// X<T>::<Kind>::KnownValue) to its instantiation
14383 /// (X<int>::<Kind>::KnownValue).
14384 /// \p FindInstantiatedDecl performs this mapping from within the
14385 /// instantiation of X<int>.
14386 NamedDecl *
14388 const MultiLevelTemplateArgumentList &TemplateArgs,
14389 bool FindingInstantiatedContext = false);
14390
14391 /// Finds the instantiation of the given declaration context
14392 /// within the current instantiation.
14393 ///
14394 /// \returns NULL if there was an error
14395 DeclContext *
14397 const MultiLevelTemplateArgumentList &TemplateArgs);
14398
14399 Decl *SubstDecl(Decl *D, DeclContext *Owner,
14400 const MultiLevelTemplateArgumentList &TemplateArgs);
14401
14402 /// Substitute the name and return type of a defaulted 'operator<=>' to form
14403 /// an implicit 'operator=='.
14405 FunctionDecl *Spaceship);
14406
14407 /// Performs template instantiation for all implicit template
14408 /// instantiations we have seen until this point.
14409 void PerformPendingInstantiations(bool LocalOnly = false,
14410 bool AtEndOfTU = true);
14411
14414 const MultiLevelTemplateArgumentList &TemplateArgs,
14415 bool EvaluateConstraints = true);
14416
14418 const DeclContext *Pattern,
14419 const MultiLevelTemplateArgumentList &TemplateArgs);
14420
14421private:
14422 /// Introduce the instantiated local variables into the local
14423 /// instantiation scope.
14424 void addInstantiatedLocalVarsToScope(FunctionDecl *Function,
14425 const FunctionDecl *PatternDecl,
14427 /// Introduce the instantiated function parameters into the local
14428 /// instantiation scope, and set the parameter names to those used
14429 /// in the template.
14430 bool addInstantiatedParametersToScope(
14431 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14433 const MultiLevelTemplateArgumentList &TemplateArgs);
14434
14435 /// Introduce the instantiated captures of the lambda into the local
14436 /// instantiation scope.
14437 bool addInstantiatedCapturesToScope(
14438 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14440 const MultiLevelTemplateArgumentList &TemplateArgs);
14441
14442 int ParsingClassDepth = 0;
14443
14444 class SavePendingParsedClassStateRAII {
14445 public:
14446 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
14447
14448 ~SavePendingParsedClassStateRAII() {
14449 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
14450 "there shouldn't be any pending delayed exception spec checks");
14451 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
14452 "there shouldn't be any pending delayed exception spec checks");
14453 swapSavedState();
14454 }
14455
14456 SavePendingParsedClassStateRAII(const SavePendingParsedClassStateRAII &) =
14457 delete;
14458 SavePendingParsedClassStateRAII &
14459 operator=(const SavePendingParsedClassStateRAII &) = delete;
14460
14461 private:
14462 Sema &S;
14464 SavedOverridingExceptionSpecChecks;
14466 SavedEquivalentExceptionSpecChecks;
14467
14468 void swapSavedState() {
14469 SavedOverridingExceptionSpecChecks.swap(
14470 S.DelayedOverridingExceptionSpecChecks);
14471 SavedEquivalentExceptionSpecChecks.swap(
14472 S.DelayedEquivalentExceptionSpecChecks);
14473 }
14474 };
14475
14476 ///@}
14477
14478 //
14479 //
14480 // -------------------------------------------------------------------------
14481 //
14482 //
14483
14484 /// \name C++ Variadic Templates
14485 /// Implementations are in SemaTemplateVariadic.cpp
14486 ///@{
14487
14488public:
14489 /// Determine whether an unexpanded parameter pack might be permitted in this
14490 /// location. Useful for error recovery.
14492
14493 /// The context in which an unexpanded parameter pack is
14494 /// being diagnosed.
14495 ///
14496 /// Note that the values of this enumeration line up with the first
14497 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
14499 /// An arbitrary expression.
14501
14502 /// The base type of a class type.
14504
14505 /// The type of an arbitrary declaration.
14507
14508 /// The type of a data member.
14510
14511 /// The size of a bit-field.
14513
14514 /// The expression in a static assertion.
14516
14517 /// The fixed underlying type of an enumeration.
14519
14520 /// The enumerator value.
14522
14523 /// A using declaration.
14525
14526 /// A friend declaration.
14528
14529 /// A declaration qualifier.
14531
14532 /// An initializer.
14534
14535 /// A default argument.
14537
14538 /// The type of a non-type template parameter.
14540
14541 /// The type of an exception.
14543
14544 /// Explicit specialization.
14546
14547 /// Partial specialization.
14549
14550 /// Microsoft __if_exists.
14552
14553 /// Microsoft __if_not_exists.
14555
14556 /// Lambda expression.
14558
14559 /// Block expression.
14561
14562 /// A type constraint.
14564
14565 // A requirement in a requires-expression.
14567
14568 // A requires-clause.
14570 };
14571
14572 /// Diagnose unexpanded parameter packs.
14573 ///
14574 /// \param Loc The location at which we should emit the diagnostic.
14575 ///
14576 /// \param UPPC The context in which we are diagnosing unexpanded
14577 /// parameter packs.
14578 ///
14579 /// \param Unexpanded the set of unexpanded parameter packs.
14580 ///
14581 /// \returns true if an error occurred, false otherwise.
14585
14586 /// If the given type contains an unexpanded parameter pack,
14587 /// diagnose the error.
14588 ///
14589 /// \param Loc The source location where a diagnostc should be emitted.
14590 ///
14591 /// \param T The type that is being checked for unexpanded parameter
14592 /// packs.
14593 ///
14594 /// \returns true if an error occurred, false otherwise.
14597
14598 /// If the given expression contains an unexpanded parameter
14599 /// pack, diagnose the error.
14600 ///
14601 /// \param E The expression that is being checked for unexpanded
14602 /// parameter packs.
14603 ///
14604 /// \returns true if an error occurred, false otherwise.
14607
14608 /// If the given requirees-expression contains an unexpanded reference to one
14609 /// of its own parameter packs, diagnose the error.
14610 ///
14611 /// \param RE The requiress-expression that is being checked for unexpanded
14612 /// parameter packs.
14613 ///
14614 /// \returns true if an error occurred, false otherwise.
14616
14617 /// If the given nested-name-specifier contains an unexpanded
14618 /// parameter pack, diagnose the error.
14619 ///
14620 /// \param SS The nested-name-specifier that is being checked for
14621 /// unexpanded parameter packs.
14622 ///
14623 /// \returns true if an error occurred, false otherwise.
14626
14627 /// If the given name contains an unexpanded parameter pack,
14628 /// diagnose the error.
14629 ///
14630 /// \param NameInfo The name (with source location information) that
14631 /// is being checked for unexpanded parameter packs.
14632 ///
14633 /// \returns true if an error occurred, false otherwise.
14636
14637 /// If the given template name contains an unexpanded parameter pack,
14638 /// diagnose the error.
14639 ///
14640 /// \param Loc The location of the template name.
14641 ///
14642 /// \param Template The template name that is being checked for unexpanded
14643 /// parameter packs.
14644 ///
14645 /// \returns true if an error occurred, false otherwise.
14649
14650 /// If the given template argument contains an unexpanded parameter
14651 /// pack, diagnose the error.
14652 ///
14653 /// \param Arg The template argument that is being checked for unexpanded
14654 /// parameter packs.
14655 ///
14656 /// \returns true if an error occurred, false otherwise.
14659
14660 /// Collect the set of unexpanded parameter packs within the given
14661 /// template argument.
14662 ///
14663 /// \param Arg The template argument that will be traversed to find
14664 /// unexpanded parameter packs.
14666 TemplateArgument Arg,
14668
14669 /// Collect the set of unexpanded parameter packs within the given
14670 /// template argument.
14671 ///
14672 /// \param Arg The template argument that will be traversed to find
14673 /// unexpanded parameter packs.
14677
14678 /// Collect the set of unexpanded parameter packs within the given
14679 /// type.
14680 ///
14681 /// \param T The type that will be traversed to find
14682 /// unexpanded parameter packs.
14685
14686 /// Collect the set of unexpanded parameter packs within the given
14687 /// type.
14688 ///
14689 /// \param TL The type that will be traversed to find
14690 /// unexpanded parameter packs.
14693
14694 /// Collect the set of unexpanded parameter packs within the given
14695 /// nested-name-specifier.
14696 ///
14697 /// \param NNS The nested-name-specifier that will be traversed to find
14698 /// unexpanded parameter packs.
14702
14703 /// Collect the set of unexpanded parameter packs within the given
14704 /// name.
14705 ///
14706 /// \param NameInfo The name that will be traversed to find
14707 /// unexpanded parameter packs.
14709 const DeclarationNameInfo &NameInfo,
14711
14712 /// Collect the set of unexpanded parameter packs within the given
14713 /// expression.
14716
14717 /// Invoked when parsing a template argument.
14718 ///
14719 /// \param Arg the template argument, which may already be invalid.
14720 ///
14721 /// If it is followed by ellipsis, this function is called before
14722 /// `ActOnPackExpansion`.
14725
14726 /// Invoked when parsing a template argument followed by an
14727 /// ellipsis, which creates a pack expansion.
14728 ///
14729 /// \param Arg The template argument preceding the ellipsis, which
14730 /// may already be invalid.
14731 ///
14732 /// \param EllipsisLoc The location of the ellipsis.
14734 SourceLocation EllipsisLoc);
14735
14736 /// Invoked when parsing a type followed by an ellipsis, which
14737 /// creates a pack expansion.
14738 ///
14739 /// \param Type The type preceding the ellipsis, which will become
14740 /// the pattern of the pack expansion.
14741 ///
14742 /// \param EllipsisLoc The location of the ellipsis.
14744
14745 /// Construct a pack expansion type from the pattern of the pack
14746 /// expansion.
14748 SourceLocation EllipsisLoc,
14749 UnsignedOrNone NumExpansions);
14750
14751 /// Construct a pack expansion type from the pattern of the pack
14752 /// expansion.
14753 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
14754 SourceLocation EllipsisLoc,
14755 UnsignedOrNone NumExpansions);
14756
14757 /// Invoked when parsing an expression followed by an ellipsis, which
14758 /// creates a pack expansion.
14759 ///
14760 /// \param Pattern The expression preceding the ellipsis, which will become
14761 /// the pattern of the pack expansion.
14762 ///
14763 /// \param EllipsisLoc The location of the ellipsis.
14764 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
14765
14766 /// Invoked when parsing an expression followed by an ellipsis, which
14767 /// creates a pack expansion.
14768 ///
14769 /// \param Pattern The expression preceding the ellipsis, which will become
14770 /// the pattern of the pack expansion.
14771 ///
14772 /// \param EllipsisLoc The location of the ellipsis.
14773 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
14774 UnsignedOrNone NumExpansions);
14775
14776 /// Determine whether we could expand a pack expansion with the
14777 /// given set of parameter packs into separate arguments by repeatedly
14778 /// transforming the pattern.
14779 ///
14780 /// \param EllipsisLoc The location of the ellipsis that identifies the
14781 /// pack expansion.
14782 ///
14783 /// \param PatternRange The source range that covers the entire pattern of
14784 /// the pack expansion.
14785 ///
14786 /// \param Unexpanded The set of unexpanded parameter packs within the
14787 /// pattern.
14788 ///
14789 /// \param ShouldExpand Will be set to \c true if the transformer should
14790 /// expand the corresponding pack expansions into separate arguments. When
14791 /// set, \c NumExpansions must also be set.
14792 ///
14793 /// \param RetainExpansion Whether the caller should add an unexpanded
14794 /// pack expansion after all of the expanded arguments. This is used
14795 /// when extending explicitly-specified template argument packs per
14796 /// C++0x [temp.arg.explicit]p9.
14797 ///
14798 /// \param NumExpansions The number of separate arguments that will be in
14799 /// the expanded form of the corresponding pack expansion. This is both an
14800 /// input and an output parameter, which can be set by the caller if the
14801 /// number of expansions is known a priori (e.g., due to a prior substitution)
14802 /// and will be set by the callee when the number of expansions is known.
14803 /// The callee must set this value when \c ShouldExpand is \c true; it may
14804 /// set this value in other cases.
14805 ///
14806 /// \returns true if an error occurred (e.g., because the parameter packs
14807 /// are to be instantiated with arguments of different lengths), false
14808 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
14809 /// must be set.
14811 SourceLocation EllipsisLoc, SourceRange PatternRange,
14813 const MultiLevelTemplateArgumentList &TemplateArgs,
14814 bool FailOnPackProducingTemplates, bool &ShouldExpand,
14815 bool &RetainExpansion, UnsignedOrNone &NumExpansions,
14816 bool Diagnose = true);
14817
14818 /// Determine the number of arguments in the given pack expansion
14819 /// type.
14820 ///
14821 /// This routine assumes that the number of arguments in the expansion is
14822 /// consistent across all of the unexpanded parameter packs in its pattern.
14823 ///
14824 /// Returns an empty Optional if the type can't be expanded.
14826 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
14827
14830 const MultiLevelTemplateArgumentList &TemplateArgs);
14831
14832 /// Determine whether the given declarator contains any unexpanded
14833 /// parameter packs.
14834 ///
14835 /// This routine is used by the parser to disambiguate function declarators
14836 /// with an ellipsis prior to the ')', e.g.,
14837 ///
14838 /// \code
14839 /// void f(T...);
14840 /// \endcode
14841 ///
14842 /// To determine whether we have an (unnamed) function parameter pack or
14843 /// a variadic function.
14844 ///
14845 /// \returns true if the declarator contains any unexpanded parameter packs,
14846 /// false otherwise.
14848
14849 /// Returns the pattern of the pack expansion for a template argument.
14850 ///
14851 /// \param OrigLoc The template argument to expand.
14852 ///
14853 /// \param Ellipsis Will be set to the location of the ellipsis.
14854 ///
14855 /// \param NumExpansions Will be set to the number of expansions that will
14856 /// be generated from this pack expansion, if known a priori.
14859 SourceLocation &Ellipsis,
14860 UnsignedOrNone &NumExpansions) const;
14861
14862 /// Given a template argument that contains an unexpanded parameter pack, but
14863 /// which has already been substituted, attempt to determine the number of
14864 /// elements that will be produced once this argument is fully-expanded.
14865 ///
14866 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
14867 /// avoid actually expanding the pack where possible.
14869
14870 /// Called when an expression computing the size of a parameter pack
14871 /// is parsed.
14872 ///
14873 /// \code
14874 /// template<typename ...Types> struct count {
14875 /// static const unsigned value = sizeof...(Types);
14876 /// };
14877 /// \endcode
14878 ///
14879 //
14880 /// \param OpLoc The location of the "sizeof" keyword.
14881 /// \param Name The name of the parameter pack whose size will be determined.
14882 /// \param NameLoc The source location of the name of the parameter pack.
14883 /// \param RParenLoc The location of the closing parentheses.
14885 IdentifierInfo &Name,
14886 SourceLocation NameLoc,
14887 SourceLocation RParenLoc);
14888
14889 ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression,
14890 SourceLocation EllipsisLoc,
14891 SourceLocation LSquareLoc, Expr *IndexExpr,
14892 SourceLocation RSquareLoc);
14893
14894 ExprResult BuildPackIndexingExpr(Expr *PackExpression,
14895 SourceLocation EllipsisLoc, Expr *IndexExpr,
14896 SourceLocation RSquareLoc,
14897 ArrayRef<Expr *> ExpandedExprs = {},
14898 bool FullySubstituted = false);
14899
14900 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
14901 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
14902 tok::TokenKind Operator,
14903 SourceLocation EllipsisLoc, Expr *RHS,
14904 SourceLocation RParenLoc);
14905 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
14906 SourceLocation LParenLoc, Expr *LHS,
14907 BinaryOperatorKind Operator,
14908 SourceLocation EllipsisLoc, Expr *RHS,
14909 SourceLocation RParenLoc,
14910 UnsignedOrNone NumExpansions);
14911 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
14912 BinaryOperatorKind Operator);
14913
14914 ///@}
14915
14916 //
14917 //
14918 // -------------------------------------------------------------------------
14919 //
14920 //
14921
14922 /// \name Constraints and Concepts
14923 /// Implementations are in SemaConcept.cpp
14924 ///@{
14925
14926public:
14927 ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI);
14928
14929 ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc,
14930 TypeSourceInfo *TSI);
14931
14932public:
14934 const llvm::FoldingSetNodeID &ID) {
14935 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
14936 SatisfactionStack.emplace_back(Can, ID);
14937 }
14938
14939 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
14940
14942 const llvm::FoldingSetNodeID &ID) const {
14943 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
14944 return llvm::is_contained(SatisfactionStack,
14945 SatisfactionStackEntryTy{Can, ID});
14946 }
14947
14949 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
14950
14951 // Resets the current SatisfactionStack for cases where we are instantiating
14952 // constraints as a 'side effect' of normal instantiation in a way that is not
14953 // indicative of recursive definition.
14956 Sema &SemaRef;
14957
14958 public:
14960 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
14961 }
14962
14964 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
14965 }
14966
14970 };
14971
14974 SatisfactionStack.swap(NewSS);
14975 }
14976
14978 llvm::PointerUnion<const NamedDecl *,
14980
14981 /// Check whether the given expression is a valid constraint expression.
14982 /// A diagnostic is emitted if it is not, false is returned, and
14983 /// PossibleNonPrimary will be set to true if the failure might be due to a
14984 /// non-primary expression being used as an atomic constraint.
14985 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
14986 bool *PossibleNonPrimary = nullptr,
14987 bool IsTrailingRequiresClause = false);
14988
14989 /// \brief Check whether the given list of constraint expressions are
14990 /// satisfied (as if in a 'conjunction') given template arguments.
14991 /// \param Template the template-like entity that triggered the constraints
14992 /// check (either a concept or a constrained entity).
14993 /// \param ConstraintExprs a list of constraint expressions, treated as if
14994 /// they were 'AND'ed together.
14995 /// \param TemplateArgLists the list of template arguments to substitute into
14996 /// the constraint expression.
14997 /// \param TemplateIDRange The source range of the template id that
14998 /// caused the constraints check.
14999 /// \param Satisfaction if true is returned, will contain details of the
15000 /// satisfaction, with enough information to diagnose an unsatisfied
15001 /// expression.
15002 /// \returns true if an error occurred and satisfaction could not be checked,
15003 /// false otherwise.
15006 ArrayRef<AssociatedConstraint> AssociatedConstraints,
15007 const MultiLevelTemplateArgumentList &TemplateArgLists,
15008 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction,
15009 const ConceptReference *TopLevelConceptId = nullptr,
15010 Expr **ConvertedExpr = nullptr);
15011
15012 /// Check whether the given function decl's trailing requires clause is
15013 /// satisfied, if any. Returns false and updates Satisfaction with the
15014 /// satisfaction verdict if successful, emits a diagnostic and returns true if
15015 /// an error occurred and satisfaction could not be determined.
15016 ///
15017 /// \returns true if an error occurred, false otherwise.
15019 ConstraintSatisfaction &Satisfaction,
15020 SourceLocation UsageLoc = SourceLocation(),
15021 bool ForOverloadResolution = false);
15022
15023 // Calculates whether two constraint expressions are equal irrespective of a
15024 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
15025 // 'New', which are the "source" of the constraint, since this is necessary
15026 // for figuring out the relative 'depth' of the constraint. The depth of the
15027 // 'primary template' and the 'instantiated from' templates aren't necessarily
15028 // the same, such as a case when one is a 'friend' defined in a class.
15030 const Expr *OldConstr,
15032 const Expr *NewConstr);
15033
15034 // Calculates whether the friend function depends on an enclosing template for
15035 // the purposes of [temp.friend] p9.
15037
15038 /// \brief Ensure that the given template arguments satisfy the constraints
15039 /// associated with the given template, emitting a diagnostic if they do not.
15040 ///
15041 /// \param Template The template to which the template arguments are being
15042 /// provided.
15043 ///
15044 /// \param TemplateArgs The converted, canonicalized template arguments.
15045 ///
15046 /// \param TemplateIDRange The source range of the template id that
15047 /// caused the constraints check.
15048 ///
15049 /// \returns true if the constrains are not satisfied or could not be checked
15050 /// for satisfaction, false if the constraints are satisfied.
15053 const MultiLevelTemplateArgumentList &TemplateArgs,
15054 SourceRange TemplateIDRange);
15055
15056 bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation,
15058 ArrayRef<TemplateArgument> TemplateArgs,
15059 ConstraintSatisfaction &Satisfaction);
15060
15061 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15062 /// unsatisfied.
15063 /// \param First whether this is the first time an unsatisfied constraint is
15064 /// diagnosed for this error.
15066 SourceLocation Loc = {},
15067 bool First = true);
15068
15069 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15070 /// unsatisfied.
15071 void
15073 bool First = true);
15074
15077 ArrayRef<AssociatedConstraint> AssociatedConstraints);
15078
15079 /// \brief Check whether the given declaration's associated constraints are
15080 /// at least as constrained than another declaration's according to the
15081 /// partial ordering of constraints.
15082 ///
15083 /// \param Result If no error occurred, receives the result of true if D1 is
15084 /// at least constrained than D2, and false otherwise.
15085 ///
15086 /// \returns true if an error occurred, false otherwise.
15087 bool IsAtLeastAsConstrained(const NamedDecl *D1,
15089 const NamedDecl *D2,
15091 bool &Result);
15092
15093 /// If D1 was not at least as constrained as D2, but would've been if a pair
15094 /// of atomic constraints involved had been declared in a concept and not
15095 /// repeated in two separate places in code.
15096 /// \returns true if such a diagnostic was emitted, false otherwise.
15100
15101 /// Cache the satisfaction of an atomic constraint.
15102 /// The key is based on the unsubstituted expression and the parameter
15103 /// mapping. This lets us not substituting the mapping more than once,
15104 /// which is (very!) expensive.
15105 /// FIXME: this should be private.
15106 llvm::DenseMap<llvm::FoldingSetNodeID,
15109
15110 /// Cache the instantiation results of template parameter mappings within
15111 /// concepts. Substituting into normalized concepts can be extremely expensive
15112 /// due to the redundancy of template parameters. This cache is intended for
15113 /// use by TemplateInstantiator to avoid redundant semantic checking.
15114 llvm::DenseMap<llvm::FoldingSetNodeID, TemplateArgumentLoc>
15116
15117private:
15118 /// Caches pairs of template-like decls whose associated constraints were
15119 /// checked for subsumption and whether or not the first's constraints did in
15120 /// fact subsume the second's.
15121 llvm::DenseMap<std::pair<const NamedDecl *, const NamedDecl *>, bool>
15122 SubsumptionCache;
15123 /// Caches the normalized associated constraints of declarations (concepts or
15124 /// constrained declarations). If an error occurred while normalizing the
15125 /// associated constraints of the template or concept, nullptr will be cached
15126 /// here.
15127 llvm::DenseMap<ConstrainedDeclOrNestedRequirement, NormalizedConstraint *>
15128 NormalizationCache;
15129
15130 /// Cache whether the associated constraint of a declaration
15131 /// is satisfied.
15132 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
15133 SatisfactionCache;
15134
15135 // The current stack of constraint satisfactions, so we can exit-early.
15137
15138 /// Used by SetupConstraintCheckingTemplateArgumentsAndScope to set up the
15139 /// LocalInstantiationScope of the current non-lambda function. For lambdas,
15140 /// use LambdaScopeForCallOperatorInstantiationRAII.
15141 bool
15142 SetupConstraintScope(FunctionDecl *FD,
15143 std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15144 const MultiLevelTemplateArgumentList &MLTAL,
15146
15147 /// Used during constraint checking, sets up the constraint template argument
15148 /// lists, and calls SetupConstraintScope to set up the
15149 /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
15150 std::optional<MultiLevelTemplateArgumentList>
15151 SetupConstraintCheckingTemplateArgumentsAndScope(
15152 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15154
15155 ///@}
15156
15157 //
15158 //
15159 // -------------------------------------------------------------------------
15160 //
15161 //
15162
15163 /// \name Types
15164 /// Implementations are in SemaType.cpp
15165 ///@{
15166
15167public:
15168 /// A mapping that describes the nullability we've seen in each header file.
15170
15171 static int getPrintable(int I) { return I; }
15172 static unsigned getPrintable(unsigned I) { return I; }
15173 static bool getPrintable(bool B) { return B; }
15174 static const char *getPrintable(const char *S) { return S; }
15175 static StringRef getPrintable(StringRef S) { return S; }
15176 static const std::string &getPrintable(const std::string &S) { return S; }
15177 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
15178 return II;
15179 }
15181 static QualType getPrintable(QualType T) { return T; }
15182 static SourceRange getPrintable(SourceRange R) { return R; }
15184 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
15186
15187 enum class CompleteTypeKind {
15188 /// Apply the normal rules for complete types. In particular,
15189 /// treat all sizeless types as incomplete.
15191
15192 /// Relax the normal rules for complete types so that they include
15193 /// sizeless built-in types.
15195
15196 // FIXME: Eventually we should flip the default to Normal and opt in
15197 // to AcceptSizeless rather than opt out of it.
15199 };
15200
15202 const DeclSpec *DS = nullptr);
15203 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
15204 const DeclSpec *DS = nullptr);
15205
15206 /// Build a pointer type.
15207 ///
15208 /// \param T The type to which we'll be building a pointer.
15209 ///
15210 /// \param Loc The location of the entity whose type involves this
15211 /// pointer type or, if there is no such entity, the location of the
15212 /// type that will have pointer type.
15213 ///
15214 /// \param Entity The name of the entity that involves the pointer
15215 /// type, if known.
15216 ///
15217 /// \returns A suitable pointer type, if there are no
15218 /// errors. Otherwise, returns a NULL type.
15220 DeclarationName Entity);
15221
15222 /// Build a reference type.
15223 ///
15224 /// \param T The type to which we'll be building a reference.
15225 ///
15226 /// \param Loc The location of the entity whose type involves this
15227 /// reference type or, if there is no such entity, the location of the
15228 /// type that will have reference type.
15229 ///
15230 /// \param Entity The name of the entity that involves the reference
15231 /// type, if known.
15232 ///
15233 /// \returns A suitable reference type, if there are no
15234 /// errors. Otherwise, returns a NULL type.
15235 QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc,
15236 DeclarationName Entity);
15237
15238 /// Build an array type.
15239 ///
15240 /// \param T The type of each element in the array.
15241 ///
15242 /// \param ASM C99 array size modifier (e.g., '*', 'static').
15243 ///
15244 /// \param ArraySize Expression describing the size of the array.
15245 ///
15246 /// \param Brackets The range from the opening '[' to the closing ']'.
15247 ///
15248 /// \param Entity The name of the entity that involves the array
15249 /// type, if known.
15250 ///
15251 /// \returns A suitable array type, if there are no errors. Otherwise,
15252 /// returns a NULL type.
15254 unsigned Quals, SourceRange Brackets,
15255 DeclarationName Entity);
15256 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
15257
15258 /// Build an ext-vector type.
15259 ///
15260 /// Run the required checks for the extended vector type.
15262 SourceLocation AttrLoc);
15263 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
15264 SourceLocation AttrLoc);
15265
15267 Expr *CountExpr,
15268 bool CountInBytes,
15269 bool OrNull);
15270
15271 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an
15272 /// expression is uninstantiated. If instantiated it will apply the
15273 /// appropriate address space to the type. This function allows dependent
15274 /// template variables to be used in conjunction with the address_space
15275 /// attribute
15276 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
15277 SourceLocation AttrLoc);
15278
15279 /// Same as above, but constructs the AddressSpace index if not provided.
15281 SourceLocation AttrLoc);
15282
15284
15286
15287 /// Build a function type.
15288 ///
15289 /// This routine checks the function type according to C++ rules and
15290 /// under the assumption that the result type and parameter types have
15291 /// just been instantiated from a template. It therefore duplicates
15292 /// some of the behavior of GetTypeForDeclarator, but in a much
15293 /// simpler form that is only suitable for this narrow use case.
15294 ///
15295 /// \param T The return type of the function.
15296 ///
15297 /// \param ParamTypes The parameter types of the function. This array
15298 /// will be modified to account for adjustments to the types of the
15299 /// function parameters.
15300 ///
15301 /// \param Loc The location of the entity whose type involves this
15302 /// function type or, if there is no such entity, the location of the
15303 /// type that will have function type.
15304 ///
15305 /// \param Entity The name of the entity that involves the function
15306 /// type, if known.
15307 ///
15308 /// \param EPI Extra information about the function type. Usually this will
15309 /// be taken from an existing function with the same prototype.
15310 ///
15311 /// \returns A suitable function type, if there are no errors. The
15312 /// unqualified type will always be a FunctionProtoType.
15313 /// Otherwise, returns a NULL type.
15315 SourceLocation Loc, DeclarationName Entity,
15317
15318 /// Build a member pointer type \c T Class::*.
15319 ///
15320 /// \param T the type to which the member pointer refers.
15321 /// \param Class the class type into which the member pointer points.
15322 /// \param Loc the location where this type begins
15323 /// \param Entity the name of the entity that will have this member pointer
15324 /// type
15325 ///
15326 /// \returns a member pointer type, if successful, or a NULL type if there was
15327 /// an error.
15329 CXXRecordDecl *Cls, SourceLocation Loc,
15330 DeclarationName Entity);
15331
15332 /// Build a block pointer type.
15333 ///
15334 /// \param T The type to which we'll be building a block pointer.
15335 ///
15336 /// \param Loc The source location, used for diagnostics.
15337 ///
15338 /// \param Entity The name of the entity that involves the block pointer
15339 /// type, if known.
15340 ///
15341 /// \returns A suitable block pointer type, if there are no
15342 /// errors. Otherwise, returns a NULL type.
15344 DeclarationName Entity);
15345
15346 /// Build a paren type including \p T.
15349
15350 /// Build a Read-only Pipe type.
15351 ///
15352 /// \param T The type to which we'll be building a Pipe.
15353 ///
15354 /// \param Loc We do not use it for now.
15355 ///
15356 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15357 /// a NULL type.
15359
15360 /// Build a Write-only Pipe type.
15361 ///
15362 /// \param T The type to which we'll be building a Pipe.
15363 ///
15364 /// \param Loc We do not use it for now.
15365 ///
15366 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15367 /// a NULL type.
15369
15370 /// Build a bit-precise integer type.
15371 ///
15372 /// \param IsUnsigned Boolean representing the signedness of the type.
15373 ///
15374 /// \param BitWidth Size of this int type in bits, or an expression
15375 /// representing that.
15376 ///
15377 /// \param Loc Location of the keyword.
15378 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
15379
15380 /// GetTypeForDeclarator - Convert the type for the specified
15381 /// declarator to Type instances.
15382 ///
15383 /// The result of this call will never be null, but the associated
15384 /// type may be a null type if there's an unrecoverable error.
15387
15388 /// Package the given type and TSI into a ParsedType.
15391 TypeSourceInfo **TInfo = nullptr);
15392
15394
15395 // Check whether the size of array element of type \p EltTy is a multiple of
15396 // its alignment and return false if it isn't.
15398
15399 void
15400 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
15401 SourceLocation FallbackLoc,
15402 SourceLocation ConstQualLoc = SourceLocation(),
15403 SourceLocation VolatileQualLoc = SourceLocation(),
15404 SourceLocation RestrictQualLoc = SourceLocation(),
15405 SourceLocation AtomicQualLoc = SourceLocation(),
15406 SourceLocation UnalignedQualLoc = SourceLocation());
15407
15408 /// Retrieve the keyword associated
15410
15411 /// Adjust the calling convention of a method to be the ABI default if it
15412 /// wasn't specified explicitly. This handles method types formed from
15413 /// function type typedefs and typename template arguments.
15414 void adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
15415 bool IsCtorOrDtor, SourceLocation Loc);
15416
15417 // Check if there is an explicit attribute, but only look through parens.
15418 // The intent is to look for an attribute on the current declarator, but not
15419 // one that came from a typedef.
15421
15422 /// Check whether a nullability type specifier can be added to the given
15423 /// type through some means not written in source (e.g. API notes).
15424 ///
15425 /// \param Type The type to which the nullability specifier will be
15426 /// added. On success, this type will be updated appropriately.
15427 ///
15428 /// \param Nullability The nullability specifier to add.
15429 ///
15430 /// \param DiagLoc The location to use for diagnostics.
15431 ///
15432 /// \param AllowArrayTypes Whether to accept nullability specifiers on an
15433 /// array type (e.g., because it will decay to a pointer).
15434 ///
15435 /// \param OverrideExisting Whether to override an existing, locally-specified
15436 /// nullability specifier rather than complaining about the conflict.
15437 ///
15438 /// \returns true if nullability cannot be applied, false otherwise.
15440 NullabilityKind Nullability,
15441 SourceLocation DiagLoc,
15442 bool AllowArrayTypes,
15443 bool OverrideExisting);
15444
15445 /// Check whether the given variable declaration has a size that fits within
15446 /// the address space it is declared in. This issues a diagnostic if not.
15447 ///
15448 /// \param VD The variable declaration to check the size of.
15449 ///
15450 /// \param AS The address space to check the size of \p VD against.
15451 ///
15452 /// \returns true if the variable's size fits within the address space, false
15453 /// otherwise.
15454 bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS);
15455
15456 /// Get the type of expression E, triggering instantiation to complete the
15457 /// type if necessary -- that is, if the expression refers to a templated
15458 /// static data member of incomplete array type.
15459 ///
15460 /// May still return an incomplete type if instantiation was not possible or
15461 /// if the type is incomplete for a different reason. Use
15462 /// RequireCompleteExprType instead if a diagnostic is expected for an
15463 /// incomplete expression type.
15465
15467
15468 /// Ensure that the type of the given expression is complete.
15469 ///
15470 /// This routine checks whether the expression \p E has a complete type. If
15471 /// the expression refers to an instantiable construct, that instantiation is
15472 /// performed as needed to complete its type. Furthermore
15473 /// Sema::RequireCompleteType is called for the expression's type (or in the
15474 /// case of a reference type, the referred-to type).
15475 ///
15476 /// \param E The expression whose type is required to be complete.
15477 /// \param Kind Selects which completeness rules should be applied.
15478 /// \param Diagnoser The object that will emit a diagnostic if the type is
15479 /// incomplete.
15480 ///
15481 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
15482 /// otherwise.
15484 TypeDiagnoser &Diagnoser);
15485 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
15486
15487 template <typename... Ts>
15488 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
15489 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15491 }
15492
15493 // Returns the underlying type of a decltype with the given expression.
15495
15497 /// If AsUnevaluated is false, E is treated as though it were an evaluated
15498 /// context, such as when building a type for decltype(auto).
15499 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
15500
15501 QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr,
15502 SourceLocation Loc,
15503 SourceLocation EllipsisLoc);
15504 QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr,
15505 SourceLocation Loc, SourceLocation EllipsisLoc,
15506 bool FullySubstituted = false,
15507 ArrayRef<QualType> Expansions = {});
15508
15509 using UTTKind = UnaryTransformType::UTTKind;
15511 SourceLocation Loc);
15517 SourceLocation Loc);
15519 SourceLocation Loc);
15521 SourceLocation Loc);
15522
15524 return BuiltinRemoveReference(BaseType, UTTKind::RemoveCVRef, Loc);
15525 }
15526
15528 SourceLocation Loc);
15530 SourceLocation Loc);
15531
15532 bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT);
15533
15534 /// Ensure that the type T is a literal type.
15535 ///
15536 /// This routine checks whether the type @p T is a literal type. If @p T is an
15537 /// incomplete type, an attempt is made to complete it. If @p T is a literal
15538 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
15539 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
15540 /// it the type @p T), along with notes explaining why the type is not a
15541 /// literal type, and returns true.
15542 ///
15543 /// @param Loc The location in the source that the non-literal type
15544 /// diagnostic should refer to.
15545 ///
15546 /// @param T The type that this routine is examining for literalness.
15547 ///
15548 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
15549 ///
15550 /// @returns @c true if @p T is not a literal type and a diagnostic was
15551 /// emitted, @c false otherwise.
15553 TypeDiagnoser &Diagnoser);
15554 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
15555
15556 template <typename... Ts>
15557 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
15558 const Ts &...Args) {
15559 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15560 return RequireLiteralType(Loc, T, Diagnoser);
15561 }
15562
15565 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
15566 }
15567
15568 /// Ensure that the type T is a complete type.
15569 ///
15570 /// This routine checks whether the type @p T is complete in any
15571 /// context where a complete type is required. If @p T is a complete
15572 /// type, returns false. If @p T is a class template specialization,
15573 /// this routine then attempts to perform class template
15574 /// instantiation. If instantiation fails, or if @p T is incomplete
15575 /// and cannot be completed, issues the diagnostic @p diag (giving it
15576 /// the type @p T) and returns true.
15577 ///
15578 /// @param Loc The location in the source that the incomplete type
15579 /// diagnostic should refer to.
15580 ///
15581 /// @param T The type that this routine is examining for completeness.
15582 ///
15583 /// @param Kind Selects which completeness rules should be applied.
15584 ///
15585 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
15586 /// @c false otherwise.
15588 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
15590 CompleteTypeKind Kind, unsigned DiagID);
15591
15593 TypeDiagnoser &Diagnoser) {
15594 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
15595 }
15596 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
15597 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
15598 }
15599
15600 template <typename... Ts>
15601 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
15602 const Ts &...Args) {
15603 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15604 return RequireCompleteType(Loc, T, Diagnoser);
15605 }
15606
15607 /// Determine whether a declaration is visible to name lookup.
15608 bool isVisible(const NamedDecl *D) {
15609 return D->isUnconditionallyVisible() ||
15610 isAcceptableSlow(D, AcceptableKind::Visible);
15611 }
15612
15613 /// Determine whether a declaration is reachable.
15614 bool isReachable(const NamedDecl *D) {
15615 // All visible declarations are reachable.
15616 return D->isUnconditionallyVisible() ||
15617 isAcceptableSlow(D, AcceptableKind::Reachable);
15618 }
15619
15620 /// Determine whether a declaration is acceptable (visible/reachable).
15622 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
15623 }
15624
15625 /// Determine if \p D and \p Suggested have a structurally compatible
15626 /// layout as described in C11 6.2.7/1.
15627 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
15628
15629 /// Determine if \p D has a visible definition. If not, suggest a declaration
15630 /// that should be made visible to expose the definition.
15631 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
15632 bool OnlyNeedComplete = false);
15634 NamedDecl *Hidden;
15635 return hasVisibleDefinition(const_cast<NamedDecl *>(D), &Hidden);
15636 }
15637 /// Determine if \p D has a definition which allows we redefine it in current
15638 /// TU. \p Suggested is the definition that should be made visible to expose
15639 /// the definition.
15640 bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,
15641 bool &Visible);
15643 NamedDecl *Hidden;
15644 return isRedefinitionAllowedFor(const_cast<NamedDecl *>(D), &Hidden,
15645 Visible);
15646 }
15647
15648 /// Determine if \p D has a reachable definition. If not, suggest a
15649 /// declaration that should be made reachable to expose the definition.
15650 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
15651 bool OnlyNeedComplete = false);
15653 NamedDecl *Hidden;
15654 return hasReachableDefinition(D, &Hidden);
15655 }
15656
15657 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
15658 AcceptableKind Kind,
15659 bool OnlyNeedComplete = false);
15661 NamedDecl *Hidden;
15662 return hasAcceptableDefinition(D, &Hidden, Kind);
15663 }
15664
15665 /// Try to parse the conditional expression attached to an effect attribute
15666 /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty
15667 /// optional on error.
15668 std::optional<FunctionEffectMode>
15669 ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName);
15670
15671 void ActOnCleanupAttr(Decl *D, const Attr *A);
15672 void ActOnInitPriorityAttr(Decl *D, const Attr *A);
15673
15674private:
15675 /// The implementation of RequireCompleteType
15676 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
15677 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
15678
15679 /// Nullability type specifiers.
15680 IdentifierInfo *Ident__Nonnull = nullptr;
15681 IdentifierInfo *Ident__Nullable = nullptr;
15682 IdentifierInfo *Ident__Nullable_result = nullptr;
15683 IdentifierInfo *Ident__Null_unspecified = nullptr;
15684
15685 ///@}
15686
15687 //
15688 //
15689 // -------------------------------------------------------------------------
15690 //
15691 //
15692
15693 /// \name FixIt Helpers
15694 /// Implementations are in SemaFixItUtils.cpp
15695 ///@{
15696
15697public:
15698 /// Get a string to suggest for zero-initialization of a type.
15700 SourceLocation Loc) const;
15701 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
15702
15703 ///@}
15704
15705 //
15706 //
15707 // -------------------------------------------------------------------------
15708 //
15709 //
15710
15711 /// \name Function Effects
15712 /// Implementations are in SemaFunctionEffects.cpp
15713 ///@{
15714public:
15717
15720 std::optional<FunctionEffectWithCondition>
15721 Old; // Invalid when 'Kind' is 'Added'.
15722 std::optional<FunctionEffectWithCondition>
15723 New; // Invalid when 'Kind' is 'Removed'.
15724
15725 StringRef effectName() const {
15726 if (Old)
15727 return Old.value().Effect.name();
15728 return New.value().Effect.name();
15729 }
15730
15731 /// Describes the result of effects differing between a base class's virtual
15732 /// method and an overriding method in a subclass.
15733 enum class OverrideResult {
15736 Merge // Merge missing effect from base to derived.
15737 };
15738
15739 /// Return true if adding or removing the effect as part of a type
15740 /// conversion should generate a diagnostic.
15742 const FunctionEffectsRef &SrcFX,
15743 QualType DstType,
15744 const FunctionEffectsRef &DstFX) const;
15745
15746 /// Return true if adding or removing the effect in a redeclaration should
15747 /// generate a diagnostic.
15748 bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction,
15749 const FunctionEffectsRef &OldFX,
15750 const FunctionDecl &NewFunction,
15751 const FunctionEffectsRef &NewFX) const;
15752
15753 /// Return true if adding or removing the effect in a C++ virtual method
15754 /// override should generate a diagnostic.
15756 const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,
15757 const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const;
15758 };
15759
15760 struct FunctionEffectDiffVector : public SmallVector<FunctionEffectDiff> {
15761 /// Caller should short-circuit by checking for equality first.
15763 const FunctionEffectsRef &New);
15764 };
15765
15766 /// All functions/lambdas/blocks which have bodies and which have a non-empty
15767 /// FunctionEffectsRef to be verified.
15769
15770 /// The union of all effects present on DeclsWithEffectsToVerify. Conditions
15771 /// are all null.
15773
15774public:
15775 /// Warn and return true if adding a function effect to a set would create a
15776 /// conflict.
15779 SourceLocation NewAttrLoc);
15780
15781 // Report a failure to merge function effects between declarations due to a
15782 // conflict.
15783 void
15785 SourceLocation NewLoc,
15786 SourceLocation OldLoc);
15787
15788 /// Inline checks from the start of maybeAddDeclWithEffects, to
15789 /// minimize performance impact on code not using effects.
15790 template <class FuncOrBlockDecl>
15791 void maybeAddDeclWithEffects(FuncOrBlockDecl *D) {
15792 if (Context.hasAnyFunctionEffects())
15793 if (FunctionEffectsRef FX = D->getFunctionEffects(); !FX.empty())
15795 }
15796
15797 /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify.
15798 void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15799
15800 /// Unconditionally add a Decl to DeclsWithEfffectsToVerify.
15801 void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15802
15804
15805 ///@}
15806};
15807
15808DeductionFailureInfo
15810 sema::TemplateDeductionInfo &Info);
15811
15812/// Contains a late templated function.
15813/// Will be parsed at the end of the translation unit, used by Sema & Parser.
15816 /// The template function declaration to be late parsed.
15818 /// Floating-point options in the point of definition.
15820};
15821
15822template <>
15824 PragmaMsStackAction Action,
15825 llvm::StringRef StackSlotLabel,
15827
15828} // end namespace clang
15829
15830#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 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.
Defines enumerations for expression traits intrinsics.
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.
#define SM(sm)
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:50
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
This file declares semantic analysis functions specific to RISC-V.
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.
Defines enumerations for the type traits support.
TypePropertyCache< Private > Cache
Definition Type.cpp:4922
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
Represents a member of a struct/union/class.
Definition Decl.h:3202
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:122
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:223
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:97
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:2727
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
Attr - This represents one attribute.
Definition Attr.h:46
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3517
A binding in a decomposition declaration.
Definition DeclCXX.h:4206
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4714
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:2633
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2968
Represents a C++ base or member initializer.
Definition DeclCXX.h:2398
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2630
Represents a C++ destructor within a class.
Definition DeclCXX.h:2898
CXXFieldCollector - Used to keep track of CXXFieldDecls during parsing of C++ classes.
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
Represents the this expression in C++.
Definition ExprCXX.h:1158
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:69
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition Decl.h:4986
CaseStmt - Represent a case statement.
Definition Stmt.h:1930
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3682
CharUnits - 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:130
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:3698
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:1399
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
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:871
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:854
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
The name of a declaration.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1952
A decomposition declaration.
Definition DeclCXX.h:4270
Captures a template argument whose value has been deduced via c++ template argument deduction.
Definition Template.h:333
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:234
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3465
Represents an enum.
Definition Decl.h:4053
Store information needed for an explicit specifier.
Definition DeclCXX.h:1944
The return type of classify().
Definition Expr.h:339
This represents one expression.
Definition Expr.h:112
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) 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:808
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:3202
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:260
FileNullability & operator[](FileID file)
Definition Sema.h:271
FileNullability Nullability
Definition Sema.h:267
Represents a function declaration or definition.
Definition Decl.h:2027
A mutable set of FunctionEffect::Kind.
Definition TypeBase.h:5225
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5339
Kind
Identifies the particular effect.
Definition TypeBase.h:4987
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5171
Represents a reference to a function parameter pack, init-capture pack, or binding pack that has been...
Definition ExprCXX.h:4841
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
Declaration of a template function.
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4593
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
One of these records is kept for each identifier that is lexed.
IdentifierResolver - Keeps track of shadowed decls on enclosing scopes.
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:622
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3509
Describes an C or C++ initializer list.
Definition Expr.h:5314
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:524
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:371
Represents the results of name lookup.
Definition Lookup.h:147
A global _GUID constant.
Definition DeclCXX.h:4419
An instance of this class represents the declaration of a property member.
Definition DeclCXX.h:4365
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:4920
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
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:877
Module(ModuleConstructorTag, StringRef Name, SourceLocation DefinitionLoc, Module *Parent, bool IsFramework, bool IsExplicit, unsigned VisibilityID)
Construct a new module or submodule.
Definition Module.cpp:36
bool isModuleImplementation() const
Is this a module implementation.
Definition Module.h:882
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:274
Represent a C++ namespace.
Definition Decl.h:592
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:1154
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:8065
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:1160
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
static constexpr unsigned IdxBitWidth
Definition Attr.h:281
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2188
Represents a parameter to a function.
Definition Decl.h:1817
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:937
Represents the parsed form of a C++ template argument.
void Emit(const DiagnosticBuilder &DB) const
PreferredTypeBuilder(ASTContext *Ctx, bool Enabled)
Definition Sema.h:294
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:330
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:2698
A (possibly-)qualified type.
Definition TypeBase.h:937
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
Represents a struct/union/class.
Definition Decl.h:4367
Represents the body of a requires-expression.
Definition DeclCXX.h:2114
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:1874
bool operator==(const AlignPackInfo &Info) const
Definition Sema.h:1934
static AlignPackInfo getFromRawEncoding(unsigned Encoding)
Definition Sema.h:1906
unsigned getPackNumber() const
Definition Sema.h:1924
bool IsXLStack() const
Definition Sema.h:1932
bool IsPackSet() const
Definition Sema.h:1926
AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
Definition Sema.h:1880
bool IsAlignAttr() const
Definition Sema.h:1920
bool IsPackAttr() const
Definition Sema.h:1918
bool operator!=(const AlignPackInfo &Info) const
Definition Sema.h:1940
AlignPackInfo(bool IsXL)
Definition Sema.h:1884
static uint32_t getRawEncoding(const AlignPackInfo &Info)
Definition Sema.h:1891
Mode getAlignMode() const
Definition Sema.h:1922
ArgPackSubstIndexRAII(Sema &Self, UnsignedOrNone NewSubstIndex)
Definition Sema.h:13749
ArgPackSubstIndexRAII & operator=(const ArgPackSubstIndexRAII &)=delete
ArgPackSubstIndexRAII(const ArgPackSubstIndexRAII &)=delete
BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
Definition Sema.h:8360
void diagnose(Sema &S, SourceLocation Loc, QualType T) override
Definition Sema.h:8365
void emit(const SemaDiagnosticBuilder &DB, std::index_sequence< Is... >) const
Definition Sema.h:8352
std::tuple< const Ts &... > Args
Definition Sema.h:8349
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:1318
CompoundScopeRAII(const CompoundScopeRAII &)=delete
std::pair< VarDecl *, Expr * > get() const
Definition Sema.h:7899
std::optional< bool > getKnownValue() const
Definition Sema.h:7903
A RAII object to temporarily push a declaration context.
Definition Sema.h:3531
ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext=true)
Definition Sema.h:3541
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:10404
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:10409
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.
DefaultedComparisonKind asComparison() const
Definition Sema.h:6475
DefaultedFunctionKind(CXXSpecialMemberKind CSM)
Definition Sema.h:6452
unsigned getDiagnosticIndex() const
Get the index of this function kind for use in diagnostics.
Definition Sema.h:6480
DefaultedFunctionKind(DefaultedComparisonKind Comp)
Definition Sema.h:6455
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6472
DeferDiagsRAII(Sema &S, bool DeferDiags)
Definition Sema.h:10132
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:1387
DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool)
Enter a new scope.
Definition Sema.h:1406
void popUndelayed(DelayedDiagnosticsState state)
Undo a previous pushUndelayed().
Definition Sema.h:1430
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1399
sema::DelayedDiagnosticPool * getCurrentPool() const
Returns the current delayed-diagnostics pool.
Definition Sema.h:1402
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:1416
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1422
A helper class for building up ExtParameterInfos.
Definition Sema.h:13114
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:13133
void set(unsigned index, FunctionProtoType::ExtParameterInfo info)
Set the ExtParameterInfo for the parameter at the given index,.
Definition Sema.h:13121
FPFeaturesStateRAII(const FPFeaturesStateRAII &)=delete
FPOptionsOverride getOverrides()
Definition Sema.h:14155
FPFeaturesStateRAII & operator=(const FPFeaturesStateRAII &)=delete
FpPragmaStackSaveRAII(const FpPragmaStackSaveRAII &)=delete
FpPragmaStackSaveRAII & operator=(const FpPragmaStackSaveRAII &)=delete
FullExprArg(Sema &actions)
Definition Sema.h:7843
ExprResult release()
Definition Sema.h:7845
friend class Sema
Definition Sema.h:7854
Expr * get() const
Definition Sema.h:7847
GlobalEagerInstantiationScope(const GlobalEagerInstantiationScope &)=delete
GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
Definition Sema.h:14167
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:10468
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:10460
unsigned size() const
The number of exceptions in the exception specification.
Definition Sema.h:5574
ExceptionSpecificationType getExceptionSpecType() const
Get the computed exception specification type.
Definition Sema.h:5567
const QualType * data() const
The set of exceptions in the exception specification.
Definition Sema.h:5577
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:5583
FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const
Overwrite an EPI's exception specification with this computed exception specification.
Definition Sema.h:5590
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:14118
LocalEagerInstantiationScope(const LocalEagerInstantiationScope &)=delete
static NameClassification DependentNonType()
Definition Sema.h:3752
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3762
ExprResult getExpression() const
Definition Sema.h:3788
NameClassification(const IdentifierInfo *Keyword)
Definition Sema.h:3725
static NameClassification Unknown()
Definition Sema.h:3732
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3736
NameClassificationKind getKind() const
Definition Sema.h:3786
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3780
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3768
NamedDecl * getNonTypeDecl() const
Definition Sema.h:3798
NameClassification(ParsedType Type)
Definition Sema.h:3722
TemplateName getTemplateName() const
Definition Sema.h:3803
ParsedType getType() const
Definition Sema.h:3793
TemplateNameKind getTemplateNameKind() const
Definition Sema.h:3812
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3742
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3774
static NameClassification UndeclaredNonType()
Definition Sema.h:3748
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3756
static NameClassification Error()
Definition Sema.h:3728
void operator()(sema::FunctionScopeInfo *Scope) const
Definition Sema.cpp:2590
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:11494
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11496
RequiredTemplateKind(SourceLocation TemplateKWLoc=SourceLocation())
Template name is required if TemplateKWLoc is valid.
Definition Sema.h:11491
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12547
SFINAETrap & operator=(const SFINAETrap &)=delete
SFINAETrap(const SFINAETrap &)=delete
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12581
SFINAETrap(Sema &S, bool WithAccessChecking=false)
Definition Sema.h:12563
bool withAccessChecking() const
Definition Sema.h:12584
sema::TemplateDeductionInfo * getDeductionInfo() const
Definition Sema.h:12576
SFINAETrap(Sema &S, sema::TemplateDeductionInfo &Info)
Definition Sema.h:12566
SatisfactionStackResetRAII(const SatisfactionStackResetRAII &)=delete
SatisfactionStackResetRAII & operator=(const SatisfactionStackResetRAII &)=delete
ScopedCodeSynthesisContext(Sema &S, const CodeSynthesisContext &Ctx)
Definition Sema.h:13668
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:8377
void diagnose(Sema &S, SourceLocation Loc, QualType T) override
Definition Sema.h:8382
SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
Definition Sema.h:8379
SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
Definition Sema.h:9395
SpecialMemberOverloadResult(CXXMethodDecl *MD)
Definition Sema.h:9382
CXXMethodDecl * getMethod() const
Definition Sema.h:9385
void setMethod(CXXMethodDecl *MD)
Definition Sema.h:9386
void addContextNote(SourceLocation UseLoc)
Definition Sema.h:13634
SynthesizedFunctionScope(const SynthesizedFunctionScope &)=delete
SynthesizedFunctionScope(Sema &S, DeclContext *DC)
Definition Sema.h:13622
SynthesizedFunctionScope & operator=(const SynthesizedFunctionScope &)=delete
SourceLocation getLocation() const
Definition Sema.h:12305
bool ContainsDecl(const NamedDecl *ND) const
Definition Sema.h:12295
const DeclContext * getDeclContext() const
Definition Sema.h:12301
TemplateCompareNewDeclInfo(const DeclContext *DeclCtx, const DeclContext *LexicalDeclCtx, SourceLocation Loc)
Definition Sema.h:12279
const NamedDecl * getDecl() const
Definition Sema.h:12293
TemplateCompareNewDeclInfo(const NamedDecl *ND)
Definition Sema.h:12278
const DeclContext * getLexicalDeclContext() const
Definition Sema.h:12297
TentativeAnalysisScope(Sema &SemaRef)
Definition Sema.h:12598
TentativeAnalysisScope & operator=(const TentativeAnalysisScope &)=delete
TentativeAnalysisScope(const TentativeAnalysisScope &)=delete
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
VerifyICEDiagnoser(bool Suppress=false)
Definition Sema.h:7802
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:869
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:1449
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:3630
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:13699
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:8282
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:13683
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:11052
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13143
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2663
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:1142
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:1592
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:14103
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
void PopParsingClass(ParsingClassState state)
Definition Sema.h:6643
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:10145
void LoadExternalWeakUndeclaredIdentifiers()
Load weak undeclared identifiers from the external source.
Definition Sema.cpp:1095
bool containsUnexpandedParameterPacks(Declarator &D)
Determine whether the given declarator contains any unexpanded parameter packs.
std::optional< QualType > BuiltinVectorMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
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:6632
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)
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
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:8332
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:8250
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:963
bool isAttrContext() const
Definition Sema.h:7039
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:8325
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition Sema.cpp:2763
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6394
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9411
@ LookupLabel
Label name lookup.
Definition Sema.h:9420
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9415
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9442
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9434
@ LookupOMPReductionName
Look up the name of an OpenMP user-defined reduction operation.
Definition Sema.h:9456
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9450
@ LookupObjCProtocolName
Look up the name of an Objective-C protocol.
Definition Sema.h:9452
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9447
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9427
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition Sema.h:9454
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition Sema.h:9438
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9423
@ LookupDestructorName
Look up a name following ~ in a destructor name.
Definition Sema.h:9430
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9418
@ LookupOMPMapperName
Look up the name of an OpenMP user-defined mapper.
Definition Sema.h:9458
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9460
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:417
llvm::DenseMap< IdentifierInfo *, SrcLocSet > IdentifierSourceLocations
Definition Sema.h:9361
LazyVector< TypedefNameDecl *, ExternalSemaSource, &ExternalSemaSource::ReadExtVectorDecls, 2, 2 > ExtVectorDeclsType
Definition Sema.h:4955
UnaryTransformType::UTTKind UTTKind
Definition Sema.h:15509
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:6331
SemaM68k & M68k()
Definition Sema.h:1499
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:13761
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.
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:1382
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:2142
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:9849
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:4900
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:5129
OpaquePtr< QualType > TypeTy
Definition Sema.h:1302
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:170
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
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:366
void PrintContextStack()
Definition Sema.h:13770
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:632
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
SemaOpenMP & OpenMP()
Definition Sema.h:1534
void CheckDelegatingCtorCycles()
llvm::SmallSet< SourceLocation, 2 > SrcLocSet
Definition Sema.h:9360
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:2317
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition Sema.h:6369
bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is visible.
Definition Sema.h:9725
bool FormatStringHasSArg(const StringLiteral *FExpr)
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:1370
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:3586
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:15177
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:1263
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:4802
void CheckFloatComparison(SourceLocation Loc, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3612
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1846
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:15633
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:6605
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:5228
void emitAndClearUnusedLocalTypedefWarnings()
Definition Sema.cpp:1195
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:6586
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:1252
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, UnsignedOrNone NumExpansions, bool ExpectParameterPack, bool EvaluateConstraints=true)
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:1474
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:372
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
Definition Sema.h:7919
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7921
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7920
void LateTemplateParserCB(void *P, LateParsedTemplate &LPT)
Callback to the parser to parse templated functions when needed.
Definition Sema.h:1351
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:15592
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
static SourceRange getPrintable(SourceLocation L)
Definition Sema.h:15183
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:8270
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:9963
@ Interface
'export module X;'
Definition Sema.h:9960
@ Implementation
'module X;'
Definition Sema.h:9961
@ PartitionInterface
'export module X:Y;'
Definition Sema.h:9962
SourceLocation LocationOfExcessPrecisionNotSatisfied
Definition Sema.h:8412
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1245
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:9672
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition Sema.h:10487
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10490
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10496
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10494
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:1804
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
@ AR_dependent
Definition Sema.h:1689
@ AR_accessible
Definition Sema.h:1687
@ AR_inaccessible
Definition Sema.h:1688
@ AR_delayed
Definition Sema.h:1690
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:15190
@ AcceptSizeless
Relax the normal rules for complete types so that they include sizeless built-in types.
Definition Sema.h:15194
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:661
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc)
DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, SourceLocation EllipsisLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists)
Handle a friend tag declaration where the scope specifier was templated.
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:939
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7017
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2435
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:439
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:8401
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl)
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2077
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...
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition Sema.h:8313
void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, StringLiteral *DeletedMessage=nullptr)
static SourceRange getPrintable(const Expr *E)
Definition Sema.h:15184
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2071
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 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:15772
void setFunctionHasBranchIntoScope()
Definition Sema.cpp:2616
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:4960
ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val)
Definition SemaStmt.cpp:486
SourceLocation getOptimizeOffPragmaLocation() const
Get the location for the currently active "\#pragma clang optimizeoff". If this location is invalid,...
Definition Sema.h:2151
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:6846
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.
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
SmallVector< AlignPackIncludeState, 8 > AlignPackIncludeStack
Definition Sema.h:2066
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:11217
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)
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation, bool ReportInvalid)
type checking for vector binary operators.
void ActOnComment(SourceRange Comment)
Definition Sema.cpp:2715
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:4203
@ Default
= default ;
Definition Sema.h:4205
@ Delete
deleted-function-body
Definition Sema.h:4211
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:14065
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:1274
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:2078
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:1489
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.
FieldDecl * BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture)
Build a FieldDecl suitable to hold the given capture.
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...
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.
llvm::DenseMap< llvm::FoldingSetNodeID, UnsubstitutedConstraintSatisfactionCacheResult > UnsubstitutedConstraintSatisfactionCache
Cache the satisfaction of an atomic constraint.
Definition Sema.h:15108
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.
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:1559
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:2990
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:7029
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:1733
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:840
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
LateParsedTemplateMapT LateParsedTemplateMap
Definition Sema.h:11459
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)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:12058
@ CTAK_DeducedFromArrayBound
The template argument was deduced from an array bound via template argument deduction.
Definition Sema.h:12069
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12061
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12065
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:9355
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:1579
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:13703
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:1309
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:8237
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:694
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:9366
FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC)
Definition Sema.h:7864
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:227
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'.
Definition SemaAttr.cpp:976
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:2359
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:937
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)
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...
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:4429
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:15557
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
bool CheckCaseExpression(Expr *E)
void resetFPOptions(FPOptions FPO)
Definition Sema.h:11440
bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind)
Definition Sema.h:15660
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:9946
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:15173
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1519
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1374
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:2945
bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
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:1444
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 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:940
ClassTemplateDecl * StdCoroutineTraitsCache
The C++ "std::coroutine_traits" template, which is defined in <coroutine_traits>
Definition Sema.h:3204
bool captureSwiftVersionIndependentAPINotes()
Whether APINotes should be gathered for all applicable Swift language versions, without being applied...
Definition Sema.h:1670
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:2074
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void PrintInstantiationStack()
Definition Sema.h:13774
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:3620
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:761
bool isImmediateFunctionContext() const
Definition Sema.h:8262
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:940
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1082
void addExternalSource(IntrusiveRefCntPtr< ExternalSemaSource > E)
Registers an external source.
Definition Sema.cpp:669
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition SemaExpr.cpp:771
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:6612
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:1436
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:6696
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:2070
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:770
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:890
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.
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:2638
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:6639
@ FRS_Success
Definition Sema.h:10875
@ FRS_DiagnosticIssued
Definition Sema.h:10877
@ FRS_NoViableFunction
Definition Sema.h:10876
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:14238
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:990
void mergeVisibilityType(Decl *D, SourceLocation Loc, VisibilityAttr::VisibilityType Type)
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9408
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:9358
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.
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Sema.h:6164
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
Definition Sema.h:6178
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
Definition Sema.h:6175
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
Definition Sema.h:6172
@ None
This is not a defaultable comparison operator.
Definition Sema.h:6166
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
Definition Sema.h:6169
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)
llvm::SmallVector< QualType, 4 > CurrentParameterCopyTypes
Stack of types that correspond to the parameter entities that are currently being copy-initialized.
Definition Sema.h:9097
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:15768
@ Conversions
Allow explicit conversion functions but not explicit constructors.
Definition Sema.h:10196
@ All
Allow both explicit conversion functions and explicit constructors.
Definition Sema.h:10198
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:1235
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMemberKind > SpecialMemberDecl
Definition Sema.h:6627
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:1213
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:14977
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:3643
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
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:1738
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:2706
unsigned InventedParameterInfosStart
The index of the first InventedParameterInfo that refers to the current context.
Definition Sema.h:3528
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:2626
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:12237
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12255
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12245
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12265
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:4951
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:1752
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:8443
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:11509
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11516
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11513
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
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:2745
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2454
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:427
SourceRange getExprRange(Expr *E) const
Definition SemaExpr.cpp:512
bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS)
The parser has parsed a global nested-name-specifier '::'.
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
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:11445
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...
LazyVector< const DeclaratorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2 > UnusedFileScopedDeclsType
Definition Sema.h:3616
std::optional< ExpressionEvaluationContextRecord::InitializationContext > OutermostDeclarationWithDelayedImmediateInvocations() const
Definition Sema.h:8297
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:15180
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition Sema.h:4640
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:1590
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
void addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI)
Add a no_cluster attribute to a particular declaration.
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:935
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition Sema.h:8395
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
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:2472
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 PopCompoundScope()
Definition Sema.cpp:2605
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:15601
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:14498
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition Sema.h:14518
@ UPPC_RequiresClause
Definition Sema.h:14569
@ UPPC_UsingDeclaration
A using declaration.
Definition Sema.h:14524
@ UPPC_IfExists
Microsoft __if_exists.
Definition Sema.h:14551
@ UPPC_Requirement
Definition Sema.h:14566
@ UPPC_ExceptionType
The type of an exception.
Definition Sema.h:14542
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14521
@ UPPC_Lambda
Lambda expression.
Definition Sema.h:14557
@ UPPC_IfNotExists
Microsoft __if_not_exists.
Definition Sema.h:14554
@ UPPC_PartialSpecialization
Partial specialization.
Definition Sema.h:14548
@ UPPC_Initializer
An initializer.
Definition Sema.h:14533
@ UPPC_BaseType
The base type of a class type.
Definition Sema.h:14503
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14527
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14536
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14506
@ UPPC_Expression
An arbitrary expression.
Definition Sema.h:14500
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14545
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14530
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14509
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition Sema.h:14515
@ UPPC_Block
Block expression.
Definition Sema.h:14560
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14512
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14539
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14563
api_notes::APINotesManager APINotes
Definition Sema.h:1313
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:12617
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:933
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:13157
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:5943
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:2566
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)
SourceLocation CurInitSegLoc
Definition Sema.h:2113
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispMode Value)
Called on well formed #pragma vtordisp().
Definition SemaAttr.cpp:767
SemaCodeCompletion & CodeCompletion()
Definition Sema.h:1469
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:3637
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:1524
void SwapSatisfactionStack(llvm::SmallVectorImpl< SatisfactionStackEntryTy > &NewSS)
Definition Sema.h:14972
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
ReuseLambdaContextDecl_t
Definition Sema.h:7108
@ ReuseLambdaContextDecl
Definition Sema.h:7108
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:941
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:1464
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:1353
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:1308
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:2160
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:1348
SmallVector< PragmaAttributeGroup, 2 > PragmaAttributeStack
Definition Sema.h:2138
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:2244
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.
LazyVector< VarDecl *, ExternalSemaSource, &ExternalSemaSource::ReadTentativeDefinitions, 2, 2 > TentativeDefinitionsType
Definition Sema.h:3624
SemaDirectX & DirectX()
Definition Sema.h:1479
llvm::SmallSetVector< const NamedDecl *, 16 > NamedDeclSetType
Definition Sema.h:6588
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:1509
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:1591
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:1307
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 ...
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:1241
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2681
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:1236
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
llvm::DenseMap< unsigned, CXXDeductionGuideDecl * > AggregateDeductionCandidates
Definition Sema.h:9100
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:959
void ActOnStartOfCompoundStmt(bool IsStmtExpr)
Definition SemaStmt.cpp:417
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:15614
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:6590
SemaHLSL & HLSL()
Definition Sema.h:1484
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:11458
bool CollectStats
Flag indicating whether or not to collect detailed statistics.
Definition Sema.h:1239
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9407
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:1214
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:7023
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:1847
void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1504
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:1549
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:15791
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
SourceLocation ImplicitMSInheritanceAttrLoc
Source location for newly created implicit MSInheritanceAttrs.
Definition Sema.h:1836
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:5949
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.
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:216
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:5323
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
Definition Sema.h:5326
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
Definition Sema.h:5330
MemberPointerConversionDirection
Definition Sema.h:10328
SmallVector< PendingImplicitInstantiation, 1 > LateParsedInstantiations
Queue of implicit template instantiations that cannot be performed eagerly.
Definition Sema.h:14101
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6583
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:78
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:2811
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:15175
SemaSwift & Swift()
Definition Sema.h:1564
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:2059
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:6688
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7053
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained).
Definition Sema.h:13730
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6620
StmtResult ActOnExprStmtError()
Definition SemaStmt.cpp:66
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2069
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.
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
void completeExprArrayBound(Expr *E)
DeclContext * getCurLexicalContext() const
Definition Sema.h:1146
std::function< TypeResult(StringRef, StringRef, SourceLocation)> ParseTypeFromStringCallback
Callback to the parser to parse a type expressed as a string.
Definition Sema.h:1362
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:2116
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:1745
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:1304
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:11863
ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand, UnresolvedLookupExpr *Lookup)
SmallVector< std::deque< PendingImplicitInstantiation >, 8 > SavedPendingInstantiations
Definition Sema.h:14105
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:2163
ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen)
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:877
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:4817
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:10515
FileNullabilityMap NullabilityMap
A mapping that describes the nullability we've seen in each header file.
Definition Sema.h:15169
ProcessingContextState ParsingClassState
Definition Sema.h:6638
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:1342
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:2600
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 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:3034
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:3889
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition Sema.h:2718
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:15523
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
llvm::DenseMap< llvm::FoldingSetNodeID, TemplateArgumentLoc > * CurrentCachedTemplateArgs
Cache the instantiation results of template parameter mappings within concepts.
Definition Sema.h:15115
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.
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...
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition Sema.h:7050
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 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)
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:2418
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:11858
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:13155
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:4911
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl * > Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams, ExtParameterInfoBuilder &ParamInfos)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
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:5939
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:645
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:15608
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition Sema.h:8266
llvm::MapVector< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3608
StringLiteral * CurInitSeg
Last section used with pragma init_seg.
Definition Sema.h:2112
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9941
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,...
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:2573
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:8133
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:2636
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:7065
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:6597
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...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1447
auto getDefaultDiagFunc()
Definition Sema.h:2319
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 FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose=true)
Finds the overloads of operator new and delete that are appropriate for the allocation.
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:315
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:12618
ClassTemplateDecl * StdTypeIdentity
The C++ "std::type_identity" template, which is defined in <type_traits>.
Definition Sema.h:6616
SemaOpenCL & OpenCL()
Definition Sema.h:1529
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:14114
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:2243
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.
void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName)
Called on well-formed #pragma init_seg().
Definition SemaAttr.cpp:931
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:15185
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:2648
@ FAPK_Elsewhere
Definition Sema.h:2652
@ FAPK_Fixed
Definition Sema.h:2649
@ FAPK_Variadic
Definition Sema.h:2650
@ FAPK_VAList
Definition Sema.h:2651
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:8258
ObjCMethodDecl * SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl< ObjCMethodDecl * > &Methods)
llvm::DenseMap< ParmVarDecl *, llvm::TinyPtrVector< ParmVarDecl * > > UnparsedDefaultArgInstantiationsMap
Definition Sema.h:13146
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1713
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...
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)
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:15621
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:14948
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:8454
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:3634
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition Sema.h:6849
ExprResult BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index, QualType ParamType, SourceLocation loc, TemplateArgument Replacement, UnsignedOrNone PackIndex, bool Final)
bool MSStructPragmaOn
Definition Sema.h:1833
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)
void deduceHLSLAddressSpace(VarDecl *decl)
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:13714
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:14049
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID)
Definition Sema.h:15596
SourceManager & getSourceManager() const
Definition Sema.h:938
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:8525
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:4889
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:644
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:3582
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:980
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:710
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:12337
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:2331
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition Sema.h:9401
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
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,...
bool ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc, QualType Type)
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:14054
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...
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:6059
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.
bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc)
PragmaClangSection PragmaClangTextSection
Definition Sema.h:1848
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:7562
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.
LabelDecl * LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc=SourceLocation())
LookupOrCreateLabel - Do a name lookup of a label with the specified name.
NonTrivialCUnionKind
Definition Sema.h:4142
@ NTCUK_Destruct
Definition Sema.h:4144
@ NTCUK_Init
Definition Sema.h:4143
@ NTCUK_Copy
Definition Sema.h:4145
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:1383
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:8411
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1845
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.
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...
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
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:9196
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...
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:2466
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:2058
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:6847
void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro, SourceLocation MutableLoc)
ExternalSemaSource * getExternalSource() const
Definition Sema.h:943
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:1249
void * VisContext
VisContext - Manages the stack for #pragma GCC visibility.
Definition Sema.h:2119
SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const
Returns the top most location responsible for the definition of N.
bool isSFINAEContext() const
Definition Sema.h:13782
FunctionDecl * BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl, QualType AllocType, SourceLocation)
QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs=true)
Definition Sema.h:8881
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:15182
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:13738
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:14933
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:15563
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, const PartialDiagnostic &PD, const FunctionDecl *FD=nullptr)
Definition Sema.h:1152
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:2996
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:2109
void setFunctionHasMustTail()
Definition Sema.cpp:2631
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...
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:8450
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:14939
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:2621
RedeclarationKind forRedeclarationInCurContext() const
bool hasReachableDefinition(NamedDecl *D)
Definition Sema.h:15652
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:2640
bool CheckAttrTarget(const ParsedAttr &CurrAttr)
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition Sema.h:6608
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:1208
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:1588
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:11323
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:1585
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:1310
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:4703
bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount)
Checks that a call expression's argument count is the desired number.
PragmaAlignPackDiagnoseKind
Definition Sema.h:2221
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:7057
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:126
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1347
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:1859
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14097
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:9969
@ PrivateFragmentImportFinished
after 'module :private;' but a non-import decl has already been seen.
Definition Sema.h:9976
@ ImportFinished
after any non-import decl.
Definition Sema.h:9973
@ PrivateFragmentImportAllowed
after 'module :private;' but before any non-import decl.
Definition Sema.h:9974
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:9970
@ GlobalFragment
after 'module;' but before 'module X;'
Definition Sema.h:9971
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
Definition Sema.h:9978
@ ImportAllowed
after 'module X;' but before any non-import decl.
Definition Sema.h:9972
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:15181
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
StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested)
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl)
void incrementMSManglingNumber() const
Definition Sema.h:1270
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:6791
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6813
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6803
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6818
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6808
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6828
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6797
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6823
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6838
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:13722
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:4865
@ AP_InferredFromAnyAppleOS
The availability attribute was inferred from an 'anyAppleOS' availability attribute.
Definition Sema.h:4879
@ AP_PragmaClangAttribute
The availability attribute was applied using 'pragma clang attribute'.
Definition Sema.h:4871
@ AP_InferredFromOtherPlatform
The availability attribute for a specific platform was inferred from an availability attribute for an...
Definition Sema.h:4875
@ AP_PragmaClangAttribute_InferredFromAnyAppleOS
The availability attribute was inferred from an 'anyAppleOS' availability attribute that was applied ...
Definition Sema.h:4884
@ AP_Explicit
The availability attribute was specified explicitly next to the declaration.
Definition Sema.h:4868
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:989
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:14059
SemaPPC & PPC()
Definition Sema.h:1539
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:2479
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:4948
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:1268
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:14941
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:1352
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:8461
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:3627
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:10124
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:8248
SemaSystemZ & SystemZ()
Definition Sema.h:1569
DarwinSDKInfo * getDarwinSDKInfoForAvailabilityChecking()
Definition Sema.cpp:124
bool isRedefinitionAllowedFor(const NamedDecl *D, bool &Visible)
Definition Sema.h:15642
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:3018
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.
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8398
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:10320
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
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:9955
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:649
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...
QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind, SourceLocation Loc)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition Sema.h:1312
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:11486
@ TemplateNameIsRequired
Definition Sema.h:11486
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:790
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,...
LazyVector< CXXConstructorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadDelegatingConstructors, 2, 2 > DelegatingCtorDeclsType
Definition Sema.h:6601
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:1311
CXXMethodDecl * CreateLambdaCallOperator(SourceRange IntroducerRange, CXXRecordDecl *Class)
void DiagnoseUnterminatedPragmaAlignPack()
Definition SemaAttr.cpp:632
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition Sema.h:7868
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:934
FPOptions CurFPFeatures
Definition Sema.h:1305
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:1355
QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc)
llvm::SmallPtrSet< const CXXRecordDecl *, 8 > RecordDeclSetTy
Definition Sema.h:6592
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 AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
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:1105
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:521
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2068
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)
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:3057
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 ...
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef< ParsedType > Args, SourceLocation RParenLoc)
Parsed one of the type trait support pseudo-functions.
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition Sema.h:11669
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11679
@ TPC_FriendFunctionTemplate
Definition Sema.h:11677
@ TPC_ClassTemplateMember
Definition Sema.h:11675
@ TPC_FunctionTemplate
Definition Sema.h:11674
@ TPC_FriendClassTemplate
Definition Sema.h:11676
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11678
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:1459
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
friend class InitializationSequence
Definition Sema.h:1589
bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl)
Certain globally-unique variables might be accidentally duplicated if built into multiple shared libr...
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:2147
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:972
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:7827
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:6624
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition Sema.h:13694
void PrintStats() const
Print out statistics about the semantic analysis.
Definition Sema.cpp:684
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:15172
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:1831
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:1254
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:11146
@ BFRK_Check
Determining whether a for-range statement could be built.
Definition Sema.h:11154
@ BFRK_Build
Initial building of a for-range statement.
Definition Sema.h:11148
@ BFRK_Rebuild
Instantiation or recovery rebuild of a for-range statement.
Definition Sema.h:11151
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
SemaNVPTX & NVPTX()
Definition Sema.h:1514
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().
QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc)
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:564
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:2088
@ PSK_ConstSeg
Definition Sema.h:2091
@ PSK_DataSeg
Definition Sema.h:2089
@ PSK_CodeSeg
Definition Sema.h:2092
@ PSK_BSSSeg
Definition Sema.h:2090
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD)
Produce notes explaining why a defaulted function was defined as deleted.
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:639
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:338
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:6368
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...
void ActOnCXXForRangeDecl(Decl *D)
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:3601
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2227
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:1844
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:1366
QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel)
AbstractDiagSelID
Definition Sema.h:6314
@ AbstractSynthesizedIvarType
Definition Sema.h:6321
@ AbstractVariableType
Definition Sema.h:6318
@ AbstractReturnType
Definition Sema.h:6316
@ AbstractNone
Definition Sema.h:6315
@ AbstractFieldType
Definition Sema.h:6319
@ AbstractArrayType
Definition Sema.h:6322
@ AbstractParamType
Definition Sema.h:6317
@ AbstractIvarType
Definition Sema.h:6320
StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
Definition SemaStmt.cpp:951
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.
ExprResult CheckVarOrConceptTemplateTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs)
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:1554
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:8447
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...
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.
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 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:8056
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:9464
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition Sema.h:9468
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition Sema.h:9474
@ LOLR_Error
The lookup resulted in an error.
Definition Sema.h:9466
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition Sema.h:9471
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition Sema.h:9482
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition Sema.h:9478
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:2651
const ExpressionEvaluationContextRecord & parentEvaluationContext() const
Definition Sema.h:7035
SemaLoongArch & LoongArch()
Definition Sema.h:1494
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:6503
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6508
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6505
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:14093
void CheckVariableDeclarationType(VarDecl *NewVD)
sema::CompoundScopeInfo & getCurCompoundScope() const
Definition SemaStmt.cpp:433
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:3010
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1301
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:722
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:3578
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:1758
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:15488
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:7905
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef< Stmt * > Elts, bool isStmtExpr)
Definition SemaStmt.cpp:437
void NoteTemplateParameterLocation(const NamedDecl &Decl)
SemaWasm & Wasm()
Definition Sema.h:1574
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:3524
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:13690
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:1544
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:2612
StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt)
Definition SemaStmt.cpp:589
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11451
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:7861
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:8406
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1300
static int getPrintable(int I)
Definition Sema.h:15171
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
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition Sema.h:9734
bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling)
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:12986
StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope)
Definition SemaStmt.cpp:569
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:3875
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:15176
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:533
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:8274
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:13705
SemaARM & ARM()
Definition Sema.h:1454
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:13686
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:15174
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:11056
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:665
QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a block pointer type.
PragmaMsStackAction
Definition Sema.h:1850
@ PSK_Push_Set
Definition Sema.h:1856
@ PSK_Reset
Definition Sema.h:1851
@ PSK_Pop_Set
Definition Sema.h:1857
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:8743
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:13779
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:298
Stmt - This represents one statement.
Definition Stmt.h:86
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:1805
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3759
Exposes information about the current target.
Definition TargetInfo.h:227
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.).
This is a base class for callbacks that will be notified at every template instantiation.
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:4677
The top declaration context.
Definition Decl.h:105
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:227
Represents a declaration of a type.
Definition Decl.h:3555
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:8418
The base class of the type hierarchy.
Definition TypeBase.h:1875
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3709
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3604
Simple class containing the result of Sema::CorrectTypo.
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1039
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3390
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4126
A set of unresolved declarations.
The iterator over UnresolvedSets.
Represents a C++ using-declaration.
Definition DeclCXX.h:3612
Represents C++ using-directive.
Definition DeclCXX.h:3117
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3420
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
Represents a variable declaration or definition.
Definition Decl.h:932
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:4239
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2832
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:786
Retains information about a captured region.
Definition ScopeInfo.h:812
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:855
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:27
The JSON file list parser is used to communicate input to InstallAPI.
PragmaClangSectionAction
Definition Sema.h:476
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:56
ImplicitTypenameContext
Definition DeclSpec.h:1935
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
OverloadKind
Definition Sema.h:823
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:834
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:826
bool isa(CodeGen::Address addr)
Definition Address.h:330
OpaquePtr< TemplateName > ParsedTemplateTy
Definition Ownership.h:256
ArrayTypeTrait
Names for the array type traits.
Definition TypeTraits.h:42
@ CPlusPlus
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
VariadicCallType
Definition Sema.h:513
FunctionEffectMode
Used with attributes/effects with a boolean condition, e.g. nonblocking.
Definition Sema.h:459
CUDAFunctionTarget
Definition Cuda.h:63
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:791
@ Both
Look for allocation functions in both the global scope and in the scope of the allocated class.
Definition Sema.h:799
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:653
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:661
@ BitwiseOp
A bitwise operation.
Definition Sema.h:665
@ Arithmetic
An arithmetic operation.
Definition Sema.h:663
@ Conditional
A conditional (?:) operator.
Definition Sema.h:669
@ CompAssign
A compound assignment expression.
Definition Sema.h:671
@ Comparison
A comparison.
Definition Sema.h:667
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:349
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:272
@ Success
Annotation was successful.
Definition Parser.h:65
CXXConstructionKind
Definition ExprCXX.h:1544
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:150
PointerAuthDiscArgKind
Definition Sema.h:594
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:604
@ TemplateTemplateArgument
Definition Sema.h:613
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition Overload.h:84
NonTrivialCUnionContext
Definition Sema.h:532
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition Sema.h:628
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:636
@ OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition Sema.h:642
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:633
@ ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition Sema.h:639
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:238
@ 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:918
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ AS_none
Definition Specifiers.h:128
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:249
void inferNoReturnAttr(Sema &S, Decl *D)
Expr * Cond
};
llvm::MutableArrayRef< ImplicitConversionSequence > ConversionSequenceList
A list of implicit conversion sequences for the arguments of an OverloadCandidate.
Definition Overload.h:929
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition TypeTraits.h:51
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:40
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:2876
@ CopyInit
[a = b], [a = {b}]
Definition DeclSpec.h:2878
@ 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:478
@ Undefined
Keep undefined.
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OffsetOfKind
Definition Sema.h:616
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3783
CorrectTypoKind
Definition Sema.h:818
ActionResult< CXXCtorInitializer * > MemInitResult
Definition Ownership.h:253
OptionalUnsigned< unsigned > UnsignedOrNone
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
bool isFunctionOrMethodVariadic(const Decl *D)
Definition Attr.h:112
@ 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:689
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:712
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition Sema.h:787
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition Sema.h:704
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition Sema.h:759
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition Sema.h:749
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition Sema.h:776
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition Sema.h:763
@ CompatibleOBTDiscards
CompatibleOBTDiscards - Assignment discards overflow behavior.
Definition Sema.h:783
@ IncompatibleOBTKinds
IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType kinds, e....
Definition Sema.h:780
@ CompatibleVoidPtrToNonVoidPtr
CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because a void * can implicitly convert...
Definition Sema.h:696
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition Sema.h:738
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:733
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition Sema.h:772
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:691
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition Sema.h:723
@ IncompatiblePointerDiscardsOverflowBehavior
IncompatiblePointerDiscardsOverflowBehavior - The assignment discards overflow behavior annotations b...
Definition Sema.h:743
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition Sema.h:700
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition Sema.h:708
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition Sema.h:755
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition Sema.h:717
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:729
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition Sema.h:767
TagUseKind
Definition Sema.h:451
MSVtorDispMode
In the Microsoft ABI, this controls the placement of virtual displacement members used to implement v...
Definition LangOptions.h:38
PragmaClangSectionKind
pragma clang section kind
Definition Sema.h:467
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5995
TUFragmentKind
Definition Sema.h:487
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:555
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:587
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:562
@ DependentNonType
The name denotes a member of a dependent type that could not be resolved.
Definition Sema.h:576
@ UndeclaredTemplate
The name was classified as an ADL-only function template name.
Definition Sema.h:589
@ NonType
The name was classified as a specific non-type, non-template declaration.
Definition Sema.h:568
@ Unknown
This name is not a type or template in this context, but might be something else.
Definition Sema.h:558
@ Error
Classification failed; an error has been produced.
Definition Sema.h:560
@ Type
The name was classified as a type.
Definition Sema.h:564
@ TypeTemplate
The name was classified as a template whose specializations are types.
Definition Sema.h:583
@ Concept
The name was classified as a concept name.
Definition Sema.h:591
@ OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
Definition Sema.h:581
@ UndeclaredNonType
The name was classified as an ADL-only function name.
Definition Sema.h:572
@ VarTemplate
The name was classified as a variable template name.
Definition Sema.h:585
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:499
CastKind
CastKind - The kind of operation required for a conversion.
AllowFoldKind
Definition Sema.h:655
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:676
PragmaMSStructKind
Definition PragmaKinds.h:24
AssignmentAction
Definition Sema.h:216
@ Deduced
The normal deduced case.
Definition TypeBase.h:1814
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:427
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:521
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:126
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:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
TypeAwareAllocationMode
Definition ExprCXX.h:2255
IfExistsResult
Describes the result of an "if-exists" condition check.
Definition Sema.h:803
@ Exists
The symbol exists.
Definition Sema.h:805
@ DoesNotExist
The symbol does not exist.
Definition Sema.h:808
MSInheritanceModel
Assigned inheritance model for a class in the MS C++ ABI.
Definition Specifiers.h:413
bool hasFunctionProto(const Decl *D)
hasFunctionProto - Return true if the given decl has a argument information.
Definition Attr.h:55
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
unsigned getFunctionOrMethodNumParams(const Decl *D)
getFunctionOrMethodNumParams - Return number of function or method parameters.
Definition Attr.h:64
TPOC
The context in which partial ordering of function templates occurs.
Definition Template.h:304
TrivialABIHandling
Definition Sema.h:645
@ ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition Sema.h:650
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:647
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:369
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:419
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:414
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:417
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:390
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:376
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:412
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:421
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:409
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:379
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:393
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:382
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:396
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:385
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:406
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:400
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:403
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
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:1256
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:838
@ CaseValue
Expression in a case label.
Definition Sema.h:839
@ StaticAssertMessageData
Call to data() in a static assert message.
Definition Sema.h:849
@ Enumerator
Enumerator value with fixed underlying type.
Definition Sema.h:840
@ StaticAssertMessageSize
Call to size() in a static assert message.
Definition Sema.h:847
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:846
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:844
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:842
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:851
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:845
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
SourceLocIdentKind
Definition Expr.h:5019
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5970
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5981
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5984
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5988
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
TypeTrait
Names for traits that operate specifically on types.
Definition TypeTraits.h:21
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2249
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:1995
CheckedConversionKind
The kind of conversion being performed.
Definition Sema.h:438
@ Implicit
An implicit conversion.
Definition Sema.h:440
@ CStyleCast
A C-style cast.
Definition Sema.h:442
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
Definition Sema.h:448
@ OtherCast
A cast other than a C-style cast.
Definition Sema.h:446
@ FunctionalCast
A functional-style cast.
Definition Sema.h:444
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition Specifiers.h:174
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
int const char * function
Definition c++config.h:31
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 uint8_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:91
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:242
SourceLocation PointerEndLoc
The end location for the first pointer declarator in the file.
Definition Sema.h:249
SourceLocation PointerLoc
The first pointer declarator (of any pointer kind) in the file that does not have a corresponding nul...
Definition Sema.h:245
bool SawTypeNullability
Whether we saw any type nullability annotations in the given file.
Definition Sema.h:255
uint8_t PointerKind
Which kind of pointer declarator we saw.
Definition Sema.h:252
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition TypeBase.h:5108
Holds information about the various types of exception specification.
Definition TypeBase.h:5428
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5430
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5433
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5436
Extra information about a function prototype.
Definition TypeBase.h:5456
Represents a complete lambda introducer.
Definition DeclSpec.h:2884
Contains a late templated function.
Definition Sema.h:15814
FPOptions FPO
Floating-point options in the point of definition.
Definition Sema.h:15819
Decl * D
The template function declaration to be late parsed.
Definition Sema.h:15817
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:933
Describes how types, statements, expressions, and declarations should be printed.
SourceLocation CurrentPragmaLocation
Definition Sema.h:2063
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10607
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10614
CheckNonDependentConversionsFlag(bool SuppressUserConversions, bool OnlyInitializeNonUserDefinedConversions)
Definition Sema.h:10616
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:12096
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12092
CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &)=delete
CheckTemplateArgumentInfo(bool PartialOrdering=false, bool MatchingTTP=false)
Definition Sema.h:12073
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12085
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12082
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12082
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:13194
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition Sema.h:13362
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
bool InParameterMappingSubstitution
Whether we're substituting into the parameter mapping of a constraint.
Definition Sema.h:13319
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition Sema.h:13335
ArrayRef< TemplateArgument > template_arguments() const
Definition Sema.h:13354
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation,...
Definition Sema.h:13330
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13322
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13348
bool InConstraintSubstitution
Whether we're substituting into constraints.
Definition Sema.h:13316
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13338
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition Sema.h:13345
SynthesisKind
The kind of template instantiation we are performing.
Definition Sema.h:13196
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13285
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition Sema.h:13206
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition Sema.h:13215
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition Sema.h:13234
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13282
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition Sema.h:13242
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition Sema.h:13249
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13289
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition Sema.h:13260
@ Memoization
Added for Template instantiation observation.
Definition Sema.h:13295
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition Sema.h:13225
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition Sema.h:13301
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13298
@ PartialOrderingTTP
We are performing partial ordering for template template parameters.
Definition Sema.h:13304
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13222
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition Sema.h:13230
@ SYCLKernelLaunchOverloadResolution
We are performing overload resolution for a call to a function template or variable template named 's...
Definition Sema.h:13312
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13238
@ TemplateInstantiation
We are instantiating a template declaration.
Definition Sema.h:13199
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition Sema.h:13252
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13256
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13211
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13279
@ SYCLKernelLaunchLookup
We are performing name lookup for a function template or variable template named 'sycl_kernel_launch'...
Definition Sema.h:13308
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition Sema.h:13245
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13325
CXXSpecialMemberKind SpecialMember
The special member being declared or defined.
Definition Sema.h:13351
bool isInstantiationRecord() const
Determines whether this template is an actual instantiation that should be counted toward the maximum...
ConstraintEvalRAII & operator=(const ConstraintEvalRAII &)=delete
ConstraintEvalRAII(const ConstraintEvalRAII &)=delete
InitializationContext(SourceLocation Loc, ValueDecl *Decl, DeclContext *Context)
Definition Sema.h:6952
Data structure used to record current or nested expression evaluation contexts.
Definition Sema.h:6853
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:6886
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition Sema.h:6888
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6939
Decl * ManglingContextDecl
The declaration that provides context for lambda expressions and block literals if the normal declara...
Definition Sema.h:6873
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:6882
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition Sema.h:6893
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:6901
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition Sema.h:6897
bool IsCaseExpr
Whether evaluating an expression for a switch case label.
Definition Sema.h:6942
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6907
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:6868
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition Sema.h:6915
bool RebuildDefaultArgOrDefaultInit
Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
Definition Sema.h:6945
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6911
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition Sema.h:6858
VarDecl * DeclForInitializer
Declaration for initializer if one is currently being parsed.
Definition Sema.h:6878
std::optional< InitializationContext > DelayedDefaultInitializationContext
Definition Sema.h:6962
ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext)
Definition Sema.h:6964
ExpressionEvaluationContext Context
The expression evaluation context.
Definition Sema.h:6855
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition Sema.h:6862
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2660
FunctionEffectDiffVector(const FunctionEffectsRef &Old, const FunctionEffectsRef &New)
Caller should short-circuit by checking for equality first.
std::optional< FunctionEffectWithCondition > Old
Definition Sema.h:15721
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:15725
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:15733
std::optional< FunctionEffectWithCondition > New
Definition Sema.h:15723
FunctionEffect::Kind EffectKind
Definition Sema.h:15718
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13532
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:14231
LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, Decl *D)
Definition Sema.h:14234
bool isMoveEligible() const
Definition Sema.h:11214
bool isCopyElidable() const
Definition Sema.h:11215
const VarDecl * Candidate
Definition Sema.h:11209
IdentifierInfo * Identifier
The identifier preceding the '::'.
Definition Sema.h:3337
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType=ParsedType())
Creates info object for the most typical case.
Definition Sema.h:3346
SourceLocation IdentifierLoc
The location of the identifier.
Definition Sema.h:3340
SourceLocation CCLoc
The location of the '::'.
Definition Sema.h:3343
ParsedType ObjectType
The type of the object, if we're parsing nested-name-specifier in a member access expression.
Definition Sema.h:3334
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType)
Definition Sema.h:3352
OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType)
Definition Sema.h:12718
Information from a C++ pragma export, for a symbol that we haven't seen the declaration for yet.
Definition Sema.h:2354
This an attribute introduced by #pragma clang attribute.
Definition Sema.h:2122
SmallVector< attr::SubjectMatchRule, 4 > MatchRules
Definition Sema.h:2125
A push'd group of PragmaAttributeEntries.
Definition Sema.h:2130
SourceLocation Loc
The location of the push attribute.
Definition Sema.h:2132
SmallVector< PragmaAttributeEntry, 2 > Entries
Definition Sema.h:2135
const IdentifierInfo * Namespace
The namespace of this push group.
Definition Sema.h:2134
SourceLocation PragmaLocation
Definition Sema.h:1841
PragmaMsStackAction Action
Definition Sema.h:1861
Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
Definition Sema.h:1974
llvm::StringRef StackSlotLabel
Definition Sema.h:1970
SourceLocation PragmaLocation
Definition Sema.h:1972
SourceLocation PragmaPushLocation
Definition Sema.h:1973
ValueType CurrentValue
Definition Sema.h:2044
void SentinelAction(PragmaMsStackAction Action, StringRef Label)
Definition Sema.h:2030
bool hasValue() const
Definition Sema.h:2040
SmallVector< Slot, 2 > Stack
Definition Sema.h:2042
ValueType DefaultValue
Definition Sema.h:2043
SourceLocation CurrentPragmaLocation
Definition Sema.h:2045
PragmaStack(const ValueType &Default)
Definition Sema.h:2037
void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value)
Definition Sema.h:1981
ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val)
Definition Sema.h:5163
ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val)
Definition Sema.h:5157
RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
Definition Sema.h:13166
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:10504
SFINAEContextBase & operator=(const SFINAEContextBase &)=delete
SFINAEContextBase(Sema &S, SFINAETrap *Cur)
Definition Sema.h:12527
SFINAEContextBase(const SFINAEContextBase &)=delete
Abstract class used to diagnose incomplete types.
Definition Sema.h:8339
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull)
Definition Sema.h:2702
unsigned LayoutCompatible
If true, Type should be compared with other expression's types for layout-compatibility.
Definition Sema.h:2711
bool CheckSameAsPrevious
Definition Sema.h:355
NamedDecl * Previous
Definition Sema.h:356
SkipBodyInfo()=default
NamedDecl * New
Definition Sema.h:357
Information about a template-id annotation token.