clang 24.0.0git
Sema.h
Go to the documentation of this file.
1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/ASTLambda.h"
20#include "clang/AST/Attr.h"
22#include "clang/AST/CharUnits.h"
23#include "clang/AST/DeclBase.h"
24#include "clang/AST/DeclCXX.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
33#include "clang/AST/StmtCXX.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
41#include "clang/Basic/Cuda.h"
44#include "clang/Basic/LLVM.h"
45#include "clang/Basic/Lambda.h"
47#include "clang/Basic/Module.h"
58#include "clang/Sema/Attr.h"
60#include "clang/Sema/DeclSpec.h"
66#include "clang/Sema/Scope.h"
67#include "clang/Sema/SemaBase.h"
71#include "clang/Sema/Weak.h"
72#include "llvm/ADT/APInt.h"
73#include "llvm/ADT/ArrayRef.h"
74#include "llvm/ADT/BitmaskEnum.h"
75#include "llvm/ADT/DenseMap.h"
76#include "llvm/ADT/DenseSet.h"
77#include "llvm/ADT/FloatingPointMode.h"
78#include "llvm/ADT/FoldingSet.h"
79#include "llvm/ADT/MapVector.h"
80#include "llvm/ADT/PointerIntPair.h"
81#include "llvm/ADT/PointerUnion.h"
82#include "llvm/ADT/STLExtras.h"
83#include "llvm/ADT/STLForwardCompat.h"
84#include "llvm/ADT/STLFunctionalExtras.h"
85#include "llvm/ADT/SetVector.h"
86#include "llvm/ADT/SmallBitVector.h"
87#include "llvm/ADT/SmallPtrSet.h"
88#include "llvm/ADT/SmallSet.h"
89#include "llvm/ADT/SmallVector.h"
90#include "llvm/ADT/StringExtras.h"
91#include "llvm/ADT/StringMap.h"
92#include "llvm/ADT/TinyPtrVector.h"
93#include "llvm/Support/Allocator.h"
94#include "llvm/Support/Compiler.h"
95#include "llvm/Support/Error.h"
96#include "llvm/Support/ErrorHandling.h"
97#include <cassert>
98#include <climits>
99#include <cstddef>
100#include <cstdint>
101#include <deque>
102#include <functional>
103#include <iterator>
104#include <memory>
105#include <optional>
106#include <string>
107#include <tuple>
108#include <type_traits>
109#include <utility>
110#include <vector>
111
112namespace llvm {
113struct InlineAsmIdentifierInfo;
114} // namespace llvm
115
116namespace clang {
117class ADLResult;
118class APValue;
120class ASTConsumer;
121class ASTContext;
122class ASTDeclReader;
124class ASTReader;
125class ASTWriter;
126class CXXBasePath;
127class CXXBasePaths;
130enum class ComparisonCategoryType : unsigned char;
132class DarwinSDKInfo;
133class DeclGroupRef;
137class Designation;
138class IdentifierInfo;
145enum class LangAS : unsigned int;
147class LookupResult;
150class ModuleLoader;
154class ObjCMethodDecl;
155struct OverloadCandidate;
156enum class OverloadCandidateParamOrder : char;
157enum OverloadCandidateRewriteKind : unsigned;
159class Preprocessor;
161struct ResolvedAllocation;
162class SemaAMDGPU;
163class SemaARM;
164class SemaAVR;
165class SemaBPF;
167class SemaCUDA;
168class SemaDirectX;
169class SemaHLSL;
170class SemaHexagon;
171class SemaLoongArch;
172class SemaM68k;
173class SemaMIPS;
174class SemaMSP430;
175class SemaNVPTX;
176class SemaObjC;
177class SemaOpenACC;
178class SemaOpenCL;
179class SemaOpenMP;
180class SemaPPC;
181class SemaPseudoObject;
182class SemaRISCV;
183class SemaSPIRV;
184class SemaSYCL;
185class SemaSwift;
186class SemaSystemZ;
187class SemaWasm;
188class SemaX86;
190class TemplateArgument;
192class TemplateInstantiationCallback;
195class Token;
196class TypeConstraint;
201
202namespace sema {
203class BlockScopeInfo;
204class Capture;
211class LambdaScopeInfo;
212class SemaPPCallbacks;
214} // namespace sema
215
216// AssignmentAction - This is used by all the assignment diagnostic functions
217// to represent what is actually causing the operation
228
229// Inline capacity for type-aware, aligned, and unaligned allocation argument
230// list candidates.
232
233namespace threadSafety {
234class BeforeSet;
235void threadSafetyCleanup(BeforeSet *Cache);
236} // namespace threadSafety
237
238// FIXME: No way to easily map from TemplateTypeParmTypes to
239// TemplateTypeParmDecls, so we have this horrible PointerUnion.
240typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *,
241 const TemplateSpecializationType *,
242 const SubstBuiltinTemplatePackType *>,
243 SourceLocation>
245
246/// Describes whether we've seen any nullability information for the given
247/// file.
249 /// The first pointer declarator (of any pointer kind) in the file that does
250 /// not have a corresponding nullability annotation.
252
253 /// The end location for the first pointer declarator in the file. Used for
254 /// placing fix-its.
256
257 /// Which kind of pointer declarator we saw.
259
260 /// Whether we saw any type nullability annotations in the given file.
261 bool SawTypeNullability = false;
262};
263
264/// A mapping from file IDs to a record of whether we've seen nullability
265/// information in that file.
267 /// A mapping from file IDs to the nullability information for each file ID.
268 llvm::DenseMap<FileID, FileNullability> Map;
269
270 /// A single-element cache based on the file ID.
271 struct {
274 } Cache;
275
276public:
278 // Check the single-element cache.
279 if (file == Cache.File)
280 return Cache.Nullability;
281
282 // It's not in the single-element cache; flush the cache if we have one.
283 if (!Cache.File.isInvalid()) {
284 Map[Cache.File] = Cache.Nullability;
285 }
286
287 // Pull this entry into the cache.
288 Cache.File = file;
289 Cache.Nullability = Map[file];
290 return Cache.Nullability;
291 }
292};
293
294/// Tracks expected type during expression parsing, for use in code completion.
295/// The type is tied to a particular token, all functions that update or consume
296/// the type take a start location of the token they are looking at as a
297/// parameter. This avoids updating the type on hot paths in the parser.
299public:
301 : Ctx(Ctx), Enabled(Enabled) {}
302
306 /// Handles e.g. BaseType{ .D = Tok...
308 const Designation &D);
309 /// Computing a type for the function argument may require running
310 /// overloading, so we postpone its computation until it is actually needed.
311 ///
312 /// Clients should be very careful when using this function, as it stores a
313 /// function_ref, clients should make sure all calls to get() with the same
314 /// location happen while function_ref is alive.
315 ///
316 /// The callback should also emit signature help as a side-effect, but only
317 /// if the completion point has been reached.
319 llvm::function_ref<QualType()> ComputeType);
320
323 SourceLocation OpLoc);
326 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
327 /// Handles all type casts, including C-style cast, C++ casts, etc.
329
330 /// Get the expected type associated with this location, if any.
331 ///
332 /// If the location is a function argument, determining the expected type
333 /// involves considering all function overloads and the arguments so far.
334 /// In this case, signature help for these function overloads will be reported
335 /// as a side-effect (only if the completion point has been reached).
337 if (!Enabled || Tok != ExpectedLoc)
338 return QualType();
339 if (!Type.isNull())
340 return Type;
341 if (ComputeType)
342 return ComputeType();
343 return QualType();
344 }
345
346private:
347 ASTContext *Ctx;
348 bool Enabled;
349 /// Start position of a token for which we store expected type.
350 SourceLocation ExpectedLoc;
351 /// Expected type for a token starting at ExpectedLoc.
353 /// A function to compute expected type at ExpectedLoc. It is only considered
354 /// if Type is null.
355 llvm::function_ref<QualType()> ComputeType;
356};
357
359 SkipBodyInfo() = default;
360 bool ShouldSkip = false;
362 NamedDecl *Previous = nullptr;
363 NamedDecl *New = nullptr;
364};
365
366/// Describes the result of template argument deduction.
367///
368/// The TemplateDeductionResult enumeration describes the result of
369/// template argument deduction, as returned from
370/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
371/// structure provides additional information about the results of
372/// template argument deduction, e.g., the deduced template argument
373/// list (if successful) or the specific template parameters or
374/// deduced arguments that were involved in the failure.
376 /// Template argument deduction was successful.
378 /// The declaration was invalid; do nothing.
380 /// Template argument deduction exceeded the maximum template
381 /// instantiation depth (which has already been diagnosed).
383 /// Template argument deduction did not deduce a value
384 /// for every template parameter.
386 /// Template argument deduction did not deduce a value for every
387 /// expansion of an expanded template parameter pack.
389 /// Template argument deduction produced inconsistent
390 /// deduced values for the given template parameter.
392 /// Template argument deduction failed due to inconsistent
393 /// cv-qualifiers on a template parameter type that would
394 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
395 /// but were given a non-const "X".
397 /// Substitution of the deduced template argument values
398 /// resulted in an error.
400 /// After substituting deduced template arguments, a dependent
401 /// parameter type did not match the corresponding argument.
403 /// After substituting deduced template arguments, an element of
404 /// a dependent parameter type did not match the corresponding element
405 /// of the corresponding argument (when deducing from an initializer list).
407 /// A non-depnedent component of the parameter did not match the
408 /// corresponding component of the argument.
410 /// When performing template argument deduction for a function
411 /// template, there were too many call arguments.
413 /// When performing template argument deduction for a function
414 /// template, there were too few call arguments.
416 /// The explicitly-specified template arguments were not valid
417 /// template arguments for the given template.
419 /// Checking non-dependent argument conversions failed.
421 /// The deduced arguments did not satisfy the constraints associated
422 /// with the template.
424 /// Deduction failed; that's all we know.
426 /// CUDA Target attributes do not match.
428 /// Some error which was already diagnosed.
430};
431
432/// The kind of conversion being performed.
434 /// An implicit conversion.
436 /// A C-style cast.
438 /// A functional-style cast.
440 /// A cast other than a C-style cast.
442 /// A conversion for an operand of a builtin overloaded operator.
444};
445
446enum class TagUseKind {
447 Reference, // Reference to a tag: 'struct foo *X;'
448 Declaration, // Fwd decl of a tag: 'struct foo;'
449 Definition, // Definition of a tag: 'struct foo { int X; } Y;'
450 Friend // Friend declaration: 'friend struct foo;'
451};
452
453/// Used with attributes/effects with a boolean condition, e.g. `nonblocking`.
455 None, // effect is not present.
456 False, // effect(false).
457 True, // effect(true).
458 Dependent // effect(expr) where expr is dependent.
459};
460
461/// pragma clang section kind
464 BSS = 1,
465 Data = 2,
467 Text = 4,
469};
470
471enum class PragmaClangSectionAction { Set = 0, Clear = 1 };
472
474 Native, // #pragma options align=native
475 Natural, // #pragma options align=natural
476 Packed, // #pragma options align=packed
477 Power, // #pragma options align=power
478 Mac68k, // #pragma options align=mac68k
479 Reset // #pragma options align=reset
480};
481
482enum class TUFragmentKind {
483 /// The global module fragment, between 'module;' and a module-declaration.
485 /// A normal translation unit fragment. For a non-module unit, this is the
486 /// entire translation unit. Otherwise, it runs from the module-declaration
487 /// to the private-module-fragment (if any) or the end of the TU (if not).
489 /// The private module fragment, between 'module :private;' and the end of
490 /// the translation unit.
492};
493
506
507// Used for emitting the right warning by DefaultVariadicArgumentPromotion
515
524
525// Contexts where using non-trivial C union types can be disallowed. This is
526// passed to err_non_trivial_c_union_in_invalid_context.
528 // Function parameter.
530 // Function return.
532 // Default-initialized object.
534 // Variable with automatic storage duration.
536 // Initializer expression that might copy from another object.
538 // Assignment.
540 // Compound literal.
542 // Block capture.
544 // lvalue-to-rvalue conversion of volatile type.
546};
547
548/// Describes the result of the name lookup and resolution performed
549/// by \c Sema::ClassifyName().
551 /// This name is not a type or template in this context, but might be
552 /// something else.
554 /// Classification failed; an error has been produced.
556 /// The name has been typo-corrected to a keyword.
558 /// The name was classified as a type.
560 /// The name was classified as a specific non-type, non-template
561 /// declaration. ActOnNameClassifiedAsNonType should be called to
562 /// convert the declaration to an expression.
564 /// The name was classified as an ADL-only function name.
565 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
566 /// result to an expression.
568 /// The name denotes a member of a dependent type that could not be
569 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
570 /// convert the result to an expression.
572 /// The name was classified as an overload set, and an expression
573 /// representing that overload set has been formed.
574 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
575 /// expression referencing the overload set.
577 /// The name was classified as a template whose specializations are types.
579 /// The name was classified as a variable template name.
581 /// The name was classified as a function template name.
583 /// The name was classified as an ADL-only function template name.
585 /// The name was classified as a concept name.
587};
588
590 // Address discrimination argument of __ptrauth.
592
593 // Extra discriminator argument of __ptrauth.
595};
596
597/// Common ways to introduce type names without a tag for use in diagnostics.
598/// Keep in sync with err_tag_reference_non_tag.
610
611enum class OffsetOfKind {
612 // Not parsing a type within __builtin_offsetof.
614 // Parsing a type within __builtin_offsetof.
616 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
617 // To improve our diagnostic message.
619};
620
621/// Describes the kind of merge to perform for availability
622/// attributes (including "deprecated", "unavailable", and "availability").
624 /// Don't merge availability attributes at all.
626 /// Merge availability attributes for a redeclaration, which requires
627 /// an exact match.
629 /// Merge availability attributes for an override, which requires
630 /// an exact match or a weakening of constraints.
632 /// Merge availability attributes for an implementation of
633 /// a protocol requirement.
635 /// Merge availability attributes for an implementation of
636 /// an optional protocol requirement.
638};
639
641 /// The triviality of a method unaffected by "trivial_abi".
643
644 /// The triviality of a method affected by "trivial_abi".
646};
647
649
650enum class AllowFoldKind {
653};
654
655/// Context in which we're performing a usual arithmetic conversion.
656enum class ArithConvKind {
657 /// An arithmetic operation.
659 /// A bitwise operation.
661 /// A comparison.
663 /// A conditional (?:) operator.
665 /// A compound assignment expression.
667};
668
669// Used for determining in which context a type is allowed to be passed to a
670// vararg function.
678
679/// AssignConvertType - All of the 'assignment' semantic checks return this
680/// enum to indicate whether the assignment was allowed. These checks are
681/// done for simple assignments, as well as initialization, return from
682/// function, argument passing, etc. The query is phrased in terms of a
683/// source and destination type.
685 /// Compatible - the types are compatible according to the standard.
687
688 /// CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because
689 /// a void * can implicitly convert to another pointer type, which we
690 /// differentiate for better diagnostic behavior.
692
693 /// PointerToInt - The assignment converts a pointer to an int, which we
694 /// accept as an extension.
696
697 /// IntToPointer - The assignment converts an int to a pointer, which we
698 /// accept as an extension.
700
701 /// FunctionVoidPointer - The assignment is between a function pointer and
702 /// void*, which the standard doesn't allow, but we accept as an extension.
704
705 /// IncompatiblePointer - The assignment is between two pointers types that
706 /// are not compatible, but we accept them as an extension.
708
709 /// IncompatibleFunctionPointer - The assignment is between two function
710 /// pointers types that are not compatible, but we accept them as an
711 /// extension.
713
714 /// IncompatibleFunctionPointerStrict - The assignment is between two
715 /// function pointer types that are not identical, but are compatible,
716 /// unless compiled with -fsanitize=cfi, in which case the type mismatch
717 /// may trip an indirect call runtime check.
719
720 /// IncompatiblePointerSign - The assignment is between two pointers types
721 /// which point to integers which have a different sign, but are otherwise
722 /// identical. This is a subset of the above, but broken out because it's by
723 /// far the most common case of incompatible pointers.
725
726 /// CompatiblePointerDiscardsQualifiers - The assignment discards
727 /// c/v/r qualifiers, which we accept as an extension.
729
730 /// IncompatiblePointerDiscardsQualifiers - The assignment
731 /// discards qualifiers that we don't permit to be discarded,
732 /// like address spaces.
734
735 /// IncompatiblePointerDiscardsOverflowBehavior - The assignment
736 /// discards overflow behavior annotations between otherwise compatible
737 /// pointer types.
739
740 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
741 /// changes address spaces in nested pointer types which is not allowed.
742 /// For instance, converting __private int ** to __generic int ** is
743 /// illegal even though __private could be converted to __generic.
745
746 /// IncompatibleNestedPointerQualifiers - The assignment is between two
747 /// nested pointer types, and the qualifiers other than the first two
748 /// levels differ e.g. char ** -> const char **, but we accept them as an
749 /// extension.
751
752 /// IncompatibleVectors - The assignment is between two vector types that
753 /// have the same size, which we accept as an extension.
755
756 /// IntToBlockPointer - The assignment converts an int to a block
757 /// pointer. We disallow this.
759
760 /// IncompatibleBlockPointer - The assignment is between two block
761 /// pointers types that are not compatible.
763
764 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
765 /// id type and something else (that is incompatible with it). For example,
766 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
768
769 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
770 /// object with __weak qualifier.
772
773 /// IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType
774 /// kinds, e.g., from __ob_trap to __ob_wrap or vice versa.
776
777 /// CompatibleOBTDiscards - Assignment discards overflow behavior
779
780 /// Incompatible - We reject this conversion outright, it is invalid to
781 /// represent it in the AST.
783};
784
785/// The scope in which to find allocation functions.
787 /// Only look for allocation functions in the global scope.
789 /// Only look for allocation functions in the scope of the
790 /// allocated class.
792 /// Look for allocation functions in both the global scope
793 /// and in the scope of the allocated class.
795};
796
797/// Describes the result of an "if-exists" condition check.
798enum class IfExistsResult {
799 /// The symbol exists.
801
802 /// The symbol does not exist.
804
805 /// The name is a dependent name, so the results will differ
806 /// from one instantiation to the next.
808
809 /// An error occurred.
811};
812
813enum class CorrectTypoKind {
814 NonError, // CorrectTypo used in a non error recovery situation.
815 ErrorRecovery // CorrectTypo used in normal error recovery.
816};
817
818enum class OverloadKind {
819 /// This is a legitimate overload: the existing declarations are
820 /// functions or function templates with different signatures.
822
823 /// This is not an overload because the signature exactly matches
824 /// an existing declaration.
826
827 /// This is not an overload because the lookup results contain a
828 /// non-function.
830};
831
832/// Contexts in which a converted constant expression is required.
833enum class CCEKind {
834 CaseValue, ///< Expression in a case label.
835 Enumerator, ///< Enumerator value with fixed underlying type.
836 TemplateArg, ///< Value of a non-type template parameter.
837 TempArgStrict, ///< As above, but applies strict template checking
838 ///< rules.
839 ArrayBound, ///< Array bound in array declarator or new-expression.
840 ExplicitBool, ///< Condition in an explicit(bool) specifier.
841 Noexcept, ///< Condition in a noexcept(bool) specifier.
842 StaticAssertMessageSize, ///< Call to size() in a static assert
843 ///< message.
844 StaticAssertMessageData, ///< Call to data() in a static assert
845 ///< message.
846 PackIndex ///< Index of a pack indexing expression or specifier.
847};
848
849/// Enums for the diagnostics of target, target_version and target_clones.
850namespace DiagAttrParams {
854} // end namespace DiagAttrParams
855
856void inferNoReturnAttr(Sema &S, Decl *D);
857
858#ifdef __GNUC__
859#pragma GCC diagnostic push
860#pragma GCC diagnostic ignored "-Wattributes"
861#endif
862/// Sema - This implements semantic analysis and AST building for C.
863/// \nosubgrouping
864class Sema final : public SemaBase {
865#ifdef __GNUC__
866#pragma GCC diagnostic pop
867#endif
868 // Table of Contents
869 // -----------------
870 // 1. Semantic Analysis (Sema.cpp)
871 // 2. API Notes (SemaAPINotes.cpp)
872 // 3. C++ Access Control (SemaAccess.cpp)
873 // 4. Attributes (SemaAttr.cpp)
874 // 5. Availability Attribute Handling (SemaAvailability.cpp)
875 // 6. Bounds Safety (SemaBoundsSafety.cpp)
876 // 7. Casts (SemaCast.cpp)
877 // 8. Extra Semantic Checking (SemaChecking.cpp)
878 // 9. C++ Coroutines (SemaCoroutine.cpp)
879 // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
880 // 11. Declarations (SemaDecl.cpp)
881 // 12. Declaration Attribute Handling (SemaDeclAttr.cpp)
882 // 13. C++ Declarations (SemaDeclCXX.cpp)
883 // 14. C++ Exception Specifications (SemaExceptionSpec.cpp)
884 // 15. Expressions (SemaExpr.cpp)
885 // 16. C++ Expressions (SemaExprCXX.cpp)
886 // 17. Member Access Expressions (SemaExprMember.cpp)
887 // 18. Initializers (SemaInit.cpp)
888 // 19. C++ Lambda Expressions (SemaLambda.cpp)
889 // 20. Name Lookup (SemaLookup.cpp)
890 // 21. Modules (SemaModule.cpp)
891 // 22. C++ Overloading (SemaOverload.cpp)
892 // 23. Statements (SemaStmt.cpp)
893 // 24. `inline asm` Statement (SemaStmtAsm.cpp)
894 // 25. Statement Attribute Handling (SemaStmtAttr.cpp)
895 // 26. C++ Templates (SemaTemplate.cpp)
896 // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
897 // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp)
898 // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
899 // 30. C++ Template Declaration Instantiation
900 // (SemaTemplateInstantiateDecl.cpp)
901 // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp)
902 // 32. Constraints and Concepts (SemaConcept.cpp)
903 // 33. Types (SemaType.cpp)
904 // 34. FixIt Helpers (SemaFixItUtils.cpp)
905 // 35. Function Effects (SemaFunctionEffects.cpp)
906 // 36. C++ Expansion Statements (SemaExpand.cpp)
907
908 /// \name Semantic Analysis
909 /// Implementations are in Sema.cpp
910 ///@{
911
912public:
913 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
915 CodeCompleteConsumer *CompletionConsumer = nullptr);
916 ~Sema();
917
918 /// Perform initialization that occurs after the parser has been
919 /// initialized but before it parses anything.
920 void Initialize();
921
922 /// This virtual key function only exists to limit the emission of debug info
923 /// describing the Sema class. GCC and Clang only emit debug info for a class
924 /// with a vtable when the vtable is emitted. Sema is final and not
925 /// polymorphic, but the debug info size savings are so significant that it is
926 /// worth adding a vtable just to take advantage of this optimization.
928
929 const LangOptions &getLangOpts() const { return LangOpts; }
932
935 Preprocessor &getPreprocessor() const { return PP; }
936 ASTContext &getASTContext() const { return Context; }
940
942 StringRef Platform);
944
945 /// Registers an external source. If an external source already exists,
946 /// creates a multiplex external source and appends to it.
947 ///
948 ///\param[in] E - A non-null external sema source.
949 ///
951
952 /// Print out statistics about the semantic analysis.
953 void PrintStats() const;
954
955 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
956 /// guaranteed). Produces a warning if we're low on stack space and allocates
957 /// more in that case. Use this in code that may recurse deeply (for example,
958 /// in template instantiation) to avoid stack overflow.
960 llvm::function_ref<void()> Fn);
961
962 /// Returns default addr space for method qualifiers.
964
965 /// Load weak undeclared identifiers from the external source.
967
968 /// Load #pragma redefine_extname'd undeclared identifiers from the external
969 /// source.
971
972 /// Determine if VD, which must be a variable or function, is an external
973 /// symbol that nonetheless can't be referenced from outside this translation
974 /// unit because its type has no linkage and it's not extern "C".
975 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
976
977 /// Determines whether the given source location is in the main file
978 /// and we're in a context where we should warn about unused entities.
979 bool isMainFileLoc(SourceLocation Loc) const;
980
981 /// Obtain a sorted list of functions that are undefined but ODR-used.
983 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined);
984
985 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
987 /// Retrieves list of suspicious delete-expressions that will be checked at
988 /// the end of translation unit.
989 const llvm::MapVector<FieldDecl *, DeleteLocs> &
991
992 /// Cause the built diagnostic to be emitted on the DiagosticsEngine.
993 /// This is closely coupled to the SemaDiagnosticBuilder class and
994 /// should not be used elsewhere.
995 void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB);
996
997 void addImplicitTypedef(StringRef Name, QualType T);
998
999 /// Whether uncompilable error has occurred. This includes error happens
1000 /// in deferred diagnostics.
1001 bool hasUncompilableErrorOccurred() const;
1002
1003 /// Looks through the macro-expansion chain for the given
1004 /// location, looking for a macro expansion with the given name.
1005 /// If one is found, returns true and sets the location to that
1006 /// expansion loc.
1007 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1008
1009 /// Calls \c Lexer::getLocForEndOfToken()
1010 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1011
1012 /// Calls \c Lexer::findNextToken() to find the next token, and if the
1013 /// locations of both ends of the token can be resolved it return that
1014 /// range; Otherwise it returns an invalid SourceRange.
1016 SourceLocation Loc, bool IncludeMacros, bool IncludeComments,
1017 std::optional<tok::TokenKind> ExpectedToken = std::nullopt);
1018
1019 /// Retrieve the module loader associated with the preprocessor.
1021
1022 /// Invent a new identifier for parameters of abbreviated templates.
1025 unsigned Index);
1026
1028
1029 // Emit all deferred diagnostics.
1030 void emitDeferredDiags();
1031
1032 /// This is called before the very first declaration in the translation unit
1033 /// is parsed. Note that the ASTContext may have already injected some
1034 /// declarations.
1036 /// ActOnEndOfTranslationUnit - This is called at the very end of the
1037 /// translation unit when EOF is reached and all but the top-level scope is
1038 /// popped.
1041
1042 /// Determines the active Scope associated with the given declaration
1043 /// context.
1044 ///
1045 /// This routine maps a declaration context to the active Scope object that
1046 /// represents that declaration context in the parser. It is typically used
1047 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1048 /// declarations) that injects a name for name-lookup purposes and, therefore,
1049 /// must update the Scope.
1050 ///
1051 /// \returns The scope corresponding to the given declaraion context, or NULL
1052 /// if no such scope is open.
1054
1055 void PushFunctionScope();
1056 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1058
1059 /// This is used to inform Sema what the current TemplateParameterDepth
1060 /// is during Parsing. Currently it is used to pass on the depth
1061 /// when parsing generic lambda 'auto' parameters.
1062 void RecordParsingTemplateParameterDepth(unsigned Depth);
1063
1064 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1066 unsigned OpenMPCaptureLevel = 0);
1067
1068 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1069 /// time after they've been popped.
1071 Sema *Self;
1072
1073 public:
1074 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1076 };
1077
1079 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1080
1081 /// Pop a function (or block or lambda or captured region) scope from the
1082 /// stack.
1083 ///
1084 /// \param WP The warning policy to use for CFG-based warnings, or null if
1085 /// such warnings should not be produced.
1086 /// \param D The declaration corresponding to this function scope, if
1087 /// producing CFG-based warnings.
1088 /// \param BlockType The type of the block expression, if D is a BlockDecl.
1091 Decl *D = nullptr, QualType BlockType = QualType());
1092
1094
1099
1100 void PushCompoundScope(bool IsStmtExpr);
1101 void PopCompoundScope();
1102
1103 /// Determine whether any errors occurred within this function/method/
1104 /// block.
1106
1107 /// Retrieve the current block, if any.
1109
1110 /// Get the innermost lambda or block enclosing the current location, if any.
1111 /// This looks through intervening non-lambda, non-block scopes such as local
1112 /// functions.
1114
1115 /// Retrieve the current lambda scope info, if any.
1116 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1117 /// lambda scope info ignoring all inner capturing scopes that are not
1118 /// lambda scopes.
1120 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1121
1122 /// Retrieve the current generic lambda info, if any.
1124
1125 /// Retrieve the current captured region, if any.
1127
1128 void ActOnComment(SourceRange Comment);
1129
1130 /// Retrieve the parser's current scope.
1131 ///
1132 /// This routine must only be used when it is certain that semantic analysis
1133 /// and the parser are in precisely the same context, which is not the case
1134 /// when, e.g., we are performing any kind of template instantiation.
1135 /// Therefore, the only safe places to use this scope are in the parser
1136 /// itself and in routines directly invoked from the parser and *never* from
1137 /// template substitution or instantiation.
1138 Scope *getCurScope() const { return CurScope; }
1139
1141
1145
1146 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
1147 const FunctionDecl *FD = nullptr);
1149 const PartialDiagnostic &PD,
1150 const FunctionDecl *FD = nullptr) {
1151 return targetDiag(Loc, PD.getDiagID(), FD) << PD;
1152 }
1153
1154 /// Check if the type is allowed to be used for the current target.
1156 ValueDecl *D = nullptr);
1157
1158 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
1159 /// cast. If there is already an implicit cast, merge into the existing one.
1160 /// If isLvalue, the result of the cast is an lvalue.
1163 const CXXCastPath *BasePath = nullptr,
1165
1166 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
1167 /// to the conversion from scalar type ScalarTy to the Boolean type.
1169
1170 /// If \p AllowLambda is true, treat lambda as function.
1171 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
1172
1173 /// Returns a pointer to the innermost enclosing function, or nullptr if the
1174 /// current context is not inside a function. If \p AllowLambda is true,
1175 /// this can return the call operator of an enclosing lambda, otherwise
1176 /// lambdas are skipped when looking for an enclosing function.
1177 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
1178
1179 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1180 /// the method decl for the method being parsed. If we're currently
1181 /// in a 'block', this returns the containing context.
1183
1184 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1185 /// or C function we're in, otherwise return null. If we're currently
1186 /// in a 'block', this returns the containing context.
1188
1189 /// Warn if we're implicitly casting from a _Nullable pointer type to a
1190 /// _Nonnull one.
1192 SourceLocation Loc);
1193
1194 /// Warn when implicitly casting 0 to nullptr.
1195 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
1196
1197 /// Warn when implicitly changing function effects.
1199 SourceLocation Loc);
1200
1201 /// makeUnavailableInSystemHeader - There is an error in the current
1202 /// context. If we're still in a system header, and we can plausibly
1203 /// make the relevant declaration unavailable instead of erroring, do
1204 /// so and return true.
1206 UnavailableAttr::ImplicitReason reason);
1207
1208 /// Retrieve a suitable printing policy for diagnostics.
1212
1213 /// Retrieve a suitable printing policy for diagnostics.
1215 const Preprocessor &PP);
1216
1217 /// Scope actions.
1219
1220 /// Determine whether \param D is function like (function or function
1221 /// template) for parsing.
1223
1224 /// The maximum alignment, same as in llvm::Value. We duplicate them here
1225 /// because that allows us not to duplicate the constants in clang code,
1226 /// which we must to since we can't directly use the llvm constants.
1227 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
1228 ///
1229 /// This is the greatest alignment value supported by load, store, and alloca
1230 /// instructions, and global values.
1231 static const unsigned MaxAlignmentExponent = 32;
1232 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
1233
1234 /// Flag indicating whether or not to collect detailed statistics.
1236
1237 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
1238
1239 /// Stack containing information about each of the nested
1240 /// function, block, and method scopes that are currently active.
1242
1243 /// The index of the first FunctionScope that corresponds to the current
1244 /// context.
1246
1247 /// Track the number of currently active capturing scopes.
1249
1250 llvm::BumpPtrAllocator BumpAlloc;
1251
1252 /// The kind of translation unit we are processing.
1253 ///
1254 /// When we're processing a complete translation unit, Sema will perform
1255 /// end-of-translation-unit semantic tasks (such as creating
1256 /// initializers for tentative definitions in C) once parsing has
1257 /// completed. Modules and precompiled headers perform different kinds of
1258 /// checks.
1260
1261 /// Translation Unit Scope - useful to Objective-C actions that need
1262 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1263 /// For example, user-defined classes, built-in "id" type, etc.
1265
1267 return CurScope->incrementMSManglingNumber();
1268 }
1269
1270 /// Try to recover by turning the given expression into a
1271 /// call. Returns true if recovery was attempted or an error was
1272 /// emitted; this may also leave the ExprResult invalid.
1274 bool ForceComplain = false,
1275 bool (*IsPlausibleResult)(QualType) = nullptr);
1276
1277 // Adds implicit lifetime bound attribute for implicit this to its
1278 // TypeSourceInfo.
1280
1281 /// Figure out if an expression could be turned into a call.
1282 ///
1283 /// Use this when trying to recover from an error where the programmer may
1284 /// have written just the name of a function instead of actually calling it.
1285 ///
1286 /// \param E - The expression to examine.
1287 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1288 /// with no arguments, this parameter is set to the type returned by such a
1289 /// call; otherwise, it is set to an empty QualType.
1290 /// \param OverloadSet - If the expression is an overloaded function
1291 /// name, this parameter is populated with the decls of the various
1292 /// overloads.
1293 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1294 UnresolvedSetImpl &NonTemplateOverloads);
1295
1299
1302
1310
1311 std::unique_ptr<APINotesSelectorDiagnosticState> APINotesSelectorDiagnostics;
1312
1313 /// A RAII object to enter scope of a compound statement.
1315 public:
1316 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
1317 S.ActOnStartOfCompoundStmt(IsStmtExpr);
1318 }
1319
1320 ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); }
1323
1324 private:
1325 Sema &S;
1326 };
1327
1328 /// An RAII helper that pops function a function scope on exit.
1334 if (Active)
1335 S.PopFunctionScopeInfo();
1336 }
1337 void disable() { Active = false; }
1338 };
1339
1341 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1342 }
1343
1344 /// Worker object for performing CFG-based warnings.
1347
1348 /// Callback to the parser to parse templated functions when needed.
1349 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
1352
1354 LateTemplateParser = LTP;
1355 OpaqueParser = P;
1356 }
1357
1358 /// Callback to the parser to parse a type expressed as a string.
1359 std::function<TypeResult(StringRef, StringRef, SourceLocation)>
1361
1362 /// VAListTagName - The declaration name corresponding to __va_list_tag.
1363 /// This is used as part of a hack to omit that class from ADL results.
1365
1366 /// Is the last error level diagnostic immediate. This is used to determined
1367 /// whether the next info diagnostic should be immediate.
1369
1370 /// Track if we're currently analyzing overflow behavior types in assignment
1371 /// context.
1373
1374 class DelayedDiagnostics;
1375
1377 sema::DelayedDiagnosticPool *SavedPool = nullptr;
1379 };
1382
1383 /// A class which encapsulates the logic for delaying diagnostics
1384 /// during parsing and other processing.
1386 /// The current pool of diagnostics into which delayed
1387 /// diagnostics should go.
1388 sema::DelayedDiagnosticPool *CurPool = nullptr;
1389
1390 public:
1392
1393 /// Adds a delayed diagnostic.
1394 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
1395
1396 /// Determines whether diagnostics should be delayed.
1397 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
1398
1399 /// Returns the current delayed-diagnostics pool.
1400 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
1401
1402 /// Enter a new scope. Access and deprecation diagnostics will be
1403 /// collected in this pool.
1406 state.SavedPool = CurPool;
1407 CurPool = &pool;
1408 return state;
1409 }
1410
1411 /// Leave a delayed-diagnostic state that was previously pushed.
1412 /// Do not emit any of the diagnostics. This is performed as part
1413 /// of the bookkeeping of popping a pool "properly".
1415 CurPool = state.SavedPool;
1416 }
1417
1418 /// Enter a new scope where access and deprecation diagnostics are
1419 /// not delayed.
1422 state.SavedPool = CurPool;
1423 CurPool = nullptr;
1424 return state;
1425 }
1426
1427 /// Undo a previous pushUndelayed().
1429 assert(CurPool == nullptr);
1430 CurPool = state.SavedPool;
1431 }
1433
1437
1438 /// Diagnostics that are emitted only if we discover that the given function
1439 /// must be codegen'ed. Because handling these correctly adds overhead to
1440 /// compilation, this is currently only used for offload languages like CUDA,
1441 /// OpenMP, and SYCL.
1442 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
1443
1444 /// CurContext - This is the current declaration context of parsing.
1446
1448 assert(AMDGPUPtr);
1449 return *AMDGPUPtr;
1450 }
1451
1453 assert(ARMPtr);
1454 return *ARMPtr;
1455 }
1456
1458 assert(AVRPtr);
1459 return *AVRPtr;
1460 }
1461
1463 assert(BPFPtr);
1464 return *BPFPtr;
1465 }
1466
1468 assert(CodeCompletionPtr);
1469 return *CodeCompletionPtr;
1470 }
1471
1473 assert(CUDAPtr);
1474 return *CUDAPtr;
1475 }
1476
1478 assert(DirectXPtr);
1479 return *DirectXPtr;
1480 }
1481
1483 assert(HLSLPtr);
1484 return *HLSLPtr;
1485 }
1486
1488 assert(HexagonPtr);
1489 return *HexagonPtr;
1490 }
1491
1493 assert(LoongArchPtr);
1494 return *LoongArchPtr;
1495 }
1496
1498 assert(M68kPtr);
1499 return *M68kPtr;
1500 }
1501
1503 assert(MIPSPtr);
1504 return *MIPSPtr;
1505 }
1506
1508 assert(MSP430Ptr);
1509 return *MSP430Ptr;
1510 }
1511
1513 assert(NVPTXPtr);
1514 return *NVPTXPtr;
1515 }
1516
1518 assert(ObjCPtr);
1519 return *ObjCPtr;
1520 }
1521
1523 assert(OpenACCPtr);
1524 return *OpenACCPtr;
1525 }
1526
1528 assert(OpenCLPtr);
1529 return *OpenCLPtr;
1530 }
1531
1533 assert(OpenMPPtr && "SemaOpenMP is dead");
1534 return *OpenMPPtr;
1535 }
1536
1538 assert(PPCPtr);
1539 return *PPCPtr;
1540 }
1541
1543 assert(PseudoObjectPtr);
1544 return *PseudoObjectPtr;
1545 }
1546
1548 assert(RISCVPtr);
1549 return *RISCVPtr;
1550 }
1551
1553 assert(SPIRVPtr);
1554 return *SPIRVPtr;
1555 }
1556
1558 assert(SYCLPtr);
1559 return *SYCLPtr;
1560 }
1561
1563 assert(SwiftPtr);
1564 return *SwiftPtr;
1565 }
1566
1568 assert(SystemZPtr);
1569 return *SystemZPtr;
1570 }
1571
1573 assert(WasmPtr);
1574 return *WasmPtr;
1575 }
1576
1578 assert(X86Ptr);
1579 return *X86Ptr;
1580 }
1581
1582 /// Source of additional semantic information.
1584
1585protected:
1586 friend class Parser;
1588 friend class ASTReader;
1589 friend class ASTDeclReader;
1590 friend class ASTWriter;
1591
1592private:
1593 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1594 bool WarnedDarwinSDKInfoMissing = false;
1595
1596 StackExhaustionHandler StackHandler;
1597
1598 Sema(const Sema &) = delete;
1599 void operator=(const Sema &) = delete;
1600
1601 /// The handler for the FileChanged preprocessor events.
1602 ///
1603 /// Used for diagnostics that implement custom semantic analysis for #include
1604 /// directives, like -Wpragma-pack.
1605 sema::SemaPPCallbacks *SemaPPCallbackHandler;
1606
1607 /// The parser's current scope.
1608 ///
1609 /// The parser maintains this state here.
1610 Scope *CurScope;
1611
1612 mutable IdentifierInfo *Ident_super;
1613
1614 std::unique_ptr<SemaAMDGPU> AMDGPUPtr;
1615 std::unique_ptr<SemaARM> ARMPtr;
1616 std::unique_ptr<SemaAVR> AVRPtr;
1617 std::unique_ptr<SemaBPF> BPFPtr;
1618 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1619 std::unique_ptr<SemaCUDA> CUDAPtr;
1620 std::unique_ptr<SemaDirectX> DirectXPtr;
1621 std::unique_ptr<SemaHLSL> HLSLPtr;
1622 std::unique_ptr<SemaHexagon> HexagonPtr;
1623 std::unique_ptr<SemaLoongArch> LoongArchPtr;
1624 std::unique_ptr<SemaM68k> M68kPtr;
1625 std::unique_ptr<SemaMIPS> MIPSPtr;
1626 std::unique_ptr<SemaMSP430> MSP430Ptr;
1627 std::unique_ptr<SemaNVPTX> NVPTXPtr;
1628 std::unique_ptr<SemaObjC> ObjCPtr;
1629 std::unique_ptr<SemaOpenACC> OpenACCPtr;
1630 std::unique_ptr<SemaOpenCL> OpenCLPtr;
1631 std::unique_ptr<SemaOpenMP> OpenMPPtr;
1632 std::unique_ptr<SemaPPC> PPCPtr;
1633 std::unique_ptr<SemaPseudoObject> PseudoObjectPtr;
1634 std::unique_ptr<SemaRISCV> RISCVPtr;
1635 std::unique_ptr<SemaSPIRV> SPIRVPtr;
1636 std::unique_ptr<SemaSYCL> SYCLPtr;
1637 std::unique_ptr<SemaSwift> SwiftPtr;
1638 std::unique_ptr<SemaSystemZ> SystemZPtr;
1639 std::unique_ptr<SemaWasm> WasmPtr;
1640 std::unique_ptr<SemaX86> X86Ptr;
1641
1642 ///@}
1643
1644 //
1645 //
1646 // -------------------------------------------------------------------------
1647 //
1648 //
1649
1650 /// \name API Notes
1651 /// Implementations are in SemaAPINotes.cpp
1652 ///@{
1653
1654public:
1655 /// Map any API notes provided for this declaration to attributes on the
1656 /// declaration.
1657 ///
1658 /// Triggered by declaration-attribute processing.
1659 void ProcessAPINotes(Decl *D);
1660 /// Apply the 'Nullability:' annotation to the specified declaration
1661 void ApplyNullability(Decl *D, NullabilityKind Nullability);
1662 /// Apply the 'Type:' annotation to the specified declaration
1663 void ApplyAPINotesType(Decl *D, StringRef TypeString);
1664
1665 /// Diagnose exact API notes selectors that were not matched by any
1666 /// declaration processed in this translation unit.
1668
1669 /// Whether APINotes should be gathered for all applicable Swift language
1670 /// versions, without being applied. Leaving clients of the current module
1671 /// to select and apply the correct version.
1673 return APINotes.captureVersionIndependentSwift();
1674 }
1675 ///@}
1676
1677 //
1678 //
1679 // -------------------------------------------------------------------------
1680 //
1681 //
1682
1683 /// \name C++ Access Control
1684 /// Implementations are in SemaAccess.cpp
1685 ///@{
1686
1687public:
1694
1695 /// SetMemberAccessSpecifier - Set the access specifier of a member.
1696 /// Returns true on error (when the previous member decl access specifier
1697 /// is different from the new member decl access specifier).
1698 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1699 NamedDecl *PrevMemberDecl,
1700 AccessSpecifier LexicalAS);
1701
1702 /// Perform access-control checking on a previously-unresolved member
1703 /// access which has now been resolved to a member.
1705 DeclAccessPair FoundDecl);
1707 DeclAccessPair FoundDecl);
1708
1709 /// Checks access to an overloaded operator new or delete.
1711 SourceRange PlacementRange,
1712 CXXRecordDecl *NamingClass,
1713 DeclAccessPair FoundDecl,
1714 bool Diagnose = true);
1715
1716 /// Checks access to a constructor.
1718 DeclAccessPair FoundDecl,
1719 const InitializedEntity &Entity,
1720 bool IsCopyBindingRefToTemp = false);
1721
1722 /// Checks access to a constructor.
1724 DeclAccessPair FoundDecl,
1725 const InitializedEntity &Entity,
1726 const PartialDiagnostic &PDiag);
1728 CXXDestructorDecl *Dtor,
1729 const PartialDiagnostic &PDiag,
1730 QualType objectType = QualType());
1731
1732 /// Checks access to the target of a friend declaration.
1734
1735 /// Checks access to a member.
1737 CXXRecordDecl *NamingClass,
1739
1740 /// Checks implicit access to a member in a structured binding.
1743 CXXRecordDecl *DecomposedClass,
1744 DeclAccessPair Field);
1746 const SourceRange &,
1747 DeclAccessPair FoundDecl);
1748
1749 /// Checks access to an overloaded member operator, including
1750 /// conversion operators.
1752 Expr *ArgExpr,
1753 DeclAccessPair FoundDecl);
1755 ArrayRef<Expr *> ArgExprs,
1756 DeclAccessPair FoundDecl);
1758 DeclAccessPair FoundDecl);
1759
1760 /// Checks access for a hierarchy conversion.
1761 ///
1762 /// \param ForceCheck true if this check should be performed even if access
1763 /// control is disabled; some things rely on this for semantics
1764 /// \param ForceUnprivileged true if this check should proceed as if the
1765 /// context had no special privileges
1767 QualType Derived, const CXXBasePath &Path,
1768 unsigned DiagID, bool ForceCheck = false,
1769 bool ForceUnprivileged = false);
1770
1772 SourceLocation AccessLoc, CXXRecordDecl *Base, CXXRecordDecl *Derived,
1773 const CXXBasePath &Path, unsigned DiagID,
1774 llvm::function_ref<void(PartialDiagnostic &PD)> SetupPDiag,
1775 bool ForceCheck = false, bool ForceUnprivileged = false);
1776
1777 /// Checks access to all the declarations in the given result set.
1778 void CheckLookupAccess(const LookupResult &R);
1779
1780 /// Checks access to Target from the given class. The check will take access
1781 /// specifiers into account, but no member access expressions and such.
1782 ///
1783 /// \param Target the declaration to check if it can be accessed
1784 /// \param NamingClass the class in which the lookup was started.
1785 /// \param BaseType type of the left side of member access expression.
1786 /// \p BaseType and \p NamingClass are used for C++ access control.
1787 /// Depending on the lookup case, they should be set to the following:
1788 /// - lhs.target (member access without a qualifier):
1789 /// \p BaseType and \p NamingClass are both the type of 'lhs'.
1790 /// - lhs.X::target (member access with a qualifier):
1791 /// BaseType is the type of 'lhs', NamingClass is 'X'
1792 /// - X::target (qualified lookup without member access):
1793 /// BaseType is null, NamingClass is 'X'.
1794 /// - target (unqualified lookup).
1795 /// BaseType is null, NamingClass is the parent class of 'target'.
1796 /// \return true if the Target is accessible from the Class, false otherwise.
1797 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1798 QualType BaseType);
1799
1800 /// Is the given member accessible for the purposes of deciding whether to
1801 /// define a special member function as deleted?
1803 DeclAccessPair Found, QualType ObjectType,
1804 SourceLocation Loc,
1805 const PartialDiagnostic &Diag);
1808 QualType ObjectType) {
1809 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1810 SourceLocation(), PDiag());
1811 }
1812
1814 const DependentDiagnostic &DD,
1815 const MultiLevelTemplateArgumentList &TemplateArgs);
1817
1818 ///@}
1819
1820 //
1821 //
1822 // -------------------------------------------------------------------------
1823 //
1824 //
1825
1826 /// \name Attributes
1827 /// Implementations are in SemaAttr.cpp
1828 ///@{
1829
1830public:
1831 /// Controls member pointer representation format under the MS ABI.
1834
1835 bool MSStructPragmaOn; // True when \#pragma ms_struct on
1836
1837 /// Source location for newly created implicit MSInheritanceAttrs
1839
1845
1851
1853 PSK_Reset = 0x0, // #pragma ()
1854 PSK_Set = 0x1, // #pragma (value)
1855 PSK_Push = 0x2, // #pragma (push[, id])
1856 PSK_Pop = 0x4, // #pragma (pop[, id])
1857 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
1858 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1859 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
1860 };
1861
1867
1868 // #pragma pack and align.
1870 public:
1871 // `Native` represents default align mode, which may vary based on the
1872 // platform.
1873 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1874
1875 // #pragma pack info constructor
1876 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1877 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1878 assert(Num == PackNumber && "The pack number has been truncated.");
1879 }
1880
1881 // #pragma align info constructor
1883 : PackAttr(false), AlignMode(M),
1884 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1885
1886 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1887
1889
1890 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1891 // integer encoding for it. This should only be passed to
1892 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
1894 std::uint32_t Encoding{};
1895 if (Info.IsXLStack())
1896 Encoding |= IsXLMask;
1897
1898 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1899
1900 if (Info.IsPackAttr())
1901 Encoding |= PackAttrMask;
1902
1903 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1904
1905 return Encoding;
1906 }
1907
1908 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1909 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1911 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1912 int PackNumber = (Encoding & PackNumMask) >> 4;
1913
1914 if (Encoding & PackAttrMask)
1915 return AlignPackInfo(M, PackNumber, IsXL);
1916
1917 return AlignPackInfo(M, IsXL);
1918 }
1919
1920 bool IsPackAttr() const { return PackAttr; }
1921
1922 bool IsAlignAttr() const { return !PackAttr; }
1923
1924 Mode getAlignMode() const { return AlignMode; }
1925
1926 unsigned getPackNumber() const { return PackNumber; }
1927
1928 bool IsPackSet() const {
1929 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1930 // attriute on a decl.
1931 return PackNumber != UninitPackVal && PackNumber != 0;
1932 }
1933
1934 bool IsXLStack() const { return XLStack; }
1935
1936 bool operator==(const AlignPackInfo &Info) const {
1937 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
1938 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
1939 Info.XLStack);
1940 }
1941
1942 bool operator!=(const AlignPackInfo &Info) const {
1943 return !(*this == Info);
1944 }
1945
1946 private:
1947 /// \brief True if this is a pragma pack attribute,
1948 /// not a pragma align attribute.
1949 bool PackAttr;
1950
1951 /// \brief The alignment mode that is in effect.
1952 Mode AlignMode;
1953
1954 /// \brief The pack number of the stack.
1955 unsigned char PackNumber;
1956
1957 /// \brief True if it is a XL #pragma align/pack stack.
1958 bool XLStack;
1959
1960 /// \brief Uninitialized pack value.
1961 static constexpr unsigned char UninitPackVal = -1;
1962
1963 // Masks to encode and decode an AlignPackInfo.
1964 static constexpr uint32_t IsXLMask{0x0000'0001};
1965 static constexpr uint32_t AlignModeMask{0x0000'0006};
1966 static constexpr uint32_t PackAttrMask{0x00000'0008};
1967 static constexpr uint32_t PackNumMask{0x0000'01F0};
1968 };
1969
1970 template <typename ValueType> struct PragmaStack {
1982
1983 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
1984 llvm::StringRef StackSlotLabel, ValueType Value) {
1985 if (Action == PSK_Reset) {
1987 CurrentPragmaLocation = PragmaLocation;
1988 return;
1989 }
1990 if (Action & PSK_Push)
1991 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
1992 PragmaLocation);
1993 else if (Action & PSK_Pop) {
1994 if (!StackSlotLabel.empty()) {
1995 // If we've got a label, try to find it and jump there.
1996 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
1997 return x.StackSlotLabel == StackSlotLabel;
1998 });
1999 // If we found the label so pop from there.
2000 if (I != Stack.rend()) {
2001 CurrentValue = I->Value;
2002 CurrentPragmaLocation = I->PragmaLocation;
2003 Stack.erase(std::prev(I.base()), Stack.end());
2004 }
2005 } else if (!Stack.empty()) {
2006 // We do not have a label, just pop the last entry.
2007 CurrentValue = Stack.back().Value;
2008 CurrentPragmaLocation = Stack.back().PragmaLocation;
2009 Stack.pop_back();
2010 }
2011 }
2012 if (Action & PSK_Set) {
2014 CurrentPragmaLocation = PragmaLocation;
2015 }
2016 }
2017
2018 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
2019 // method body to restore the stacks on exit, so it works like this:
2020 //
2021 // struct S {
2022 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
2023 // void Method {}
2024 // #pragma <name>(pop, InternalPragmaSlot)
2025 // };
2026 //
2027 // It works even with #pragma vtordisp, although MSVC doesn't support
2028 // #pragma vtordisp(push [, id], n)
2029 // syntax.
2030 //
2031 // Push / pop a named sentinel slot.
2032 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
2033 assert((Action == PSK_Push || Action == PSK_Pop) &&
2034 "Can only push / pop #pragma stack sentinels!");
2035 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
2036 }
2037
2038 // Constructors.
2039 explicit PragmaStack(const ValueType &Default)
2041
2042 bool hasValue() const { return CurrentValue != DefaultValue; }
2043
2045 ValueType DefaultValue; // Value used for PSK_Reset action.
2046 ValueType CurrentValue;
2048 };
2049 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
2050 // we shouldn't do so if they're in a module).
2051
2052 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
2053 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
2054 ///
2055 /// 0: Suppress all vtordisps
2056 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
2057 /// structors
2058 /// 2: Always insert vtordisps to support RTTI on partially constructed
2059 /// objects
2062 // The current #pragma align/pack values and locations at each #include.
2069 // Segment #pragmas.
2074
2075 // #pragma strict_gs_check.
2077
2078 // This stack tracks the current state of Sema.CurFPFeatures.
2081 FPOptionsOverride result;
2082 if (!FpPragmaStack.hasValue()) {
2083 result = FPOptionsOverride();
2084 } else {
2085 result = FpPragmaStack.CurrentValue;
2086 }
2087 return result;
2088 }
2089
2096
2097 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
2098 // Actions should be performed only if we enter / exit a C++ method body.
2100 public:
2101 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
2106
2107 private:
2108 Sema &S;
2109 StringRef SlotLabel;
2110 bool ShouldAct;
2111 };
2112
2113 /// Last section used with #pragma init_seg.
2116
2117 /// Sections used with #pragma alloc_text.
2118 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
2119
2120 /// VisContext - Manages the stack for \#pragma GCC visibility.
2121 void *VisContext; // Really a "PragmaVisStack*"
2122
2123 /// This an attribute introduced by \#pragma clang attribute.
2130
2131 /// A push'd group of PragmaAttributeEntries.
2133 /// The location of the push attribute.
2135 /// The namespace of this push group.
2138 };
2139
2141
2142 /// The declaration that is currently receiving an attribute from the
2143 /// #pragma attribute stack.
2145
2146 /// This represents the last location of a "#pragma clang optimize off"
2147 /// directive if such a directive has not been closed by an "on" yet. If
2148 /// optimizations are currently "on", this is set to an invalid location.
2150
2151 /// Get the location for the currently active "\#pragma clang optimize
2152 /// off". If this location is invalid, then the state of the pragma is "on".
2156
2157 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
2158 /// whether the optimizations in the list passed to the pragma should be
2159 /// turned off or on. This boolean is true by default because command line
2160 /// options are honored when `#pragma optimize("", on)`.
2161 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
2163
2164 /// Set of no-builtin functions listed by \#pragma function.
2166
2167 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
2168 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
2170
2171 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
2173
2174 /// Add gsl::Pointer attribute to std::container::iterator
2175 /// \param ND The declaration that introduces the name
2176 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
2177 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
2178
2179 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
2181
2182 /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
2184
2185 /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
2187
2188 /// Add [[gsl::Pointer]] attributes for std:: types.
2190
2191 LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
2192 StringRef ParamName);
2193 // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
2194 // can be the name of a function parameter, we need to parse the function
2195 // declaration and rest of the parameters before processesing 'X'. Therefore
2196 // do this lazily instead of processing while parsing the annotation itself.
2198
2199 /// Add _Nullable attributes for std:: types.
2201
2202 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
2205 PragmaClangSectionKind SecKind,
2206 StringRef SecName);
2207
2208 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
2210 SourceLocation PragmaLoc);
2211
2212 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
2213 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
2214 StringRef SlotLabel, Expr *Alignment);
2215
2216 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
2217 /// (unless they are value dependent or type dependent). Returns false
2218 /// and emits a diagnostic if one or more of the arguments could not be
2219 /// folded into a constant.
2222
2227
2229 SourceLocation IncludeLoc);
2231
2232 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
2234
2235 /// ActOnPragmaMSComment - Called on well formed
2236 /// \#pragma comment(kind, "arg").
2238 StringRef Arg);
2239
2240 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
2241 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
2242 StringRef Value);
2243
2244 /// Are precise floating point semantics currently enabled?
2246 return !CurFPFeatures.getAllowFPReassociate() &&
2247 !CurFPFeatures.getNoSignedZero() &&
2248 !CurFPFeatures.getAllowReciprocal() &&
2249 !CurFPFeatures.getAllowApproxFunc();
2250 }
2251
2254
2255 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
2256 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
2258
2259 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
2260 /// pointers_to_members(representation method[, general purpose
2261 /// representation]).
2264 SourceLocation PragmaLoc);
2265
2266 /// Called on well formed \#pragma vtordisp().
2267 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
2269
2270 bool UnifySection(StringRef SectionName, int SectionFlags,
2271 NamedDecl *TheDecl);
2272 bool UnifySection(StringRef SectionName, int SectionFlags,
2273 SourceLocation PragmaSectionLocation);
2274
2275 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
2276 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
2277 PragmaMsStackAction Action,
2278 llvm::StringRef StackSlotLabel,
2279 StringLiteral *SegmentName, llvm::StringRef PragmaName);
2280
2281 /// Called on well formed \#pragma section().
2282 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
2283 StringLiteral *SegmentName);
2284
2285 /// Called on well-formed \#pragma init_seg().
2286 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
2287 StringLiteral *SegmentName);
2288
2289 /// Called on well-formed \#pragma alloc_text().
2291 SourceLocation PragmaLocation, StringRef Section,
2292 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
2293 &Functions);
2294
2295 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
2296 /// strict_gs_check.
2298 PragmaMsStackAction Action,
2299 bool Value);
2300
2301 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
2302 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
2303 SourceLocation PragmaLoc);
2304
2306 SourceLocation PragmaLoc,
2309 const IdentifierInfo *Namespace);
2310
2311 /// Called on well-formed '\#pragma clang attribute pop'.
2313 const IdentifierInfo *Namespace);
2314
2315 /// Adds the attributes that have been specified using the
2316 /// '\#pragma clang attribute push' directives to the given declaration.
2317 void AddPragmaAttributes(Scope *S, Decl *D);
2318
2320 llvm::function_ref<void(SourceLocation, PartialDiagnostic)>;
2322 return [this](SourceLocation Loc, PartialDiagnostic PD) {
2323 // This bypasses a lot of the filters in the diag engine, as it's
2324 // to be used to attach notes to diagnostics which have already
2325 // been filtered through.
2326 DiagnosticBuilder Builder(Diags.Report(Loc, PD.getDiagID()));
2327 PD.Emit(Builder);
2328 };
2329 }
2330
2336
2338
2339 /// Called on well formed \#pragma clang optimize.
2340 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
2341
2342 /// #pragma optimize("[optimization-list]", on | off).
2343 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
2344
2345 /// Call on well formed \#pragma function.
2346 void
2348 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
2349
2351 SourceLocation NameLoc,
2352 Scope *curScope);
2353
2354 /// Information from a C++ #pragma export, for a symbol that we
2355 /// haven't seen the declaration for yet.
2360
2361 llvm::DenseMap<IdentifierInfo *, PendingPragmaInfo> PendingExportedNames;
2362
2363 /// ActonPragmaExport - called on well-formed '\#pragma export'.
2364 void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc,
2365 Scope *curScope);
2366
2367 /// Only called on function definitions; if there is a pragma in scope
2368 /// with the effect of a range-based optnone, consider marking the function
2369 /// with attribute optnone.
2371
2372 /// Only called on function definitions; if there is a `#pragma alloc_text`
2373 /// that decides which code section the function should be in, add
2374 /// attribute section to the function.
2376
2377 /// Adds the 'optnone' attribute to the function declaration if there
2378 /// are no conflicts; Loc represents the location causing the 'optnone'
2379 /// attribute to be added (usually because of a pragma).
2381
2382 /// Only called on function definitions; if there is a MSVC #pragma optimize
2383 /// in scope, consider changing the function's attributes based on the
2384 /// optimization list passed to the pragma.
2386
2387 /// Only called on function definitions; if there is a pragma in scope
2388 /// with the effect of a range-based no_builtin, consider marking the function
2389 /// with attribute no_builtin.
2391
2392 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
2393 /// add an appropriate visibility attribute.
2395
2396 /// FreeVisContext - Deallocate and null out VisContext.
2397 void FreeVisContext();
2398
2399 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
2400 void ActOnPragmaVisibility(const IdentifierInfo *VisType,
2401 SourceLocation PragmaLoc);
2402
2403 /// ActOnPragmaFPContract - Called on well formed
2404 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
2405 /// \#pragma clang fp contract
2407
2408 /// Called on well formed
2409 /// \#pragma clang fp reassociate
2410 /// or
2411 /// \#pragma clang fp reciprocal
2413 bool IsEnabled);
2414
2415 /// ActOnPragmaFenvAccess - Called on well formed
2416 /// \#pragma STDC FENV_ACCESS
2417 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
2418
2419 /// ActOnPragmaCXLimitedRange - Called on well formed
2420 /// \#pragma STDC CX_LIMITED_RANGE
2423
2424 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
2427
2428 /// Called to set constant rounding mode for floating point operations.
2429 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
2430
2431 /// Called to set exception behavior for floating point operations.
2433
2434 /// PushNamespaceVisibilityAttr - Note that we've entered a
2435 /// namespace with a visibility attribute.
2436 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
2437 SourceLocation Loc);
2438
2439 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
2440 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
2441 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
2442
2443 /// Handles semantic checking for features that are common to all attributes,
2444 /// such as checking whether a parameter was properly specified, or the
2445 /// correct number of arguments were passed, etc. Returns true if the
2446 /// attribute has been diagnosed.
2447 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
2448 bool SkipArgCountCheck = false);
2449 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
2450 bool SkipArgCountCheck = false);
2451
2452 ///@}
2453
2454 //
2455 //
2456 // -------------------------------------------------------------------------
2457 //
2458 //
2459
2460 /// \name Availability Attribute Handling
2461 /// Implementations are in SemaAvailability.cpp
2462 ///@{
2463
2464public:
2465 /// Issue any -Wunguarded-availability warnings in \c FD
2467
2469
2470 /// Retrieve the current function, if any, that should be analyzed for
2471 /// potential availability violations.
2473
2475 const ObjCInterfaceDecl *UnknownObjCClass,
2476 bool ObjCPropertyAccess,
2477 bool AvoidPartialAvailabilityChecks,
2478 ObjCInterfaceDecl *ClassReceiver);
2479
2481
2482 std::pair<AvailabilityResult, const NamedDecl *>
2483 ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
2484 ObjCInterfaceDecl *ClassReceiver);
2485 ///@}
2486
2487 //
2488 //
2489 // -------------------------------------------------------------------------
2490 //
2491 //
2492
2493 /// \name Bounds Safety
2494 /// Implementations are in SemaBoundsSafety.cpp
2495 ///@{
2496public:
2497 /// Check if applying the specified attribute variant from the "counted by"
2498 /// family of attributes to FieldDecl \p FD is semantically valid. If
2499 /// semantically invalid diagnostics will be emitted explaining the problems.
2500 ///
2501 /// \param FD The FieldDecl to apply the attribute to
2502 /// \param E The count expression on the attribute
2503 /// \param CountInBytes If true the attribute is from the "sized_by" family of
2504 /// attributes. If the false the attribute is from
2505 /// "counted_by" family of attributes.
2506 /// \param OrNull If true the attribute is from the "_or_null" suffixed family
2507 /// of attributes. If false the attribute does not have the
2508 /// suffix.
2509 ///
2510 /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g.
2511 /// \p CountInBytes and \p OrNull both being true indicates the
2512 /// `counted_by_or_null` attribute.
2513 ///
2514 /// \returns false iff semantically valid.
2515 bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
2516 bool OrNull);
2517
2518 /// Perform Bounds Safety Semantic checks for assigning to a `__counted_by` or
2519 /// `__counted_by_or_null` pointer type \param LHSTy.
2520 ///
2521 /// \param LHSTy The type being assigned to. Checks will only be performed if
2522 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2523 /// \param RHSExpr The expression being assigned from.
2524 /// \param Action The type assignment being performed
2525 /// \param Loc The SourceLocation to use for error diagnostics
2526 /// \param Assignee The ValueDecl being assigned. This is used to compute
2527 /// the name of the assignee. If the assignee isn't known this can
2528 /// be set to nullptr.
2529 /// \param ShowFullyQualifiedAssigneeName If set to true when using \p
2530 /// Assignee to compute the name of the assignee use the fully
2531 /// qualified name, otherwise use the unqualified name.
2532 ///
2533 /// \returns True iff no diagnostic where emitted, false otherwise.
2535 QualType LHSTy, Expr *RHSExpr, AssignmentAction Action,
2536 SourceLocation Loc, const ValueDecl *Assignee,
2537 bool ShowFullyQualifiedAssigneeName);
2538
2539 /// Perform Bounds Safety Semantic checks for initializing a Bounds Safety
2540 /// pointer.
2541 ///
2542 /// \param Entity The entity being initialized
2543 /// \param Kind The kind of initialization being performed
2544 /// \param Action The type assignment being performed
2545 /// \param LHSTy The type being assigned to. Checks will only be performed if
2546 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2547 /// \param RHSExpr The expression being used for initialization.
2548 ///
2549 /// \returns True iff no diagnostic where emitted, false otherwise.
2551 const InitializationKind &Kind,
2552 AssignmentAction Action,
2553 QualType LHSType, Expr *RHSExpr);
2554
2555 /// Perform Bounds Safety semantic checks for uses of invalid uses counted_by
2556 /// or counted_by_or_null pointers in \param E.
2557 ///
2558 /// \param E the expression to check
2559 ///
2560 /// \returns True iff no diagnostic where emitted, false otherwise.
2562 ///@}
2563
2564 //
2565 //
2566 // -------------------------------------------------------------------------
2567 //
2568 //
2569
2570 /// \name Casts
2571 /// Implementations are in SemaCast.cpp
2572 ///@{
2573
2574public:
2580
2581 /// ActOnCXXNamedCast - Parse
2582 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
2584 SourceLocation LAngleBracketLoc, Declarator &D,
2585 SourceLocation RAngleBracketLoc,
2586 SourceLocation LParenLoc, Expr *E,
2587 SourceLocation RParenLoc);
2588
2590 TypeSourceInfo *Ty, Expr *E,
2591 SourceRange AngleBrackets, SourceRange Parens);
2592
2594 ExprResult Operand,
2595 SourceLocation RParenLoc);
2596
2598 Expr *Operand, SourceLocation RParenLoc);
2599
2600 // Checks that reinterpret casts don't have undefined behavior.
2601 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2602 bool IsDereference, SourceRange Range);
2603
2604 // Checks that the vector type should be initialized from a scalar
2605 // by splatting the value rather than populating a single element.
2606 // This is the case for AltiVecVector types as well as with
2607 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
2608 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
2609
2610 // Checks if the -faltivec-src-compat=gcc option is specified.
2611 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
2612 // treated the same way as they are when trying to initialize
2613 // these vectors on gcc (an error is emitted).
2615 QualType SrcTy);
2616
2618 SourceLocation RParenLoc, Expr *Op);
2619
2621 SourceLocation LParenLoc,
2622 Expr *CastExpr,
2623 SourceLocation RParenLoc);
2624
2625 ///@}
2626
2627 //
2628 //
2629 // -------------------------------------------------------------------------
2630 //
2631 //
2632
2633 /// \name Extra Semantic Checking
2634 /// Implementations are in SemaChecking.cpp
2635 ///@{
2636
2637public:
2638 /// Used to change context to isConstantEvaluated without pushing a heavy
2639 /// ExpressionEvaluationContextRecord object.
2641
2646
2648 unsigned ByteNo) const;
2649
2651 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
2652 FAPK_Variadic, // values to format are passed as variadic arguments
2653 FAPK_VAList, // values to format are passed in a va_list
2654 FAPK_Elsewhere, // values to format are not passed to this function
2655 };
2656
2657 // Used to grab the relevant information from a FormatAttr and a
2658 // FunctionDeclaration.
2664
2665 /// Given a function and its FormatAttr or FormatMatchesAttr info, attempts to
2666 /// populate the FormatStringInfo parameter with the attribute's correct
2667 /// format_idx and firstDataArg. Returns true when the format fits the
2668 /// function and the FormatStringInfo has been populated.
2669 static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx,
2670 unsigned FirstArg, FormatStringInfo *FSI);
2671 static bool getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
2672 bool HasImplicitThisParam, bool IsVariadic,
2673 FormatStringInfo *FSI);
2674
2675 // Used by C++ template instantiation.
2677
2678 /// ConvertVectorExpr - Handle __builtin_convertvector
2680 SourceLocation BuiltinLoc,
2681 SourceLocation RParenLoc);
2682
2683 static StringRef GetFormatStringTypeName(FormatStringType FST);
2684 static FormatStringType GetFormatStringType(StringRef FormatFlavor);
2685 static FormatStringType GetFormatStringType(const FormatAttr *Format);
2686 static FormatStringType GetFormatStringType(const FormatMatchesAttr *Format);
2687
2688 bool FormatStringHasSArg(const StringLiteral *FExpr);
2689
2690 /// Check for comparisons of floating-point values using == and !=. Issue a
2691 /// warning if the comparison is not likely to do what the programmer
2692 /// intended.
2693 void CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
2694 const Expr *RHS, BinaryOperatorKind Opcode);
2695
2696 /// Register a magic integral constant to be used as a type tag.
2697 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
2698 uint64_t MagicValue, QualType Type,
2699 bool LayoutCompatible, bool MustBeNull);
2700
2703
2707
2709
2710 /// If true, \c Type should be compared with other expression's types for
2711 /// layout-compatibility.
2712 LLVM_PREFERRED_TYPE(bool)
2714 LLVM_PREFERRED_TYPE(bool)
2715 unsigned MustBeNull : 1;
2716 };
2717
2718 /// A pair of ArgumentKind identifier and magic value. This uniquely
2719 /// identifies the magic value.
2720 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
2721
2722 /// Diagnoses the current set of gathered accesses. This happens at the end of
2723 /// each expression evaluation context. Diagnostics are emitted only for
2724 /// accesses gathered in the current evaluation context.
2726
2727 /// This function checks if the expression is in the sef of potentially
2728 /// misaligned members and it is converted to some pointer type T with lower
2729 /// or equal alignment requirements. If so it removes it. This is used when
2730 /// we do not want to diagnose such misaligned access (e.g. in conversions to
2731 /// void*).
2732 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
2733
2734 /// Returns true if `From` is a function or pointer to a function with the
2735 /// `cfi_unchecked_callee` attribute but `To` is a function or pointer to
2736 /// function without this attribute.
2737 bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const;
2738
2739 /// This function calls Action when it determines that E designates a
2740 /// misaligned member due to the packed attribute. This is used to emit
2741 /// local diagnostics like in reference binding.
2743 Expr *E,
2744 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
2745 Action);
2746
2747 enum class AtomicArgumentOrder { API, AST };
2749 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
2750 SourceLocation RParenLoc, MultiExprArg Args,
2753
2754 /// Check to see if a given expression could have '.c_str()' called on it.
2755 bool hasCStrMethod(const Expr *E);
2756
2757 /// Diagnose pointers that are always non-null.
2758 /// \param E the expression containing the pointer
2759 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
2760 /// compared to a null pointer
2761 /// \param IsEqual True when the comparison is equal to a null pointer
2762 /// \param Range Extra SourceRange to highlight in the diagnostic
2765 bool IsEqual, SourceRange Range);
2766
2767 /// CheckParmsForFunctionDef - Check that the parameters of the given
2768 /// function are appropriate for the definition of a function. This
2769 /// takes care of any checks that cannot be performed on the
2770 /// declaration itself, e.g., that the types of each of the function
2771 /// parameters are complete.
2773 bool CheckParameterNames);
2774
2775 /// CheckCastAlign - Implements -Wcast-align, which warns when a
2776 /// pointer cast increases the alignment requirements.
2777 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2778
2779 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
2780 /// to weak/__unsafe_unretained type.
2781 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
2782
2783 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
2784 /// to weak/__unsafe_unretained expression.
2785 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
2786
2787 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2788 /// statement as a \p Body, and it is located on the same line.
2789 ///
2790 /// This helps prevent bugs due to typos, such as:
2791 /// if (condition);
2792 /// do_stuff();
2793 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
2794 unsigned DiagID);
2795
2796 /// Warn if a for/while loop statement \p S, which is followed by
2797 /// \p PossibleBody, has a suspicious null statement as a body.
2798 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
2799
2800 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
2801 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2802 SourceLocation OpLoc);
2803
2804 bool IsLayoutCompatible(QualType T1, QualType T2) const;
2806 const TypeSourceInfo *Derived);
2807
2808 /// CheckFunctionCall - Check a direct function call for various correctness
2809 /// and safety properties not strictly enforced by the C type system.
2810 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2811 const FunctionProtoType *Proto);
2812
2819
2820 /// \param FPOnly restricts the arguments to floating-point types.
2821 std::optional<QualType>
2822 BuiltinVectorMath(CallExpr *TheCall,
2825 bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2826
2827 void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction,
2828 const Expr *ThisArg, ArrayRef<const Expr *> Args);
2829
2830 /// Handles the checks for format strings, non-POD arguments to vararg
2831 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
2832 /// attributes and AArch64 SME attributes.
2833 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2834 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2835 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2836 VariadicCallType CallType);
2837
2838 /// Verify that two format strings (as understood by attribute(format) and
2839 /// attribute(format_matches) are compatible. If they are incompatible,
2840 /// diagnostics are emitted with the assumption that \c
2841 /// AuthoritativeFormatString is correct and
2842 /// \c TestedFormatString is wrong. If \c FunctionCallArg is provided,
2843 /// diagnostics will point to it and a note will refer to \c
2844 /// TestedFormatString or \c AuthoritativeFormatString as appropriate.
2845 bool
2847 const StringLiteral *AuthoritativeFormatString,
2848 const StringLiteral *TestedFormatString,
2849 const Expr *FunctionCallArg = nullptr);
2850
2851 /// Verify that one format string (as understood by attribute(format)) is
2852 /// self-consistent; for instance, that it doesn't have multiple positional
2853 /// arguments referring to the same argument in incompatible ways. Diagnose
2854 /// if it isn't.
2856
2857 /// \brief Enforce the bounds of a TCB
2858 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
2859 /// directly calls other functions in the same TCB as marked by the
2860 /// enforce_tcb and enforce_tcb_leaf attributes.
2861 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2862 const NamedDecl *Callee);
2863
2864 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2865
2866 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2867 /// TheCall is a constant expression.
2868 bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
2869 llvm::APSInt &Result);
2870
2871 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2872 /// TheCall is a constant expression in the range [Low, High].
2873 bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
2874 int High, bool RangeIsError = true);
2875
2876 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
2877 /// TheCall is a constant expression is a multiple of Num..
2878 bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
2879 unsigned Multiple);
2880
2881 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
2882 /// constant expression representing a power of 2.
2883 bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum);
2884
2885 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
2886 /// a constant expression representing an arbitrary byte value shifted left by
2887 /// a multiple of 8 bits.
2888 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
2889 unsigned ArgBits);
2890
2891 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
2892 /// TheCall is a constant expression representing either a shifted byte value,
2893 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
2894 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
2895 /// Arm MVE intrinsics.
2896 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum,
2897 unsigned ArgBits);
2898
2899 /// Checks that a call expression's argument count is at least the desired
2900 /// number. This is useful when doing custom type-checking on a variadic
2901 /// function. Returns true on error.
2902 bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount);
2903
2904 /// Checks that a call expression's argument count is at most the desired
2905 /// number. This is useful when doing custom type-checking on a variadic
2906 /// function. Returns true on error.
2907 bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount);
2908
2909 /// Checks that a call expression's argument count is in the desired range.
2910 /// This is useful when doing custom type-checking on a variadic function.
2911 /// Returns true on error.
2912 bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
2913 unsigned MaxArgCount);
2914
2915 /// Checks that a call expression's argument count is the desired number.
2916 /// This is useful when doing custom type-checking. Returns true on error.
2917 bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount);
2918
2919 /// Returns true if the argument consists of one contiguous run of 1s with any
2920 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
2921 /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
2922 /// since all 1s are not contiguous.
2923 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
2924
2926 bool *ICContext = nullptr,
2927 bool IsListInit = false);
2928
2929 /// Check for overflow behavior type related implicit conversion diagnostics.
2930 /// Returns true if OBT-related diagnostic was issued, false otherwise.
2932 SourceLocation CC);
2933
2934 bool
2939 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr =
2941
2942private:
2943 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
2944 const ArraySubscriptExpr *ASE = nullptr,
2945 bool AllowOnePastEnd = true, bool IndexNegated = false);
2946 void CheckArrayAccess(const Expr *E);
2947
2948 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2949 const FunctionProtoType *Proto);
2950
2951 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2952 /// such as function pointers returned from functions.
2953 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
2954
2955 /// CheckConstructorCall - Check a constructor call for correctness and safety
2956 /// properties not enforced by the C type system.
2957 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
2959 const FunctionProtoType *Proto, SourceLocation Loc);
2960
2961 /// Warn if a pointer or reference argument passed to a function points to an
2962 /// object that is less aligned than the parameter. This can happen when
2963 /// creating a typedef with a lower alignment than the original type and then
2964 /// calling functions defined in terms of the original type.
2965 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
2966 StringRef ParamName, QualType ArgTy, QualType ParamTy);
2967
2968 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
2969
2970 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2971 CallExpr *TheCall);
2972
2973 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2974 CallExpr *TheCall);
2975
2976 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
2977
2978 /// Argument-value fortify checks for libc functions that are not builtins,
2979 /// dispatched by name (e.g. umask). Diagnostics belong to -Wfortify-source.
2980 void checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall);
2981
2982 /// Check the arguments to '__builtin_va_start', '__builtin_ms_va_start',
2983 /// or '__builtin_c23_va_start' for validity. Emit an error and return true
2984 /// on failure; return false on success.
2985 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
2986 bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
2987
2988 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2989 /// friends. This is declared to take (...), so we have to check everything.
2990 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
2991
2992 /// BuiltinSemaBuiltinFPClassification - Handle functions like
2993 /// __builtin_isnan and friends. This is declared to take (...), so we have
2994 /// to check everything.
2995 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
2996 unsigned BuiltinID);
2997
2998 /// Perform semantic analysis for a call to __builtin_complex.
2999 bool BuiltinComplex(CallExpr *TheCall);
3000 bool BuiltinOSLogFormat(CallExpr *TheCall);
3001
3002 /// BuiltinPrefetch - Handle __builtin_prefetch.
3003 /// This is declared to take (const void*, ...) and can take two
3004 /// optional constant int args.
3005 bool BuiltinPrefetch(CallExpr *TheCall);
3006
3007 /// Handle __builtin_alloca_with_align. This is declared
3008 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3009 /// than 8.
3010 bool BuiltinAllocaWithAlign(CallExpr *TheCall);
3011
3012 /// BuiltinArithmeticFence - Handle __arithmetic_fence.
3013 bool BuiltinArithmeticFence(CallExpr *TheCall);
3014
3015 /// BuiltinAssume - Handle __assume (MS Extension).
3016 /// __assume does not evaluate its arguments, and should warn if its argument
3017 /// has side effects.
3018 bool BuiltinAssume(CallExpr *TheCall);
3019
3020 /// Handle __builtin_assume_aligned. This is declared
3021 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3022 bool BuiltinAssumeAligned(CallExpr *TheCall);
3023
3024 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3025 /// This checks that the target supports __builtin_longjmp and
3026 /// that val is a constant 1.
3027 bool BuiltinLongjmp(CallExpr *TheCall);
3028
3029 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3030 /// This checks that the target supports __builtin_setjmp.
3031 bool BuiltinSetjmp(CallExpr *TheCall);
3032
3033 /// We have a call to a function like __sync_fetch_and_add, which is an
3034 /// overloaded function based on the pointer type of its first argument.
3035 /// The main BuildCallExpr routines have already promoted the types of
3036 /// arguments because all of these calls are prototyped as void(...).
3037 ///
3038 /// This function goes through and does final semantic checking for these
3039 /// builtins, as well as generating any warnings.
3040 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
3041
3042 /// BuiltinNontemporalOverloaded - We have a call to
3043 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3044 /// overloaded function based on the pointer type of its last argument.
3045 ///
3046 /// This function goes through and does final semantic checking for these
3047 /// builtins.
3048 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
3049 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
3051
3052 /// \param FPOnly restricts the arguments to floating-point types.
3053 bool BuiltinElementwiseMath(CallExpr *TheCall,
3056 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
3057
3058 bool BuiltinNonDeterministicValue(CallExpr *TheCall);
3059
3060 bool CheckInvalidBuiltinCountedByRef(const Expr *E,
3062 bool BuiltinCountedByRef(CallExpr *TheCall);
3063
3064 // Matrix builtin handling.
3065 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
3066 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
3067 ExprResult CallResult);
3068 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
3069 ExprResult CallResult);
3070
3071 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3072 /// functions) for correct use of format strings.
3073 /// Returns true if a format string has been fully checked.
3074 bool CheckFormatArguments(const FormatAttr *Format,
3075 ArrayRef<const Expr *> Args, bool IsCXXMember,
3076 VariadicCallType CallType, SourceLocation Loc,
3077 SourceRange Range,
3078 llvm::SmallBitVector &CheckedVarArgs);
3079 bool CheckFormatString(const FormatMatchesAttr *Format,
3080 ArrayRef<const Expr *> Args, bool IsCXXMember,
3081 VariadicCallType CallType, SourceLocation Loc,
3082 SourceRange Range,
3083 llvm::SmallBitVector &CheckedVarArgs);
3084 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
3085 FormatArgumentPassingKind FAPK,
3086 StringLiteral *ReferenceFormatString,
3087 unsigned format_idx, unsigned firstDataArg,
3089 SourceLocation Loc, SourceRange range,
3090 llvm::SmallBitVector &CheckedVarArgs);
3091
3092 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
3093
3094 /// Warn when using the wrong abs() function.
3095 void CheckAbsoluteValueFunction(const CallExpr *Call,
3096 const FunctionDecl *FDecl);
3097
3098 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
3099
3100 /// Check for dangerous or invalid arguments to memset().
3101 ///
3102 /// This issues warnings on known problematic, dangerous or unspecified
3103 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3104 /// function calls.
3105 ///
3106 /// \param Call The call expression to diagnose.
3107 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
3108 IdentifierInfo *FnName);
3109
3110 bool CheckSizeofMemaccessArgument(const Expr *SizeOfArg, const Expr *Dest,
3111 IdentifierInfo *FnName);
3112 // Warn if the user has made the 'size' argument to strlcpy or strlcat
3113 // be the size of the source, instead of the destination.
3114 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
3115
3116 // Warn on anti-patterns as the 'size' argument to strncat.
3117 // The correct size argument should look like following:
3118 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3119 void CheckStrncatArguments(const CallExpr *Call,
3120 const IdentifierInfo *FnName);
3121
3122 /// Alerts the user that they are attempting to free a non-malloc'd object.
3123 void CheckFreeArguments(const CallExpr *E);
3124
3125 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
3126 SourceLocation ReturnLoc, bool isObjCMethod = false,
3127 const AttrVec *Attrs = nullptr,
3128 const FunctionDecl *FD = nullptr);
3129
3130 /// Diagnoses "dangerous" implicit conversions within the given
3131 /// expression (which is a full expression). Implements -Wconversion
3132 /// and -Wsign-compare.
3133 ///
3134 /// \param CC the "context" location of the implicit conversion, i.e.
3135 /// the most location of the syntactic entity requiring the implicit
3136 /// conversion
3137 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
3138
3139 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
3140 /// Input argument E is a logical expression.
3142
3143 /// Diagnose when expression is an integer constant expression and its
3144 /// evaluation results in integer overflow
3145 void CheckForIntOverflow(const Expr *E);
3146 void CheckUnsequencedOperations(const Expr *E);
3147
3148 /// Perform semantic checks on a completed expression. This will either
3149 /// be a full-expression or a default argument expression.
3150 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
3151 bool IsConstexpr = false);
3152
3153 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
3154 Expr *Init);
3155
3156 /// A map from magic value to type information.
3157 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
3158 TypeTagForDatatypeMagicValues;
3159
3160 /// Peform checks on a call of a function with argument_with_type_tag
3161 /// or pointer_with_type_tag attributes.
3162 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
3163 const ArrayRef<const Expr *> ExprArgs,
3164 SourceLocation CallSiteLoc);
3165
3166 /// Check if we are taking the address of a packed field
3167 /// as this may be a problem if the pointer value is dereferenced.
3168 void CheckAddressOfPackedMember(Expr *rhs);
3169
3170 /// Helper class that collects misaligned member designations and
3171 /// their location info for delayed diagnostics.
3172 struct MisalignedMember {
3173 Expr *E;
3174 RecordDecl *RD;
3175 ValueDecl *MD;
3176 CharUnits Alignment;
3177
3178 MisalignedMember() : E(), RD(), MD() {}
3179 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
3180 CharUnits Alignment)
3181 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
3182 explicit MisalignedMember(Expr *E)
3183 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
3184
3185 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
3186 };
3187
3188 /// Adds an expression to the set of gathered misaligned members.
3189 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
3190 CharUnits Alignment);
3191 ///@}
3192
3193 //
3194 //
3195 // -------------------------------------------------------------------------
3196 //
3197 //
3198
3199 /// \name C++ Coroutines
3200 /// Implementations are in SemaCoroutine.cpp
3201 ///@{
3202
3203public:
3204 /// The C++ "std::coroutine_traits" template, which is defined in
3205 /// <coroutine_traits>
3207
3209 StringRef Keyword);
3213
3216 UnresolvedLookupExpr *Lookup);
3218 Expr *Awaiter, bool IsImplicit = false);
3220 UnresolvedLookupExpr *Lookup);
3223 bool IsImplicit = false);
3228
3229 // As a clang extension, enforces that a non-coroutine function must be marked
3230 // with [[clang::coro_wrapper]] if it returns a type marked with
3231 // [[clang::coro_return_type]].
3232 // Expects that FD is not a coroutine.
3234 /// Lookup 'coroutine_traits' in std namespace and std::experimental
3235 /// namespace. The namespace found is recorded in Namespace.
3237 SourceLocation FuncLoc);
3238 /// Check that the expression co_await promise.final_suspend() shall not be
3239 /// potentially-throwing.
3240 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
3241
3242 ///@}
3243
3244 //
3245 //
3246 // -------------------------------------------------------------------------
3247 //
3248 //
3249
3250 /// \name C++ Scope Specifiers
3251 /// Implementations are in SemaCXXScopeSpec.cpp
3252 ///@{
3253
3254public:
3255 // Marks SS invalid if it represents an incomplete type.
3257 // Complete an enum decl, maybe without a scope spec.
3259 CXXScopeSpec *SS = nullptr);
3260
3261 /// Compute the DeclContext that is associated with the given type.
3262 ///
3263 /// \param T the type for which we are attempting to find a DeclContext.
3264 ///
3265 /// \returns the declaration context represented by the type T,
3266 /// or NULL if the declaration context cannot be computed (e.g., because it is
3267 /// dependent and not the current instantiation).
3269
3270 /// Compute the DeclContext that is associated with the given
3271 /// scope specifier.
3272 ///
3273 /// \param SS the C++ scope specifier as it appears in the source
3274 ///
3275 /// \param EnteringContext when true, we will be entering the context of
3276 /// this scope specifier, so we can retrieve the declaration context of a
3277 /// class template or class template partial specialization even if it is
3278 /// not the current instantiation.
3279 ///
3280 /// \returns the declaration context represented by the scope specifier @p SS,
3281 /// or NULL if the declaration context cannot be computed (e.g., because it is
3282 /// dependent and not the current instantiation).
3284 bool EnteringContext = false);
3286
3287 /// If the given nested name specifier refers to the current
3288 /// instantiation, return the declaration that corresponds to that
3289 /// current instantiation (C++0x [temp.dep.type]p1).
3290 ///
3291 /// \param NNS a dependent nested name specifier.
3293
3294 /// The parser has parsed a global nested-name-specifier '::'.
3295 ///
3296 /// \param CCLoc The location of the '::'.
3297 ///
3298 /// \param SS The nested-name-specifier, which will be updated in-place
3299 /// to reflect the parsed nested-name-specifier.
3300 ///
3301 /// \returns true if an error occurred, false otherwise.
3303
3304 /// The parser has parsed a '__super' nested-name-specifier.
3305 ///
3306 /// \param SuperLoc The location of the '__super' keyword.
3307 ///
3308 /// \param ColonColonLoc The location of the '::'.
3309 ///
3310 /// \param SS The nested-name-specifier, which will be updated in-place
3311 /// to reflect the parsed nested-name-specifier.
3312 ///
3313 /// \returns true if an error occurred, false otherwise.
3315 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
3316
3317 /// Determines whether the given declaration is an valid acceptable
3318 /// result for name lookup of a nested-name-specifier.
3319 /// \param SD Declaration checked for nested-name-specifier.
3320 /// \param IsExtension If not null and the declaration is accepted as an
3321 /// extension, the pointed variable is assigned true.
3323 bool *CanCorrect = nullptr);
3324
3325 /// If the given nested-name-specifier begins with a bare identifier
3326 /// (e.g., Base::), perform name lookup for that identifier as a
3327 /// nested-name-specifier within the given scope, and return the result of
3328 /// that name lookup.
3330
3331 /// Keeps information about an identifier in a nested-name-spec.
3332 ///
3334 /// The type of the object, if we're parsing nested-name-specifier in
3335 /// a member access expression.
3337
3338 /// The identifier preceding the '::'.
3340
3341 /// The location of the identifier.
3343
3344 /// The location of the '::'.
3346
3347 /// Creates info object for the most typical case.
3349 SourceLocation ColonColonLoc,
3352 CCLoc(ColonColonLoc) {}
3353
3355 SourceLocation ColonColonLoc, QualType ObjectType)
3357 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
3358 };
3359
3360 /// Build a new nested-name-specifier for "identifier::", as described
3361 /// by ActOnCXXNestedNameSpecifier.
3362 ///
3363 /// \param S Scope in which the nested-name-specifier occurs.
3364 /// \param IdInfo Parser information about an identifier in the
3365 /// nested-name-spec.
3366 /// \param EnteringContext If true, enter the context specified by the
3367 /// nested-name-specifier.
3368 /// \param SS Optional nested name specifier preceding the identifier.
3369 /// \param ScopeLookupResult Provides the result of name lookup within the
3370 /// scope of the nested-name-specifier that was computed at template
3371 /// definition time.
3372 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
3373 /// error recovery and what kind of recovery is performed.
3374 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
3375 /// are allowed. The bool value pointed by this parameter is set to
3376 /// 'true' if the identifier is treated as if it was followed by ':',
3377 /// not '::'.
3378 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3379 ///
3380 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
3381 /// that it contains an extra parameter \p ScopeLookupResult, which provides
3382 /// the result of name lookup within the scope of the nested-name-specifier
3383 /// that was computed at template definition time.
3384 ///
3385 /// If ErrorRecoveryLookup is true, then this call is used to improve error
3386 /// recovery. This means that it should not emit diagnostics, it should
3387 /// just return true on failure. It also means it should only return a valid
3388 /// scope if it *knows* that the result is correct. It should not return in a
3389 /// dependent context, for example. Nor will it extend \p SS with the scope
3390 /// specifier.
3391 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3392 bool EnteringContext, CXXScopeSpec &SS,
3393 NamedDecl *ScopeLookupResult,
3394 bool ErrorRecoveryLookup,
3395 bool *IsCorrectedToColon = nullptr,
3396 bool OnlyNamespace = false);
3397
3398 /// The parser has parsed a nested-name-specifier 'identifier::'.
3399 ///
3400 /// \param S The scope in which this nested-name-specifier occurs.
3401 ///
3402 /// \param IdInfo Parser information about an identifier in the
3403 /// nested-name-spec.
3404 ///
3405 /// \param EnteringContext Whether we're entering the context nominated by
3406 /// this nested-name-specifier.
3407 ///
3408 /// \param SS The nested-name-specifier, which is both an input
3409 /// parameter (the nested-name-specifier before this type) and an
3410 /// output parameter (containing the full nested-name-specifier,
3411 /// including this new type).
3412 ///
3413 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
3414 /// are allowed. The bool value pointed by this parameter is set to 'true'
3415 /// if the identifier is treated as if it was followed by ':', not '::'.
3416 ///
3417 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3418 ///
3419 /// \returns true if an error occurred, false otherwise.
3420 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3421 bool EnteringContext, CXXScopeSpec &SS,
3422 bool *IsCorrectedToColon = nullptr,
3423 bool OnlyNamespace = false);
3424
3425 /// The parser has parsed a nested-name-specifier
3426 /// 'template[opt] template-name < template-args >::'.
3427 ///
3428 /// \param S The scope in which this nested-name-specifier occurs.
3429 ///
3430 /// \param SS The nested-name-specifier, which is both an input
3431 /// parameter (the nested-name-specifier before this type) and an
3432 /// output parameter (containing the full nested-name-specifier,
3433 /// including this new type).
3434 ///
3435 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
3436 /// \param TemplateName the template name.
3437 /// \param TemplateNameLoc The location of the template name.
3438 /// \param LAngleLoc The location of the opening angle bracket ('<').
3439 /// \param TemplateArgs The template arguments.
3440 /// \param RAngleLoc The location of the closing angle bracket ('>').
3441 /// \param CCLoc The location of the '::'.
3442 ///
3443 /// \param EnteringContext Whether we're entering the context of the
3444 /// nested-name-specifier.
3445 ///
3446 ///
3447 /// \returns true if an error occurred, false otherwise.
3449 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3450 TemplateTy TemplateName, SourceLocation TemplateNameLoc,
3451 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
3452 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
3453
3455 SourceLocation ColonColonLoc);
3456
3458 const DeclSpec &DS,
3459 SourceLocation ColonColonLoc,
3460 QualType Type);
3461
3462 /// IsInvalidUnlessNestedName - This method is used for error recovery
3463 /// purposes to determine whether the specified identifier is only valid as
3464 /// a nested name specifier, for example a namespace name. It is
3465 /// conservatively correct to always return false from this method.
3466 ///
3467 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
3469 NestedNameSpecInfo &IdInfo,
3470 bool EnteringContext);
3471
3472 /// Given a C++ nested-name-specifier, produce an annotation value
3473 /// that the parser can use later to reconstruct the given
3474 /// nested-name-specifier.
3475 ///
3476 /// \param SS A nested-name-specifier.
3477 ///
3478 /// \returns A pointer containing all of the information in the
3479 /// nested-name-specifier \p SS.
3481
3482 /// Given an annotation pointer for a nested-name-specifier, restore
3483 /// the nested-name-specifier structure.
3484 ///
3485 /// \param Annotation The annotation pointer, produced by
3486 /// \c SaveNestedNameSpecifierAnnotation().
3487 ///
3488 /// \param AnnotationRange The source range corresponding to the annotation.
3489 ///
3490 /// \param SS The nested-name-specifier that will be updated with the contents
3491 /// of the annotation pointer.
3492 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3493 SourceRange AnnotationRange,
3494 CXXScopeSpec &SS);
3495
3496 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3497
3498 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3499 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3500 /// After this method is called, according to [C++ 3.4.3p3], names should be
3501 /// looked up in the declarator-id's scope, until the declarator is parsed and
3502 /// ActOnCXXExitDeclaratorScope is called.
3503 /// The 'SS' should be a non-empty valid CXXScopeSpec.
3505
3506 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3507 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3508 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3509 /// Used to indicate that names should revert to being looked up in the
3510 /// defining scope.
3512
3513 ///@}
3514
3515 //
3516 //
3517 // -------------------------------------------------------------------------
3518 //
3519 //
3520
3521 /// \name Declarations
3522 /// Implementations are in SemaDecl.cpp
3523 ///@{
3524
3525public:
3527
3528 /// The index of the first InventedParameterInfo that refers to the current
3529 /// context.
3531
3532 /// A RAII object to temporarily push a declaration context.
3534 private:
3535 Sema &S;
3536 DeclContext *SavedContext;
3537 ProcessingContextState SavedContextState;
3538 QualType SavedCXXThisTypeOverride;
3539 unsigned SavedFunctionScopesStart;
3540 unsigned SavedInventedParameterInfosStart;
3541
3542 public:
3543 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
3544 : S(S), SavedContext(S.CurContext),
3545 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
3546 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
3547 SavedFunctionScopesStart(S.FunctionScopesStart),
3548 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
3549 assert(ContextToPush && "pushing null context");
3550 S.CurContext = ContextToPush;
3551 if (NewThisContext)
3552 S.CXXThisTypeOverride = QualType();
3553 // Any saved FunctionScopes do not refer to this context.
3554 S.FunctionScopesStart = S.FunctionScopes.size();
3555 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
3556 }
3557
3558 void pop() {
3559 if (!SavedContext)
3560 return;
3561 S.CurContext = SavedContext;
3562 S.DelayedDiagnostics.popUndelayed(SavedContextState);
3563 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
3564 S.FunctionScopesStart = SavedFunctionScopesStart;
3565 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
3566 SavedContext = nullptr;
3567 }
3568
3570 ContextRAII(const ContextRAII &) = delete;
3572 };
3573
3574 void DiagnoseInvalidJumps(Stmt *Body);
3575
3576 /// The function definitions which were renamed as part of typo-correction
3577 /// to match their respective declarations. We want to keep track of them
3578 /// to ensure that we don't emit a "redefinition" error if we encounter a
3579 /// correctly named definition after the renamed definition.
3581
3582 /// A cache of the flags available in enumerations with the flag_enum
3583 /// attribute.
3584 llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
3585
3586 /// A cache of enumerator values for enums checked by -Wassign-enum.
3587 llvm::DenseMap<const EnumDecl *, llvm::SmallVector<llvm::APSInt>>
3589
3590 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
3591 /// declared. Rare. May alias another identifier, declared or undeclared.
3592 ///
3593 /// For aliases, the target identifier is used as a key for eventual
3594 /// processing when the target is declared. For the single-identifier form,
3595 /// the sole identifier is used as the key. Each entry is a `SetVector`
3596 /// (ordered by parse order) of aliases (identified by the alias name) in case
3597 /// of multiple aliases to the same undeclared identifier.
3598 llvm::MapVector<
3600 llvm::SetVector<
3602 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
3604
3605 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
3606 /// \#pragma redefine_extname before declared. Used in Solaris system headers
3607 /// to define functions that occur in multiple standards to call the version
3608 /// in the currently selected standard.
3609 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>
3611
3612 /// Set containing all typedefs that are likely unused.
3615
3616 /// Store UnusedLocalTypedefNameCandidates in \p Sorted in a deterministic
3617 /// order.
3620
3624
3625 /// The set of file scoped decls seen so far that have not been used
3626 /// and must warn if not used. Only contains the first declaration.
3628
3632
3633 /// All the tentative definitions encountered in the TU.
3635
3636 /// All the external declarations encoutered and used in the TU.
3638
3639 /// Generally null except when we temporarily switch decl contexts,
3640 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
3642
3643 /// Is the module scope we are in a C++ Header Unit?
3645 return ModuleScopes.empty() ? false
3646 : ModuleScopes.back().Module->isHeaderUnit();
3647 }
3648
3649 /// Get the module owning an entity.
3650 Module *getOwningModule(const Decl *Entity) {
3651 return Entity->getOwningModule();
3652 }
3653
3654 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
3655
3657 /// Returns the TypeDeclType for the given type declaration,
3658 /// as ASTContext::getTypeDeclType would, but
3659 /// performs the required semantic checks for name lookup of said entity.
3660 void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD,
3661 SourceLocation NameLoc);
3662
3663 /// If the identifier refers to a type name within this scope,
3664 /// return the declaration of that type.
3665 ///
3666 /// This routine performs ordinary name lookup of the identifier II
3667 /// within the given scope, with optional C++ scope specifier SS, to
3668 /// determine whether the name refers to a type. If so, returns an
3669 /// opaque pointer (actually a QualType) corresponding to that
3670 /// type. Otherwise, returns NULL.
3672 Scope *S, CXXScopeSpec *SS = nullptr,
3673 bool isClassName = false, bool HasTrailingDot = false,
3674 ParsedType ObjectType = nullptr,
3675 bool IsCtorOrDtorName = false,
3676 bool WantNontrivialTypeSourceInfo = false,
3677 bool IsClassTemplateDeductionContext = true,
3678 ImplicitTypenameContext AllowImplicitTypename =
3680 IdentifierInfo **CorrectedII = nullptr);
3681
3682 /// isTagName() - This method is called *for error recovery purposes only*
3683 /// to determine if the specified name is a valid tag name ("struct foo"). If
3684 /// so, this returns the TST for the tag corresponding to it (TST_enum,
3685 /// TST_union, TST_struct, TST_interface, TST_class). This is used to
3686 /// diagnose cases in C where the user forgot to specify the tag.
3688
3689 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
3690 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
3691 /// then downgrade the missing typename error to a warning.
3692 /// This is needed for MSVC compatibility; Example:
3693 /// @code
3694 /// template<class T> class A {
3695 /// public:
3696 /// typedef int TYPE;
3697 /// };
3698 /// template<class T> class B : public A<T> {
3699 /// public:
3700 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
3701 /// };
3702 /// @endcode
3703 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
3705 Scope *S, CXXScopeSpec *SS,
3706 ParsedType &SuggestedType,
3707 bool IsTemplateName = false);
3708
3709 /// Attempt to behave like MSVC in situations where lookup of an unqualified
3710 /// type name has failed in a dependent context. In these situations, we
3711 /// automatically form a DependentTypeName that will retry lookup in a related
3712 /// scope during instantiation.
3714 SourceLocation NameLoc,
3715 bool IsTemplateTypeArg);
3716
3717 class NameClassification {
3719 union {
3724 };
3725
3726 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
3727
3728 public:
3731
3734
3735 static NameClassification Error() {
3736 return NameClassification(NameClassificationKind::Error);
3737 }
3738
3739 static NameClassification Unknown() {
3740 return NameClassification(NameClassificationKind::Unknown);
3741 }
3742
3743 static NameClassification OverloadSet(ExprResult E) {
3744 NameClassification Result(NameClassificationKind::OverloadSet);
3745 Result.Expr = E;
3746 return Result;
3747 }
3748
3749 static NameClassification NonType(NamedDecl *D) {
3750 NameClassification Result(NameClassificationKind::NonType);
3751 Result.NonTypeDecl = D;
3752 return Result;
3753 }
3754
3755 static NameClassification UndeclaredNonType() {
3756 return NameClassification(NameClassificationKind::UndeclaredNonType);
3757 }
3758
3759 static NameClassification DependentNonType() {
3760 return NameClassification(NameClassificationKind::DependentNonType);
3761 }
3762
3763 static NameClassification TypeTemplate(TemplateName Name) {
3764 NameClassification Result(NameClassificationKind::TypeTemplate);
3765 Result.Template = Name;
3766 return Result;
3767 }
3768
3769 static NameClassification VarTemplate(TemplateName Name) {
3770 NameClassification Result(NameClassificationKind::VarTemplate);
3771 Result.Template = Name;
3772 return Result;
3773 }
3774
3775 static NameClassification FunctionTemplate(TemplateName Name) {
3777 Result.Template = Name;
3778 return Result;
3779 }
3780
3781 static NameClassification Concept(TemplateName Name) {
3782 NameClassification Result(NameClassificationKind::Concept);
3783 Result.Template = Name;
3784 return Result;
3785 }
3786
3787 static NameClassification UndeclaredTemplate(TemplateName Name) {
3789 Result.Template = Name;
3790 return Result;
3791 }
3792
3793 NameClassificationKind getKind() const { return Kind; }
3794
3797 return Expr;
3798 }
3799
3801 assert(Kind == NameClassificationKind::Type);
3802 return Type;
3803 }
3804
3806 assert(Kind == NameClassificationKind::NonType);
3807 return NonTypeDecl;
3808 }
3809
3818
3820 switch (Kind) {
3822 return TNK_Type_template;
3824 return TNK_Function_template;
3826 return TNK_Var_template;
3828 return TNK_Concept_template;
3831 default:
3832 llvm_unreachable("unsupported name classification.");
3833 }
3834 }
3835 };
3836
3837 /// Perform name lookup on the given name, classifying it based on
3838 /// the results of name lookup and the following token.
3839 ///
3840 /// This routine is used by the parser to resolve identifiers and help direct
3841 /// parsing. When the identifier cannot be found, this routine will attempt
3842 /// to correct the typo and classify based on the resulting name.
3843 ///
3844 /// \param S The scope in which we're performing name lookup.
3845 ///
3846 /// \param SS The nested-name-specifier that precedes the name.
3847 ///
3848 /// \param Name The identifier. If typo correction finds an alternative name,
3849 /// this pointer parameter will be updated accordingly.
3850 ///
3851 /// \param NameLoc The location of the identifier.
3852 ///
3853 /// \param NextToken The token following the identifier. Used to help
3854 /// disambiguate the name.
3855 ///
3856 /// \param CCC The correction callback, if typo correction is desired.
3857 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
3858 IdentifierInfo *&Name, SourceLocation NameLoc,
3859 const Token &NextToken,
3860 CorrectionCandidateCallback *CCC = nullptr);
3861
3862 /// Act on the result of classifying a name as an undeclared (ADL-only)
3863 /// non-type declaration.
3865 SourceLocation NameLoc);
3866 /// Act on the result of classifying a name as an undeclared member of a
3867 /// dependent base class.
3869 IdentifierInfo *Name,
3870 SourceLocation NameLoc,
3871 bool IsAddressOfOperand);
3872 /// Act on the result of classifying a name as a specific non-type
3873 /// declaration.
3876 SourceLocation NameLoc,
3877 const Token &NextToken);
3878 /// Act on the result of classifying a name as an overload set.
3880
3881 /// Describes the detailed kind of a template name. Used in diagnostics.
3893
3894 /// Determine whether it's plausible that E was intended to be a
3895 /// template-name.
3897 if (!getLangOpts().CPlusPlus || E.isInvalid())
3898 return false;
3899 Dependent = false;
3900 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
3901 return !DRE->hasExplicitTemplateArgs();
3902 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
3903 return !ME->hasExplicitTemplateArgs();
3904 Dependent = true;
3905 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
3906 return !DSDRE->hasExplicitTemplateArgs();
3907 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
3908 return !DSME->hasExplicitTemplateArgs();
3909 // Any additional cases recognized here should also be handled by
3910 // diagnoseExprIntendedAsTemplateName.
3911 return false;
3912 }
3913
3914 void warnOnReservedIdentifier(const NamedDecl *D);
3916
3917 void ProcessPragmaExport(DeclaratorDecl *newDecl);
3918
3920
3922 MultiTemplateParamsArg TemplateParameterLists);
3923
3924 /// Attempt to fold a variable-sized type to a constant-sized type, returning
3925 /// true if we were successful.
3927 SourceLocation Loc,
3928 unsigned FailedFoldDiagID);
3929
3930 /// Register the given locally-scoped extern "C" declaration so
3931 /// that it can be found later for redeclarations. We include any extern "C"
3932 /// declaration that is not visible in the translation unit here, not just
3933 /// function-scope declarations.
3935
3936 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3937 /// If T is the name of a class, then each of the following shall have a
3938 /// name different from T:
3939 /// - every static data member of class T;
3940 /// - every member function of class T
3941 /// - every member of class T that is itself a type;
3942 /// \returns true if the declaration name violates these rules.
3944
3945 /// Diagnose a declaration whose declarator-id has the given
3946 /// nested-name-specifier.
3947 ///
3948 /// \param SS The nested-name-specifier of the declarator-id.
3949 ///
3950 /// \param DC The declaration context to which the nested-name-specifier
3951 /// resolves.
3952 ///
3953 /// \param Name The name of the entity being declared.
3954 ///
3955 /// \param Loc The location of the name of the entity being declared.
3956 ///
3957 /// \param IsMemberSpecialization Whether we are declaring a member
3958 /// specialization.
3959 ///
3960 /// \param TemplateId The template-id, if any.
3961 ///
3962 /// \returns true if we cannot safely recover from this error, false
3963 /// otherwise.
3966 TemplateIdAnnotation *TemplateId,
3967 bool IsMemberSpecialization);
3968
3970
3971 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
3972
3974 unsigned &IntVal);
3975
3976 /// Diagnose function specifiers on a declaration of an identifier that
3977 /// does not identify a function.
3978 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
3979
3980 /// Return the declaration shadowed by the given typedef \p D, or null
3981 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3983 const LookupResult &R);
3984
3985 /// Return the declaration shadowed by the given variable \p D, or null
3986 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3988
3989 /// Return the declaration shadowed by the given variable \p D, or null
3990 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3992 const LookupResult &R);
3993 /// Diagnose variable or built-in function shadowing. Implements
3994 /// -Wshadow.
3995 ///
3996 /// This method is called whenever a VarDecl is added to a "useful"
3997 /// scope.
3998 ///
3999 /// \param ShadowedDecl the declaration that is shadowed by the given variable
4000 /// \param R the lookup of the name
4001 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
4002 const LookupResult &R);
4003
4004 /// Check -Wshadow without the advantage of a previous lookup.
4005 void CheckShadow(Scope *S, VarDecl *D);
4006
4007 /// Warn if 'E', which is an expression that is about to be modified, refers
4008 /// to a shadowing declaration.
4010
4011 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
4012 /// when these variables are captured by the lambda.
4014
4015 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
4016 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4017 TypedefNameDecl *NewTD);
4020 TypeSourceInfo *TInfo,
4022
4023 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4024 /// declares a typedef-name, either using the 'typedef' type specifier or via
4025 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4029 TypeSourceInfo *TInfo,
4031 MultiTemplateParamsArg TemplateParamLists,
4032 bool &AddToScope,
4034
4035private:
4036 // Perform a check on an AsmLabel to verify its consistency and emit
4037 // diagnostics in case of an error.
4038 void CheckAsmLabel(Scope *S, Expr *AsmLabelExpr, StorageClass SC,
4039 TypeSourceInfo *TInfo, VarDecl *);
4040
4041public:
4042 /// Perform semantic checking on a newly-created variable
4043 /// declaration.
4044 ///
4045 /// This routine performs all of the type-checking required for a
4046 /// variable declaration once it has been built. It is used both to
4047 /// check variables after they have been parsed and their declarators
4048 /// have been translated into a declaration, and to check variables
4049 /// that have been instantiated from a template.
4050 ///
4051 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4052 ///
4053 /// Returns true if the variable declaration is a redeclaration.
4054 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
4055 void CheckVariableDeclarationType(VarDecl *NewVD);
4056 void CheckCompleteVariableDeclaration(VarDecl *VD);
4057
4058 NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4059 TypeSourceInfo *TInfo,
4060 LookupResult &Previous,
4061 MultiTemplateParamsArg TemplateParamLists,
4062 bool &AddToScope);
4063
4064 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4065 /// and if so, check that it's a valid override and remember it.
4066 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
4067
4068 /// Perform semantic checking of a new function declaration.
4069 ///
4070 /// Performs semantic analysis of the new function declaration
4071 /// NewFD. This routine performs all semantic checking that does not
4072 /// require the actual declarator involved in the declaration, and is
4073 /// used both for the declaration of functions as they are parsed
4074 /// (called via ActOnDeclarator) and for the declaration of functions
4075 /// that have been instantiated via C++ template instantiation (called
4076 /// via InstantiateDecl).
4077 ///
4078 /// \param IsMemberSpecialization whether this new function declaration is
4079 /// a member specialization (that replaces any definition provided by the
4080 /// previous declaration).
4081 ///
4082 /// This sets NewFD->isInvalidDecl() to true if there was an error.
4083 ///
4084 /// \returns true if the function declaration is a redeclaration.
4085 bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
4086 LookupResult &Previous,
4087 bool IsMemberSpecialization, bool DeclIsDefn);
4088
4089 /// Checks if the new declaration declared in dependent context must be
4090 /// put in the same redeclaration chain as the specified declaration.
4091 ///
4092 /// \param D Declaration that is checked.
4093 /// \param PrevDecl Previous declaration found with proper lookup method for
4094 /// the same declaration name.
4095 /// \returns True if D must be added to the redeclaration chain which PrevDecl
4096 /// belongs to.
4097 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
4098
4099 /// Determines if we can perform a correct type check for \p D as a
4100 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
4101 /// best-effort check.
4102 ///
4103 /// \param NewD The new declaration.
4104 /// \param OldD The old declaration.
4105 /// \param NewT The portion of the type of the new declaration to check.
4106 /// \param OldT The portion of the type of the old declaration to check.
4107 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
4108 QualType NewT, QualType OldT);
4109 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
4110 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
4111
4112 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
4113 /// containing class. Otherwise it will return implicit SectionAttr if the
4114 /// function is a definition and there is an active value on CodeSegStack
4115 /// (from the current #pragma code-seg value).
4116 ///
4117 /// \param FD Function being declared.
4118 /// \param IsDefinition Whether it is a definition or just a declaration.
4119 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
4120 /// nullptr if no attribute should be added.
4121 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
4122 bool IsDefinition);
4123
4124 /// Common checks for a parameter-declaration that should apply to both
4125 /// function parameters and non-type template parameters.
4126 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
4127
4128 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4129 /// to introduce parameters into function prototype scope.
4130 Decl *ActOnParamDeclarator(Scope *S, Declarator &D,
4131 SourceLocation ExplicitThisLoc = {});
4132
4133 /// Synthesizes a variable for a parameter arising from a
4134 /// typedef.
4135 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
4136 QualType T);
4137 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
4138 SourceLocation NameLoc,
4139 const IdentifierInfo *Name, QualType T,
4140 TypeSourceInfo *TSInfo, StorageClass SC);
4141
4142 /// Emit diagnostics if the initializer or any of its explicit or
4143 /// implicitly-generated subexpressions require copying or
4144 /// default-initializing a type that is or contains a C union type that is
4145 /// non-trivial to copy or default-initialize.
4146 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
4147
4148 // These flags are passed to checkNonTrivialCUnion.
4154
4155 /// Emit diagnostics if a non-trivial C union type or a struct that contains
4156 /// a non-trivial C union is used in an invalid context.
4158 NonTrivialCUnionContext UseContext,
4159 unsigned NonTrivialKind);
4160
4161 /// Certain globally-unique variables might be accidentally duplicated if
4162 /// built into multiple shared libraries with hidden visibility. This can
4163 /// cause problems if the variable is mutable, its initialization is
4164 /// effectful, or its address is taken.
4167
4168 /// AddInitializerToDecl - Adds the initializer Init to the
4169 /// declaration dcl. If DirectInit is true, this is C++ direct
4170 /// initialization rather than copy initialization.
4171 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
4172 void ActOnUninitializedDecl(Decl *dcl);
4173
4174 /// ActOnInitializerError - Given that there was an error parsing an
4175 /// initializer for the given declaration, try to at least re-establish
4176 /// invariants such as whether a variable's type is either dependent or
4177 /// complete.
4178 void ActOnInitializerError(Decl *Dcl);
4179
4180 void ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt);
4182 IdentifierInfo *Ident,
4183 ParsedAttributes &Attrs);
4184
4185 /// Check if VD needs to be dllexport/dllimport due to being in a
4186 /// dllexport/import function.
4189
4190 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
4191 /// any semantic actions necessary after any initializer has been attached.
4192 void FinalizeDeclaration(Decl *D);
4194 ArrayRef<Decl *> Group);
4195
4196 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
4197 /// group, performing any necessary semantic checking.
4199
4200 /// Should be called on all declarations that might have attached
4201 /// documentation comments.
4202 void ActOnDocumentableDecl(Decl *D);
4204
4205 enum class FnBodyKind {
4206 /// C++26 [dcl.fct.def.general]p1
4207 /// function-body:
4208 /// ctor-initializer[opt] compound-statement
4209 /// function-try-block
4211 /// = default ;
4213 /// deleted-function-body
4214 ///
4215 /// deleted-function-body:
4216 /// = delete ;
4217 /// = delete ( unevaluated-string ) ;
4219 };
4220
4222 SourceLocation LocAfterDecls);
4224 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
4225 SkipBodyInfo *SkipBody = nullptr);
4227 MultiTemplateParamsArg TemplateParamLists,
4228 SkipBodyInfo *SkipBody = nullptr,
4229 FnBodyKind BodyKind = FnBodyKind::Other);
4231 SkipBodyInfo *SkipBody = nullptr,
4232 FnBodyKind BodyKind = FnBodyKind::Other);
4234
4235 /// Determine whether we can delay parsing the body of a function or
4236 /// function template until it is used, assuming we don't care about emitting
4237 /// code for that function.
4238 ///
4239 /// This will be \c false if we may need the body of the function in the
4240 /// middle of parsing an expression (where it's impractical to switch to
4241 /// parsing a different function), for instance, if it's constexpr in C++11
4242 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
4243 bool canDelayFunctionBody(const Declarator &D);
4244
4245 /// Determine whether we can skip parsing the body of a function
4246 /// definition, assuming we don't care about analyzing its body or emitting
4247 /// code for that function.
4248 ///
4249 /// This will be \c false only if we may need the body of the function in
4250 /// order to parse the rest of the program (for instance, if it is
4251 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
4252 bool canSkipFunctionBody(Decl *D);
4253
4254 /// Given the set of return statements within a function body,
4255 /// compute the variables that are subject to the named return value
4256 /// optimization.
4257 ///
4258 /// Each of the variables that is subject to the named return value
4259 /// optimization will be marked as NRVO variables in the AST, and any
4260 /// return statement that has a marked NRVO variable as its NRVO candidate can
4261 /// use the named return value optimization.
4262 ///
4263 /// This function applies a very simplistic algorithm for NRVO: if every
4264 /// return statement in the scope of a variable has the same NRVO candidate,
4265 /// that candidate is an NRVO variable.
4267
4268 /// Performs semantic analysis at the end of a function body.
4269 ///
4270 /// \param RetainFunctionScopeInfo If \c true, the client is responsible for
4271 /// releasing the associated \p FunctionScopeInfo. This is useful when
4272 /// building e.g. LambdaExprs.
4274 bool IsInstantiation = false,
4275 bool RetainFunctionScopeInfo = false);
4278
4279 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
4280 /// attribute for which parsing is delayed.
4282
4283 /// Diagnose any unused parameters in the given sequence of
4284 /// ParmVarDecl pointers.
4286
4287 /// Diagnose whether the size of parameters or return value of a
4288 /// function or obj-c method definition is pass-by-value and larger than a
4289 /// specified threshold.
4290 void
4292 QualType ReturnTy, NamedDecl *D);
4293
4295 SourceLocation RParenLoc);
4296
4299
4300 void ActOnPopScope(SourceLocation Loc, Scope *S);
4301
4302 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4303 /// no declarator (e.g. "struct foo;") is parsed.
4305 const ParsedAttributesView &DeclAttrs,
4306 RecordDecl *&AnonRecord);
4307
4308 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4309 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4310 /// parameters to cope with template friend declarations.
4312 const ParsedAttributesView &DeclAttrs,
4313 MultiTemplateParamsArg TemplateParams,
4314 bool IsExplicitInstantiation,
4315 RecordDecl *&AnonRecord,
4316 SourceLocation EllipsisLoc = {});
4317
4318 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4319 /// anonymous structure or union. Anonymous unions are a C++ feature
4320 /// (C++ [class.union]) and a C11 feature; anonymous structures
4321 /// are a C11 feature and GNU C++ extension.
4322 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS,
4323 RecordDecl *Record,
4324 const PrintingPolicy &Policy);
4325
4326 /// Called once it is known whether
4327 /// a tag declaration is an anonymous union or struct.
4329
4330 /// Emit diagnostic warnings for placeholder members.
4331 /// We can only do that after the class is fully constructed,
4332 /// as anonymous union/structs can insert placeholders
4333 /// in their parent scope (which might be a Record).
4335
4336 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4337 /// Microsoft C anonymous structure.
4338 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4339 /// Example:
4340 ///
4341 /// struct A { int a; };
4342 /// struct B { struct A; int b; };
4343 ///
4344 /// void foo() {
4345 /// B var;
4346 /// var.a = 3;
4347 /// }
4348 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4349 RecordDecl *Record);
4350
4351 /// Given a non-tag type declaration, returns an enum useful for indicating
4352 /// what kind of non-tag type this is.
4353 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
4354
4355 /// Determine whether a tag with a given kind is acceptable
4356 /// as a redeclaration of the given tag declaration.
4357 ///
4358 /// \returns true if the new tag kind is acceptable, false otherwise.
4360 bool isDefinition, SourceLocation NewTagLoc,
4361 const IdentifierInfo *Name);
4362
4363 /// This is invoked when we see 'struct foo' or 'struct {'. In the
4364 /// former case, Name will be non-null. In the later case, Name will be null.
4365 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is
4366 /// a reference/declaration/definition of a tag.
4367 ///
4368 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
4369 /// trailing-type-specifier) other than one in an alias-declaration.
4370 ///
4371 /// \param SkipBody If non-null, will be set to indicate if the caller should
4372 /// skip the definition of this tag and treat it as if it were a declaration.
4373 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4374 SourceLocation KWLoc, CXXScopeSpec &SS,
4375 IdentifierInfo *Name, SourceLocation NameLoc,
4376 const ParsedAttributesView &Attr, AccessSpecifier AS,
4377 SourceLocation ModulePrivateLoc,
4378 MultiTemplateParamsArg TemplateParameterLists,
4379 bool &OwnedDecl, bool &IsDependent,
4380 SourceLocation ScopedEnumKWLoc,
4381 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
4382 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
4383 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
4384
4385 /// ActOnField - Each field of a C struct/union is passed into this in order
4386 /// to create a FieldDecl object for it.
4387 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
4388 Declarator &D, Expr *BitfieldWidth);
4389
4390 /// HandleField - Analyze a field of a C struct or a C++ data member.
4391 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
4392 Declarator &D, Expr *BitfieldWidth,
4393 InClassInitStyle InitStyle, AccessSpecifier AS);
4394
4395 /// Build a new FieldDecl and check its well-formedness.
4396 ///
4397 /// This routine builds a new FieldDecl given the fields name, type,
4398 /// record, etc. \p PrevDecl should refer to any previous declaration
4399 /// with the same name and in the same scope as the field to be
4400 /// created.
4401 ///
4402 /// \returns a new FieldDecl.
4403 ///
4404 /// \todo The Declarator argument is a hack. It will be removed once
4405 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
4406 TypeSourceInfo *TInfo, RecordDecl *Record,
4407 SourceLocation Loc, bool Mutable,
4408 Expr *BitfieldWidth, InClassInitStyle InitStyle,
4409 SourceLocation TSSL, AccessSpecifier AS,
4410 NamedDecl *PrevDecl, Declarator *D = nullptr);
4411
4413
4414 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
4415 /// class and class extensions. For every class \@interface and class
4416 /// extension \@interface, if the last ivar is a bitfield of any type,
4417 /// then add an implicit `char :0` ivar to the end of that interface.
4418 void ActOnLastBitfield(SourceLocation DeclStart,
4419 SmallVectorImpl<Decl *> &AllIvarDecls);
4420
4421 // This is used for both record definitions and ObjC interface declarations.
4422 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
4423 ArrayRef<Decl *> Fields, SourceLocation LBrac,
4424 SourceLocation RBrac, const ParsedAttributesView &AttrList);
4425
4426 /// ActOnTagStartDefinition - Invoked when we have entered the
4427 /// scope of a tag's definition (e.g., for an enumeration, class,
4428 /// struct, or union).
4429 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
4430
4431 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
4432 /// Differently from C++, actually parse the body and reject / error out
4433 /// in case of a structural mismatch.
4434 bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody);
4435
4437
4438 /// Invoked when we enter a tag definition that we're skipping.
4440
4441 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
4442 /// C++ record definition's base-specifiers clause and are starting its
4443 /// member declarations.
4445 SourceLocation FinalLoc,
4446 bool IsFinalSpelledSealed,
4447 bool IsAbstract,
4448 SourceLocation LBraceLoc);
4449
4450 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
4451 /// the definition of a tag (enumeration, class, struct, or union).
4453 SourceRange BraceRange);
4454
4457
4459
4460 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
4461 /// error parsing the definition of a tag.
4463
4465 EnumConstantDecl *LastEnumConst,
4466 SourceLocation IdLoc, IdentifierInfo *Id,
4467 Expr *val);
4468
4469 /// Check that this is a valid underlying type for an enum declaration.
4471
4472 /// Check whether this is a valid redeclaration of a previous enumeration.
4473 /// \return true if the redeclaration was invalid.
4474 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
4475 QualType EnumUnderlyingTy, bool IsFixed,
4476 const EnumDecl *Prev);
4477
4478 /// Determine whether the body of an anonymous enumeration should be skipped.
4479 /// \param II The name of the first enumerator.
4481 SourceLocation IILoc);
4482
4483 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
4484 SourceLocation IdLoc, IdentifierInfo *Id,
4485 const ParsedAttributesView &Attrs,
4486 SourceLocation EqualLoc, Expr *Val,
4487 SkipBodyInfo *SkipBody = nullptr);
4488 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
4489 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
4490 const ParsedAttributesView &Attr);
4491
4492 /// Set the current declaration context until it gets popped.
4493 void PushDeclContext(Scope *S, DeclContext *DC);
4494 void PopDeclContext();
4495
4496 /// EnterDeclaratorContext - Used when we must lookup names in the context
4497 /// of a declarator's nested name specifier.
4500
4501 /// Enter a template parameter scope, after it's been associated with a
4502 /// particular DeclContext. Causes lookup within the scope to chain through
4503 /// enclosing contexts in the correct order.
4505
4506 /// Push the parameters of D, which must be a function, into scope.
4509
4510 /// Add this decl to the scope shadowed decl chains.
4511 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
4512
4513 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
4514 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
4515 /// true if 'D' belongs to the given declaration context.
4516 ///
4517 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
4518 /// enclosing namespace set of the context, rather than contained
4519 /// directly within it.
4520 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
4521 bool AllowInlineNamespace = false) const;
4522
4523 /// Finds the scope corresponding to the given decl context, if it
4524 /// happens to be an enclosing scope. Otherwise return NULL.
4526
4527 /// Subroutines of ActOnDeclarator().
4529 TypeSourceInfo *TInfo);
4531
4532 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
4534 NamedDecl *New, Decl *Old,
4536
4537 /// CheckAttributesOnDeducedType - Calls Sema functions for attributes that
4538 /// requires the type to be deduced.
4540
4541 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
4542 /// same name and scope as a previous declaration 'Old'. Figure out
4543 /// how to resolve this situation, merging decls or emitting
4544 /// diagnostics as appropriate. If there was an error, set New to be invalid.
4546 LookupResult &OldDecls);
4547
4548 /// CleanupMergedEnum - We have just merged the decl 'New' by making another
4549 /// definition visible.
4550 /// This method performs any necessary cleanup on the parser state to discard
4551 /// child nodes from newly parsed decl we are retiring.
4552 void CleanupMergedEnum(Scope *S, Decl *New);
4553
4554 /// MergeFunctionDecl - We just parsed a function 'New' from
4555 /// declarator D which has the same name and scope as a previous
4556 /// declaration 'Old'. Figure out how to resolve this situation,
4557 /// merging decls or emitting diagnostics as appropriate.
4558 ///
4559 /// In C++, New and Old must be declarations that are not
4560 /// overloaded. Use IsOverload to determine whether New and Old are
4561 /// overloaded, and to select the Old declaration that New should be
4562 /// merged with.
4563 ///
4564 /// Returns true if there was an error, false otherwise.
4566 bool MergeTypeWithOld, bool NewDeclIsDefn);
4567
4568 /// Completes the merge of two function declarations that are
4569 /// known to be compatible.
4570 ///
4571 /// This routine handles the merging of attributes and other
4572 /// properties of function declarations from the old declaration to
4573 /// the new declaration, once we know that New is in fact a
4574 /// redeclaration of Old.
4575 ///
4576 /// \returns false
4578 Scope *S, bool MergeTypeWithOld);
4580
4581 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4582 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4583 /// situation, merging decls or emitting diagnostics as appropriate.
4584 ///
4585 /// Tentative definition rules (C99 6.9.2p2) are checked by
4586 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4587 /// definitions here, since the initializer hasn't been attached.
4589
4590 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4591 /// scope as a previous declaration 'Old'. Figure out how to merge their
4592 /// types, emitting diagnostics as appropriate.
4593 ///
4594 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call
4595 /// back to here in AddInitializerToDecl. We can't check them before the
4596 /// initializer is attached.
4597 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
4598
4599 /// We've just determined that \p Old and \p New both appear to be definitions
4600 /// of the same variable. Either diagnose or fix the problem.
4601 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
4603
4604 /// Filters out lookup results that don't fall within the given scope
4605 /// as determined by isDeclInScope.
4607 bool ConsiderLinkage, bool AllowInlineNamespace);
4608
4609 /// We've determined that \p New is a redeclaration of \p Old. Check that they
4610 /// have compatible owning modules.
4612
4613 /// [module.interface]p6:
4614 /// A redeclaration of an entity X is implicitly exported if X was introduced
4615 /// by an exported declaration; otherwise it shall not be exported.
4617
4618 /// A wrapper function for checking the semantic restrictions of
4619 /// a redeclaration within a module.
4621
4622 /// Check the redefinition in C++20 Modules.
4623 ///
4624 /// [basic.def.odr]p14:
4625 /// For any definable item D with definitions in multiple translation units,
4626 /// - if D is a non-inline non-templated function or variable, or
4627 /// - if the definitions in different translation units do not satisfy the
4628 /// following requirements,
4629 /// the program is ill-formed; a diagnostic is required only if the
4630 /// definable item is attached to a named module and a prior definition is
4631 /// reachable at the point where a later definition occurs.
4632 /// - Each such definition shall not be attached to a named module
4633 /// ([module.unit]).
4634 /// - Each such definition shall consist of the same sequence of tokens, ...
4635 /// ...
4636 ///
4637 /// Return true if the redefinition is not allowed. Return false otherwise.
4638 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
4639
4641
4642 /// If it's a file scoped decl that must warn if not used, keep track
4643 /// of it.
4645
4646 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
4648
4651 DiagReceiverTy DiagReceiver);
4652 void DiagnoseUnusedDecl(const NamedDecl *ND);
4653
4654 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
4655 /// unless they are marked attr(unused).
4656 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
4657
4658 /// If VD is set but not otherwise used, diagnose, for a parameter or a
4659 /// variable.
4660 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
4661
4662 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
4663 /// from S, where a non-field would be declared. This routine copes
4664 /// with the difference between C and C++ scoping rules in structs and
4665 /// unions. For example, the following code is well-formed in C but
4666 /// ill-formed in C++:
4667 /// @code
4668 /// struct S6 {
4669 /// enum { BAR } e;
4670 /// };
4671 ///
4672 /// void test_S6() {
4673 /// struct S6 a;
4674 /// a.e = BAR;
4675 /// }
4676 /// @endcode
4677 /// For the declaration of BAR, this routine will return a different
4678 /// scope. The scope S will be the scope of the unnamed enumeration
4679 /// within S6. In C++, this routine will return the scope associated
4680 /// with S6, because the enumeration's scope is a transparent
4681 /// context but structures can contain non-field names. In C, this
4682 /// routine will return the translation unit scope, since the
4683 /// enumeration's scope is a transparent context and structures cannot
4684 /// contain non-field names.
4686
4688 SourceLocation Loc);
4689
4690 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
4691 /// file scope. lazily create a decl for it. ForRedeclaration is true
4692 /// if we're creating this built-in in anticipation of redeclaring the
4693 /// built-in.
4694 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S,
4695 bool ForRedeclaration, SourceLocation Loc);
4696
4697 /// Get the outermost AttributedType node that sets a calling convention.
4698 /// Valid types should not have multiple attributes with different CCs.
4699 const AttributedType *getCallingConvAttributedType(QualType T) const;
4700
4701 /// GetNameForDeclarator - Determine the full declaration name for the
4702 /// given Declarator.
4704
4705 /// Retrieves the declaration name from a parsed unqualified-id.
4707
4708 /// ParsingInitForAutoVars - a set of declarations with auto types for which
4709 /// we are currently parsing the initializer.
4711
4712 /// Look for a locally scoped extern "C" declaration by the given name.
4714
4717
4718 /// Adjust the \c DeclContext for a function or variable that might be a
4719 /// function-local external declaration.
4721
4723
4724 /// Checks if the variant/multiversion functions are compatible.
4726 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
4727 const PartialDiagnostic &NoProtoDiagID,
4728 const PartialDiagnosticAt &NoteCausedDiagIDAt,
4729 const PartialDiagnosticAt &NoSupportDiagIDAt,
4730 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
4731 bool ConstexprSupported, bool CLinkageMayDiffer);
4732
4733 /// type checking declaration initializers (C99 6.7.8)
4735 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
4736
4739 SourceRange Range, bool DirectInit,
4740 Expr *Init);
4741
4743 Expr *Init);
4744
4746
4747 // Heuristically tells if the function is `get_return_object` member of a
4748 // coroutine promise_type by matching the function name.
4749 static bool CanBeGetReturnObject(const FunctionDecl *FD);
4750 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
4751
4752 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4753 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4755 Scope *S);
4756
4757 /// If this function is a C++ replaceable global allocation function
4758 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
4759 /// adds any function attributes that we know a priori based on the standard.
4760 ///
4761 /// We need to check for duplicate attributes both here and where user-written
4762 /// attributes are applied to declarations.
4764 FunctionDecl *FD);
4765
4766 /// Adds any function attributes that we know a priori based on
4767 /// the declaration of this function.
4768 ///
4769 /// These attributes can apply both to implicitly-declared builtins
4770 /// (like __builtin___printf_chk) or to library-declared functions
4771 /// like NSLog or printf.
4772 ///
4773 /// We need to check for duplicate attributes both here and where user-written
4774 /// attributes are applied to declarations.
4776
4777 /// VerifyBitField - verifies that a bit field expression is an ICE and has
4778 /// the correct width, and that the field type is valid.
4779 /// Returns false on success.
4781 const IdentifierInfo *FieldName, QualType FieldTy,
4782 bool IsMsStruct, Expr *BitWidth);
4783
4784 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
4785 /// enum. If AllowMask is true, then we also allow the complement of a valid
4786 /// value, to be used as a mask.
4787 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
4788 bool AllowMask) const;
4789
4790 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
4791 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
4792 SourceLocation WeakNameLoc);
4793
4794 /// ActOnPragmaRedefineExtname - Called on well formed
4795 /// \#pragma redefine_extname oldname newname.
4797 IdentifierInfo *AliasName,
4798 SourceLocation PragmaLoc,
4799 SourceLocation WeakNameLoc,
4800 SourceLocation AliasNameLoc);
4801
4802 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
4803 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
4804 SourceLocation PragmaLoc,
4805 SourceLocation WeakNameLoc,
4806 SourceLocation AliasNameLoc);
4807
4808 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4811 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4812 OMPDiscarded, // Discarded due to OpenMP hostness
4813 TemplateDiscarded, // Discarded due to uninstantiated templates
4815 };
4816 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4817 bool Final = false);
4818
4819 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4821
4822 /// Function or variable declarations to be checked for whether the deferred
4823 /// diagnostics should be emitted.
4825
4826private:
4827 /// Map of current shadowing declarations to shadowed declarations. Warn if
4828 /// it looks like the user is trying to modify the shadowing declaration.
4829 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
4830
4831 // We need this to handle
4832 //
4833 // typedef struct {
4834 // void *foo() { return 0; }
4835 // } A;
4836 //
4837 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
4838 // for example. If 'A', foo will have external linkage. If we have '*A',
4839 // foo will have no linkage. Since we can't know until we get to the end
4840 // of the typedef, this function finds out if D might have non-external
4841 // linkage. Callers should verify at the end of the TU if it D has external
4842 // linkage or not.
4843 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
4844
4845#include "clang/Sema/AttrIsTypeDependent.inc"
4846
4847 ///@}
4848
4849 //
4850 //
4851 // -------------------------------------------------------------------------
4852 //
4853 //
4854
4855 /// \name Declaration Attribute Handling
4856 /// Implementations are in SemaDeclAttr.cpp
4857 ///@{
4858
4859public:
4860 /// Describes the kind of priority given to an availability attribute.
4861 ///
4862 /// The sum of priorities deteremines the final priority of the attribute.
4863 /// The final priority determines how the attribute will be merged.
4864 /// An attribute with a lower priority will always remove higher priority
4865 /// attributes for the specified platform when it is being applied. An
4866 /// attribute with a higher priority will not be applied if the declaration
4867 /// already has an availability attribute with a lower priority for the
4868 /// specified platform. The final prirority values are not expected to match
4869 /// the values in this enumeration, but instead should be treated as a plain
4870 /// integer value. This enumeration just names the priority weights that are
4871 /// used to calculate that final vaue.
4873 /// The availability attribute was specified explicitly next to the
4874 /// declaration.
4876
4877 /// The availability attribute was applied using '#pragma clang attribute'.
4879
4880 /// The availability attribute for a specific platform was inferred from
4881 /// an availability attribute for another platform.
4883
4884 /// The availability attribute was inferred from an 'anyAppleOS'
4885 /// availability attribute.
4887
4888 /// The availability attribute was inferred from an 'anyAppleOS'
4889 /// availability attribute that was applied using '#pragma clang attribute'.
4890 /// This has the lowest priority.
4892 };
4893
4894 /// Describes the reason a calling convention specification was ignored, used
4895 /// for diagnostics.
4902
4903 /// A helper function to provide Attribute Location for the Attr types
4904 /// AND the ParsedAttr.
4905 template <typename AttrInfo>
4906 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
4907 getAttrLoc(const AttrInfo &AL) {
4908 return AL.getLocation();
4909 }
4911
4912 /// If Expr is a valid integer constant, get the value of the integer
4913 /// expression and return success or failure. May output an error.
4914 ///
4915 /// Negative argument is implicitly converted to unsigned, unless
4916 /// \p StrictlyUnsigned is true.
4917 template <typename AttrInfo>
4918 bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val,
4919 unsigned Idx = UINT_MAX,
4920 bool StrictlyUnsigned = false) {
4921 std::optional<llvm::APSInt> I = llvm::APSInt(32);
4922 if (Expr->isTypeDependent() ||
4924 if (Idx != UINT_MAX)
4925 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
4926 << &AI << Idx << AANT_ArgumentIntegerConstant
4927 << Expr->getSourceRange();
4928 else
4929 Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
4931 return false;
4932 }
4933
4934 if (!I->isIntN(32)) {
4935 Diag(Expr->getExprLoc(), diag::err_ice_too_large)
4936 << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
4937 return false;
4938 }
4939
4940 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
4941 Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
4942 << &AI << /*non-negative*/ 1;
4943 return false;
4944 }
4945
4946 Val = (uint32_t)I->getZExtValue();
4947 return true;
4948 }
4949
4950 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
4951 /// \#pragma weak during processing of other Decls.
4952 /// I couldn't figure out a clean way to generate these in-line, so
4953 /// we store them here and handle separately -- which is a hack.
4954 /// It would be best to refactor this.
4956
4957 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
4959
4963
4964 /// ExtVectorDecls - This is a list all the extended vector types. This allows
4965 /// us to associate a raw vector type with one of the ext_vector type names.
4966 /// This is only necessary for issuing pretty diagnostics.
4968
4969 /// Check if the argument \p E is a ASCII string literal. If not emit an error
4970 /// and return false, otherwise set \p Str to the value of the string literal
4971 /// and return true.
4973 const Expr *E, StringRef &Str,
4974 SourceLocation *ArgLocation = nullptr);
4975
4976 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
4977 /// If not emit an error and return false. If the argument is an identifier it
4978 /// will emit an error with a fixit hint and treat it as if it was a string
4979 /// literal.
4980 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4981 StringRef &Str,
4982 SourceLocation *ArgLocation = nullptr);
4983
4984 /// Determine if type T is a valid subject for a nonnull and similar
4985 /// attributes. Dependent types are considered valid so they can be checked
4986 /// during instantiation time. By default, we look through references (the
4987 /// behavior used by nonnull), but if the second parameter is true, then we
4988 /// treat a reference type as valid.
4989 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4990
4991 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
4992 /// declaration.
4993 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4994 Expr *OE);
4995
4996 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
4997 /// declaration.
4998 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
4999 Expr *ParamExpr);
5000
5001 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
5002 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
5003
5004 AvailabilityAttr *
5006 const IdentifierInfo *Platform, bool Implicit,
5007 VersionTuple Introduced, VersionTuple Deprecated,
5008 VersionTuple Obsoleted, bool IsUnavailable,
5009 StringRef Message, bool IsStrict, StringRef Replacement,
5010 AvailabilityMergeKind AMK, int Priority,
5011 const IdentifierInfo *IIEnvironment,
5012 const IdentifierInfo *InferredPlatformII = nullptr);
5013
5014 AvailabilityAttr *mergeAndInferAvailabilityAttr(
5015 NamedDecl *D, const AttributeCommonInfo &CI,
5016 const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced,
5017 VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable,
5018 StringRef Message, bool IsStrict, StringRef Replacement,
5019 AvailabilityMergeKind AMK, int Priority,
5020 const IdentifierInfo *IIEnvironment,
5021 const IdentifierInfo *InferredPlatformII);
5022
5023 TypeVisibilityAttr *
5025 TypeVisibilityAttr::VisibilityType Vis);
5026 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5027 VisibilityAttr::VisibilityType Vis);
5029 VisibilityAttr::VisibilityType Type);
5030 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
5031 StringRef Name);
5032
5033 /// Used to implement to perform semantic checking on
5034 /// attribute((section("foo"))) specifiers.
5035 ///
5036 /// In this case, "foo" is passed in to be checked. If the section
5037 /// specifier is invalid, return an Error that indicates the problem.
5038 ///
5039 /// This is a simple quality of implementation feature to catch errors
5040 /// and give good diagnostics in cases when the assembler or code generator
5041 /// would otherwise reject the section specifier.
5042 llvm::Error isValidSectionSpecifier(StringRef Str);
5043 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
5044 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
5045 StringRef Name);
5046
5047 // Check for things we'd like to warn about. Multiversioning issues are
5048 // handled later in the process, once we know how many exist.
5049 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
5050
5051 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
5052 StringRef NewUserDiagnostic);
5053 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
5054 const IdentifierInfo *Format, int FormatIdx,
5055 int FirstArg);
5056 FormatMatchesAttr *mergeFormatMatchesAttr(Decl *D,
5057 const AttributeCommonInfo &CI,
5058 const IdentifierInfo *Format,
5059 int FormatIdx,
5060 StringLiteral *FormatStr);
5061 ModularFormatAttr *mergeModularFormatAttr(Decl *D,
5062 const AttributeCommonInfo &CI,
5063 const IdentifierInfo *ModularImplFn,
5064 StringRef ImplName,
5066
5067 PersonalityAttr *mergePersonalityAttr(Decl *D, FunctionDecl *Routine,
5068 const AttributeCommonInfo &CI);
5069
5070 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
5071 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5072 bool IsPackExpansion);
5074 bool IsPackExpansion);
5075
5076 /// AddAlignValueAttr - Adds an align_value attribute to a particular
5077 /// declaration.
5078 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
5079
5080 /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
5081 Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
5084
5086 bool BestCase,
5087 MSInheritanceModel SemanticSpelling);
5088
5090
5091 /// AddModeAttr - Adds a mode attribute to a particular declaration.
5092 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
5093 const IdentifierInfo *Name, bool InInstantiation = false);
5094 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
5095 const AttributeCommonInfo &CI,
5096 const IdentifierInfo *Ident);
5097 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
5098 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
5099 const AttributeCommonInfo &CI);
5100 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
5101 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
5102 const InternalLinkageAttr &AL);
5103
5104 /// Check validaty of calling convention attribute \p attr. If \p FD
5105 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
5106 /// target. Otherwise, it is specified by \p CFT.
5108 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
5110
5111 /// Checks a regparm attribute, returning true if it is ill-formed and
5112 /// otherwise setting numParams to the appropriate value.
5113 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
5114
5115 /// Create a CUDALaunchBoundsAttr attribute. By default, the function only
5116 /// supports nvptx target architectures and skips MaxBlocks if it is previous
5117 /// to sm_90. Use \p IgnoreArch to skip the architecture check.
5118 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
5119 Expr *MaxThreads,
5120 Expr *MinBlocks, Expr *MaxBlocks,
5121 bool IgnoreArch = false);
5122
5123 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
5124 /// declaration.
5125 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5126 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
5127
5128 /// Add a cluster_dims attribute to a particular declaration.
5129 CUDAClusterDimsAttr *createClusterDimsAttr(const AttributeCommonInfo &CI,
5130 Expr *X, Expr *Y, Expr *Z);
5131 void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X,
5132 Expr *Y, Expr *Z);
5133 /// Add a no_cluster attribute to a particular declaration.
5134 void addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI);
5135
5136 enum class RetainOwnershipKind { NS, CF, OS };
5137
5138 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5139 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
5140
5141 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
5142
5143 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
5144 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
5145 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
5146 const AttributeCommonInfo &CI,
5147 bool BestCase,
5148 MSInheritanceModel Model);
5149
5150 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
5151 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
5152 const EnforceTCBLeafAttr &AL);
5153
5154 /// Helper for delayed processing TransparentUnion or
5155 /// BPFPreserveAccessIndexAttr attribute.
5157 const ParsedAttributesView &AttrList);
5158
5159 // Options for ProcessDeclAttributeList().
5163
5166 Result.IncludeCXX11Attributes = Val;
5167 return Result;
5168 }
5169
5172 Result.IgnoreTypeAttributes = Val;
5173 return Result;
5174 }
5175
5176 // Should C++11 attributes be processed?
5178
5179 // Should any type attributes encountered be ignored?
5180 // If this option is false, a diagnostic will be emitted for any type
5181 // attributes of a kind that does not "slide" from the declaration to
5182 // the decl-specifier-seq.
5184 };
5185
5186 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5187 /// attribute list to the specified decl, ignoring any type attributes.
5189 const ParsedAttributesView &AttrList,
5190 const ProcessDeclAttributeOptions &Options =
5192
5193 /// Annotation attributes are the only attributes allowed after an access
5194 /// specifier.
5196 const ParsedAttributesView &AttrList);
5197
5198 /// checkUnusedDeclAttributes - Given a declarator which is not being
5199 /// used to build a declaration, complain about any decl attributes
5200 /// which might be lying around on it.
5202
5203 void DiagnoseUnknownAttribute(const ParsedAttr &AL);
5204
5205 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5206 /// \#pragma weak needs a non-definition decl and source may not have one.
5208 SourceLocation Loc);
5209
5210 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5211 /// applied to it, possibly with an alias.
5212 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
5213
5214 void ProcessPragmaWeak(Scope *S, Decl *D);
5215 // Decl attributes - this routine is the top level dispatcher.
5216 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
5217
5219
5220 /// Given a set of delayed diagnostics, re-emit them as if they had
5221 /// been delayed in the current context instead of in the given pool.
5222 /// Essentially, this just moves them to the current pool.
5224
5225 /// Check that the type is a plain record with one field being a pointer
5226 /// type and the other field being an integer. This matches the common
5227 /// implementation of std::span or sized_allocation_t in P0901R11.
5228 bool CheckSpanLikeType(const AttributeCommonInfo &CI, const QualType &Ty);
5229
5230 /// Check if IdxExpr is a valid parameter index for a function or
5231 /// instance method D. May output an error.
5232 ///
5233 /// \returns true if IdxExpr is a valid index.
5234 template <typename AttrInfo>
5236 const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
5237 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false,
5238 bool CanIndexVariadicArguments = false) {
5240
5241 // In C++ the implicit 'this' function parameter also counts.
5242 // Parameters are counted from one.
5243 bool HP = hasFunctionProto(D);
5244 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
5245 bool IV = HP && isFunctionOrMethodVariadic(D);
5246 unsigned NumParams =
5247 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
5248
5249 std::optional<llvm::APSInt> IdxInt;
5250 if (IdxExpr->isTypeDependent() ||
5251 !(IdxInt = IdxExpr->getIntegerConstantExpr(Context))) {
5252 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5253 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
5254 << IdxExpr->getSourceRange();
5255 return false;
5256 }
5257
5258 constexpr unsigned Limit = 1 << ParamIdx::IdxBitWidth;
5259 unsigned IdxSource = IdxInt->getLimitedValue(Limit);
5260 if (IdxSource < 1 || IdxSource == Limit ||
5261 ((!IV || !CanIndexVariadicArguments) && IdxSource > NumParams)) {
5262 Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
5263 << &AI << AttrArgNum << IdxExpr->getSourceRange();
5264 return false;
5265 }
5266 if (HasImplicitThisParam && !CanIndexImplicitThis) {
5267 if (IdxSource == 1) {
5268 Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
5269 << &AI << IdxExpr->getSourceRange();
5270 return false;
5271 }
5272 }
5273
5274 Idx = ParamIdx(IdxSource, D);
5275 return true;
5276 }
5277
5278 ///@}
5279
5280 //
5281 //
5282 // -------------------------------------------------------------------------
5283 //
5284 //
5285
5286 /// \name C++ Declarations
5287 /// Implementations are in SemaDeclCXX.cpp
5288 ///@{
5289
5290public:
5292
5293 /// Called before parsing a function declarator belonging to a function
5294 /// declaration.
5296 unsigned TemplateParameterDepth);
5297
5298 /// Called after parsing a function declarator belonging to a function
5299 /// declaration.
5301
5302 // Act on C++ namespaces
5304 SourceLocation NamespaceLoc,
5305 SourceLocation IdentLoc, IdentifierInfo *Ident,
5306 SourceLocation LBrace,
5307 const ParsedAttributesView &AttrList,
5308 UsingDirectiveDecl *&UsingDecl, bool IsNested);
5309
5310 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5311 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5312 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5313
5315
5316 /// Retrieve the special "std" namespace, which may require us to
5317 /// implicitly define the namespace.
5319
5321 EnumDecl *getStdAlignValT() const;
5322
5325 QualType AllocType, SourceLocation);
5326
5328 const IdentifierInfo *MemberOrBase);
5329
5331 /// The '<=>' operator was used in an expression and a builtin operator
5332 /// was selected.
5334 /// A defaulted 'operator<=>' needed the comparison category. This
5335 /// typically only applies to 'std::strong_ordering', due to the implicit
5336 /// fallback return value.
5338 };
5339
5340 /// Lookup the specified comparison category types in the standard
5341 /// library, an check the VarDecls possibly returned by the operator<=>
5342 /// builtins for that type.
5343 ///
5344 /// \return The type of the comparison category type corresponding to the
5345 /// specified Kind, or a null type if an error occurs
5347 SourceLocation Loc,
5349
5350 /// Tests whether Ty is an instance of std::initializer_list and, if
5351 /// it is and Element is not NULL, assigns the element type to Element.
5352 bool isStdInitializerList(QualType Ty, QualType *Element);
5353
5354 /// Tests whether Ty is an instance of std::type_identity and, if
5355 /// it is and TypeArgument is not NULL, assigns the element type to Element.
5356 /// If MalformedDecl is not null, and type_identity was ruled out due to being
5357 /// incorrectly structured despite having the correct name, the faulty Decl
5358 /// will be assigned to MalformedDecl.
5359 bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument,
5360 const Decl **MalformedDecl = nullptr);
5361
5362 /// Looks for the std::initializer_list template and instantiates it
5363 /// with Element, or emits an error if it's not found.
5364 ///
5365 /// \returns The instantiated template, or null on error.
5367
5368 /// Looks for the std::type_identity template and instantiates it
5369 /// with Type, or returns a null type if type_identity has not been declared
5370 ///
5371 /// \returns The instantiated template, or null if std::type_identity is not
5372 /// declared
5374
5375 /// Determine whether Ctor is an initializer-list constructor, as
5376 /// defined in [dcl.init.list]p2.
5377 bool isInitListConstructor(const FunctionDecl *Ctor);
5378
5379 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5380 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5381 SourceLocation IdentLoc,
5382 IdentifierInfo *NamespcName,
5383 const ParsedAttributesView &AttrList);
5384
5386
5387 Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc,
5388 SourceLocation AliasLoc, IdentifierInfo *Alias,
5389 CXXScopeSpec &SS, SourceLocation IdentLoc,
5390 IdentifierInfo *Ident);
5391
5392 /// Remove decls we can't actually see from a lookup being used to declare
5393 /// shadow using decls.
5394 ///
5395 /// \param S - The scope of the potential shadow decl
5396 /// \param Previous - The lookup of a potential shadow decl's name.
5397 void FilterUsingLookup(Scope *S, LookupResult &lookup);
5398
5399 /// Hides a using shadow declaration. This is required by the current
5400 /// using-decl implementation when a resolvable using declaration in a
5401 /// class is followed by a declaration which would hide or override
5402 /// one or more of the using decl's targets; for example:
5403 ///
5404 /// struct Base { void foo(int); };
5405 /// struct Derived : Base {
5406 /// using Base::foo;
5407 /// void foo(int);
5408 /// };
5409 ///
5410 /// The governing language is C++03 [namespace.udecl]p12:
5411 ///
5412 /// When a using-declaration brings names from a base class into a
5413 /// derived class scope, member functions in the derived class
5414 /// override and/or hide member functions with the same name and
5415 /// parameter types in a base class (rather than conflicting).
5416 ///
5417 /// There are two ways to implement this:
5418 /// (1) optimistically create shadow decls when they're not hidden
5419 /// by existing declarations, or
5420 /// (2) don't create any shadow decls (or at least don't make them
5421 /// visible) until we've fully parsed/instantiated the class.
5422 /// The problem with (1) is that we might have to retroactively remove
5423 /// a shadow decl, which requires several O(n) operations because the
5424 /// decl structures are (very reasonably) not designed for removal.
5425 /// (2) avoids this but is very fiddly and phase-dependent.
5426 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5427
5428 /// Determines whether to create a using shadow decl for a particular
5429 /// decl, given the set of decls existing prior to this using lookup.
5431 const LookupResult &PreviousDecls,
5432 UsingShadowDecl *&PrevShadow);
5433
5434 /// Builds a shadow declaration corresponding to a 'using' declaration.
5437 UsingShadowDecl *PrevDecl);
5438
5439 /// Checks that the given using declaration is not an invalid
5440 /// redeclaration. Note that this is checking only for the using decl
5441 /// itself, not for any ill-formedness among the UsingShadowDecls.
5443 bool HasTypenameKeyword,
5444 const CXXScopeSpec &SS,
5445 SourceLocation NameLoc,
5446 const LookupResult &Previous);
5447
5448 /// Checks that the given nested-name qualifier used in a using decl
5449 /// in the current context is appropriately related to the current
5450 /// scope. If an error is found, diagnoses it and returns true.
5451 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's
5452 /// the result of that lookup. UD is likewise nullptr, except when we have an
5453 /// already-populated UsingDecl whose shadow decls contain the same
5454 /// information (i.e. we're instantiating a UsingDecl with non-dependent
5455 /// scope).
5456 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5457 const CXXScopeSpec &SS,
5458 const DeclarationNameInfo &NameInfo,
5459 SourceLocation NameLoc,
5460 const LookupResult *R = nullptr,
5461 const UsingDecl *UD = nullptr);
5462
5463 /// Builds a using declaration.
5464 ///
5465 /// \param IsInstantiation - Whether this call arises from an
5466 /// instantiation of an unresolved using declaration. We treat
5467 /// the lookup differently for these declarations.
5469 SourceLocation UsingLoc,
5470 bool HasTypenameKeyword,
5471 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5472 DeclarationNameInfo NameInfo,
5473 SourceLocation EllipsisLoc,
5474 const ParsedAttributesView &AttrList,
5475 bool IsInstantiation, bool IsUsingIfExists);
5477 SourceLocation UsingLoc,
5478 SourceLocation EnumLoc,
5479 SourceLocation NameLoc,
5480 TypeSourceInfo *EnumType, EnumDecl *ED);
5481 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5482 ArrayRef<NamedDecl *> Expansions);
5483
5484 /// Additional checks for a using declaration referring to a constructor name.
5486
5487 /// Given a derived-class using shadow declaration for a constructor and the
5488 /// correspnding base class constructor, find or create the implicit
5489 /// synthesized derived class constructor to use for this initialization.
5492 ConstructorUsingShadowDecl *DerivedShadow);
5493
5495 SourceLocation UsingLoc,
5496 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5497 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5498 const ParsedAttributesView &AttrList);
5500 SourceLocation UsingLoc,
5501 SourceLocation EnumLoc, SourceRange TyLoc,
5502 const IdentifierInfo &II, ParsedType Ty,
5503 const CXXScopeSpec &SS);
5505 MultiTemplateParamsArg TemplateParams,
5506 SourceLocation UsingLoc, UnqualifiedId &Name,
5507 const ParsedAttributesView &AttrList,
5508 TypeResult Type, Decl *DeclFromDeclSpec);
5509
5510 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5511 /// including handling of its default argument expressions.
5512 ///
5513 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5515 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5517 bool HadMultipleCandidates, bool IsListInitialization,
5518 bool IsStdInitListInitialization, bool RequiresZeroInit,
5519 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5520
5521 /// Build a CXXConstructExpr whose constructor has already been resolved if
5522 /// it denotes an inherited constructor.
5524 SourceLocation ConstructLoc, QualType DeclInitType,
5525 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5526 bool HadMultipleCandidates, bool IsListInitialization,
5527 bool IsStdInitListInitialization, bool RequiresZeroInit,
5528 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5529
5530 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5531 // the constructor can be elidable?
5533 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5534 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5535 bool HadMultipleCandidates, bool IsListInitialization,
5536 bool IsStdInitListInitialization, bool RequiresZeroInit,
5537 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5538
5540 SourceLocation InitLoc);
5541
5542 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5543 /// constructed variable.
5544 void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit);
5545
5546 /// Helper class that collects exception specifications for
5547 /// implicitly-declared special member functions.
5549 // Pointer to allow copying
5550 Sema *Self;
5551 // We order exception specifications thus:
5552 // noexcept is the most restrictive, but is only used in C++11.
5553 // throw() comes next.
5554 // Then a throw(collected exceptions)
5555 // Finally no specification, which is expressed as noexcept(false).
5556 // throw(...) is used instead if any called function uses it.
5557 ExceptionSpecificationType ComputedEST;
5558 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5559 SmallVector<QualType, 4> Exceptions;
5560
5561 void ClearExceptions() {
5562 ExceptionsSeen.clear();
5563 Exceptions.clear();
5564 }
5565
5566 public:
5568 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5569 if (!Self.getLangOpts().CPlusPlus11)
5570 ComputedEST = EST_DynamicNone;
5571 }
5572
5573 /// Get the computed exception specification type.
5575 assert(!isComputedNoexcept(ComputedEST) &&
5576 "noexcept(expr) should not be a possible result");
5577 return ComputedEST;
5578 }
5579
5580 /// The number of exceptions in the exception specification.
5581 unsigned size() const { return Exceptions.size(); }
5582
5583 /// The set of exceptions in the exception specification.
5584 const QualType *data() const { return Exceptions.data(); }
5585
5586 /// Integrate another called method into the collected data.
5587 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5588
5589 /// Integrate an invoked expression into the collected data.
5590 void CalledExpr(Expr *E) { CalledStmt(E); }
5591
5592 /// Integrate an invoked statement into the collected data.
5593 void CalledStmt(Stmt *S);
5594
5595 /// Overwrite an EPI's exception specification with this
5596 /// computed exception specification.
5599 ESI.Type = getExceptionSpecType();
5600 if (ESI.Type == EST_Dynamic) {
5601 ESI.Exceptions = Exceptions;
5602 } else if (ESI.Type == EST_None) {
5603 /// C++11 [except.spec]p14:
5604 /// The exception-specification is noexcept(false) if the set of
5605 /// potential exceptions of the special member function contains "any"
5606 ESI.Type = EST_NoexceptFalse;
5607 ESI.NoexceptExpr =
5608 Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get();
5609 }
5610 return ESI;
5611 }
5612 };
5613
5614 /// Evaluate the implicit exception specification for a defaulted
5615 /// special member function.
5617
5618 /// Check the given exception-specification and update the
5619 /// exception specification information with the results.
5620 void checkExceptionSpecification(bool IsTopLevel,
5622 ArrayRef<ParsedType> DynamicExceptions,
5623 ArrayRef<SourceRange> DynamicExceptionRanges,
5624 Expr *NoexceptExpr,
5625 SmallVectorImpl<QualType> &Exceptions,
5627
5628 /// Add an exception-specification to the given member or friend function
5629 /// (or function template). The exception-specification was parsed
5630 /// after the function itself was declared.
5632 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
5633 ArrayRef<ParsedType> DynamicExceptions,
5634 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr);
5635
5636 class InheritedConstructorInfo;
5637
5638 /// Determine if a special member function should have a deleted
5639 /// definition when it is defaulted.
5641 InheritedConstructorInfo *ICI = nullptr,
5642 bool Diagnose = false);
5643
5644 /// Produce notes explaining why a defaulted function was defined as deleted.
5646
5647 /// Declare the implicit default constructor for the given class.
5648 ///
5649 /// \param ClassDecl The class declaration into which the implicit
5650 /// default constructor will be added.
5651 ///
5652 /// \returns The implicitly-declared default constructor.
5655
5656 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5657 /// defining this constructor as the default constructor.
5660
5661 /// Declare the implicit destructor for the given class.
5662 ///
5663 /// \param ClassDecl The class declaration into which the implicit
5664 /// destructor will be added.
5665 ///
5666 /// \returns The implicitly-declared destructor.
5668
5669 /// DefineImplicitDestructor - Checks for feasibility of
5670 /// defining this destructor as the default destructor.
5671 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5673
5674 /// Build an exception spec for destructors that don't have one.
5675 ///
5676 /// C++11 says that user-defined destructors with no exception spec get one
5677 /// that looks as if the destructor was implicitly declared.
5679
5680 /// Define the specified inheriting constructor.
5683
5684 /// Declare the implicit copy constructor for the given class.
5685 ///
5686 /// \param ClassDecl The class declaration into which the implicit
5687 /// copy constructor will be added.
5688 ///
5689 /// \returns The implicitly-declared copy constructor.
5691
5692 /// DefineImplicitCopyConstructor - Checks for feasibility of
5693 /// defining this constructor as the copy constructor.
5694 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5696
5697 /// Declare the implicit move constructor for the given class.
5698 ///
5699 /// \param ClassDecl The Class declaration into which the implicit
5700 /// move constructor will be added.
5701 ///
5702 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5703 /// declared.
5705
5706 /// DefineImplicitMoveConstructor - Checks for feasibility of
5707 /// defining this constructor as the move constructor.
5708 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5710
5711 /// Declare the implicit copy assignment operator for the given class.
5712 ///
5713 /// \param ClassDecl The class declaration into which the implicit
5714 /// copy assignment operator will be added.
5715 ///
5716 /// \returns The implicitly-declared copy assignment operator.
5718
5719 /// Defines an implicitly-declared copy assignment operator.
5720 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5721 CXXMethodDecl *MethodDecl);
5722
5723 /// Declare the implicit move assignment operator for the given class.
5724 ///
5725 /// \param ClassDecl The Class declaration into which the implicit
5726 /// move assignment operator will be added.
5727 ///
5728 /// \returns The implicitly-declared move assignment operator, or NULL if it
5729 /// wasn't declared.
5731
5732 /// Defines an implicitly-declared move assignment operator.
5733 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5734 CXXMethodDecl *MethodDecl);
5735
5736 /// Check a completed declaration of an implicit special member.
5738
5739 /// Determine whether the given function is an implicitly-deleted
5740 /// special member function.
5742
5743 /// Check whether 'this' shows up in the type of a static member
5744 /// function after the (naturally empty) cv-qualifier-seq would be.
5745 ///
5746 /// \returns true if an error occurred.
5748
5749 /// Whether this' shows up in the exception specification of a static
5750 /// member function.
5752
5753 /// Check whether 'this' shows up in the attributes of the given
5754 /// static member function.
5755 ///
5756 /// \returns true if an error occurred.
5758
5760 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI);
5761
5763
5764 /// Given a constructor and the set of arguments provided for the
5765 /// constructor, convert the arguments and add any required default arguments
5766 /// to form a proper call to this constructor.
5767 ///
5768 /// \returns true if an error occurred, false otherwise.
5770 QualType DeclInitType, MultiExprArg ArgsPtr,
5771 SourceLocation Loc,
5772 SmallVectorImpl<Expr *> &ConvertedArgs,
5773 bool AllowExplicit = false,
5774 bool IsListInitialization = false);
5775
5776 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5777 /// initializer for the declaration 'Dcl'.
5778 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5779 /// static data member of class X, names should be looked up in the scope of
5780 /// class X.
5782
5783 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5784 /// initializer for the declaration 'Dcl'.
5785 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5786
5787 /// Define the "body" of the conversion from a lambda object to a
5788 /// function pointer.
5789 ///
5790 /// This routine doesn't actually define a sensible body; rather, it fills
5791 /// in the initialization expression needed to copy the lambda object into
5792 /// the block, and IR generation actually generates the real body of the
5793 /// block pointer conversion.
5794 void
5796 CXXConversionDecl *Conv);
5797
5798 /// Define the "body" of the conversion from a lambda object to a
5799 /// block pointer.
5800 ///
5801 /// This routine doesn't actually define a sensible body; rather, it fills
5802 /// in the initialization expression needed to copy the lambda object into
5803 /// the block, and IR generation actually generates the real body of the
5804 /// block pointer conversion.
5806 CXXConversionDecl *Conv);
5807
5808 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5809 /// linkage specification, including the language and (if present)
5810 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
5811 /// language string literal. LBraceLoc, if valid, provides the location of
5812 /// the '{' brace. Otherwise, this linkage specification does not
5813 /// have any braces.
5815 Expr *LangStr, SourceLocation LBraceLoc);
5816
5817 /// ActOnFinishLinkageSpecification - Complete the definition of
5818 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
5819 /// valid, it's the position of the closing '}' brace in a linkage
5820 /// specification that uses braces.
5822 SourceLocation RBraceLoc);
5823
5824 //===--------------------------------------------------------------------===//
5825 // C++ Classes
5826 //
5827
5828 /// Get the class that is directly named by the current context. This is the
5829 /// class for which an unqualified-id in this scope could name a constructor
5830 /// or destructor.
5831 ///
5832 /// If the scope specifier denotes a class, this will be that class.
5833 /// If the scope specifier is empty, this will be the class whose
5834 /// member-specification we are currently within. Otherwise, there
5835 /// is no such class.
5837
5838 /// isCurrentClassName - Determine whether the identifier II is the
5839 /// name of the class type currently being defined. In the case of
5840 /// nested classes, this will only return true if II is the name of
5841 /// the innermost class.
5842 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5843 const CXXScopeSpec *SS = nullptr);
5844
5845 /// Determine whether the identifier II is a typo for the name of
5846 /// the class type currently being defined. If so, update it to the identifier
5847 /// that should have been used.
5849
5850 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
5852 SourceLocation ColonLoc,
5853 const ParsedAttributesView &Attrs);
5854
5855 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
5856 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
5857 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
5858 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
5859 /// present (but parsing it has been deferred).
5860 NamedDecl *
5862 MultiTemplateParamsArg TemplateParameterLists,
5863 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5864 InClassInitStyle InitStyle);
5865
5866 /// Enter a new C++ default initializer scope. After calling this, the
5867 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
5868 /// parsing or instantiating the initializer failed.
5870
5871 /// This is invoked after parsing an in-class initializer for a
5872 /// non-static C++ class member, and after instantiating an in-class
5873 /// initializer in a class template. Such actions are deferred until the class
5874 /// is complete.
5876 SourceLocation EqualLoc,
5878
5879 /// Handle a C++ member initializer using parentheses syntax.
5881 ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS,
5882 IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy,
5883 const DeclSpec &DS, SourceLocation IdLoc,
5884 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
5885 SourceLocation RParenLoc, SourceLocation EllipsisLoc);
5886
5887 /// Handle a C++ member initializer using braced-init-list syntax.
5888 MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S,
5889 CXXScopeSpec &SS,
5890 IdentifierInfo *MemberOrBase,
5891 ParsedType TemplateTypeTy,
5892 const DeclSpec &DS, SourceLocation IdLoc,
5893 Expr *InitList, SourceLocation EllipsisLoc);
5894
5895 /// Handle a C++ member initializer.
5896 MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S,
5897 CXXScopeSpec &SS,
5898 IdentifierInfo *MemberOrBase,
5899 ParsedType TemplateTypeTy,
5900 const DeclSpec &DS, SourceLocation IdLoc,
5901 Expr *Init, SourceLocation EllipsisLoc);
5902
5904 SourceLocation IdLoc);
5905
5907 TypeSourceInfo *BaseTInfo, Expr *Init,
5908 CXXRecordDecl *ClassDecl,
5909 SourceLocation EllipsisLoc);
5910
5912 CXXRecordDecl *ClassDecl);
5913
5916
5918 ArrayRef<CXXCtorInitializer *> Initializers = {});
5919
5920 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5921 /// mark all the non-trivial destructors of its members and bases as
5922 /// referenced.
5923 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5924 CXXRecordDecl *Record);
5925
5926 /// Mark destructors of virtual bases of this class referenced. In the Itanium
5927 /// C++ ABI, this is done when emitting a destructor for any non-abstract
5928 /// class. In the Microsoft C++ ABI, this is done any time a class's
5929 /// destructor is referenced.
5931 SourceLocation Location, CXXRecordDecl *ClassDecl,
5932 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases =
5933 nullptr);
5934
5935 /// Do semantic checks to allow the complete destructor variant to be emitted
5936 /// when the destructor is defined in another translation unit. In the Itanium
5937 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
5938 /// can be emitted in separate TUs. To emit the complete variant, run a subset
5939 /// of the checks performed when emitting a regular destructor.
5940 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
5941 CXXDestructorDecl *Dtor);
5942
5943 /// The list of classes whose vtables have been used within
5944 /// this translation unit, and the source locations at which the
5945 /// first use occurred.
5946 typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse;
5947
5948 /// The list of vtables that are required but have not yet been
5949 /// materialized.
5951
5952 /// The set of classes whose vtables have been used within
5953 /// this translation unit, and a bit that will be true if the vtable is
5954 /// required to be emitted (otherwise, it should be emitted only if needed
5955 /// by code generation).
5956 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5957
5958 /// Load any externally-stored vtable uses.
5960
5961 /// Note that the vtable for the given class was used at the
5962 /// given location.
5964 bool DefinitionRequired = false);
5965
5966 /// Mark the exception specifications of all virtual member functions
5967 /// in the given class as needed.
5969 const CXXRecordDecl *RD);
5970
5971 /// MarkVirtualMembersReferenced - Will mark all members of the given
5972 /// CXXRecordDecl referenced.
5974 bool ConstexprOnly = false);
5975
5976 /// Define all of the vtables that have been used in this
5977 /// translation unit and reference any virtual members used by those
5978 /// vtables.
5979 ///
5980 /// \returns true if any work was done, false otherwise.
5981 bool DefineUsedVTables();
5982
5983 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5984 /// special functions, such as the default constructor, copy
5985 /// constructor, or destructor, to the given C++ class (C++
5986 /// [special]p1). This routine can only be executed just before the
5987 /// definition of the class is complete.
5989
5990 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5991 void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc,
5993 bool AnyErrors);
5994
5995 /// Check class-level dllimport/dllexport attribute. The caller must
5996 /// ensure that referenceDLLExportedClassMethods is called some point later
5997 /// when all outer classes of Class are complete.
6000
6002
6003 /// Perform propagation of DLL attributes from a derived class to a
6004 /// templated base class for MS compatibility.
6006 CXXRecordDecl *Class, Attr *ClassAttr,
6007 ClassTemplateSpecializationDecl *BaseTemplateSpec,
6008 SourceLocation BaseLoc);
6009
6010 /// Perform semantic checks on a class definition that has been
6011 /// completing, introducing implicitly-declared members, checking for
6012 /// abstract types, etc.
6013 ///
6014 /// \param S The scope in which the class was parsed. Null if we didn't just
6015 /// parse a class definition.
6016 /// \param Record The completed class.
6018
6019 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6020 /// conditions that are needed for the attribute to have an effect.
6022
6023 /// Check that VTable Pointer authentication is only being set on the first
6024 /// first instantiation of the vtable
6026
6028 Decl *TagDecl, SourceLocation LBrac,
6029 SourceLocation RBrac,
6030 const ParsedAttributesView &AttrList);
6031
6032 /// Perform any semantic analysis which needs to be delayed until all
6033 /// pending class member declarations have been parsed.
6036
6037 /// This is used to implement the constant expression evaluation part of the
6038 /// attribute enable_if extension. There is nothing in standard C++ which
6039 /// would require reentering parameters.
6042 llvm::function_ref<Scope *()> EnterScope);
6044
6045 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6046 /// parsing a top-level (non-nested) C++ class, and we are now
6047 /// parsing those parts of the given Method declaration that could
6048 /// not be parsed earlier (C++ [class.mem]p2), such as default
6049 /// arguments. This action should enter the scope of the given
6050 /// Method declaration as if we had just parsed the qualified method
6051 /// name. However, it should not bring the parameters into scope;
6052 /// that will be performed by ActOnDelayedCXXMethodParameter.
6054 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6056
6057 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6058 /// processing the delayed method declaration for Method. The method
6059 /// declaration is now considered finished. There may be a separate
6060 /// ActOnStartOfFunctionDef action later (not necessarily
6061 /// immediately!) for this method, if it was also defined inside the
6062 /// class body.
6065
6067
6068 bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
6069 StringEvaluationContext EvalContext,
6070 bool ErrorOnInvalidMessage);
6071 bool EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
6072 StringEvaluationContext EvalContext,
6073 bool ErrorOnInvalidMessage);
6074
6076 Expr *AssertExpr, Expr *AssertMessageExpr,
6077 SourceLocation RParenLoc);
6079 Expr *AssertExpr, Expr *AssertMessageExpr,
6080 SourceLocation RParenLoc, bool Failed);
6081
6082 /// Try to print more useful information about a failed static_assert
6083 /// with expression \E
6084 void DiagnoseStaticAssertDetails(const Expr *E);
6085
6086 /// If E represents a built-in type trait, or a known standard type trait,
6087 /// try to print more information about why the type type-trait failed.
6088 /// This assumes we already evaluated the expression to a false boolean value.
6089 void DiagnoseTypeTraitDetails(const Expr *E);
6090
6091 /// Handle a friend type declaration. This works in tandem with
6092 /// ActOnTag.
6093 ///
6094 /// Notes on friend class templates:
6095 ///
6096 /// We generally treat friend class declarations as if they were
6097 /// declaring a class. So, for example, the elaborated type specifier
6098 /// in a friend declaration is required to obey the restrictions of a
6099 /// class-head (i.e. no typedefs in the scope chain), template
6100 /// parameters are required to match up with simple template-ids, &c.
6101 /// However, unlike when declaring a template specialization, it's
6102 /// okay to refer to a template specialization without an empty
6103 /// template parameter declaration, e.g.
6104 /// friend class A<T>::B<unsigned>;
6105 /// We permit this as a special case; if there are any template
6106 /// parameters present at all, require proper matching, i.e.
6107 /// template <> template <class T> friend class A<int>::B;
6108 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6109 MultiTemplateParamsArg TemplateParams,
6110 SourceLocation EllipsisLoc);
6112 MultiTemplateParamsArg TemplateParams);
6113
6114 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6115 /// the well-formedness of the constructor declarator @p D with type @p
6116 /// R. If there are any errors in the declarator, this routine will
6117 /// emit diagnostics and set the invalid bit to true. In any case, the type
6118 /// will be updated to reflect a well-formed type for the constructor and
6119 /// returned.
6121 StorageClass &SC);
6122
6123 /// CheckConstructor - Checks a fully-formed constructor for
6124 /// well-formedness, issuing any diagnostics required. Returns true if
6125 /// the constructor declarator is invalid.
6127
6128 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6129 /// the well-formednes of the destructor declarator @p D with type @p
6130 /// R. If there are any errors in the declarator, this routine will
6131 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6132 /// will be updated to reflect a well-formed type for the destructor and
6133 /// returned.
6135 StorageClass &SC);
6136
6137 /// CheckDestructor - Checks a fully-formed destructor definition for
6138 /// well-formedness, issuing any diagnostics required. Returns true
6139 /// on error.
6141
6142 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6143 /// well-formednes of the conversion function declarator @p D with
6144 /// type @p R. If there are any errors in the declarator, this routine
6145 /// will emit diagnostics and return true. Otherwise, it will return
6146 /// false. Either way, the type @p R will be updated to reflect a
6147 /// well-formed type for the conversion operator.
6149
6150 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6151 /// the declaration of the given C++ conversion function. This routine
6152 /// is responsible for recording the conversion function in the C++
6153 /// class, if possible.
6155
6156 /// Check the validity of a declarator that we parsed for a deduction-guide.
6157 /// These aren't actually declarators in the grammar, so we need to check that
6158 /// the user didn't specify any pieces that are not part of the
6159 /// deduction-guide grammar. Return true on invalid deduction-guide.
6161 StorageClass &SC);
6162
6164
6167 SourceLocation DefaultLoc);
6169
6173 FunctionDecl *Spaceship);
6176
6178 QualType R, bool IsLambda,
6179 DeclContext *DC = nullptr);
6181 DeclarationName Name, QualType R);
6183
6184 //===--------------------------------------------------------------------===//
6185 // C++ Derived Classes
6186 //
6187
6188 /// Check the validity of a C++ base class specifier.
6189 ///
6190 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
6191 /// and returns NULL otherwise.
6193 SourceRange SpecifierRange, bool Virtual,
6194 AccessSpecifier Access,
6195 TypeSourceInfo *TInfo,
6196 SourceLocation EllipsisLoc);
6197
6198 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
6199 /// one entry in the base class list of a class specifier, for
6200 /// example:
6201 /// class foo : public bar, virtual private baz {
6202 /// 'public bar' and 'virtual private baz' are each base-specifiers.
6203 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
6204 const ParsedAttributesView &Attrs, bool Virtual,
6205 AccessSpecifier Access, ParsedType basetype,
6206 SourceLocation BaseLoc,
6207 SourceLocation EllipsisLoc);
6208
6209 /// Performs the actual work of attaching the given base class
6210 /// specifiers to a C++ class.
6213
6214 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
6215 /// class, after checking whether there are any duplicate base
6216 /// classes.
6217 void ActOnBaseSpecifiers(Decl *ClassDecl,
6219
6220 /// Determine whether the type \p Derived is a C++ class that is
6221 /// derived from the type \p Base.
6222 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6224 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6228 CXXBasePaths &Paths);
6229
6230 // FIXME: I don't like this name.
6231 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6232
6234 SourceLocation Loc, SourceRange Range,
6235 CXXCastPath *BasePath = nullptr,
6236 bool IgnoreAccess = false);
6237
6238 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
6239 /// conversion (where Derived and Base are class types) is
6240 /// well-formed, meaning that the conversion is unambiguous (and
6241 /// that all of the base classes are accessible). Returns true
6242 /// and emits a diagnostic if the code is ill-formed, returns false
6243 /// otherwise. Loc is the location where this routine should point to
6244 /// if there is an error, and Range is the source range to highlight
6245 /// if there is an error.
6246 ///
6247 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
6248 /// diagnostic for the respective type of error will be suppressed, but the
6249 /// check for ill-formed code will still be performed.
6251 unsigned InaccessibleBaseID,
6252 unsigned AmbiguousBaseConvID,
6253 SourceLocation Loc, SourceRange Range,
6254 DeclarationName Name, CXXCastPath *BasePath,
6255 bool IgnoreAccess = false);
6256
6257 /// Builds a string representing ambiguous paths from a
6258 /// specific derived class to different subobjects of the same base
6259 /// class.
6260 ///
6261 /// This function builds a string that can be used in error messages
6262 /// to show the different paths that one can take through the
6263 /// inheritance hierarchy to go from the derived class to different
6264 /// subobjects of a base class. The result looks something like this:
6265 /// @code
6266 /// struct D -> struct B -> struct A
6267 /// struct D -> struct C -> struct A
6268 /// @endcode
6269 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6270
6272 const CXXMethodDecl *Old);
6273
6274 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6275 /// covariant, according to C++ [class.virtual]p5.
6277 const CXXMethodDecl *Old);
6278
6279 // Check that the overriding method has no explicit object parameter.
6281 const CXXMethodDecl *Old);
6282
6283 /// Mark the given method pure.
6284 ///
6285 /// \param Method the method to be marked pure.
6286 ///
6287 /// \param InitRange the source range that covers the "0" initializer.
6289
6290 /// CheckOverrideControl - Check C++11 override control semantics.
6292
6293 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6294 /// not used in the declaration of an overriding method.
6296
6297 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
6298 /// function overrides a virtual member function marked 'final', according to
6299 /// C++11 [class.virtual]p4.
6301 const CXXMethodDecl *Old);
6302
6313
6314 struct TypeDiagnoser;
6315
6318 TypeDiagnoser &Diagnoser);
6319 template <typename... Ts>
6321 const Ts &...Args) {
6322 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6323 return RequireNonAbstractType(Loc, T, Diagnoser);
6324 }
6325
6326 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6327
6328 //===--------------------------------------------------------------------===//
6329 // C++ Overloaded Operators [C++ 13.5]
6330 //
6331
6332 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
6333 /// of this overloaded operator is well-formed. If so, returns false;
6334 /// otherwise, emits appropriate diagnostics and returns true.
6336
6337 /// CheckLiteralOperatorDeclaration - Check whether the declaration
6338 /// of this literal operator function is well-formed. If so, returns
6339 /// false; otherwise, emits appropriate diagnostics and returns true.
6341
6342 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
6343 /// found in an explicit(bool) specifier.
6345
6346 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
6347 /// Returns true if the explicit specifier is now resolved.
6349
6350 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6351 /// C++ if/switch/while/for statement.
6352 /// e.g: "if (int x = f()) {...}"
6354
6355 // Emitting members of dllexported classes is delayed until the class
6356 // (including field initializers) is fully parsed.
6359
6360 /// Merge the exception specifications of two variable declarations.
6361 ///
6362 /// This is called when there's a redeclaration of a VarDecl. The function
6363 /// checks if the redeclaration might have an exception specification and
6364 /// validates compatibility and merges the specs if necessary.
6366
6367 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
6368 /// function, once we already know that they have the same
6369 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
6370 /// error, false otherwise.
6372
6373 /// Helpers for dealing with blocks and functions.
6375
6376 /// CheckExtraCXXDefaultArguments - Check for any extra default
6377 /// arguments in the declarator, which is not a function declaration
6378 /// or definition and therefore is not permitted to have default
6379 /// arguments. This routine should be invoked for every declarator
6380 /// that is not a function declaration or definition.
6382
6383 /// Perform semantic analysis for the variable declaration that
6384 /// occurs within a C++ catch clause, returning the newly-created
6385 /// variable.
6387 SourceLocation StartLoc,
6388 SourceLocation IdLoc,
6389 const IdentifierInfo *Id);
6390
6391 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6392 /// handler.
6394
6396
6397 /// Handle a friend tag declaration where the scope specifier was
6398 /// templated.
6400 unsigned TagSpec, SourceLocation TagLoc,
6401 CXXScopeSpec &SS, IdentifierInfo *Name,
6402 SourceLocation NameLoc,
6403 SourceLocation EllipsisLoc,
6405 MultiTemplateParamsArg TempParamLists,
6406 TemplateIdAnnotation *TemplateId);
6407
6410 bool IsInstantiation);
6411
6413 NestedNameSpecifierLoc NNSLoc);
6414
6416 SourceLocation DeclStart, Declarator &D,
6417 Expr *BitfieldWidth,
6418 InClassInitStyle InitStyle,
6419 AccessSpecifier AS,
6420 const ParsedAttr &MSPropertyAttr);
6421
6422 /// Diagnose why the specified class does not have a trivial special member of
6423 /// the given kind.
6426
6427 /// Determine whether a defaulted or deleted special member function is
6428 /// trivial, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6429 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6433 bool Diagnose = false);
6434
6435 /// Handle a C++11 empty-declaration and attribute-declaration.
6437 SourceLocation SemiLoc);
6438
6440 /// Diagnose issues that are non-constant or that are extensions.
6442 /// Identify whether this function satisfies the formal rules for constexpr
6443 /// functions in the current lanugage mode (with no extensions).
6445 };
6446
6447 // Check whether a function declaration satisfies the requirements of a
6448 // constexpr function definition or a constexpr constructor definition. If so,
6449 // return true. If not, produce appropriate diagnostics (unless asked not to
6450 // by Kind) and return false.
6451 //
6452 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
6454 CheckConstexprKind Kind);
6455
6456 /// Diagnose methods which overload virtual methods in a base class
6457 /// without overriding any.
6459
6460 /// Check if a method overloads virtual methods in a base class without
6461 /// overriding any.
6462 void
6464 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6465 void
6467 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6468
6469 /// ActOnParamDefaultArgument - Check whether the default argument
6470 /// provided for a function parameter is well-formed. If so, attach it
6471 /// to the parameter declaration.
6472 void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
6473 Expr *defarg);
6474
6475 /// ActOnParamUnparsedDefaultArgument - We've seen a default
6476 /// argument for a function parameter, but we can't parse it yet
6477 /// because we're inside a class definition. Note that this default
6478 /// argument will be parsed later.
6480 SourceLocation ArgLoc);
6481
6482 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
6483 /// the default argument for the parameter param failed.
6485 Expr *DefaultArg);
6487 SourceLocation EqualLoc);
6488 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6489 SourceLocation EqualLoc);
6490
6491 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
6492 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc,
6493 StringLiteral *Message = nullptr);
6494 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
6495
6496 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
6497 StringLiteral *DeletedMessage = nullptr);
6501
6502 NamedDecl *
6504 MultiTemplateParamsArg TemplateParamLists);
6507 RecordDecl *ClassDecl,
6508 const IdentifierInfo *Name);
6509
6511 SourceLocation Loc);
6513
6514 /// Stack containing information needed when in C++2a an 'auto' is encountered
6515 /// in a function declaration parameter type specifier in order to invent a
6516 /// corresponding template parameter in the enclosing abbreviated function
6517 /// template. This information is also present in LambdaScopeInfo, stored in
6518 /// the FunctionScopes stack.
6520
6521 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
6522 std::unique_ptr<CXXFieldCollector> FieldCollector;
6523
6525 /// Set containing all declared private fields that are not used.
6527
6529
6530 /// PureVirtualClassDiagSet - a set of class declarations which we have
6531 /// emitted a list of pure virtual functions. Used to prevent emitting the
6532 /// same list more than once.
6533 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
6534
6538
6539 /// All the delegating constructors seen so far in the file, used for
6540 /// cycle detection at the end of the TU.
6542
6543 /// The C++ "std" namespace, where the standard library resides.
6545
6546 /// The C++ "std::initializer_list" template, which is defined in
6547 /// <initializer_list>.
6549
6550 /// The C++ "std::type_identity" template, which is defined in
6551 /// <type_traits>.
6553
6554 // Contains the locations of the beginning of unparsed default
6555 // argument locations.
6556 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
6557
6558 /// UndefinedInternals - all the used, undefined objects which require a
6559 /// definition in this translation unit.
6560 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
6561
6562 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMemberKind>
6564
6565 /// The C++ special members which we are currently in the process of
6566 /// declaring. If this process recursively triggers the declaration of the
6567 /// same special member, we should act as if it is not yet declared.
6569
6571
6572 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
6573
6576 ParsingClassDepth++;
6578 }
6580 ParsingClassDepth--;
6582 }
6583
6585 CXXScopeSpec &SS,
6586 ParsedType TemplateTypeTy,
6587 IdentifierInfo *MemberOrBase);
6588
6589private:
6590 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
6591 QualType ResultTy,
6592 ArrayRef<QualType> Args);
6593 // Helper for ActOnFields to check for all function pointer members.
6594 bool EntirelyFunctionPointers(const RecordDecl *Record);
6595
6596 // A cache representing if we've fully checked the various comparison category
6597 // types stored in ASTContext. The bit-index corresponds to the integer value
6598 // of a ComparisonCategoryType enumerator.
6599 llvm::SmallBitVector FullyCheckedComparisonCategories;
6600
6601 /// Check if there is a field shadowing.
6602 void CheckShadowInheritedFields(const SourceLocation &Loc,
6603 DeclarationName FieldName,
6604 const CXXRecordDecl *RD,
6605 bool DeclIsField = true);
6606
6607 ///@}
6608
6609 //
6610 //
6611 // -------------------------------------------------------------------------
6612 //
6613 //
6614
6615 /// \name C++ Exception Specifications
6616 /// Implementations are in SemaExceptionSpec.cpp
6617 ///@{
6618
6619public:
6620 /// All the overriding functions seen during a class definition
6621 /// that had their exception spec checks delayed, plus the overridden
6622 /// function.
6625
6626 /// All the function redeclarations seen during a class definition that had
6627 /// their exception spec checks delayed, plus the prior declaration they
6628 /// should be checked against. Except during error recovery, the new decl
6629 /// should always be a friend declaration, as that's the only valid way to
6630 /// redeclare a special member before its class is complete.
6633
6634 /// Determine if we're in a case where we need to (incorrectly) eagerly
6635 /// parse an exception specification to work around a libstdc++ bug.
6637
6638 /// Check the given noexcept-specifier, convert its expression, and compute
6639 /// the appropriate ExceptionSpecificationType.
6640 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6642
6643 CanThrowResult canThrow(const Stmt *E);
6644 /// Determine whether the callee of a particular function call can throw.
6645 /// E, D and Loc are all optional.
6646 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
6649 const FunctionProtoType *FPT);
6652
6653 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
6654 /// exception specification. Incomplete types, or pointers to incomplete types
6655 /// other than void are not allowed.
6656 ///
6657 /// \param[in,out] T The exception type. This will be decayed to a pointer
6658 /// type
6659 /// when the input is an array or a function type.
6661
6662 /// CheckDistantExceptionSpec - Check if the given type is a pointer or
6663 /// pointer to member to a function with an exception specification. This
6664 /// means that it is invalid to add another level of indirection.
6667
6668 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
6669 /// exception specifications. Exception specifications are equivalent if
6670 /// they allow exactly the same set of exception types. It does not matter how
6671 /// that is achieved. See C++ [except.spec]p2.
6673 SourceLocation OldLoc,
6674 const FunctionProtoType *New,
6675 SourceLocation NewLoc);
6677 const PartialDiagnostic &NoteID,
6678 const FunctionProtoType *Old,
6679 SourceLocation OldLoc,
6680 const FunctionProtoType *New,
6681 SourceLocation NewLoc);
6682 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
6683
6684 /// CheckExceptionSpecSubset - Check whether the second function type's
6685 /// exception specification is a subset (or equivalent) of the first function
6686 /// type. This is used by override and pointer assignment checks.
6688 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
6689 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
6690 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
6691 SourceLocation SuperLoc, const FunctionProtoType *Subset,
6692 bool SkipSubsetFirstParameter, SourceLocation SubLoc);
6693
6694 /// CheckParamExceptionSpec - Check if the parameter and return types of the
6695 /// two functions have equivalent exception specs. This is part of the
6696 /// assignment and override compatibility check. We do not check the
6697 /// parameters of parameter function pointers recursively, as no sane
6698 /// programmer would even be able to write such a function type.
6700 const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID,
6701 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
6702 SourceLocation TargetLoc, const FunctionProtoType *Source,
6703 bool SkipSourceFirstParameter, SourceLocation SourceLoc);
6704
6705 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6706
6707 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6708 /// spec is a subset of base spec.
6710 const CXXMethodDecl *Old);
6711
6712 ///@}
6713
6714 //
6715 //
6716 // -------------------------------------------------------------------------
6717 //
6718 //
6719
6720 /// \name Expressions
6721 /// Implementations are in SemaExpr.cpp
6722 ///@{
6723
6724public:
6725 /// Describes how the expressions currently being parsed are
6726 /// evaluated at run-time, if at all.
6728 /// The current expression and its subexpressions occur within an
6729 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
6730 /// \c sizeof, where the type of the expression may be significant but
6731 /// no code will be generated to evaluate the value of the expression at
6732 /// run time.
6734
6735 /// The current expression occurs within a braced-init-list within
6736 /// an unevaluated operand. This is mostly like a regular unevaluated
6737 /// context, except that we still instantiate constexpr functions that are
6738 /// referenced here so that we can perform narrowing checks correctly.
6740
6741 /// The current expression occurs within a discarded statement.
6742 /// This behaves largely similarly to an unevaluated operand in preventing
6743 /// definitions from being required, but not in other ways.
6745
6746 /// The current expression occurs within an unevaluated
6747 /// operand that unconditionally permits abstract references to
6748 /// fields, such as a SIZE operator in MS-style inline assembly.
6750
6751 /// The current context is "potentially evaluated" in C++11 terms,
6752 /// but the expression is evaluated at compile-time (like the values of
6753 /// cases in a switch statement).
6755
6756 /// In addition of being constant evaluated, the current expression
6757 /// occurs in an immediate function context - either a consteval function
6758 /// or a consteval if statement.
6760
6761 /// The current expression is potentially evaluated at run time,
6762 /// which means that code may be generated to evaluate the value of the
6763 /// expression at run time.
6765
6766 /// The current expression is potentially evaluated, but any
6767 /// declarations referenced inside that expression are only used if
6768 /// in fact the current expression is used.
6769 ///
6770 /// This value is used when parsing default function arguments, for which
6771 /// we would like to provide diagnostics (e.g., passing non-POD arguments
6772 /// through varargs) but do not want to mark declarations as "referenced"
6773 /// until the default argument is used.
6775 };
6776
6777 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
6778 /// to a variable (constant) that may or may not be odr-used in this Expr, and
6779 /// we won't know until all lvalue-to-rvalue and discarded value conversions
6780 /// have been applied to all subexpressions of the enclosing full expression.
6781 /// This is cleared at the end of each full expression.
6784
6785 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
6786
6787 /// Data structure used to record current or nested
6788 /// expression evaluation contexts.
6790 /// The expression evaluation context.
6792
6793 /// Whether the enclosing context needed a cleanup.
6795
6796 /// The number of active cleanup objects when we entered
6797 /// this expression evaluation context.
6799
6801
6802 /// The lambdas that are present within this context, if it
6803 /// is indeed an unevaluated context.
6805
6806 /// The declaration that provides context for lambda expressions
6807 /// and block literals if the normal declaration context does not
6808 /// suffice, e.g., in a default function argument.
6810
6811 /// Declaration for initializer if one is currently being
6812 /// parsed. Used when an expression has a possibly unreachable
6813 /// diagnostic to reference the declaration as a whole.
6815
6816 /// If we are processing a decltype type, a set of call expressions
6817 /// for which we have deferred checking the completeness of the return type.
6819
6820 /// If we are processing a decltype type, a set of temporary binding
6821 /// expressions for which we have deferred checking the destructor.
6823
6825
6826 /// Expressions appearing as the LHS of a volatile assignment in this
6827 /// context. We produce a warning for these when popping the context if
6828 /// they are not discarded-value expressions nor unevaluated operands.
6830
6831 /// Set of candidates for starting an immediate invocation.
6834
6835 /// Set of DeclRefExprs referencing a consteval function when used in a
6836 /// context not already known to be immediately invoked.
6838
6839 /// P2718R0 - Lifetime extension in range-based for loops.
6840 /// MaterializeTemporaryExprs in for-range-init expressions which need to
6841 /// extend lifetime. Add MaterializeTemporaryExpr* if the value of
6842 /// InLifetimeExtendingContext is true.
6844
6845 /// Small set of gathered accesses to potentially misaligned members
6846 /// due to the packed attribute.
6848
6849 /// \brief Describes whether we are in an expression constext which we have
6850 /// to handle differently.
6858
6859 // A context can be nested in both a discarded statement context and
6860 // an immediate function context, so they need to be tracked independently.
6864
6866
6867 // We are in a constant context, but we also allow
6868 // non constant expressions, for example for array bounds (which may be
6869 // VLAs).
6871
6872 /// Whether we are currently in a context in which all temporaries must be
6873 /// lifetime-extended, even if they're not bound to a reference (for
6874 /// example, in a for-range initializer).
6876
6877 /// Whether evaluating an expression for a switch case label.
6878 bool IsCaseExpr = false;
6879
6880 /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
6882
6883 // When evaluating immediate functions in the initializer of a default
6884 // argument or default member initializer, this is the declaration whose
6885 // default initializer is being evaluated and the location of the call
6886 // or constructor definition.
6890 : Loc(Loc), Decl(Decl), Context(Context) {
6891 assert(Decl && Context && "invalid initialization context");
6892 }
6893
6895 ValueDecl *Decl = nullptr;
6897 };
6898 std::optional<InitializationContext> DelayedDefaultInitializationContext;
6899
6910
6916
6923
6928
6933 // C++23 [expr.const]p14:
6934 // An expression or conversion is in an immediate function
6935 // context if it is potentially evaluated and either:
6936 // * its innermost enclosing non-block scope is a function
6937 // parameter scope of an immediate function, or
6938 // * its enclosing statement is enclosed by the compound-
6939 // statement of a consteval if statement.
6942 }
6943
6951 };
6952
6954 assert(!ExprEvalContexts.empty() &&
6955 "Must be in an expression evaluation context");
6956 return ExprEvalContexts.back();
6957 }
6958
6960 assert(!ExprEvalContexts.empty() &&
6961 "Must be in an expression evaluation context");
6962 return ExprEvalContexts.back();
6963 }
6964
6966 assert(ExprEvalContexts.size() >= 2 &&
6967 "Must be in an expression evaluation context");
6968 return ExprEvalContexts[ExprEvalContexts.size() - 2];
6969 }
6970
6972 return const_cast<Sema *>(this)->parentEvaluationContext();
6973 }
6974
6979
6980 /// Increment when we find a reference; decrement when we find an ignored
6981 /// assignment. Ultimately the value is 0 if every reference is an ignored
6982 /// assignment.
6983 ///
6984 /// Uses canonical VarDecl as key so in-class decls and out-of-class defs of
6985 /// static data members get tracked as a single entry.
6986 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
6987
6988 /// Used to control the generation of ExprWithCleanups.
6990
6991 /// ExprCleanupObjects - This is the stack of objects requiring
6992 /// cleanup that are created by the current full expression.
6994
6995 /// Determine whether the use of this declaration is valid, without
6996 /// emitting diagnostics.
6997 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
6998 // A version of DiagnoseUseOfDecl that should be used if overload resolution
6999 // has been used to find this declaration, which means we don't have to bother
7000 // checking the trailing requires clause.
7002 return DiagnoseUseOfDecl(
7003 D, Loc, /*UnknownObjCClass=*/nullptr, /*ObjCPropertyAccess=*/false,
7004 /*AvoidPartialAvailabilityChecks=*/false, /*ClassReceiver=*/nullptr,
7005 /*SkipTrailingRequiresClause=*/true);
7006 }
7007
7008 /// Determine whether the use of this declaration is valid, and
7009 /// emit any corresponding diagnostics.
7010 ///
7011 /// This routine diagnoses various problems with referencing
7012 /// declarations that can occur when using a declaration. For example,
7013 /// it might warn if a deprecated or unavailable declaration is being
7014 /// used, or produce an error (and return true) if a C++0x deleted
7015 /// function is being used.
7016 ///
7017 /// \returns true if there was an error (this declaration cannot be
7018 /// referenced), false otherwise.
7020 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
7021 bool ObjCPropertyAccess = false,
7022 bool AvoidPartialAvailabilityChecks = false,
7023 ObjCInterfaceDecl *ClassReceiver = nullptr,
7024 bool SkipTrailingRequiresClause = false);
7025
7026 /// Emit a note explaining that this function is deleted.
7028
7029 /// DiagnoseSentinelCalls - This routine checks whether a call or
7030 /// message-send is to a declaration with the sentinel attribute, and
7031 /// if so, it checks that the requirements of the sentinel are
7032 /// satisfied.
7034 ArrayRef<Expr *> Args);
7035
7037 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
7040
7042 ExpressionEvaluationContext NewContext, FunctionDecl *FD);
7043
7046 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
7050
7052
7056
7057 /// Check whether E, which is either a discarded-value expression or an
7058 /// unevaluated operand, is a simple-assignment to a volatlie-qualified
7059 /// lvalue, and if so, remove it from the list of volatile-qualified
7060 /// assignments that we are going to warn are deprecated.
7062
7064
7065 // Functions for marking a declaration referenced. These functions also
7066 // contain the relevant logic for marking if a reference to a function or
7067 // variable is an odr-use (in the C++11 sense). There are separate variants
7068 // for expressions referring to a decl; these exist because odr-use marking
7069 // needs to be delayed for some constant variables when we build one of the
7070 // named expressions.
7071 //
7072 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
7073 // should usually be true. This only needs to be set to false if the lack of
7074 // odr-use cannot be determined from the current context (for instance,
7075 // because the name denotes a virtual function and was written without an
7076 // explicit nested-name-specifier).
7077 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
7078
7079 /// Mark a function referenced, and check whether it is odr-used
7080 /// (C++ [basic.def.odr]p2, C99 6.9p3)
7082 bool MightBeOdrUse = true);
7083
7084 /// Mark a variable referenced, and check whether it is odr-used
7085 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
7086 /// used directly for normal expressions referring to VarDecl.
7088
7089 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
7090 ///
7091 /// Note, this may change the dependence of the DeclRefExpr, and so needs to
7092 /// be handled with care if the DeclRefExpr is not newly-created.
7093 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
7094
7095 /// Perform reference-marking and odr-use handling for a MemberExpr.
7097
7098 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
7101 unsigned CapturingScopeIndex);
7102
7104 void CleanupVarDeclMarking();
7105
7106 /// Try to capture the given variable.
7107 ///
7108 /// \param Var The variable to capture.
7109 ///
7110 /// \param Loc The location at which the capture occurs.
7111 ///
7112 /// \param Kind The kind of capture, which may be implicit (for either a
7113 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
7114 ///
7115 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
7116 /// an explicit lambda capture.
7117 ///
7118 /// \param BuildAndDiagnose Whether we are actually supposed to add the
7119 /// captures or diagnose errors. If false, this routine merely check whether
7120 /// the capture can occur without performing the capture itself or complaining
7121 /// if the variable cannot be captured.
7122 ///
7123 /// \param CaptureType Will be set to the type of the field used to capture
7124 /// this variable in the innermost block or lambda. Only valid when the
7125 /// variable can be captured.
7126 ///
7127 /// \param DeclRefType Will be set to the type of a reference to the capture
7128 /// from within the current scope. Only valid when the variable can be
7129 /// captured.
7130 ///
7131 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
7132 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
7133 /// This is useful when enclosing lambdas must speculatively capture
7134 /// variables that may or may not be used in certain specializations of
7135 /// a nested generic lambda.
7136 ///
7137 /// \returns true if an error occurred (i.e., the variable cannot be
7138 /// captured) and false if the capture succeeded.
7140 TryCaptureKind Kind, SourceLocation EllipsisLoc,
7141 bool BuildAndDiagnose, QualType &CaptureType,
7142 QualType &DeclRefType,
7143 const unsigned *const FunctionScopeIndexToStopAt);
7144
7145 /// Try to capture the given variable.
7148 SourceLocation EllipsisLoc = SourceLocation());
7149
7150 /// Checks if the variable must be captured.
7152
7153 /// Given a variable, determine the type that a reference to that
7154 /// variable will have in the given scope.
7156
7157 /// Mark all of the declarations referenced within a particular AST node as
7158 /// referenced. Used when template instantiation instantiates a non-dependent
7159 /// type -- entities referenced by the type are now referenced.
7161
7162 /// Mark any declarations that appear within this expression or any
7163 /// potentially-evaluated subexpressions as "referenced".
7164 ///
7165 /// \param SkipLocalVariables If true, don't mark local variables as
7166 /// 'referenced'.
7167 /// \param StopAt Subexpressions that we shouldn't recurse into.
7169 bool SkipLocalVariables = false,
7170 ArrayRef<const Expr *> StopAt = {});
7171
7172 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
7173 /// conversion.
7174 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
7175
7176 /// Conditionally issue a diagnostic based on the statements's reachability
7177 /// analysis.
7178 ///
7179 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
7180 /// the function body is parsed, and then do a basic reachability analysis to
7181 /// determine if the statement is reachable. If it is unreachable, the
7182 /// diagnostic will not be emitted.
7183 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7184 const PartialDiagnostic &PD);
7185
7186 /// Conditionally issue a diagnostic based on the current
7187 /// evaluation context.
7188 ///
7189 /// \param Statement If Statement is non-null, delay reporting the
7190 /// diagnostic until the function body is parsed, and then do a basic
7191 /// reachability analysis to determine if the statement is reachable.
7192 /// If it is unreachable, the diagnostic will not be emitted.
7193 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
7194 const PartialDiagnostic &PD);
7195 /// Similar, but diagnostic is only produced if all the specified statements
7196 /// are reachable.
7197 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7198 const PartialDiagnostic &PD);
7199
7200 // Primary Expressions.
7201 SourceRange getExprRange(Expr *E) const;
7202
7203 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
7204 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
7205 bool HasTrailingLParen, bool IsAddressOfOperand,
7206 CorrectionCandidateCallback *CCC = nullptr,
7207 bool IsInlineAsmIdentifier = false);
7208
7209 /// Decomposes the given name into a DeclarationNameInfo, its location, and
7210 /// possibly a list of template arguments.
7211 ///
7212 /// If this produces template arguments, it is permitted to call
7213 /// DecomposeTemplateName.
7214 ///
7215 /// This actually loses a lot of source location information for
7216 /// non-standard name kinds; we should consider preserving that in
7217 /// some way.
7218 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
7219 TemplateArgumentListInfo &Buffer,
7220 DeclarationNameInfo &NameInfo,
7221 const TemplateArgumentListInfo *&TemplateArgs);
7222
7223 /// Diagnose a lookup that found results in an enclosing class during error
7224 /// recovery. This usually indicates that the results were found in a
7225 /// dependent base class that could not be searched as part of a template
7226 /// definition. Always issues a diagnostic (though this may be only a warning
7227 /// in MS compatibility mode).
7228 ///
7229 /// Return \c true if the error is unrecoverable, or \c false if the caller
7230 /// should attempt to recover using these lookup results.
7231 bool DiagnoseDependentMemberLookup(const LookupResult &R);
7232
7233 /// Diagnose an empty lookup.
7234 ///
7235 /// \return false if new lookup candidates were found
7236 bool
7237 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
7238 CorrectionCandidateCallback &CCC,
7239 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
7240 ArrayRef<Expr *> Args = {},
7241 DeclContext *LookupCtx = nullptr);
7242
7243 /// If \p D cannot be odr-used in the current expression evaluation context,
7244 /// return a reason explaining why. Otherwise, return NOUR_None.
7246
7247 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7248 SourceLocation Loc,
7249 const CXXScopeSpec *SS = nullptr);
7250 DeclRefExpr *
7251 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7252 const DeclarationNameInfo &NameInfo,
7253 const CXXScopeSpec *SS = nullptr,
7254 NamedDecl *FoundD = nullptr,
7255 SourceLocation TemplateKWLoc = SourceLocation(),
7256 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7257
7258 /// BuildDeclRefExpr - Build an expression that references a
7259 /// declaration that does not require a closure capture.
7260 DeclRefExpr *
7261 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7262 const DeclarationNameInfo &NameInfo,
7263 NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr,
7264 SourceLocation TemplateKWLoc = SourceLocation(),
7265 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7266
7267 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R,
7268 bool HasTrailingLParen);
7269
7270 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
7271 /// declaration name, generally during template instantiation.
7272 /// There's a large number of things which don't need to be done along
7273 /// this path.
7275 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
7276 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
7277
7278 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R,
7279 bool NeedsADL,
7280 bool AcceptInvalidDecl = false);
7281
7282 /// Complete semantic analysis for a reference to the given declaration.
7284 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
7285 NamedDecl *FoundD = nullptr,
7286 const TemplateArgumentListInfo *TemplateArgs = nullptr,
7287 bool AcceptInvalidDecl = false);
7288
7289 // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens,
7290 // where Tokens representing function local predefined macros (such as
7291 // __FUNCTION__) are replaced (expanded) with string-literal Tokens.
7292 std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks);
7293
7294 ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK);
7295 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
7296 ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val);
7297
7298 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero);
7299
7300 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
7302 Scope *UDLScope = nullptr);
7303 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
7304 ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R,
7305 MultiExprArg Val);
7306 ExprResult ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
7307 unsigned NumUserSpecifiedExprs,
7308 SourceLocation InitLoc,
7309 SourceLocation LParenLoc,
7310 SourceLocation RParenLoc);
7311
7312 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
7313 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle
7314 /// string concatenation ([C99 5.1.1.2, translation phase #6]), so it may come
7315 /// from multiple tokens. However, the common case is that StringToks points
7316 /// to one string.
7317 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
7318 Scope *UDLScope = nullptr);
7319
7320 ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks);
7321
7322 /// ControllingExprOrType is either an opaque pointer coming out of a
7323 /// ParsedType or an Expr *. FIXME: it'd be better to split this interface
7324 /// into two so we don't take a void *, but that's awkward because one of
7325 /// the operands is either a ParsedType or an Expr *, which doesn't lend
7326 /// itself to generic code very well.
7327 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
7328 SourceLocation DefaultLoc,
7329 SourceLocation RParenLoc,
7330 bool PredicateIsExpr,
7331 void *ControllingExprOrType,
7332 ArrayRef<ParsedType> ArgTypes,
7333 ArrayRef<Expr *> ArgExprs);
7334 /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME:
7335 /// it'd be better to split this interface into two so we don't take a
7336 /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that
7337 /// isn't a trivial change.
7338 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
7339 SourceLocation DefaultLoc,
7340 SourceLocation RParenLoc,
7341 bool PredicateIsExpr,
7342 void *ControllingExprOrType,
7343 ArrayRef<TypeSourceInfo *> Types,
7344 ArrayRef<Expr *> Exprs);
7345
7346 // Binary/Unary Operators. 'Tok' is the token for the operator.
7347 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
7348 Expr *InputExpr, bool IsAfterAmp = false);
7349 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
7350 Expr *Input, bool IsAfterAmp = false);
7351
7352 /// Unary Operators. 'Tok' is the token for the operator.
7353 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
7354 Expr *Input, bool IsAfterAmp = false);
7355
7356 /// Determine whether the given expression is a qualified member
7357 /// access expression, of a form that could be turned into a pointer to member
7358 /// with the address-of operator.
7359 bool isQualifiedMemberAccess(Expr *E);
7360 bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
7361 const Expr *Op,
7362 const CXXMethodDecl *MD);
7363
7364 /// CheckAddressOfOperand - The operand of & must be either a function
7365 /// designator or an lvalue designating an object. If it is an lvalue, the
7366 /// object cannot be declared with storage class register or be a bit field.
7367 /// Note: The usual conversions are *not* applied to the operand of the &
7368 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7369 /// In C++, the operand might be an overloaded function name, in which case
7370 /// we allow the '&' but retain the overloaded-function type.
7371 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
7372
7373 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
7374 /// _Alignas(type-name) .
7375 /// [dcl.align] An alignment-specifier of the form
7376 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
7377 ///
7378 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
7379 /// _Alignas(_Alignof(type-name)).
7380 bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
7381 SourceLocation OpLoc, SourceRange R);
7382 bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
7383 SourceLocation OpLoc, SourceRange R);
7384
7385 /// Build a sizeof or alignof expression given a type operand.
7386 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
7387 SourceLocation OpLoc,
7388 UnaryExprOrTypeTrait ExprKind,
7389 SourceRange R);
7390
7391 /// Build a sizeof or alignof expression given an expression
7392 /// operand.
7393 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
7394 UnaryExprOrTypeTrait ExprKind);
7395
7396 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
7397 /// expr and the same for @c alignof and @c __alignof
7398 /// Note that the ArgRange is invalid if isType is false.
7399 ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
7400 UnaryExprOrTypeTrait ExprKind,
7401 bool IsType, void *TyOrEx,
7402 SourceRange ArgRange);
7403
7404 /// Check for operands with placeholder types and complain if found.
7405 /// Returns ExprError() if there was an error and no recovery was possible.
7407 bool CheckVecStepExpr(Expr *E);
7408
7409 /// Check the constraints on expression operands to unary type expression
7410 /// and type traits.
7411 ///
7412 /// Completes any types necessary and validates the constraints on the operand
7413 /// expression. The logic mostly mirrors the type-based overload, but may
7414 /// modify the expression as it completes the type for that expression through
7415 /// template instantiation, etc.
7416 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
7417
7418 /// Check the constraints on operands to unary expression and type
7419 /// traits.
7420 ///
7421 /// This will complete any types necessary, and validate the various
7422 /// constraints on those operands.
7423 ///
7424 /// The UsualUnaryConversions() function is *not* called by this routine.
7425 /// C99 6.3.2.1p[2-4] all state:
7426 /// Except when it is the operand of the sizeof operator ...
7427 ///
7428 /// C++ [expr.sizeof]p4
7429 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
7430 /// standard conversions are not applied to the operand of sizeof.
7431 ///
7432 /// This policy is followed for all of the unary trait expressions.
7433 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
7434 SourceRange ExprRange,
7435 UnaryExprOrTypeTrait ExprKind,
7436 StringRef KWName);
7437
7438 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
7439 tok::TokenKind Kind, Expr *Input);
7440
7441 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
7442 MultiExprArg ArgExprs,
7443 SourceLocation RLoc);
7444 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
7445 Expr *Idx, SourceLocation RLoc);
7446
7447 ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx,
7448 SourceLocation RBLoc);
7449
7450 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
7451 Expr *ColumnIdx,
7452 SourceLocation RBLoc);
7453
7454 /// ConvertArgumentsForCall - Converts the arguments specified in
7455 /// Args/NumArgs to the parameter types of the function FDecl with
7456 /// function prototype Proto. Call is the call expression itself, and
7457 /// Fn is the function expression. For a C++ member function, this
7458 /// routine does not attempt to convert the object argument. Returns
7459 /// true if the call is ill-formed.
7460 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl,
7461 const FunctionProtoType *Proto,
7462 ArrayRef<Expr *> Args, SourceLocation RParenLoc,
7463 bool ExecConfig = false);
7464
7465 /// CheckStaticArrayArgument - If the given argument corresponds to a static
7466 /// array parameter, check that it is non-null, and that if it is formed by
7467 /// array-to-pointer decay, the underlying array is sufficiently large.
7468 ///
7469 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of
7470 /// the array type derivation, then for each call to the function, the value
7471 /// of the corresponding actual argument shall provide access to the first
7472 /// element of an array with at least as many elements as specified by the
7473 /// size expression.
7474 void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param,
7475 const Expr *ArgExpr);
7476
7477 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
7478 /// This provides the location of the left/right parens and a list of comma
7479 /// locations.
7480 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7481 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7482 Expr *ExecConfig = nullptr);
7483
7484 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7485 /// This provides the location of the left/right parens and a list of comma
7486 /// locations.
7487 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7488 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7489 Expr *ExecConfig = nullptr,
7490 bool IsExecConfig = false,
7491 bool AllowRecovery = false);
7492
7493 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7494 // with the specified CallArgs
7495 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7496 MultiExprArg CallArgs);
7497
7499
7500 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7501 /// i.e. an expression not of \p OverloadTy. The expression should
7502 /// unary-convert to an expression of function-pointer or
7503 /// block-pointer type.
7504 ///
7505 /// \param NDecl the declaration being called, if available
7507 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
7508 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
7509 Expr *Config = nullptr, bool IsExecConfig = false,
7510 ADLCallKind UsesADL = ADLCallKind::NotADL);
7511
7513 ParsedType &Ty, SourceLocation RParenLoc,
7514 Expr *CastExpr);
7515
7516 /// Prepares for a scalar cast, performing all the necessary stages
7517 /// except the final cast and returning the kind required.
7519
7520 /// Build an altivec or OpenCL literal.
7522 SourceLocation RParenLoc, Expr *E,
7523 TypeSourceInfo *TInfo);
7524
7525 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7526 /// the ParenListExpr into a sequence of comma binary operators.
7528
7530 SourceLocation RParenLoc, Expr *InitExpr);
7531
7533 TypeSourceInfo *TInfo,
7534 SourceLocation RParenLoc,
7535 Expr *LiteralExpr);
7536
7537 ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7538 SourceLocation RBraceLoc);
7539
7540 ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7541 SourceLocation RBraceLoc, bool IsExplicit);
7542
7543 /// Binary Operators. 'Tok' is the token for the operator.
7545 Expr *LHSExpr, Expr *RHSExpr);
7547 Expr *LHSExpr, Expr *RHSExpr,
7548 bool ForFoldExpression = false);
7549
7550 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7551 /// operator @p Opc at location @c TokLoc. This routine only supports
7552 /// built-in operations; ActOnBinOp handles overloaded operators.
7554 Expr *LHSExpr, Expr *RHSExpr,
7555 bool ForFoldExpression = false);
7557 UnresolvedSetImpl &Functions);
7558
7559 /// Look for instances where it is likely the comma operator is confused with
7560 /// another operator. There is an explicit list of acceptable expressions for
7561 /// the left hand side of the comma operator, otherwise emit a warning.
7562 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
7563
7564 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7565 /// in the case of a the GNU conditional expr extension.
7567 SourceLocation ColonLoc, Expr *CondExpr,
7568 Expr *LHSExpr, Expr *RHSExpr);
7569
7570 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
7572 LabelDecl *TheDecl);
7573
7574 void ActOnStartStmtExpr();
7575 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
7576 SourceLocation RPLoc);
7578 SourceLocation RPLoc, unsigned TemplateDepth);
7579 // Handle the final expression in a statement expression.
7581 void ActOnStmtExprError();
7582
7583 /// __builtin_offsetof(type, a.b[123][456].c)
7585 TypeSourceInfo *TInfo,
7586 const Designation &Desig,
7587 SourceLocation RParenLoc);
7590 ParsedType ParsedArgTy,
7591 const Designation &Desig,
7592 SourceLocation RParenLoc);
7593
7594 // __builtin_choose_expr(constExpr, expr1, expr2)
7595 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr,
7596 Expr *LHSExpr, Expr *RHSExpr,
7597 SourceLocation RPLoc);
7598
7599 // __builtin_va_arg(expr, type)
7601 SourceLocation RPLoc);
7603 TypeSourceInfo *TInfo, SourceLocation RPLoc);
7604
7605 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(),
7606 // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location()
7608 SourceLocation BuiltinLoc,
7609 SourceLocation RPLoc);
7610
7611 // #embed
7613 StringLiteral *BinaryData, StringRef FileName);
7614
7615 // Build a potentially resolved SourceLocExpr.
7617 SourceLocation BuiltinLoc, SourceLocation RPLoc,
7618 DeclContext *ParentContext);
7619
7620 // __null
7622
7623 bool CheckCaseExpression(Expr *E);
7624
7625 //===------------------------- "Block" Extension ------------------------===//
7626
7627 /// ActOnBlockStart - This callback is invoked when a block literal is
7628 /// started.
7629 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
7630
7631 /// ActOnBlockArguments - This callback allows processing of block arguments.
7632 /// If there are no arguments, this is still invoked.
7633 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
7634 Scope *CurScope);
7635
7636 /// ActOnBlockError - If there is an error parsing a block, this callback
7637 /// is invoked to pop the information about the block from the action impl.
7638 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
7639
7640 /// ActOnBlockStmtExpr - This is called when the body of a block statement
7641 /// literal was successfully completed. ^(int x){...}
7643 Scope *CurScope);
7644
7645 //===---------------------------- Clang Extensions ----------------------===//
7646
7647 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7648 /// provided arguments.
7649 ///
7650 /// __builtin_convertvector( value, dst type )
7651 ///
7653 SourceLocation BuiltinLoc,
7654 SourceLocation RParenLoc);
7655
7656 //===---------------------------- OpenCL Features -----------------------===//
7657
7658 /// Parse a __builtin_astype expression.
7659 ///
7660 /// __builtin_astype( value, dst type )
7661 ///
7662 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7663 SourceLocation BuiltinLoc,
7664 SourceLocation RParenLoc);
7665
7666 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7668 SourceLocation BuiltinLoc,
7669 SourceLocation RParenLoc);
7670
7671 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
7673 ArrayRef<Expr *> SubExprs,
7674 QualType T = QualType());
7675
7676 /// Cast a base object to a member's actual type.
7677 ///
7678 /// There are two relevant checks:
7679 ///
7680 /// C++ [class.access.base]p7:
7681 ///
7682 /// If a class member access operator [...] is used to access a non-static
7683 /// data member or non-static member function, the reference is ill-formed
7684 /// if the left operand [...] cannot be implicitly converted to a pointer to
7685 /// the naming class of the right operand.
7686 ///
7687 /// C++ [expr.ref]p7:
7688 ///
7689 /// If E2 is a non-static data member or a non-static member function, the
7690 /// program is ill-formed if the class of which E2 is directly a member is
7691 /// an ambiguous base (11.8) of the naming class (11.9.3) of E2.
7692 ///
7693 /// Note that the latter check does not consider access; the access of the
7694 /// "real" base class is checked as appropriate when checking the access of
7695 /// the member name.
7697 NestedNameSpecifier Qualifier,
7698 NamedDecl *FoundDecl,
7699 NamedDecl *Member);
7700
7701 /// CheckCallReturnType - Checks that a call expression's return type is
7702 /// complete. Returns true on failure. The location passed in is the location
7703 /// that best represents the call.
7704 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7705 CallExpr *CE, FunctionDecl *FD);
7706
7707 /// Emit a warning for all pending noderef expressions that we recorded.
7709
7711
7712 /// Instantiate or parse a C++ default argument expression as necessary.
7713 /// Return true on error.
7715 ParmVarDecl *Param, Expr *Init = nullptr,
7716 bool SkipImmediateInvocations = true);
7717
7718 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
7719 /// the default expr if needed.
7721 ParmVarDecl *Param, Expr *Init = nullptr);
7722
7723 /// Wrap the expression in a ConstantExpr if it is a potential immediate
7724 /// invocation.
7726
7728
7729 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
7730 bool IsInvalidSMECallConversion(QualType FromType, QualType ToType);
7731
7732 /// Abstract base class used for diagnosing integer constant
7733 /// expression violations.
7735 public:
7737
7739
7740 virtual SemaDiagnosticBuilder
7741 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
7743 SourceLocation Loc) = 0;
7746 };
7747
7748 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7749 /// and reports the appropriate diagnostics. Returns false on success.
7750 /// Can optionally return the value of the expression.
7753 VerifyICEDiagnoser &Diagnoser,
7757 unsigned DiagID,
7760 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr,
7764 AllowFoldKind CanFold = AllowFoldKind::No) {
7765 return VerifyIntegerConstantExpression(E, nullptr, CanFold);
7766 }
7767
7768 /// DiagnoseAssignmentAsCondition - Given that an expression is
7769 /// being used as a boolean condition, warn if it's an assignment.
7771
7772 /// Redundant parentheses over an equality comparison can indicate
7773 /// that the user intended an assignment used as condition.
7775
7777 public:
7779 FullExprArg(Sema &actions) : E(nullptr) {}
7780
7781 ExprResult release() { return E; }
7782
7783 Expr *get() const { return E; }
7784
7785 Expr *operator->() { return E; }
7786
7787 private:
7788 // FIXME: No need to make the entire Sema class a friend when it's just
7789 // Sema::MakeFullExpr that needs access to the constructor below.
7790 friend class Sema;
7791
7792 explicit FullExprArg(Expr *expr) : E(expr) {}
7793
7794 Expr *E;
7795 };
7796
7798 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
7799 }
7801 return FullExprArg(
7802 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
7803 }
7805 ExprResult FE =
7806 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
7807 /*DiscardedValue*/ true);
7808 return FullExprArg(FE.get());
7809 }
7810
7811 class ConditionResult {
7812 Decl *ConditionVar;
7813 ExprResult Condition;
7814 bool Invalid;
7815 std::optional<bool> KnownValue;
7816
7817 friend class Sema;
7818 ConditionResult(Sema &S, Decl *ConditionVar, ExprResult Condition,
7819 bool IsConstexpr)
7820 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
7821 if (IsConstexpr && Condition.get()) {
7822 if (std::optional<llvm::APSInt> Val =
7823 Condition.get()->getIntegerConstantExpr(S.Context)) {
7824 KnownValue = !!(*Val);
7825 }
7826 }
7827 }
7828 explicit ConditionResult(bool Invalid)
7829 : ConditionVar(nullptr), Condition(Invalid), Invalid(Invalid),
7830 KnownValue(std::nullopt) {}
7831
7832 public:
7833 ConditionResult() : ConditionResult(false) {}
7834 bool isInvalid() const { return Invalid; }
7835 std::pair<VarDecl *, Expr *> get() const {
7836 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
7837 Condition.get());
7838 }
7839 std::optional<bool> getKnownValue() const { return KnownValue; }
7840 };
7842
7843 /// CheckBooleanCondition - Diagnose problems involving the use of
7844 /// the given expression as a boolean condition (e.g. in an if
7845 /// statement). Also performs the standard function and array
7846 /// decays, possibly changing the input variable.
7847 ///
7848 /// \param Loc - A location associated with the condition, e.g. the
7849 /// 'if' keyword.
7850 /// \return true iff there were any errors
7852 bool IsConstexpr = false);
7853
7854 enum class ConditionKind {
7855 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
7856 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
7857 Switch ///< An integral condition for a 'switch' statement.
7858 };
7859
7860 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
7861 ConditionKind CK, bool MissingOK = false);
7862
7863 QualType CheckConditionalOperands( // C99 6.5.15
7865 ExprObjectKind &OK, SourceLocation QuestionLoc);
7866
7867 /// Emit a specialized diagnostic when one expression is a null pointer
7868 /// constant and the other is not a pointer. Returns true if a diagnostic is
7869 /// emitted.
7870 bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7871 SourceLocation QuestionLoc);
7872
7873 /// type checking for vector binary operators.
7875 SourceLocation Loc, bool IsCompAssign,
7876 bool AllowBothBool, bool AllowBoolConversion,
7877 bool AllowBoolOperation, bool ReportInvalid);
7878
7879 /// Return a signed ext_vector_type that is of identical size and number of
7880 /// elements. For floating point vectors, return an integer type of identical
7881 /// size and number of elements. In the non ext_vector_type case, search from
7882 /// the largest type to the smallest type to avoid cases where long long ==
7883 /// long, where long gets picked over long long.
7886
7887 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7888 /// operates on extended vector types. Instead of producing an IntTy result,
7889 /// like a scalar comparison, a vector comparison produces a vector of integer
7890 /// types.
7892 SourceLocation Loc,
7893 BinaryOperatorKind Opc);
7895 SourceLocation Loc,
7896 BinaryOperatorKind Opc);
7898 SourceLocation Loc,
7899 BinaryOperatorKind Opc);
7901 SourceLocation Loc,
7902 BinaryOperatorKind Opc);
7904 SourceLocation Loc,
7905 BinaryOperatorKind Opc);
7906 // type checking for sizeless vector binary operators.
7908 SourceLocation Loc, bool IsCompAssign,
7909 ArithConvKind OperationKind);
7910
7911 /// Type checking for matrix binary operators.
7913 SourceLocation Loc,
7914 bool IsCompAssign);
7916 SourceLocation Loc, bool IsCompAssign);
7917
7918 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from
7919 /// the first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE
7920 /// VLST) allowed?
7921 ///
7922 /// This will also return false if the two given types do not make sense from
7923 /// the perspective of SVE bitcasts.
7924 bool isValidSveBitcast(QualType srcType, QualType destType);
7925
7926 /// Are the two types matrix types and do they have the same dimensions i.e.
7927 /// do they have the same number of rows and the same number of columns?
7929
7930 bool areVectorTypesSameSize(QualType srcType, QualType destType);
7931
7932 /// Are the two types lax-compatible vector types? That is, given
7933 /// that one of them is a vector, do they have equal storage sizes,
7934 /// where the storage size is the number of elements times the element
7935 /// size?
7936 ///
7937 /// This will also return false if either of the types is neither a
7938 /// vector nor a real type.
7939 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
7940
7941 /// Is this a legal conversion between two types, one of which is
7942 /// known to be a vector type?
7943 bool isLaxVectorConversion(QualType srcType, QualType destType);
7944
7945 // This returns true if at least one of the types is an altivec vector.
7946 bool anyAltivecTypes(QualType srcType, QualType destType);
7947
7948 // type checking C++ declaration initializers (C++ [dcl.init]).
7949
7950 /// Check a cast of an unknown-any type. We intentionally only
7951 /// trigger this for C-style casts.
7954 ExprValueKind &VK, CXXCastPath &Path);
7955
7956 /// Force an expression with unknown-type to an expression of the
7957 /// given type.
7959
7960 /// Type-check an expression that's being passed to an
7961 /// __unknown_anytype parameter.
7963 QualType &paramType);
7964
7965 // CheckMatrixCast - Check type constraints for matrix casts.
7966 // We allow casting between matrixes of the same dimensions i.e. when they
7967 // have the same number of rows and column. Returns true if the cast is
7968 // invalid.
7969 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7970 CastKind &Kind);
7971
7972 // CheckVectorCast - check type constraints for vectors.
7973 // Since vectors are an extension, there are no C standard reference for this.
7974 // We allow casting between vectors and integer datatypes of the same size.
7975 // returns true if the cast is invalid
7976 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7977 CastKind &Kind);
7978
7979 /// Prepare `SplattedExpr` for a vector splat operation, adding
7980 /// implicit casts if necessary.
7981 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
7982
7983 /// Prepare `SplattedExpr` for a matrix splat operation, adding
7984 /// implicit casts if necessary.
7985 ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr);
7986
7987 // CheckExtVectorCast - check type constraints for extended vectors.
7988 // Since vectors are an extension, there are no C standard reference for this.
7989 // We allow casting between vectors and integer datatypes of the same size,
7990 // or vectors and the element type of that vector.
7991 // returns the cast expr
7993 CastKind &Kind);
7994
7996 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
7997 }
7998
7999 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2), converts
8000 // functions and arrays to their respective pointers (C99 6.3.2.1), and
8001 // promotes floating-piont types according to the language semantics.
8003
8004 // UsualUnaryFPConversions - promotes floating-point types according to the
8005 // current language semantics.
8007
8008 /// CallExprUnaryConversions - a special case of an unary conversion
8009 /// performed on a function designator of a call expression.
8011
8012 // DefaultFunctionArrayConversion - converts functions and arrays
8013 // to their respective pointers (C99 6.3.2.1).
8015
8016 // DefaultFunctionArrayLvalueConversion - converts functions and
8017 // arrays to their respective pointers and performs the
8018 // lvalue-to-rvalue conversion.
8020 bool Diagnose = true);
8021
8022 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8023 // the operand. This function is a no-op if the operand has a function type
8024 // or an array type.
8026
8027 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8028 // do not have a prototype. Integer promotions are performed on each
8029 // argument, and arguments that have type float are promoted to double.
8031
8033 const FunctionProtoType *Proto,
8034 Expr *Fn);
8035
8036 /// Determine the degree of POD-ness for an expression.
8037 /// Incomplete types are considered POD, since this check can be performed
8038 /// when we're in an unevaluated context.
8040
8041 /// Check to see if the given expression is a valid argument to a variadic
8042 /// function, issuing a diagnostic if not.
8043 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8044
8045 /// GatherArgumentsForCall - Collector argument expressions for various
8046 /// form of call prototypes.
8048 SourceLocation CallLoc, FunctionDecl *FDecl,
8049 const FunctionProtoType *Proto, unsigned FirstParam,
8052 bool AllowExplicit = false, bool IsListInitialization = false);
8053
8054 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8055 // will create a runtime trap if the resulting type is not a POD type.
8057 FunctionDecl *FDecl);
8058
8059 // Check that the usual arithmetic conversions can be performed on this pair
8060 // of expressions that might be of enumeration type.
8062 ArithConvKind ACK);
8063
8064 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8065 // operands and then handles various conversions that are common to binary
8066 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8067 // routine returns the first non-arithmetic type found. The client is
8068 // responsible for emitting appropriate error diagnostics.
8070 SourceLocation Loc, ArithConvKind ACK);
8071
8073 switch (ConvTy) {
8074 default:
8075 return false;
8079 return true;
8080 }
8081 llvm_unreachable("impossible");
8082 }
8083
8084 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8085 /// assignment conversion type specified by ConvTy. This returns true if the
8086 /// conversion was invalid or false if the conversion was accepted.
8088 QualType DstType, QualType SrcType,
8089 Expr *SrcExpr, AssignmentAction Action,
8090 bool *Complained = nullptr);
8091
8092 /// CheckAssignmentConstraints - Perform type checking for assignment,
8093 /// argument passing, variable initialization, and function return values.
8094 /// C99 6.5.16.
8096 QualType LHSType,
8097 QualType RHSType);
8098
8099 /// Check assignment constraints and optionally prepare for a conversion of
8100 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8101 /// is true.
8103 ExprResult &RHS, CastKind &Kind,
8104 bool ConvertRHS = true);
8105
8106 /// Check assignment constraints for an assignment of RHS to LHSType.
8107 ///
8108 /// \param LHSType The destination type for the assignment.
8109 /// \param RHS The source expression for the assignment.
8110 /// \param Diagnose If \c true, diagnostics may be produced when checking
8111 /// for assignability. If a diagnostic is produced, \p RHS will be
8112 /// set to ExprError(). Note that this function may still return
8113 /// without producing a diagnostic, even for an invalid assignment.
8114 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
8115 /// in an audited Core Foundation API and does not need to be checked
8116 /// for ARC retain issues.
8117 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
8118 /// conversions necessary to perform the assignment. If \c false,
8119 /// \p Diagnose must also be \c false.
8121 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
8122 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
8123
8124 // If the lhs type is a transparent union, check whether we
8125 // can initialize the transparent union with the given expression.
8127 ExprResult &RHS);
8128
8129 /// the following "Check" methods will return a valid/converted QualType
8130 /// or a null QualType (indicating an error diagnostic was issued).
8131
8132 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8134 ExprResult &RHS);
8135
8136 /// Diagnose cases where a scalar was implicitly converted to a vector and
8137 /// diagnose the underlying types. Otherwise, diagnose the error
8138 /// as invalid vector logical operands for non-C++ cases.
8140 ExprResult &RHS);
8141
8143 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8144 BinaryOperatorKind Opc);
8145 QualType CheckRemainderOperands( // C99 6.5.5
8146 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8147 bool IsCompAssign = false);
8148 QualType CheckAdditionOperands( // C99 6.5.6
8149 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8150 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8152 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8153 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8154 QualType CheckShiftOperands( // C99 6.5.7
8155 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8156 BinaryOperatorKind Opc, bool IsCompAssign = false);
8158 QualType CheckCompareOperands( // C99 6.5.8/9
8159 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8160 BinaryOperatorKind Opc);
8161 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8162 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8163 BinaryOperatorKind Opc);
8164 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8165 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8166 BinaryOperatorKind Opc);
8167 // CheckAssignmentOperands is used for both simple and compound assignment.
8168 // For simple assignment, pass both expressions and a null converted type.
8169 // For compound assignment, pass both expressions and the converted type.
8170 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8171 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
8172 BinaryOperatorKind Opc);
8173
8174 /// To be used for checking whether the arguments being passed to
8175 /// function exceeds the number of parameters expected for it.
8176 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
8177 bool PartialOverloading = false) {
8178 // We check whether we're just after a comma in code-completion.
8179 if (NumArgs > 0 && PartialOverloading)
8180 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
8181 return NumArgs > NumParams;
8182 }
8183
8184 /// Whether the AST is currently being rebuilt to correct immediate
8185 /// invocations. Immediate invocation candidates and references to consteval
8186 /// functions aren't tracked when this is set.
8188
8194
8195 /// Determines whether we are currently in a context that
8196 /// is not evaluated as per C++ [expr] p5.
8199 }
8200
8204
8208
8212
8219
8220 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8222 assert(!ExprEvalContexts.empty() &&
8223 "Must be in an expression evaluation context");
8224 for (const auto &Ctx : llvm::reverse(ExprEvalContexts)) {
8226 Ctx.DelayedDefaultInitializationContext)
8227 return Ctx.DelayedDefaultInitializationContext;
8228 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8229 Ctx.isUnevaluated())
8230 break;
8231 }
8232 return std::nullopt;
8233 }
8234
8235 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8237 assert(!ExprEvalContexts.empty() &&
8238 "Must be in an expression evaluation context");
8239 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
8240 for (auto &Ctx : llvm::reverse(ExprEvalContexts)) {
8242 !Ctx.DelayedDefaultInitializationContext && Res)
8243 break;
8244 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8245 Ctx.isUnevaluated())
8246 break;
8247 Res = Ctx.DelayedDefaultInitializationContext;
8248 }
8249 return Res;
8250 }
8251
8252 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
8253 /// SelfAssigned when inside a CXXMethodDecl.
8254 const FieldDecl *
8256
8258
8259 template <typename... Ts>
8261 const Ts &...Args) {
8262 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8263 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
8264 }
8265
8266 template <typename... Ts>
8267 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
8268 const Ts &...Args) {
8269 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8271 }
8272
8273 /// Abstract class used to diagnose incomplete types.
8276
8277 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
8278 virtual ~TypeDiagnoser() {}
8279 };
8280
8281 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
8282 protected:
8283 unsigned DiagID;
8284 std::tuple<const Ts &...> Args;
8285
8286 template <std::size_t... Is>
8288 std::index_sequence<Is...>) const {
8289 // Apply all tuple elements to the builder in order.
8290 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
8291 (void)Dummy;
8292 }
8293
8294 public:
8295 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8296 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
8297 assert(DiagID != 0 && "no diagnostic for type diagnoser");
8298 }
8299
8300 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8301 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
8302 emit(DB, std::index_sequence_for<Ts...>());
8303 DB << T;
8304 }
8305 };
8306
8307 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
8308 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
8309 /// For example, a diagnostic with no other parameters would generally have
8310 /// the form "...%select{incomplete|sizeless}0 type %1...".
8311 template <typename... Ts>
8313 public:
8314 SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8315 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
8316
8317 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8318 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
8319 this->emit(DB, std::index_sequence_for<Ts...>());
8320 DB << T->isSizelessType() << T;
8321 }
8322 };
8323
8324 /// Check an argument list for placeholders that we won't try to
8325 /// handle later.
8327
8328 /// The C++ "std::source_location::__impl" struct, defined in
8329 /// <source_location>.
8331
8332 /// A stack of expression evaluation contexts.
8334
8335 // Set of failed immediate invocations to avoid double diagnosing.
8337
8338 /// List of SourceLocations where 'self' is implicitly retained inside a
8339 /// block.
8342
8343 /// Do an explicit extend of the given block pointer if we're in ARC.
8345
8346 std::vector<std::pair<QualType, unsigned>> ExcessPrecisionNotSatisfied;
8349
8350private:
8351 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
8352
8353 /// Methods for marking which expressions involve dereferencing a pointer
8354 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
8355 /// they are parsed, meaning that a noderef pointer may not be accessed. For
8356 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
8357 /// `*p`, but need to check that `address of` is called on it. This requires
8358 /// keeping a container of all pending expressions and checking if the address
8359 /// of them are eventually taken.
8360 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
8361 void CheckAddressOfNoDeref(const Expr *E);
8362
8363 ///@}
8364
8365 //
8366 //
8367 // -------------------------------------------------------------------------
8368 //
8369 //
8370
8371 /// \name C++ Expressions
8372 /// Implementations are in SemaExprCXX.cpp
8373 ///@{
8374
8375public:
8376 /// The C++ "std::bad_alloc" class, which is defined by the C++
8377 /// standard library.
8379
8380 /// The C++ "std::align_val_t" enum class, which is defined by the C++
8381 /// standard library.
8383
8384 /// The C++ "type_info" declaration, which is defined in <typeinfo>.
8386
8387 /// A flag to remember whether the implicit forms of operator new and delete
8388 /// have been declared.
8390
8391 /// Delete-expressions to be analyzed at the end of translation unit
8392 ///
8393 /// This list contains class members, and locations of delete-expressions
8394 /// that could not be proven as to whether they mismatch with new-expression
8395 /// used in initializer of the field.
8396 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
8397
8398 /// Handle the result of the special case name lookup for inheriting
8399 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
8400 /// constructor names in member using declarations, even if 'X' is not the
8401 /// name of the corresponding type.
8403 SourceLocation NameLoc,
8404 const IdentifierInfo &Name);
8405
8407 SourceLocation NameLoc, Scope *S,
8408 CXXScopeSpec &SS, bool EnteringContext);
8410 Scope *S, CXXScopeSpec &SS,
8411 ParsedType ObjectType, bool EnteringContext);
8412
8414 ParsedType ObjectType);
8415
8416 /// Build a C++ typeid expression with a type operand.
8417 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8418 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8419
8420 /// Build a C++ typeid expression with an expression operand.
8421 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8422 Expr *Operand, SourceLocation RParenLoc);
8423
8424 /// ActOnCXXTypeid - Parse typeid( something ).
8426 bool isType, void *TyOrExpr,
8427 SourceLocation RParenLoc);
8428
8429 /// Build a Microsoft __uuidof expression with a type operand.
8430 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8431 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8432
8433 /// Build a Microsoft __uuidof expression with an expression operand.
8434 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8435 Expr *Operand, SourceLocation RParenLoc);
8436
8437 /// ActOnCXXUuidof - Parse __uuidof( something ).
8439 bool isType, void *TyOrExpr,
8440 SourceLocation RParenLoc);
8441
8442 //// ActOnCXXThis - Parse 'this' pointer.
8444
8445 /// Check whether the type of 'this' is valid in the current context.
8447
8448 /// Build a CXXThisExpr and mark it referenced in the current context.
8449 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
8451
8452 /// Try to retrieve the type of the 'this' pointer.
8453 ///
8454 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
8456
8457 /// When non-NULL, the C++ 'this' expression is allowed despite the
8458 /// current context not being a non-static member function. In such cases,
8459 /// this provides the type used for 'this'.
8461
8462 /// RAII object used to temporarily allow the C++ 'this' expression
8463 /// to be used, with the given qualifiers on the current class type.
8465 Sema &S;
8466 QualType OldCXXThisTypeOverride;
8467 bool Enabled;
8468
8469 public:
8470 /// Introduce a new scope where 'this' may be allowed (when enabled),
8471 /// using the given declaration (which is either a class template or a
8472 /// class) along with the given qualifiers.
8473 /// along with the qualifiers placed on '*this'.
8474 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
8475 bool Enabled = true);
8476
8480 };
8481
8482 /// Make sure the value of 'this' is actually available in the current
8483 /// context, if it is a potentially evaluated context.
8484 ///
8485 /// \param Loc The location at which the capture of 'this' occurs.
8486 ///
8487 /// \param Explicit Whether 'this' is explicitly captured in a lambda
8488 /// capture list.
8489 ///
8490 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
8491 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
8492 /// This is useful when enclosing lambdas must speculatively capture
8493 /// 'this' that may or may not be used in certain specializations of
8494 /// a nested generic lambda (depending on whether the name resolves to
8495 /// a non-static member function or a static function).
8496 /// \return returns 'true' if failed, 'false' if success.
8498 SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true,
8499 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
8500 bool ByCopy = false);
8501
8502 /// Determine whether the given type is the type of *this that is used
8503 /// outside of the body of a member function for a type that is currently
8504 /// being defined.
8506
8507 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
8509
8510 /// Build a boolean-typed literal expression.
8512
8513 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
8515
8516 //// ActOnCXXThrow - Parse throw expressions.
8519 bool IsThrownVarInScope);
8520
8521 /// CheckCXXThrowOperand - Validate the operand of a throw.
8522 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
8523
8524 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
8525 /// Can be interpreted either as function-style casting ("int(x)")
8526 /// or class type construction ("ClassType(x,y,z)")
8527 /// or creation of a value-initialized type ("int()").
8529 SourceLocation LParenOrBraceLoc,
8530 MultiExprArg Exprs,
8531 SourceLocation RParenOrBraceLoc,
8532 bool ListInitialization);
8533
8535 SourceLocation LParenLoc,
8536 MultiExprArg Exprs,
8537 SourceLocation RParenLoc,
8538 bool ListInitialization);
8539
8540 /// Parsed a C++ 'new' expression (C++ 5.3.4).
8541 ///
8542 /// E.g.:
8543 /// @code new (memory) int[size][4] @endcode
8544 /// or
8545 /// @code ::new Foo(23, "hello") @endcode
8546 ///
8547 /// \param StartLoc The first location of the expression.
8548 /// \param UseGlobal True if 'new' was prefixed with '::'.
8549 /// \param PlacementLParen Opening paren of the placement arguments.
8550 /// \param PlacementArgs Placement new arguments.
8551 /// \param PlacementRParen Closing paren of the placement arguments.
8552 /// \param TypeIdParens If the type is in parens, the source range.
8553 /// \param D The type to be allocated, as well as array dimensions.
8554 /// \param Initializer The initializing expression or initializer-list, or
8555 /// null if there is none.
8556 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
8557 SourceLocation PlacementLParen,
8558 MultiExprArg PlacementArgs,
8559 SourceLocation PlacementRParen,
8560 SourceRange TypeIdParens, Declarator &D,
8561 Expr *Initializer);
8563 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
8564 MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
8565 SourceRange TypeIdParens, QualType AllocType,
8566 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
8567 SourceRange DirectInitRange, Expr *Initializer);
8568
8569 /// Determine whether \p FD is an aligned allocation or deallocation
8570 /// function that is unavailable.
8572
8573 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
8574 /// function that is unavailable.
8576 SourceLocation Loc);
8577
8578 /// Checks that a type is suitable as the allocated type
8579 /// in a new-expression.
8580 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
8581 SourceRange R);
8582
8583 /// Finds the overloads of operator new and delete that are appropriate
8584 /// for the allocation.
8585 std::optional<ResolvedAllocation> FindAllocationFunctions(
8586 SourceLocation StartLoc, SourceRange Range,
8588 QualType AllocType, bool IsArray, const ImplicitAllocationParameters &IAP,
8589 MultiExprArg PlaceArgs, bool Diagnose = true);
8590
8591 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
8592 /// delete. These are:
8593 /// @code
8594 /// // C++03:
8595 /// void* operator new(std::size_t) throw(std::bad_alloc);
8596 /// void* operator new[](std::size_t) throw(std::bad_alloc);
8597 /// void operator delete(void *) throw();
8598 /// void operator delete[](void *) throw();
8599 /// // C++11:
8600 /// void* operator new(std::size_t);
8601 /// void* operator new[](std::size_t);
8602 /// void operator delete(void *) noexcept;
8603 /// void operator delete[](void *) noexcept;
8604 /// // C++1y:
8605 /// void* operator new(std::size_t);
8606 /// void* operator new[](std::size_t);
8607 /// void operator delete(void *) noexcept;
8608 /// void operator delete[](void *) noexcept;
8609 /// void operator delete(void *, std::size_t) noexcept;
8610 /// void operator delete[](void *, std::size_t) noexcept;
8611 /// @endcode
8612 /// Note that the placement and nothrow forms of new are *not* implicitly
8613 /// declared. Their use requires including <new>.
8616 ArrayRef<QualType> Params);
8617
8619 DeclarationName Name, FunctionDecl *&Operator,
8621 bool Diagnose = true);
8624 DeclarationName Name,
8625 bool Diagnose = true);
8627 CXXRecordDecl *RD,
8628 bool Diagnose,
8629 bool LookForGlobal,
8630 DeclarationName Name);
8631
8632 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
8633 /// @code ::delete ptr; @endcode
8634 /// or
8635 /// @code delete [] ptr; @endcode
8636 ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
8637 bool ArrayForm, Expr *Operand);
8639 bool IsDelete, bool CallCanBeVirtual,
8640 bool WarnOnNonAbstractTypes,
8641 SourceLocation DtorLoc);
8642
8644 Expr *Operand, SourceLocation RParen);
8646 SourceLocation RParen);
8647
8649 SourceLocation OpLoc,
8650 tok::TokenKind OpKind,
8651 ParsedType &ObjectType,
8652 bool &MayBePseudoDestructor);
8653
8655 Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8656 const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc,
8657 SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType);
8658
8660 Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8661 CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc,
8662 SourceLocation TildeLoc, UnqualifiedId &SecondTypeName);
8663
8665 SourceLocation OpLoc,
8666 tok::TokenKind OpKind,
8667 SourceLocation TildeLoc,
8668 const DeclSpec &DS);
8669
8670 /// MaybeCreateExprWithCleanups - If the current full-expression
8671 /// requires any cleanups, surround it with a ExprWithCleanups node.
8672 /// Otherwise, just returns the passed-in expression.
8676
8677 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
8678 return ActOnFinishFullExpr(
8679 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
8680 }
8682 bool DiscardedValue, bool IsConstexpr = false,
8683 bool IsTemplateArgument = false);
8685
8686 /// Process the expression contained within a decltype. For such expressions,
8687 /// certain semantic checks on temporaries are delayed until this point, and
8688 /// are omitted for the 'topmost' call in the decltype expression. If the
8689 /// topmost call bound a temporary, strip that temporary off the expression.
8691
8692 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
8693 bool IsUDSuffix);
8694
8696
8697 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
8698 SourceLocation StmtLoc,
8699 ConditionKind CK);
8700
8701 /// Check the use of the given variable as a C++ condition in an if,
8702 /// while, do-while, or switch statement.
8704 SourceLocation StmtLoc, ConditionKind CK);
8705
8706 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8707 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
8708
8709 /// Helper function to determine whether this is the (deprecated) C++
8710 /// conversion from a string literal to a pointer to non-const char or
8711 /// non-const wchar_t (for narrow and wide string literals,
8712 /// respectively).
8714
8715 /// PerformImplicitConversion - Perform an implicit conversion of the
8716 /// expression From to the type ToType using the pre-computed implicit
8717 /// conversion sequence ICS. Returns the converted
8718 /// expression. Action is the kind of conversion we're performing,
8719 /// used in the error message.
8721 Expr *From, QualType ToType, const ImplicitConversionSequence &ICS,
8722 AssignmentAction Action,
8724
8725 /// PerformImplicitConversion - Perform an implicit conversion of the
8726 /// expression From to the type ToType by following the standard
8727 /// conversion sequence SCS. Returns the converted
8728 /// expression. Flavor is the context in which we're performing this
8729 /// conversion, for use in error messages.
8731 const StandardConversionSequence &SCS,
8732 AssignmentAction Action,
8734
8735 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
8736
8737 /// Parsed one of the type trait support pseudo-functions.
8738 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8740 SourceLocation RParenLoc);
8741 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8743 SourceLocation RParenLoc);
8744
8745 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
8746 /// pseudo-functions.
8747 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8748 ParsedType LhsTy, Expr *DimExpr,
8749 SourceLocation RParen);
8750
8751 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8752 TypeSourceInfo *TSInfo, Expr *DimExpr,
8753 SourceLocation RParen);
8754
8755 /// ActOnExpressionTrait - Parsed one of the unary type trait support
8756 /// pseudo-functions.
8757 ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8758 Expr *Queried, SourceLocation RParen);
8759
8760 ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8761 Expr *Queried, SourceLocation RParen);
8762
8765 bool isIndirect);
8767 ExprResult &RHS,
8768 SourceLocation QuestionLoc);
8769
8770 //// Determines if a type is trivially relocatable
8771 /// according to the C++26 rules.
8772 // FIXME: This is in Sema because it requires
8773 // overload resolution, can we move to ASTContext?
8776
8777 /// Check the operands of ?: under C++ semantics.
8778 ///
8779 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
8780 /// extension. In this case, LHS == Cond. (But they're not aliases.)
8781 ///
8782 /// This function also implements GCC's vector extension and the
8783 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
8784 /// permit the use of a?b:c where the type of a is that of a integer vector
8785 /// with the same number of elements and size as the vectors of b and c. If
8786 /// one of either b or c is a scalar it is implicitly converted to match the
8787 /// type of the vector. Otherwise the expression is ill-formed. If both b and
8788 /// c are scalars, then b and c are checked and converted to the type of a if
8789 /// possible.
8790 ///
8791 /// The expressions are evaluated differently for GCC's and OpenCL's
8792 /// extensions. For the GCC extension, the ?: operator is evaluated as
8793 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
8794 /// For the OpenCL extensions, the ?: operator is evaluated as
8795 /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
8796 /// most-significant-bit-set(a[n]) ? b[n] : c[n]).
8798 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK,
8799 ExprObjectKind &OK, SourceLocation questionLoc);
8800
8801 /// Find a merged pointer type and convert the two expressions to it.
8802 ///
8803 /// This finds the composite pointer type for \p E1 and \p E2 according to
8804 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
8805 /// it. It does not emit diagnostics (FIXME: that's not true if \p
8806 /// ConvertArgs is \c true).
8807 ///
8808 /// \param Loc The location of the operator requiring these two expressions to
8809 /// be converted to the composite pointer type.
8810 ///
8811 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target
8812 /// type.
8814 bool ConvertArgs = true);
8816 ExprResult &E2, bool ConvertArgs = true) {
8817 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8818 QualType Composite =
8819 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
8820 E1 = E1Tmp;
8821 E2 = E2Tmp;
8822 return Composite;
8823 }
8824
8825 /// MaybeBindToTemporary - If the passed in expression has a record type with
8826 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
8827 /// it simply returns the passed in expression.
8829
8830 /// IgnoredValueConversions - Given that an expression's result is
8831 /// syntactically ignored, perform any conversions that are
8832 /// required.
8834
8836
8839 const DeclarationNameInfo &TargetNameInfo);
8840
8842 SourceLocation KeywordLoc,
8843 bool IsIfExists, CXXScopeSpec &SS,
8844 UnqualifiedId &Name);
8845
8848 ArrayRef<ParmVarDecl *> LocalParameters,
8849 Scope *BodyScope);
8853 CXXScopeSpec &SS,
8854 SourceLocation NameLoc,
8855 const IdentifierInfo *TypeName,
8856 TemplateIdAnnotation *TemplateId);
8858 SourceLocation NoexceptLoc);
8860 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8861 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8864 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8868 bool IsSatisfied, SourceLocation NoexceptLoc,
8875 BuildNestedRequirement(StringRef InvalidConstraintEntity,
8876 const ASTConstraintSatisfaction &Satisfaction);
8879 SourceLocation LParenLoc,
8880 ArrayRef<ParmVarDecl *> LocalParameters,
8881 SourceLocation RParenLoc,
8883 SourceLocation ClosingBraceLoc);
8884
8885private:
8886 ExprResult BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
8887 bool IsDelete);
8888
8889 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
8890 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
8891 bool DeleteWasArrayForm);
8892
8893 std::optional<AllocationArgumentSet>
8894 resolveAllocationArguments(LookupResult &R,
8896 ArrayRef<Expr *> PlacementArguments);
8897
8898 // Attempts to construct the type identity argument for the call to a
8899 // type aware operator new. Returns null on failure.
8900 Expr *tryGetTypeIdentityArgument(QualType Type, SourceLocation);
8901
8902 Expr *AllocationSizeExpr = nullptr;
8903 Expr *AllocationAlignmentExpr = nullptr;
8904 llvm::DenseMap<QualType, Expr *> AllocationTypeIdentityArguments;
8905
8906 ///@}
8907
8908 //
8909 //
8910 // -------------------------------------------------------------------------
8911 //
8912 //
8913
8914 /// \name Member Access Expressions
8915 /// Implementations are in SemaExprMember.cpp
8916 ///@{
8917
8918public:
8919 /// Check whether an expression might be an implicit class member access.
8921 bool IsAddressOfOperand);
8922
8923 /// Builds an expression which might be an implicit member expression.
8925 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
8926 const TemplateArgumentListInfo *TemplateArgs, const Scope *S);
8927
8928 /// Builds an implicit member access expression. The current context
8929 /// is known to be an instance method, and the given unqualified lookup
8930 /// set is known to contain only instance members, at least one of which
8931 /// is from an appropriate type.
8933 BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8934 LookupResult &R,
8935 const TemplateArgumentListInfo *TemplateArgs,
8936 bool IsDefiniteInstance, const Scope *S);
8937
8939 Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc,
8940 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8941 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
8942 const TemplateArgumentListInfo *TemplateArgs);
8943
8944 /// The main callback when the parser finds something like
8945 /// expression . [nested-name-specifier] identifier
8946 /// expression -> [nested-name-specifier] identifier
8947 /// where 'identifier' encompasses a fairly broad spectrum of
8948 /// possibilities, including destructor and operator references.
8949 ///
8950 /// \param OpKind either tok::arrow or tok::period
8951 /// \param ObjCImpDecl the current Objective-C \@implementation
8952 /// decl; this is an ugly hack around the fact that Objective-C
8953 /// \@implementations aren't properly put in the context chain
8955 tok::TokenKind OpKind, CXXScopeSpec &SS,
8956 SourceLocation TemplateKWLoc,
8957 UnqualifiedId &Member, Decl *ObjCImpDecl);
8958
8959 MemberExpr *
8960 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
8961 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
8962 ValueDecl *Member, DeclAccessPair FoundDecl,
8963 bool HadMultipleCandidates,
8964 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
8966 const TemplateArgumentListInfo *TemplateArgs = nullptr);
8967
8968 // Check whether the declarations we found through a nested-name
8969 // specifier in a member expression are actually members of the base
8970 // type. The restriction here is:
8971 //
8972 // C++ [expr.ref]p2:
8973 // ... In these cases, the id-expression shall name a
8974 // member of the class or of one of its base classes.
8975 //
8976 // So it's perfectly legitimate for the nested-name specifier to name
8977 // an unrelated class, and for us to find an overload set including
8978 // decls from classes which are not superclasses, as long as the decl
8979 // we actually pick through overload resolution is from a superclass.
8980 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
8981 const CXXScopeSpec &SS,
8982 const LookupResult &R);
8983
8984 // This struct is for use by ActOnMemberAccess to allow
8985 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
8986 // changing the access operator from a '.' to a '->' (to see if that is the
8987 // change needed to fix an error about an unknown member, e.g. when the class
8988 // defines a custom operator->).
8994
8996 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
8997 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8998 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
8999 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
9000 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9001
9004 bool IsArrow, const CXXScopeSpec &SS,
9005 SourceLocation TemplateKWLoc,
9006 NamedDecl *FirstQualifierInScope, LookupResult &R,
9007 const TemplateArgumentListInfo *TemplateArgs,
9008 const Scope *S, bool SuppressQualifierCheck = false,
9009 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9010
9011 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
9012 SourceLocation OpLoc,
9013 const CXXScopeSpec &SS, FieldDecl *Field,
9014 DeclAccessPair FoundDecl,
9015 const DeclarationNameInfo &MemberNameInfo);
9016
9017 /// Perform conversions on the LHS of a member access expression.
9019
9021 const CXXScopeSpec &SS, SourceLocation nameLoc,
9022 IndirectFieldDecl *indirectField,
9023 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
9024 Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation());
9025
9026private:
9027 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
9028
9029 ///@}
9030
9031 //
9032 //
9033 // -------------------------------------------------------------------------
9034 //
9035 //
9036
9037 /// \name Initializers
9038 /// Implementations are in SemaInit.cpp
9039 ///@{
9040
9041public:
9042 /// Stack of types that correspond to the parameter entities that are
9043 /// currently being copy-initialized. Can be empty.
9045
9046 llvm::DenseMap<unsigned, CXXDeductionGuideDecl *>
9048
9049 bool IsStringInit(Expr *Init, const ArrayType *AT);
9050
9051 /// Determine whether we can perform aggregate initialization for the purposes
9052 /// of overload resolution.
9054 const InitializedEntity &Entity, InitListExpr *From);
9055
9057 SourceLocation EqualOrColonLoc,
9058 bool GNUSyntax, ExprResult Init);
9059
9060 /// Check that the lifetime of the initializer (and its subobjects) is
9061 /// sufficient for initializing the entity, and perform lifetime extension
9062 /// (when permitted) if not.
9064
9067 bool BoundToLvalueReference);
9068
9069 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9070 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9071 /// we don't have xvalues there.
9073
9077
9081 SourceLocation EqualLoc, ExprResult Init,
9082 bool TopLevelOfInitList = false,
9083 bool AllowExplicit = false);
9084
9086 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
9087 const InitializationKind &Kind, MultiExprArg Init);
9088
9089 ///@}
9090
9091 //
9092 //
9093 // -------------------------------------------------------------------------
9094 //
9095 //
9096
9097 /// \name C++ Lambda Expressions
9098 /// Implementations are in SemaLambda.cpp
9099 ///@{
9100
9101public:
9102 /// Create a new lambda closure type.
9104 TypeSourceInfo *Info,
9105 unsigned LambdaDependencyKind,
9106 LambdaCaptureDefault CaptureDefault);
9107
9108 /// Number lambda for linkage purposes if necessary.
9110 std::optional<CXXRecordDecl::LambdaNumbering>
9111 NumberingOverride = std::nullopt);
9112
9113 /// Endow the lambda scope info with the relevant properties.
9114 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
9115 SourceRange IntroducerRange,
9116 LambdaCaptureDefault CaptureDefault,
9117 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
9118 bool Mutable);
9119
9122
9124 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
9125 TemplateParameterList *TemplateParams);
9126
9127 void
9129 SourceLocation CallOperatorLoc,
9130 const AssociatedConstraint &TrailingRequiresClause,
9131 TypeSourceInfo *MethodTyInfo,
9132 ConstexprSpecKind ConstexprKind, StorageClass SC,
9134 bool HasExplicitResultType);
9135
9136 /// Returns true if the explicit object parameter was invalid.
9138 SourceLocation CallLoc);
9139
9140 /// Perform initialization analysis of the init-capture and perform
9141 /// any implicit conversions such as an lvalue-to-rvalue conversion if
9142 /// not being used to initialize a reference.
9144 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
9145 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
9147 Loc, ByRef, EllipsisLoc, std::nullopt, Id,
9149 }
9151 SourceLocation EllipsisLoc,
9152 UnsignedOrNone NumExpansions,
9153 IdentifierInfo *Id,
9154 bool DirectInit, Expr *&Init);
9155
9156 /// Create a dummy variable within the declcontext of the lambda's
9157 /// call operator, for name lookup purposes for a lambda init capture.
9158 ///
9159 /// CodeGen handles emission of lambda captures, ignoring these dummy
9160 /// variables appropriately.
9162 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
9163 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
9164
9165 /// Add an init-capture to a lambda scope.
9166 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef);
9167
9168 /// Note that we have finished the explicit captures for the
9169 /// given lambda.
9171
9172 /// Deduce a block or lambda's return type based on the return
9173 /// statements present in the body.
9175
9176 /// Once the Lambdas capture are known, we can start to create the closure,
9177 /// call operator method, and keep track of the captures.
9178 /// We do the capture lookup here, but they are not actually captured until
9179 /// after we know what the qualifiers of the call operator are.
9181 Scope *CurContext);
9182
9183 /// This is called after parsing the explicit template parameter list
9184 /// on a lambda (if it exists) in C++2a.
9186 SourceLocation LAngleLoc,
9187 ArrayRef<NamedDecl *> TParams,
9188 SourceLocation RAngleLoc,
9189 ExprResult RequiresClause);
9190
9192 SourceLocation MutableLoc);
9193
9195 Scope *LambdaScope,
9197
9198 /// ActOnStartOfLambdaDefinition - This is called just before we start
9199 /// parsing the body of a lambda; it analyzes the explicit captures and
9200 /// arguments, and sets up various data-structures for the body of the
9201 /// lambda.
9203 Declarator &ParamInfo, const DeclSpec &DS);
9204
9205 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
9206 /// is invoked to pop the information about the lambda.
9207 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
9208 bool IsInstantiation = false);
9209
9210 /// ActOnLambdaExpr - This is called when the body of a lambda expression
9211 /// was successfully completed.
9213
9214 /// Does copying/destroying the captured variable have side effects?
9215 bool CaptureHasSideEffects(const sema::Capture &From);
9216
9217 /// Diagnose if an explicit lambda capture is unused. Returns true if a
9218 /// diagnostic is emitted.
9219 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
9220 SourceRange FixItRange,
9221 const sema::Capture &From);
9222
9223 /// Build a FieldDecl suitable to hold the given capture.
9225
9226 /// Initialize the given capture with a suitable expression.
9228 SourceLocation ImplicitCaptureLoc,
9229 bool IsOpenMPMapping = false);
9230
9231 /// Complete a lambda-expression having processed and attached the
9232 /// lambda body.
9234
9235 /// Get the return type to use for a lambda's conversion function(s) to
9236 /// function pointer type, given the type of the call operator.
9237 QualType
9239 CallingConv CC);
9240
9242 SourceLocation ConvLocation,
9243 CXXConversionDecl *Conv, Expr *Src);
9244
9246 : private FunctionScopeRAII {
9247 public:
9249 Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
9251 bool ShouldAddDeclsFromParentScope = true);
9252 };
9253
9254 /// Compute the mangling number context for a lambda expression or
9255 /// block literal. Also return the extra mangling decl if any.
9256 ///
9257 /// \param DC - The DeclContext containing the lambda expression or
9258 /// block literal.
9259 std::tuple<MangleNumberingContext *, Decl *>
9261
9262 ///@}
9263
9264 //
9265 //
9266 // -------------------------------------------------------------------------
9267 //
9268 //
9269
9270 /// \name Name Lookup
9271 ///
9272 /// These routines provide name lookup that is used during semantic
9273 /// analysis to resolve the various kinds of names (identifiers,
9274 /// overloaded operator names, constructor names, etc.) into zero or
9275 /// more declarations within a particular scope. The major entry
9276 /// points are LookupName, which performs unqualified name lookup,
9277 /// and LookupQualifiedName, which performs qualified name lookup.
9278 ///
9279 /// All name lookup is performed based on some specific criteria,
9280 /// which specify what names will be visible to name lookup and how
9281 /// far name lookup should work. These criteria are important both
9282 /// for capturing language semantics (certain lookups will ignore
9283 /// certain names, for example) and for performance, since name
9284 /// lookup is often a bottleneck in the compilation of C++. Name
9285 /// lookup criteria is specified via the LookupCriteria enumeration.
9286 ///
9287 /// The results of name lookup can vary based on the kind of name
9288 /// lookup performed, the current language, and the translation
9289 /// unit. In C, for example, name lookup will either return nothing
9290 /// (no entity found) or a single declaration. In C++, name lookup
9291 /// can additionally refer to a set of overloaded functions or
9292 /// result in an ambiguity. All of the possible results of name
9293 /// lookup are captured by the LookupResult class, which provides
9294 /// the ability to distinguish among them.
9295 ///
9296 /// Implementations are in SemaLookup.cpp
9297 ///@{
9298
9299public:
9300 /// Tracks whether we are in a context where typo correction is
9301 /// disabled.
9303
9304 /// The number of typos corrected by CorrectTypo.
9306
9307 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9308 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9309
9310 /// A cache containing identifiers for which typo correction failed and
9311 /// their locations, so that repeated attempts to correct an identifier in a
9312 /// given location are ignored if typo correction already failed for it.
9314
9315 /// SpecialMemberOverloadResult - The overloading result for a special member
9316 /// function.
9317 ///
9318 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
9319 /// integer are used to determine whether overload resolution succeeded.
9321 public:
9323
9324 private:
9325 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
9326
9327 public:
9330 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
9331
9332 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
9333 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
9334
9335 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
9336 void setKind(Kind K) { Pair.setInt(K); }
9337 };
9338
9339 class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode,
9341 public:
9342 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
9343 : FastFoldingSetNode(ID) {}
9344 };
9345
9346 /// A cache of special member function overload resolution results
9347 /// for C++ records.
9348 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
9349
9351
9352 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
9353 // TODO: make this is a typesafe union.
9356
9357 /// Describes the kind of name lookup to perform.
9359 /// Ordinary name lookup, which finds ordinary names (functions,
9360 /// variables, typedefs, etc.) in C and most kinds of names
9361 /// (functions, variables, members, types, etc.) in C++.
9363 /// Tag name lookup, which finds the names of enums, classes,
9364 /// structs, and unions.
9366 /// Label name lookup.
9368 /// Member name lookup, which finds the names of
9369 /// class/struct/union members.
9371 /// Look up of an operator name (e.g., operator+) for use with
9372 /// operator overloading. This lookup is similar to ordinary name
9373 /// lookup, but will ignore any declarations that are class members.
9375 /// Look up a name following ~ in a destructor name. This is an ordinary
9376 /// lookup, but prefers tags to typedefs.
9378 /// Look up of a name that precedes the '::' scope resolution
9379 /// operator in C++. This lookup completely ignores operator, object,
9380 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
9382 /// Look up a namespace name within a C++ using directive or
9383 /// namespace alias definition, ignoring non-namespace names (C++
9384 /// [basic.lookup.udir]p1).
9386 /// Look up all declarations in a scope with the given name,
9387 /// including resolved using declarations. This is appropriate
9388 /// for checking redeclarations for a using declaration.
9390 /// Look up an ordinary name that is going to be redeclared as a
9391 /// name with linkage. This lookup ignores any declarations that
9392 /// are outside of the current scope unless they have linkage. See
9393 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
9395 /// Look up a friend of a local class. This lookup does not look
9396 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
9398 /// Look up the name of an Objective-C protocol.
9400 /// Look up implicit 'self' parameter of an objective-c method.
9402 /// Look up the name of an OpenMP user-defined reduction operation.
9404 /// Look up the name of an OpenMP user-defined mapper.
9406 /// Look up any declaration with any name.
9408 };
9409
9410 /// The possible outcomes of name lookup for a literal operator.
9412 /// The lookup resulted in an error.
9414 /// The lookup found no match but no diagnostic was issued.
9416 /// The lookup found a single 'cooked' literal operator, which
9417 /// expects a normal literal to be built and passed to it.
9419 /// The lookup found a single 'raw' literal operator, which expects
9420 /// a string literal containing the spelling of the literal token.
9422 /// The lookup found an overload set of literal operator templates,
9423 /// which expect the characters of the spelling of the literal token to be
9424 /// passed as a non-type template argument pack.
9426 /// The lookup found an overload set of literal operator templates,
9427 /// which expect the character type and characters of the spelling of the
9428 /// string literal token to be passed as template arguments.
9430 };
9431
9432 SpecialMemberOverloadResult
9434 bool VolatileArg, bool RValueThis, bool ConstThis,
9435 bool VolatileThis);
9436
9438
9439 /// Look up a name, looking for a single declaration. Return
9440 /// null if the results were absent, ambiguous, or overloaded.
9441 ///
9442 /// It is preferable to use the elaborated form and explicitly handle
9443 /// ambiguity and overloaded.
9445 Scope *S, DeclarationName Name, SourceLocation Loc,
9446 LookupNameKind NameKind,
9448
9449 /// Lookup a builtin function, when name lookup would otherwise
9450 /// fail.
9451 bool LookupBuiltin(LookupResult &R);
9452 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
9453
9454 /// Perform unqualified name lookup starting from a given
9455 /// scope.
9456 ///
9457 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
9458 /// used to find names within the current scope. For example, 'x' in
9459 /// @code
9460 /// int x;
9461 /// int f() {
9462 /// return x; // unqualified name look finds 'x' in the global scope
9463 /// }
9464 /// @endcode
9465 ///
9466 /// Different lookup criteria can find different names. For example, a
9467 /// particular scope can have both a struct and a function of the same
9468 /// name, and each can be found by certain lookup criteria. For more
9469 /// information about lookup criteria, see the documentation for the
9470 /// class LookupCriteria.
9471 ///
9472 /// @param S The scope from which unqualified name lookup will
9473 /// begin. If the lookup criteria permits, name lookup may also search
9474 /// in the parent scopes.
9475 ///
9476 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
9477 /// look up and the lookup kind), and is updated with the results of lookup
9478 /// including zero or more declarations and possibly additional information
9479 /// used to diagnose ambiguities.
9480 ///
9481 /// @returns \c true if lookup succeeded and false otherwise.
9482 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
9483 bool ForceNoCPlusPlus = false);
9484
9485 /// Perform qualified name lookup into a given context.
9486 ///
9487 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
9488 /// names when the context of those names is explicit specified, e.g.,
9489 /// "std::vector" or "x->member", or as part of unqualified name lookup.
9490 ///
9491 /// Different lookup criteria can find different names. For example, a
9492 /// particular scope can have both a struct and a function of the same
9493 /// name, and each can be found by certain lookup criteria. For more
9494 /// information about lookup criteria, see the documentation for the
9495 /// class LookupCriteria.
9496 ///
9497 /// \param R captures both the lookup criteria and any lookup results found.
9498 ///
9499 /// \param LookupCtx The context in which qualified name lookup will
9500 /// search. If the lookup criteria permits, name lookup may also search
9501 /// in the parent contexts or (for C++ classes) base classes.
9502 ///
9503 /// \param InUnqualifiedLookup true if this is qualified name lookup that
9504 /// occurs as part of unqualified name lookup.
9505 ///
9506 /// \returns true if lookup succeeded, false if it failed.
9507 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9508 bool InUnqualifiedLookup = false);
9509
9510 /// Performs qualified name lookup or special type of lookup for
9511 /// "__super::" scope specifier.
9512 ///
9513 /// This routine is a convenience overload meant to be called from contexts
9514 /// that need to perform a qualified name lookup with an optional C++ scope
9515 /// specifier that might require special kind of lookup.
9516 ///
9517 /// \param R captures both the lookup criteria and any lookup results found.
9518 ///
9519 /// \param LookupCtx The context in which qualified name lookup will
9520 /// search.
9521 ///
9522 /// \param SS An optional C++ scope-specifier.
9523 ///
9524 /// \returns true if lookup succeeded, false if it failed.
9525 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9526 CXXScopeSpec &SS);
9527
9528 /// Performs name lookup for a name that was parsed in the
9529 /// source code, and may contain a C++ scope specifier.
9530 ///
9531 /// This routine is a convenience routine meant to be called from
9532 /// contexts that receive a name and an optional C++ scope specifier
9533 /// (e.g., "N::M::x"). It will then perform either qualified or
9534 /// unqualified name lookup (with LookupQualifiedName or LookupName,
9535 /// respectively) on the given name and return those results. It will
9536 /// perform a special type of lookup for "__super::" scope specifier.
9537 ///
9538 /// @param S The scope from which unqualified name lookup will
9539 /// begin.
9540 ///
9541 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
9542 ///
9543 /// @param EnteringContext Indicates whether we are going to enter the
9544 /// context of the scope-specifier SS (if present).
9545 ///
9546 /// @returns True if any decls were found (but possibly ambiguous)
9548 QualType ObjectType, bool AllowBuiltinCreation = false,
9549 bool EnteringContext = false);
9550
9551 /// Perform qualified name lookup into all base classes of the given
9552 /// class.
9553 ///
9554 /// \param R captures both the lookup criteria and any lookup results found.
9555 ///
9556 /// \param Class The context in which qualified name lookup will
9557 /// search. Name lookup will search in all base classes merging the results.
9558 ///
9559 /// @returns True if any decls were found (but possibly ambiguous)
9561
9563 UnresolvedSetImpl &Functions);
9564
9565 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
9566 /// If GnuLabelLoc is a valid source location, then this is a definition
9567 /// of an __label__ label name, otherwise it is a normal label definition
9568 /// or use. If IsLabelStmt is true, then this is the label of a
9569 /// labeled-statement.
9571 SourceLocation GnuLabelLoc = SourceLocation(),
9572 bool IsLabelStmt = false);
9573
9574 /// Perform a name lookup for a label with the specified name; this does not
9575 /// create a new label if the lookup fails.
9577
9578 /// Look up the constructors for the given class.
9580
9581 /// Look up the default constructor for the given class.
9583
9584 /// Look up the copying constructor for the given class.
9586 unsigned Quals);
9587
9588 /// Look up the copying assignment operator for the given class.
9590 bool RValueThis, unsigned ThisQuals);
9591
9592 /// Look up the moving constructor for the given class.
9594 unsigned Quals);
9595
9596 /// Look up the moving assignment operator for the given class.
9598 bool RValueThis, unsigned ThisQuals);
9599
9600 /// Look for the destructor of the given class.
9601 ///
9602 /// During semantic analysis, this routine should be used in lieu of
9603 /// CXXRecordDecl::getDestructor().
9604 ///
9605 /// \returns The destructor for this class.
9607
9608 /// Force the declaration of any implicitly-declared members of this
9609 /// class.
9611
9612 /// Make a merged definition of an existing hidden definition \p ND
9613 /// visible at the specified location.
9615
9616 /// Check ODR hashes for C/ObjC when merging types from modules.
9617 /// Differently from C++, actually parse the body and reject in case
9618 /// of a mismatch.
9619 template <typename T,
9620 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
9622 if (Duplicate->getODRHash() != Previous->getODRHash())
9623 return false;
9624
9625 // Make the previous decl visible.
9627 return true;
9628 }
9629
9630 /// Get the set of additional modules that should be checked during
9631 /// name lookup. A module and its imports become visible when instanting a
9632 /// template defined within it.
9633 llvm::DenseSet<Module *> &getLookupModules();
9634
9635 bool hasVisibleMergedDefinition(const NamedDecl *Def);
9637
9638 /// Determine if the template parameter \p D has a visible default argument.
9639 bool
9641 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9642 /// Determine if the template parameter \p D has a reachable default argument.
9644 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9645 /// Determine if the template parameter \p D has a reachable default argument.
9649
9650 /// Determine if there is a visible declaration of \p D that is an explicit
9651 /// specialization declaration for a specialization of a template. (For a
9652 /// member specialization, use hasVisibleMemberSpecialization.)
9654 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9655 /// Determine if there is a reachable declaration of \p D that is an explicit
9656 /// specialization declaration for a specialization of a template. (For a
9657 /// member specialization, use hasReachableMemberSpecialization.)
9659 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9660
9661 /// Determine if there is a visible declaration of \p D that is a member
9662 /// specialization declaration (as opposed to an instantiated declaration).
9664 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9665 /// Determine if there is a reachable declaration of \p D that is a member
9666 /// specialization declaration (as opposed to an instantiated declaration).
9668 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9669
9670 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
9671
9672 /// Determine whether any declaration of an entity is visible.
9673 bool
9675 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9676 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
9677 }
9678
9681 /// Determine whether any declaration of an entity is reachable.
9682 bool
9684 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9685 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
9686 }
9688 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9689
9690 void diagnoseTypo(const TypoCorrection &Correction,
9691 const PartialDiagnostic &TypoDiag,
9692 bool ErrorRecovery = true);
9693
9694 /// Diagnose a successfully-corrected typo. Separated from the correction
9695 /// itself to allow external validation of the result, etc.
9696 ///
9697 /// \param Correction The result of performing typo correction.
9698 /// \param TypoDiag The diagnostic to produce. This will have the corrected
9699 /// string added to it (and usually also a fixit).
9700 /// \param PrevNote A note to use when indicating the location of the entity
9701 /// to which we are correcting. Will have the correction string added
9702 /// to it.
9703 /// \param ErrorRecovery If \c true (the default), the caller is going to
9704 /// recover from the typo as if the corrected string had been typed.
9705 /// In this case, \c PDiag must be an error, and we will attach a fixit
9706 /// to it.
9707 void diagnoseTypo(const TypoCorrection &Correction,
9708 const PartialDiagnostic &TypoDiag,
9709 const PartialDiagnostic &PrevNote,
9710 bool ErrorRecovery = true);
9711
9712 /// Find the associated classes and namespaces for
9713 /// argument-dependent lookup for a call with the given set of
9714 /// arguments.
9715 ///
9716 /// This routine computes the sets of associated classes and associated
9717 /// namespaces searched by argument-dependent lookup
9718 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
9720 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
9721 AssociatedNamespaceSet &AssociatedNamespaces,
9722 AssociatedClassSet &AssociatedClasses);
9723
9724 /// Produce a diagnostic describing the ambiguity that resulted
9725 /// from name lookup.
9726 ///
9727 /// \param Result The result of the ambiguous lookup to be diagnosed.
9729
9730 /// LookupLiteralOperator - Determine which literal operator should be used
9731 /// for a user-defined literal, per C++11 [lex.ext].
9732 ///
9733 /// Normal overload resolution is not used to select which literal operator to
9734 /// call for a user-defined literal. Look up the provided literal operator
9735 /// name, and filter the results to the appropriate set for the given argument
9736 /// types.
9739 bool AllowRaw, bool AllowTemplate,
9740 bool AllowStringTemplate, bool DiagnoseMissing,
9741 StringLiteral *StringLit = nullptr);
9742
9744 ArrayRef<Expr *> Args, ADLResult &Functions);
9745
9746 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
9748 bool IncludeGlobalScope = true,
9749 bool LoadExternal = true);
9750 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
9752 bool IncludeGlobalScope = true,
9753 bool IncludeDependentBases = false,
9754 bool LoadExternal = true);
9755
9756 /// Try to "correct" a typo in the source code by finding
9757 /// visible declarations whose names are similar to the name that was
9758 /// present in the source code.
9759 ///
9760 /// \param TypoName the \c DeclarationNameInfo structure that contains
9761 /// the name that was present in the source code along with its location.
9762 ///
9763 /// \param LookupKind the name-lookup criteria used to search for the name.
9764 ///
9765 /// \param S the scope in which name lookup occurs.
9766 ///
9767 /// \param SS the nested-name-specifier that precedes the name we're
9768 /// looking for, if present.
9769 ///
9770 /// \param CCC A CorrectionCandidateCallback object that provides further
9771 /// validation of typo correction candidates. It also provides flags for
9772 /// determining the set of keywords permitted.
9773 ///
9774 /// \param MemberContext if non-NULL, the context in which to look for
9775 /// a member access expression.
9776 ///
9777 /// \param EnteringContext whether we're entering the context described by
9778 /// the nested-name-specifier SS.
9779 ///
9780 /// \param OPT when non-NULL, the search for visible declarations will
9781 /// also walk the protocols in the qualified interfaces of \p OPT.
9782 ///
9783 /// \returns a \c TypoCorrection containing the corrected name if the typo
9784 /// along with information such as the \c NamedDecl where the corrected name
9785 /// was declared, and any additional \c NestedNameSpecifier needed to access
9786 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
9788 Sema::LookupNameKind LookupKind, Scope *S,
9790 CorrectTypoKind Mode,
9791 DeclContext *MemberContext = nullptr,
9792 bool EnteringContext = false,
9793 const ObjCObjectPointerType *OPT = nullptr,
9794 bool RecordFailure = true);
9795
9796 /// Kinds of missing import. Note, the values of these enumerators correspond
9797 /// to %select values in diagnostics.
9805
9806 /// Diagnose that the specified declaration needs to be visible but
9807 /// isn't, and suggest a module import that would resolve the problem.
9809 MissingImportKind MIK, bool Recover = true);
9811 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
9812 MissingImportKind MIK, bool Recover);
9813
9814 /// Called on #pragma clang __debug dump II
9816
9817 /// Called on #pragma clang __debug dump E
9818 void ActOnPragmaDump(Expr *E);
9819
9820private:
9821 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
9822 //
9823 // The boolean value will be true to indicate that the namespace was loaded
9824 // from an AST/PCH file, or false otherwise.
9825 llvm::MapVector<NamespaceDecl *, bool> KnownNamespaces;
9826
9827 /// Whether we have already loaded known namespaces from an extenal
9828 /// source.
9829 bool LoadedExternalKnownNamespaces;
9830
9831 bool CppLookupName(LookupResult &R, Scope *S);
9832
9833 /// Determine if we could use all the declarations in the module.
9834 bool isUsableModule(const Module *M);
9835
9836 /// Helper for CorrectTypo used to create and populate a new
9837 /// TypoCorrectionConsumer. Returns nullptr if typo correction should be
9838 /// skipped entirely.
9839 std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(
9840 const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind,
9842 DeclContext *MemberContext, bool EnteringContext,
9843 const ObjCObjectPointerType *OPT, bool ErrorRecovery);
9844
9845 /// Cache for module units which is usable for current module.
9846 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
9847
9848 /// Record the typo correction failure and return an empty correction.
9849 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
9850 bool RecordFailure = true) {
9851 if (RecordFailure)
9852 TypoCorrectionFailures[Typo].insert(TypoLoc);
9853 return TypoCorrection();
9854 }
9855
9856 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
9857
9858 /// Determine whether two declarations should be linked together, given that
9859 /// the old declaration might not be visible and the new declaration might
9860 /// not have external linkage.
9861 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
9862 const NamedDecl *New) {
9863 if (isVisible(Old))
9864 return true;
9865 // See comment in below overload for why it's safe to compute the linkage
9866 // of the new declaration here.
9867 if (New->isExternallyDeclarable()) {
9868 assert(Old->isExternallyDeclarable() &&
9869 "should not have found a non-externally-declarable previous decl");
9870 return true;
9871 }
9872 return false;
9873 }
9874 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
9875
9876 ///@}
9877
9878 //
9879 //
9880 // -------------------------------------------------------------------------
9881 //
9882 //
9883
9884 /// \name Modules
9885 /// Implementations are in SemaModule.cpp
9886 ///@{
9887
9888public:
9889 /// Get the module unit whose scope we are currently within.
9891 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
9892 }
9893
9894 /// Is the module scope we are an implementation unit?
9896 if (ModuleScopes.empty())
9897 return false;
9898 const Module *M = ModuleScopes.back().Module;
9900 }
9901
9902 // When loading a non-modular PCH files, this is used to restore module
9903 // visibility.
9905 VisibleModules.setVisible(Mod, ImportLoc);
9906 }
9907
9908 enum class ModuleDeclKind {
9909 Interface, ///< 'export module X;'
9910 Implementation, ///< 'module X;'
9911 PartitionInterface, ///< 'export module X:Y;'
9912 PartitionImplementation, ///< 'module X:Y;'
9913 };
9914
9915 /// An enumeration to represent the transition of states in parsing module
9916 /// fragments and imports. If we are not parsing a C++20 TU, or we find
9917 /// an error in state transition, the state is set to NotACXX20Module.
9919 FirstDecl, ///< Parsing the first decl in a TU.
9920 GlobalFragment, ///< after 'module;' but before 'module X;'
9921 ImportAllowed, ///< after 'module X;' but before any non-import decl.
9922 ImportFinished, ///< after any non-import decl.
9923 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
9924 ///< non-import decl.
9925 PrivateFragmentImportFinished, ///< after 'module :private;' but a
9926 ///< non-import decl has already been seen.
9927 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
9928 };
9929
9930 /// The parser has processed a module-declaration that begins the definition
9931 /// of a module interface or implementation.
9933 SourceLocation ModuleLoc, ModuleDeclKind MDK,
9934 ModuleIdPath Path, ModuleIdPath Partition,
9935 ModuleImportState &ImportState,
9936 bool SeenNoTrivialPPDirective);
9937
9938 /// The parser has processed a global-module-fragment declaration that begins
9939 /// the definition of the global module fragment of the current module unit.
9940 /// \param ModuleLoc The location of the 'module' keyword.
9942
9943 /// The parser has processed a private-module-fragment declaration that begins
9944 /// the definition of the private module fragment of the current module unit.
9945 /// \param ModuleLoc The location of the 'module' keyword.
9946 /// \param PrivateLoc The location of the 'private' keyword.
9948 SourceLocation PrivateLoc);
9949
9950 /// The parser has processed a module import declaration.
9951 ///
9952 /// \param StartLoc The location of the first token in the declaration. This
9953 /// could be the location of an '@', 'export', or 'import'.
9954 /// \param ExportLoc The location of the 'export' keyword, if any.
9955 /// \param ImportLoc The location of the 'import' keyword.
9956 /// \param Path The module toplevel name as an access path.
9957 /// \param IsPartition If the name is for a partition.
9959 SourceLocation ExportLoc,
9960 SourceLocation ImportLoc, ModuleIdPath Path,
9961 bool IsPartition = false);
9963 SourceLocation ExportLoc,
9964 SourceLocation ImportLoc, Module *M,
9965 ModuleIdPath Path = {});
9966
9967 /// The parser has processed a module import translated from a
9968 /// #include or similar preprocessing directive.
9969 void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
9970 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
9971
9972 /// The parsed has entered a submodule.
9973 void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
9974 /// The parser has left a submodule.
9975 void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
9976
9977 /// Create an implicit import of the given module at the given
9978 /// source location, for error recovery, if possible.
9979 ///
9980 /// This routine is typically used when an entity found by name lookup
9981 /// is actually hidden within a module that we know about but the user
9982 /// has forgotten to import.
9983 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
9984 Module *Mod);
9985
9986 /// We have parsed the start of an export declaration, including the '{'
9987 /// (if present).
9988 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
9989 SourceLocation LBraceLoc);
9990
9991 /// Complete the definition of an export declaration.
9992 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
9993 SourceLocation RBraceLoc);
9994
9995private:
9996 /// The parser has begun a translation unit to be compiled as a C++20
9997 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
9998 void HandleStartOfHeaderUnit();
9999
10000 struct ModuleScope {
10001 SourceLocation BeginLoc;
10002 clang::Module *Module = nullptr;
10003 VisibleModuleSet OuterVisibleModules;
10004 };
10005 /// The modules we're currently parsing.
10006 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
10007
10008 /// For an interface unit, this is the implicitly imported interface unit.
10009 clang::Module *ThePrimaryInterface = nullptr;
10010
10011 /// The explicit global module fragment of the current translation unit.
10012 /// The explicit Global Module Fragment, as specified in C++
10013 /// [module.global.frag].
10014 clang::Module *TheGlobalModuleFragment = nullptr;
10015
10016 /// The implicit global module fragments of the current translation unit.
10017 ///
10018 /// The contents in the implicit global module fragment can't be discarded.
10019 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
10020
10021 /// Namespace definitions that we will export when they finish.
10022 llvm::SmallPtrSet<const NamespaceDecl *, 8> DeferredExportedNamespaces;
10023
10024 /// In a C++ standard module, inline declarations require a definition to be
10025 /// present at the end of a definition domain. This set holds the decls to
10026 /// be checked at the end of the TU.
10027 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
10028
10029 /// Helper function to judge if we are in module purview.
10030 /// Return false if we are not in a module.
10031 bool isCurrentModulePurview() const;
10032
10033 /// Enter the scope of the explicit global module fragment.
10034 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
10035 /// Leave the scope of the explicit global module fragment.
10036 void PopGlobalModuleFragment();
10037
10038 /// Enter the scope of an implicit global module fragment.
10039 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
10040 /// Leave the scope of an implicit global module fragment.
10041 void PopImplicitGlobalModuleFragment();
10042
10043 VisibleModuleSet VisibleModules;
10044
10045 /// Whether we had imported any named modules.
10046 bool HadImportedNamedModules = false;
10047 /// The set of instantiations we need to check if they references TU-local
10048 /// entity from TUs. This only makes sense if we imported any named modules.
10049 llvm::SmallVector<std::pair<FunctionDecl *, SourceLocation>>
10050 PendingCheckReferenceForTULocal;
10051 /// Implement [basic.link]p18, which requires that we can't use TU-local
10052 /// entities from other TUs (ignoring header units).
10053 void checkReferenceToTULocalFromOtherTU(FunctionDecl *FD,
10054 SourceLocation PointOfInstantiation);
10055 /// Implement [basic.link]p17, which diagnose for non TU local exposure in
10056 /// module interface or module partition.
10057 void checkExposure(const TranslationUnitDecl *TU);
10058
10059 ///@}
10060
10061 //
10062 //
10063 // -------------------------------------------------------------------------
10064 //
10065 //
10066
10067 /// \name C++ Overloading
10068 /// Implementations are in SemaOverload.cpp
10069 ///@{
10070
10071public:
10072 /// Whether deferrable diagnostics should be deferred.
10073 bool DeferDiags = false;
10074
10075 /// RAII class to control scope of DeferDiags.
10077 Sema &S;
10078 bool SavedDeferDiags = false;
10079
10080 public:
10082 : S(S), SavedDeferDiags(S.DeferDiags) {
10083 S.DeferDiags = SavedDeferDiags || DeferDiags;
10084 }
10085 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
10088 };
10089
10090 /// Flag indicating if Sema is building a recovery call expression.
10091 ///
10092 /// This flag is used to avoid building recovery call expressions
10093 /// if Sema is already doing so, which would cause infinite recursions.
10095
10096 /// Determine whether the given New declaration is an overload of the
10097 /// declarations in Old. This routine returns OverloadKind::Match or
10098 /// OverloadKind::NonFunction if New and Old cannot be overloaded, e.g., if
10099 /// New has the same signature as some function in Old (C++ 1.3.10) or if the
10100 /// Old declarations aren't functions (or function templates) at all. When it
10101 /// does return OverloadKind::Match or OverloadKind::NonFunction, MatchedDecl
10102 /// will point to the decl that New cannot be overloaded with. This decl may
10103 /// be a UsingShadowDecl on top of the underlying declaration.
10104 ///
10105 /// Example: Given the following input:
10106 ///
10107 /// void f(int, float); // #1
10108 /// void f(int, int); // #2
10109 /// int f(int, int); // #3
10110 ///
10111 /// When we process #1, there is no previous declaration of "f", so IsOverload
10112 /// will not be used.
10113 ///
10114 /// When we process #2, Old contains only the FunctionDecl for #1. By
10115 /// comparing the parameter types, we see that #1 and #2 are overloaded (since
10116 /// they have different signatures), so this routine returns
10117 /// OverloadKind::Overload; MatchedDecl is unchanged.
10118 ///
10119 /// When we process #3, Old is an overload set containing #1 and #2. We
10120 /// compare the signatures of #3 to #1 (they're overloaded, so we do nothing)
10121 /// and then #3 to #2. Since the signatures of #3 and #2 are identical (return
10122 /// types of functions are not part of the signature), IsOverload returns
10123 /// OverloadKind::Match and MatchedDecl will be set to point to the
10124 /// FunctionDecl for #2.
10125 ///
10126 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a
10127 /// class by a using declaration. The rules for whether to hide shadow
10128 /// declarations ignore some properties which otherwise figure into a function
10129 /// template's signature.
10131 const LookupResult &OldDecls, NamedDecl *&OldDecl,
10132 bool UseMemberUsingDeclRules);
10134 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10135
10136 // Checks whether MD constitutes an override the base class method BaseMD.
10137 // When checking for overrides, the object object members are ignored.
10138 bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
10139 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10140
10141 enum class AllowedExplicit {
10142 /// Allow no explicit functions to be used.
10144 /// Allow explicit conversion functions but not explicit constructors.
10146 /// Allow both explicit conversion functions and explicit constructors.
10148 };
10149
10151 Expr *From, QualType ToType, bool SuppressUserConversions,
10152 AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle,
10153 bool AllowObjCWritebackConversion);
10154
10155 /// PerformImplicitConversion - Perform an implicit conversion of the
10156 /// expression From to the type ToType. Returns the
10157 /// converted expression. Flavor is the kind of conversion we're
10158 /// performing, used in the error message. If @p AllowExplicit,
10159 /// explicit user-defined conversions are permitted.
10161 AssignmentAction Action,
10162 bool AllowExplicit = false);
10163
10164 /// IsIntegralPromotion - Determines whether the conversion from the
10165 /// expression From (whose potentially-adjusted type is FromType) to
10166 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
10167 /// sets PromotedType to the promoted type.
10168 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
10169
10170 /// IsFloatingPointPromotion - Determines whether the conversion from
10171 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
10172 /// returns true and sets PromotedType to the promoted type.
10173 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
10174
10175 /// Determine if a conversion is a complex promotion.
10176 ///
10177 /// A complex promotion is defined as a complex -> complex conversion
10178 /// where the conversion between the underlying real types is a
10179 /// floating-point or integral promotion.
10180 bool IsComplexPromotion(QualType FromType, QualType ToType);
10181
10182 /// IsOverflowBehaviorTypePromotion - Determines whether the conversion from
10183 /// FromType to ToType involves an OverflowBehaviorType FromType being
10184 /// promoted to an OverflowBehaviorType ToType which has a larger bitwidth.
10185 /// If so, returns true and sets FromType to ToType.
10186 bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType);
10187
10188 /// IsOverflowBehaviorTypeConversion - Determines whether the conversion from
10189 /// FromType to ToType necessarily involves both an OverflowBehaviorType and
10190 /// a non-OverflowBehaviorType. If so, returns true and sets FromType to
10191 /// ToType.
10192 bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType);
10193
10194 /// IsPointerConversion - Determines whether the conversion of the
10195 /// expression From, which has the (possibly adjusted) type FromType,
10196 /// can be converted to the type ToType via a pointer conversion (C++
10197 /// 4.10). If so, returns true and places the converted type (that
10198 /// might differ from ToType in its cv-qualifiers at some level) into
10199 /// ConvertedType.
10200 ///
10201 /// This routine also supports conversions to and from block pointers
10202 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
10203 /// pointers to interfaces. FIXME: Once we've determined the
10204 /// appropriate overloading rules for Objective-C, we may want to
10205 /// split the Objective-C checks into a different routine; however,
10206 /// GCC seems to consider all of these conversions to be pointer
10207 /// conversions, so for now they live here. IncompatibleObjC will be
10208 /// set if the conversion is an allowed Objective-C conversion that
10209 /// should result in a warning.
10210 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
10211 bool InOverloadResolution, QualType &ConvertedType,
10212 bool &IncompatibleObjC);
10213
10214 /// isObjCPointerConversion - Determines whether this is an
10215 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
10216 /// with the same arguments and return values.
10217 bool isObjCPointerConversion(QualType FromType, QualType ToType,
10218 QualType &ConvertedType, bool &IncompatibleObjC);
10219 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
10220 QualType &ConvertedType);
10221
10222 /// FunctionParamTypesAreEqual - This routine checks two function proto types
10223 /// for equality of their parameter types. Caller has already checked that
10224 /// they have same number of parameters. If the parameters are different,
10225 /// ArgPos will have the parameter index of the first different parameter.
10226 /// If `Reversed` is true, the parameters of `NewType` will be compared in
10227 /// reverse order. That's useful if one of the functions is being used as a
10228 /// C++20 synthesized operator overload with a reversed parameter order.
10231 unsigned *ArgPos = nullptr,
10232 bool Reversed = false);
10233
10235 const FunctionProtoType *NewType,
10236 unsigned *ArgPos = nullptr,
10237 bool Reversed = false);
10238
10239 bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
10240 const FunctionDecl *NewFunction,
10241 unsigned *ArgPos = nullptr,
10242 bool Reversed = false);
10243
10244 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
10245 /// function types. Catches different number of parameter, mismatch in
10246 /// parameter types, and different return types.
10248 QualType ToType);
10249
10250 /// CheckPointerConversion - Check the pointer conversion from the
10251 /// expression From to the type ToType. This routine checks for
10252 /// ambiguous or inaccessible derived-to-base pointer
10253 /// conversions for which IsPointerConversion has already returned
10254 /// true. It returns true and produces a diagnostic if there was an
10255 /// error, or returns false otherwise.
10256 bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind,
10257 CXXCastPath &BasePath, bool IgnoreBaseAccess,
10258 bool Diagnose = true);
10259
10260 /// IsMemberPointerConversion - Determines whether the conversion of the
10261 /// expression From, which has the (possibly adjusted) type FromType, can be
10262 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
10263 /// If so, returns true and places the converted type (that might differ from
10264 /// ToType in its cv-qualifiers at some level) into ConvertedType.
10265 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
10266 bool InOverloadResolution,
10267 QualType &ConvertedType);
10268
10278 /// CheckMemberPointerConversion - Check the member pointer conversion from
10279 /// the expression From to the type ToType. This routine checks for ambiguous
10280 /// or virtual or inaccessible base-to-derived member pointer conversions for
10281 /// which IsMemberPointerConversion has already returned true. It produces a
10282 // diagnostic if there was an error.
10284 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
10285 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
10286 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction);
10287
10288 /// IsQualificationConversion - Determines whether the conversion from
10289 /// an rvalue of type FromType to ToType is a qualification conversion
10290 /// (C++ 4.4).
10291 ///
10292 /// \param ObjCLifetimeConversion Output parameter that will be set to
10293 /// indicate when the qualification conversion involves a change in the
10294 /// Objective-C object lifetime.
10295 bool IsQualificationConversion(QualType FromType, QualType ToType,
10296 bool CStyle, bool &ObjCLifetimeConversion);
10297
10298 /// Determine whether the conversion from FromType to ToType is a valid
10299 /// conversion of ExtInfo/ExtProtoInfo on the nested function type.
10300 /// More precisely, this method checks whether FromType can be transformed
10301 /// into an exact match for ToType, by transforming its extended function
10302 /// type information in legal manner (e.g. by strictly stripping "noreturn"
10303 /// or "noexcept", or by stripping "noescape" for arguments).
10304 bool IsFunctionConversion(QualType FromType, QualType ToType) const;
10305
10306 /// Same as `IsFunctionConversion`, but if this would return true, it sets
10307 /// `ResultTy` to `ToType`.
10308 bool TryFunctionConversion(QualType FromType, QualType ToType,
10309 QualType &ResultTy) const;
10310
10313 DeclarationName Name,
10314 OverloadCandidateSet &CandidateSet,
10315 FunctionDecl *Fn, MultiExprArg Args,
10316 bool IsMember = false);
10317
10319 FunctionDecl *Fun);
10321 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
10323
10324 /// PerformContextuallyConvertToBool - Perform a contextual conversion
10325 /// of the expression From to bool (C++0x [conv]p3).
10327
10328 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
10329 /// conversion of the expression From to an Objective-C pointer type.
10330 /// Returns a valid but null ExprResult if no conversion sequence exists.
10332
10334 CCEKind CCE,
10335 NamedDecl *Dest = nullptr);
10336
10338 llvm::APSInt &Value, CCEKind CCE);
10340 APValue &Value, CCEKind CCE,
10341 NamedDecl *Dest = nullptr);
10342
10343 /// EvaluateConvertedConstantExpression - Evaluate an Expression
10344 /// That is a converted constant expression
10345 /// (which was built with BuildConvertedConstantExpression)
10348 CCEKind CCE, bool RequireInt,
10349 const APValue &PreNarrowingValue);
10350
10351 /// Abstract base class used to perform a contextual implicit
10352 /// conversion from an expression to any type passing a filter.
10354 public:
10357
10361
10362 /// Determine whether the specified type is a valid destination type
10363 /// for this conversion.
10364 virtual bool match(QualType T) = 0;
10365
10366 /// Emits a diagnostic complaining that the expression does not have
10367 /// integral or enumeration type.
10369 QualType T) = 0;
10370
10371 /// Emits a diagnostic when the expression has incomplete class type.
10372 virtual SemaDiagnosticBuilder
10374
10375 /// Emits a diagnostic when the only matching conversion function
10376 /// is explicit.
10378 SourceLocation Loc,
10379 QualType T,
10380 QualType ConvTy) = 0;
10381
10382 /// Emits a note for the explicit conversion function.
10383 virtual SemaDiagnosticBuilder
10385
10386 /// Emits a diagnostic when there are multiple possible conversion
10387 /// functions.
10389 QualType T) = 0;
10390
10391 /// Emits a note for one of the candidate conversions.
10392 virtual SemaDiagnosticBuilder
10394
10395 /// Emits a diagnostic when we picked a conversion function
10396 /// (for cases when we are not allowed to pick a conversion function).
10398 SourceLocation Loc,
10399 QualType T,
10400 QualType ConvTy) = 0;
10401
10403 };
10404
10406 bool AllowScopedEnumerations;
10407
10408 public:
10409 ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress,
10410 bool SuppressConversion)
10412 AllowScopedEnumerations(AllowScopedEnumerations) {}
10413
10414 /// Match an integral or (possibly scoped) enumeration type.
10415 bool match(QualType T) override;
10416
10418 QualType T) override {
10419 return diagnoseNotInt(S, Loc, T);
10420 }
10421
10422 /// Emits a diagnostic complaining that the expression does not have
10423 /// integral or enumeration type.
10425 QualType T) = 0;
10426 };
10427
10428 /// Perform a contextual implicit conversion.
10431 ContextualImplicitConverter &Converter);
10432
10433 /// ReferenceCompareResult - Expresses the result of comparing two
10434 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10435 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10437 /// Ref_Incompatible - The two types are incompatible, so direct
10438 /// reference binding is not possible.
10440 /// Ref_Related - The two types are reference-related, which means
10441 /// that their unqualified forms (T1 and T2) are either the same
10442 /// or T1 is a base class of T2.
10444 /// Ref_Compatible - The two types are reference-compatible.
10446 };
10447
10448 // Fake up a scoped enumeration that still contextually converts to bool.
10450 /// The conversions that would be performed on an lvalue of type T2 when
10451 /// binding a reference of type T1 to it, as determined when evaluating
10452 /// whether T1 is reference-compatible with T2.
10463 };
10465
10466 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
10467 /// determine whether they are reference-compatible,
10468 /// reference-related, or incompatible, for use in C++ initialization by
10469 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
10470 /// type, and the first type (T1) is the pointee type of the reference
10471 /// type being initialized.
10474 ReferenceConversions *Conv = nullptr);
10475
10476 /// AddOverloadCandidate - Adds the given function to the set of
10477 /// candidate functions, using the given function call arguments. If
10478 /// @p SuppressUserConversions, then don't allow user-defined
10479 /// conversions via constructors or conversion operators.
10480 ///
10481 /// \param PartialOverloading true if we are performing "partial" overloading
10482 /// based on an incomplete set of function arguments. This feature is used by
10483 /// code completion.
10486 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10487 bool PartialOverloading = false, bool AllowExplicit = true,
10488 bool AllowExplicitConversion = false,
10489 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10490 ConversionSequenceList EarlyConversions = {},
10492 bool AggregateCandidateDeduction = false, bool StrictPackMatch = false);
10493
10494 /// Add all of the function declarations in the given function set to
10495 /// the overload candidate set.
10497 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10498 OverloadCandidateSet &CandidateSet,
10499 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
10500 bool SuppressUserConversions = false, bool PartialOverloading = false,
10501 bool FirstArgumentIsBase = false);
10502
10503 /// AddMethodCandidate - Adds a named decl (which is some kind of
10504 /// method) as a method candidate to the given overload set.
10505 void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
10506 Expr::Classification ObjectClassification,
10507 ArrayRef<Expr *> Args,
10508 OverloadCandidateSet &CandidateSet,
10509 bool SuppressUserConversion = false,
10510 OverloadCandidateParamOrder PO = {});
10511
10512 /// AddMethodCandidate - Adds the given C++ member function to the set
10513 /// of candidate functions, using the given function call arguments
10514 /// and the object argument (@c Object). For example, in a call
10515 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
10516 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
10517 /// allow user-defined conversions via constructors or conversion
10518 /// operators.
10519 void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
10520 CXXRecordDecl *ActingContext, QualType ObjectType,
10521 Expr::Classification ObjectClassification,
10522 ArrayRef<Expr *> Args,
10523 OverloadCandidateSet &CandidateSet,
10524 bool SuppressUserConversions = false,
10525 bool PartialOverloading = false,
10526 ConversionSequenceList EarlyConversions = {},
10528 bool StrictPackMatch = false);
10529
10530 /// Add a C++ member function template as a candidate to the candidate
10531 /// set, using template argument deduction to produce an appropriate member
10532 /// function template specialization.
10534 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
10535 CXXRecordDecl *ActingContext,
10536 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
10537 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
10538 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10539 bool PartialOverloading = false, OverloadCandidateParamOrder PO = {});
10540
10541 /// Add a C++ function template specialization as a candidate
10542 /// in the candidate set, using template argument deduction to produce
10543 /// an appropriate function template specialization.
10545 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10546 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
10547 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10548 bool PartialOverloading = false, bool AllowExplicit = true,
10549 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10551 bool AggregateCandidateDeduction = false);
10552
10554 /// Do not consider any user-defined conversions when constructing the
10555 /// initializing sequence.
10557
10558 /// Before constructing the initializing sequence, we check whether the
10559 /// parameter type and argument type contain any user defined conversions.
10560 /// If so, do not initialize them. This effectively bypasses some undesired
10561 /// instantiation before checking constaints, which might otherwise result
10562 /// in non-SFINAE errors e.g. recursive constraints.
10564
10571 };
10572
10573 /// Check that implicit conversion sequences can be formed for each argument
10574 /// whose corresponding parameter has a non-dependent type, per DR1391's
10575 /// [temp.deduct.call]p10.
10578 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
10580 CheckNonDependentConversionsFlag UserConversionFlag,
10581 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
10582 Expr::Classification ObjectClassification = {},
10583 OverloadCandidateParamOrder PO = {});
10584
10585 /// AddConversionCandidate - Add a C++ conversion function as a
10586 /// candidate in the candidate set (C++ [over.match.conv],
10587 /// C++ [over.match.copy]). From is the expression we're converting from,
10588 /// and ToType is the type that we're eventually trying to convert to
10589 /// (which may or may not be the same type as the type that the
10590 /// conversion function produces).
10592 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
10593 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10594 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10595 bool AllowExplicit, bool AllowResultConversion = true,
10596 bool StrictPackMatch = false);
10597
10598 /// Adds a conversion function template specialization
10599 /// candidate to the overload set, using template argument deduction
10600 /// to deduce the template arguments of the conversion function
10601 /// template from the type that we are converting to (C++
10602 /// [temp.deduct.conv]).
10604 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10605 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10606 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10607 bool AllowExplicit, bool AllowResultConversion = true);
10608
10609 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
10610 /// converts the given @c Object to a function pointer via the
10611 /// conversion function @c Conversion, and then attempts to call it
10612 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
10613 /// the type of function that we'll eventually be calling.
10614 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
10615 DeclAccessPair FoundDecl,
10616 CXXRecordDecl *ActingContext,
10617 const FunctionProtoType *Proto, Expr *Object,
10618 ArrayRef<Expr *> Args,
10619 OverloadCandidateSet &CandidateSet);
10620
10621 /// Add all of the non-member operator function declarations in the given
10622 /// function set to the overload candidate set.
10624 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10625 OverloadCandidateSet &CandidateSet,
10626 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10627
10628 /// Add overload candidates for overloaded operators that are
10629 /// member functions.
10630 ///
10631 /// Add the overloaded operator candidates that are member functions
10632 /// for the operator Op that was used in an operator expression such
10633 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
10634 /// CandidateSet will store the added overload candidates. (C++
10635 /// [over.match.oper]).
10637 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10638 OverloadCandidateSet &CandidateSet,
10640
10641 /// AddBuiltinCandidate - Add a candidate for a built-in
10642 /// operator. ResultTy and ParamTys are the result and parameter types
10643 /// of the built-in candidate, respectively. Args and NumArgs are the
10644 /// arguments being passed to the candidate. IsAssignmentOperator
10645 /// should be true when this built-in candidate is an assignment
10646 /// operator. NumContextualBoolArguments is the number of arguments
10647 /// (at the beginning of the argument list) that will be contextually
10648 /// converted to bool.
10649 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
10650 OverloadCandidateSet &CandidateSet,
10651 bool IsAssignmentOperator = false,
10652 unsigned NumContextualBoolArguments = 0);
10653
10654 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
10655 /// operator overloads to the candidate set (C++ [over.built]), based
10656 /// on the operator @p Op and the arguments given. For example, if the
10657 /// operator is a binary '+', this routine might add "int
10658 /// operator+(int, int)" to cover integer addition.
10660 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10661 OverloadCandidateSet &CandidateSet);
10662
10663 /// Add function candidates found via argument-dependent lookup
10664 /// to the set of overloading candidates.
10665 ///
10666 /// This routine performs argument-dependent name lookup based on the
10667 /// given function name (which may also be an operator name) and adds
10668 /// all of the overload candidates found by ADL to the overload
10669 /// candidate set (C++ [basic.lookup.argdep]).
10671 DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args,
10672 TemplateArgumentListInfo *ExplicitTemplateArgs,
10673 OverloadCandidateSet &CandidateSet, bool PartialOverloading = false);
10674
10675 /// Check the enable_if expressions on the given function. Returns the first
10676 /// failing attribute, or NULL if they were all successful.
10677 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
10678 ArrayRef<Expr *> Args,
10679 bool MissingImplicitThis = false);
10680
10681 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10682 /// non-ArgDependent DiagnoseIfAttrs.
10683 ///
10684 /// Argument-dependent diagnose_if attributes should be checked each time a
10685 /// function is used as a direct callee of a function call.
10686 ///
10687 /// Returns true if any errors were emitted.
10688 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
10689 const Expr *ThisArg,
10690 ArrayRef<const Expr *> Args,
10691 SourceLocation Loc);
10692
10693 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10694 /// ArgDependent DiagnoseIfAttrs.
10695 ///
10696 /// Argument-independent diagnose_if attributes should be checked on every use
10697 /// of a function.
10698 ///
10699 /// Returns true if any errors were emitted.
10700 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
10701 SourceLocation Loc);
10702
10703 /// Determine if \p A and \p B are equivalent internal linkage declarations
10704 /// from different modules, and thus an ambiguity error can be downgraded to
10705 /// an extension warning.
10706 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10707 const NamedDecl *B);
10709 SourceLocation Loc, const NamedDecl *D,
10710 ArrayRef<const NamedDecl *> Equiv);
10711
10712 // Emit as a 'note' the specific overload candidate
10714 const NamedDecl *Found, const FunctionDecl *Fn,
10716 QualType DestType = QualType(), bool TakingAddress = false);
10717
10718 // Emit as a series of 'note's all template and non-templates identified by
10719 // the expression Expr
10720 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
10721 bool TakingAddress = false);
10722
10723 /// Returns whether the given function's address can be taken or not,
10724 /// optionally emitting a diagnostic if the address can't be taken.
10725 ///
10726 /// Returns false if taking the address of the function is illegal.
10727 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10728 bool Complain = false,
10729 SourceLocation Loc = SourceLocation());
10730
10731 // [PossiblyAFunctionType] --> [Return]
10732 // NonFunctionType --> NonFunctionType
10733 // R (A) --> R(A)
10734 // R (*)(A) --> R (A)
10735 // R (&)(A) --> R (A)
10736 // R (S::*)(A) --> R (A)
10737 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
10738
10739 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10740 /// an overloaded function (C++ [over.over]), where @p From is an
10741 /// expression with overloaded function type and @p ToType is the type
10742 /// we're trying to resolve to. For example:
10743 ///
10744 /// @code
10745 /// int f(double);
10746 /// int f(int);
10747 ///
10748 /// int (*pfd)(double) = f; // selects f(double)
10749 /// @endcode
10750 ///
10751 /// This routine returns the resulting FunctionDecl if it could be
10752 /// resolved, and NULL otherwise. When @p Complain is true, this
10753 /// routine will emit diagnostics if there is an error.
10754 FunctionDecl *
10755 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
10756 bool Complain, DeclAccessPair &Found,
10757 bool *pHadMultipleCandidates = nullptr);
10758
10759 /// Given an expression that refers to an overloaded function, try to
10760 /// resolve that function to a single function that can have its address
10761 /// taken. This will modify `Pair` iff it returns non-null.
10762 ///
10763 /// This routine can only succeed if from all of the candidates in the
10764 /// overload set for SrcExpr that can have their addresses taken, there is one
10765 /// candidate that is more constrained than the rest.
10766 FunctionDecl *
10767 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
10768
10769 /// Given an overloaded function, tries to turn it into a non-overloaded
10770 /// function reference using resolveAddressOfSingleOverloadCandidate. This
10771 /// will perform access checks, diagnose the use of the resultant decl, and,
10772 /// if requested, potentially perform a function-to-pointer decay.
10773 ///
10774 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
10775 /// Otherwise, returns true. This may emit diagnostics and return true.
10777 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
10778
10779 /// Given an expression that refers to an overloaded function, try to
10780 /// resolve that overloaded function expression down to a single function.
10781 ///
10782 /// This routine can only resolve template-ids that refer to a single function
10783 /// template, where that template-id refers to a single template whose
10784 /// template arguments are either provided by the template-id or have
10785 /// defaults, as described in C++0x [temp.arg.explicit]p3.
10786 ///
10787 /// If no template-ids are found, no diagnostics are emitted and NULL is
10788 /// returned.
10790 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
10791 TemplateSpecCandidateSet *FailedTSC = nullptr,
10792 bool ForTypeDeduction = false);
10793
10794 // Resolve and fix an overloaded expression that can be resolved
10795 // because it identifies a single function template specialization.
10796 //
10797 // Last three arguments should only be supplied if Complain = true
10798 //
10799 // Return true if it was logically possible to so resolve the
10800 // expression, regardless of whether or not it succeeded. Always
10801 // returns true if 'complain' is set.
10803 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
10804 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
10805 QualType DestTypeForComplaining = QualType(),
10806 unsigned DiagIDForComplaining = 0);
10807
10808 /// Add the overload candidates named by callee and/or found by argument
10809 /// dependent lookup to the given overload set.
10810 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10811 ArrayRef<Expr *> Args,
10812 OverloadCandidateSet &CandidateSet,
10813 bool PartialOverloading = false);
10814
10815 /// Add the call candidates from the given set of lookup results to the given
10816 /// overload set. Non-function lookup results are ignored.
10818 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
10819 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
10820
10821 // An enum used to represent the different possible results of building a
10822 // range-based for loop.
10828
10829 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
10830 /// given LookupResult is non-empty, it is assumed to describe a member which
10831 /// will be invoked. Otherwise, the function will be found via argument
10832 /// dependent lookup.
10833 /// CallExpr is set to a valid expression and FRS_Success returned on success,
10834 /// otherwise CallExpr is set to ExprError() and some non-success value
10835 /// is returned.
10837 SourceLocation RangeLoc,
10838 const DeclarationNameInfo &NameInfo,
10839 LookupResult &MemberLookup,
10840 OverloadCandidateSet *CandidateSet,
10841 Expr *Range, ExprResult *CallExpr);
10842
10843 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10844 /// (which eventually refers to the declaration Func) and the call
10845 /// arguments Args/NumArgs, attempt to resolve the function call down
10846 /// to a specific function. If overload resolution succeeds, returns
10847 /// the call expression produced by overload resolution.
10848 /// Otherwise, emits diagnostics and returns ExprError.
10850 Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
10851 MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig,
10852 bool AllowTypoCorrection = true, bool CalleesAddressIsTaken = false);
10853
10854 /// Constructs and populates an OverloadedCandidateSet from
10855 /// the given function.
10856 /// \returns true when an the ExprResult output parameter has been set.
10858 MultiExprArg Args, SourceLocation RParenLoc,
10859 OverloadCandidateSet *CandidateSet,
10861
10865 const UnresolvedSetImpl &Fns,
10866 bool PerformADL = true);
10867
10868 /// Perform lookup for an overloaded unary operator.
10871 const UnresolvedSetImpl &Fns,
10872 ArrayRef<Expr *> Args, bool RequiresADL = true);
10873
10874 /// Create a unary operation that may resolve to an overloaded
10875 /// operator.
10876 ///
10877 /// \param OpLoc The location of the operator itself (e.g., '*').
10878 ///
10879 /// \param Opc The UnaryOperatorKind that describes this operator.
10880 ///
10881 /// \param Fns The set of non-member functions that will be
10882 /// considered by overload resolution. The caller needs to build this
10883 /// set based on the context using, e.g.,
10884 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10885 /// set should not contain any member functions; those will be added
10886 /// by CreateOverloadedUnaryOp().
10887 ///
10888 /// \param Input The input argument.
10891 const UnresolvedSetImpl &Fns, Expr *input,
10892 bool RequiresADL = true);
10893
10894 /// Perform lookup for an overloaded binary operator.
10897 const UnresolvedSetImpl &Fns,
10898 ArrayRef<Expr *> Args, bool RequiresADL = true);
10899
10900 /// Create a binary operation that may resolve to an overloaded
10901 /// operator.
10902 ///
10903 /// \param OpLoc The location of the operator itself (e.g., '+').
10904 ///
10905 /// \param Opc The BinaryOperatorKind that describes this operator.
10906 ///
10907 /// \param Fns The set of non-member functions that will be
10908 /// considered by overload resolution. The caller needs to build this
10909 /// set based on the context using, e.g.,
10910 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10911 /// set should not contain any member functions; those will be added
10912 /// by CreateOverloadedBinOp().
10913 ///
10914 /// \param LHS Left-hand argument.
10915 /// \param RHS Right-hand argument.
10916 /// \param PerformADL Whether to consider operator candidates found by ADL.
10917 /// \param AllowRewrittenCandidates Whether to consider candidates found by
10918 /// C++20 operator rewrites.
10919 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
10920 /// the function in question. Such a function is never a candidate in
10921 /// our overload resolution. This also enables synthesizing a three-way
10922 /// comparison from < and == as described in C++20 [class.spaceship]p1.
10924 const UnresolvedSetImpl &Fns, Expr *LHS,
10925 Expr *RHS, bool RequiresADL = true,
10926 bool AllowRewrittenCandidates = true,
10927 FunctionDecl *DefaultedFn = nullptr);
10929 const UnresolvedSetImpl &Fns,
10930 Expr *LHS, Expr *RHS,
10931 FunctionDecl *DefaultedFn);
10932
10934 SourceLocation RLoc, Expr *Base,
10935 MultiExprArg Args);
10936
10937 /// BuildCallToMemberFunction - Build a call to a member
10938 /// function. MemExpr is the expression that refers to the member
10939 /// function (and includes the object parameter), Args/NumArgs are the
10940 /// arguments to the function call (not including the object
10941 /// parameter). The caller needs to validate that the member
10942 /// expression refers to a non-static member function or an overloaded
10943 /// member function.
10945 Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args,
10946 SourceLocation RParenLoc, Expr *ExecConfig = nullptr,
10947 bool IsExecConfig = false, bool AllowRecovery = false);
10948
10949 /// BuildCallToObjectOfClassType - Build a call to an object of class
10950 /// type (C++ [over.call.object]), which can end up invoking an
10951 /// overloaded function call operator (@c operator()) or performing a
10952 /// user-defined conversion on the object argument.
10954 SourceLocation LParenLoc,
10955 MultiExprArg Args,
10956 SourceLocation RParenLoc);
10957
10958 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
10959 /// (if one exists), where @c Base is an expression of class type and
10960 /// @c Member is the name of the member we're trying to find.
10962 SourceLocation OpLoc,
10963 bool *NoArrowOperatorFound = nullptr);
10964
10967 bool HadMultipleCandidates);
10968
10969 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call
10970 /// to a literal operator described by the provided lookup results.
10973 SourceLocation LitEndLoc,
10974 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10975
10976 /// FixOverloadedFunctionReference - E is an expression that refers to
10977 /// a C++ overloaded function (possibly with some parentheses and
10978 /// perhaps a '&' around it). We have resolved the overloaded function
10979 /// to the function declaration Fn, so patch up the expression E to
10980 /// refer (possibly indirectly) to Fn. Returns the new expr.
10982 FunctionDecl *Fn);
10984 DeclAccessPair FoundDecl,
10985 FunctionDecl *Fn);
10986
10987 /// - Returns a selector which best matches given argument list or
10988 /// nullptr if none could be found
10990 bool IsInstance,
10992
10993 ///@}
10994
10995 //
10996 //
10997 // -------------------------------------------------------------------------
10998 //
10999 //
11000
11001 /// \name Statements
11002 /// Implementations are in SemaStmt.cpp
11003 ///@{
11004
11005public:
11006 /// Stack of active SEH __finally scopes. Can be empty.
11008
11009 /// Stack of '_Defer' statements that are currently being parsed, as well
11010 /// as the locations of their '_Defer' keywords. Can be empty.
11012
11013 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
11015
11017 bool HasLeadingEmptyMacro = false);
11018
11020 SourceLocation EndLoc);
11022
11023 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
11024 /// whose result is unused, warn.
11025 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
11026
11027 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
11031 ArrayRef<Stmt *> Elts, bool isStmtExpr);
11032
11034
11037 SourceLocation DotDotDotLoc, ExprResult RHS,
11038 SourceLocation ColonLoc);
11039
11040 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
11041 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
11042
11044 SourceLocation ColonLoc, Stmt *SubStmt,
11045 Scope *CurScope);
11047 SourceLocation ColonLoc, Stmt *SubStmt);
11048
11050 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
11052 Stmt *SubStmt);
11053
11054 /// Check whether the given statement can have musttail applied to it,
11055 /// issuing a diagnostic and returning false if not. In the success case,
11056 /// the statement is rewritten to remove implicit nodes from the return
11057 /// value.
11058 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11059
11061 SourceLocation LParenLoc, Stmt *InitStmt,
11063 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11065 SourceLocation LParenLoc, Stmt *InitStmt,
11067 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11068
11070
11072 SourceLocation LParenLoc, Stmt *InitStmt,
11074 SourceLocation RParenLoc);
11076 Stmt *Body);
11077
11078 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11079 /// integer not in the range of enum values.
11080 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11081 Expr *SrcExpr);
11082
11085 Stmt *Body);
11087 SourceLocation WhileLoc, SourceLocation CondLParen,
11088 Expr *Cond, SourceLocation CondRParen);
11089
11091 Stmt *First, ConditionResult Second,
11092 FullExprArg Third, SourceLocation RParenLoc,
11093 Stmt *Body);
11094
11095 /// In an Objective C collection iteration statement:
11096 /// for (x in y)
11097 /// x can be an arbitrary l-value expression. Bind it up as a
11098 /// full-expression.
11100
11102 /// Initial building of a for-range statement.
11104 /// Instantiation or recovery rebuild of a for-range statement. Don't
11105 /// attempt any typo-correction.
11107 /// Determining whether a for-range statement could be built. Avoid any
11108 /// unnecessary or irreversible actions.
11110 };
11111
11112 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
11113 ///
11114 /// C++11 [stmt.ranged]:
11115 /// A range-based for statement is equivalent to
11116 ///
11117 /// {
11118 /// auto && __range = range-init;
11119 /// for ( auto __begin = begin-expr,
11120 /// __end = end-expr;
11121 /// __begin != __end;
11122 /// ++__begin ) {
11123 /// for-range-declaration = *__begin;
11124 /// statement
11125 /// }
11126 /// }
11127 ///
11128 /// The body of the loop is not available yet, since it cannot be analysed
11129 /// until we have determined the type of the for-range-declaration.
11131 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc,
11132 Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection,
11133 SourceLocation RParenLoc, BuildForRangeKind Kind,
11134 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11135
11136 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
11137 StmtResult BuildCXXForRangeStmt(
11138 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
11139 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
11140 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
11141 BuildForRangeKind Kind,
11142 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11143
11144 /// Set the type of a for-range declaration whose for-range or expansion
11145 /// initialiser is dependent.
11146 void ActOnDependentForRangeInitializer(VarDecl *LoopVar,
11147 BuildForRangeKind BFRK);
11148
11149 /// Holds the 'begin' and 'end' variables of a range-based for loop or
11150 /// expansion statement; begin-expr and end-expr are also provided; the
11151 /// latter are used in some diagnostics.
11153 VarDecl *BeginVar = nullptr;
11154 VarDecl *EndVar = nullptr;
11155 Expr *BeginExpr = nullptr;
11156 Expr *EndExpr = nullptr;
11157 bool isValid() const { return BeginVar != nullptr && EndVar != nullptr; }
11158 };
11159
11160 /// Determine begin-expr and end-expr and build variable declarations for
11161 /// them as per [stmt.ranged].
11162 ForRangeBeginEndInfo BuildCXXForRangeBeginEndVars(
11163 Scope *S, VarDecl *RangeVar, SourceLocation ColonLoc,
11164 SourceLocation CoawaitLoc,
11165 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps,
11166 BuildForRangeKind Kind, bool IsConstexpr,
11167 StmtResult *RebuildResult = nullptr,
11168 llvm::function_ref<StmtResult()> RebuildWithDereference = {},
11169 IdentifierInfo *BeginName = nullptr, IdentifierInfo *EndName = nullptr);
11170
11171 /// Helper used by the expansion statements and for-range code to build
11172 /// a variable declaration for e.g. 'begin' and 'end'.
11173 VarDecl *BuildForRangeVarDecl(SourceLocation Loc, QualType Type,
11174 IdentifierInfo *Name, bool IsConstexpr);
11175
11176 /// Build the range variable of a range-based for loop or iterating
11177 /// expansion statement and return its DeclStmt.
11178 StmtResult BuildCXXForRangeRangeVar(Scope *S, Expr *Range, QualType Type,
11179 bool IsConstexpr = false);
11180
11181 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
11182 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
11183 /// body cannot be performed until after the type of the range variable is
11184 /// determined.
11185 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
11186
11187 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
11188 LabelDecl *TheDecl);
11189 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
11190 SourceLocation StarLoc, Expr *DestExp);
11191 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope,
11192 LabelDecl *Label, SourceLocation LabelLoc);
11193 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope,
11194 LabelDecl *Label, SourceLocation LabelLoc);
11195
11196 void ActOnStartOfDeferStmt(SourceLocation DeferLoc, Scope *CurScope);
11197 void ActOnDeferStmtError(Scope *CurScope);
11198 StmtResult ActOnEndOfDeferStmt(Stmt *Body, Scope *CurScope);
11199
11202
11205
11206 bool isMoveEligible() const { return S != None; };
11208 };
11210
11211 /// Determine whether the given expression might be move-eligible or
11212 /// copy-elidable in either a (co_)return statement or throw expression,
11213 /// without considering function return type, if applicable.
11214 ///
11215 /// \param E The expression being returned from the function or block,
11216 /// being thrown, or being co_returned from a coroutine. This expression
11217 /// might be modified by the implementation.
11218 ///
11219 /// \param Mode Overrides detection of current language mode
11220 /// and uses the rules for C++23.
11221 ///
11222 /// \returns An aggregate which contains the Candidate and isMoveEligible
11223 /// and isCopyElidable methods. If Candidate is non-null, it means
11224 /// isMoveEligible() would be true under the most permissive language
11225 /// standard.
11226 NamedReturnInfo getNamedReturnInfo(
11228
11229 /// Determine whether the given NRVO candidate variable is move-eligible or
11230 /// copy-elidable, without considering function return type.
11231 ///
11232 /// \param VD The NRVO candidate variable.
11233 ///
11234 /// \returns An aggregate which contains the Candidate and isMoveEligible
11235 /// and isCopyElidable methods. If Candidate is non-null, it means
11236 /// isMoveEligible() would be true under the most permissive language
11237 /// standard.
11238 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
11239
11240 /// Updates given NamedReturnInfo's move-eligible and
11241 /// copy-elidable statuses, considering the function
11242 /// return type criteria as applicable to return statements.
11243 ///
11244 /// \param Info The NamedReturnInfo object to update.
11245 ///
11246 /// \param ReturnType This is the return type of the function.
11247 /// \returns The copy elision candidate, in case the initial return expression
11248 /// was copy elidable, or nullptr otherwise.
11249 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
11250 QualType ReturnType);
11251
11252 /// Perform the initialization of a potentially-movable value, which
11253 /// is the result of return value.
11254 ///
11255 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
11256 /// treat returned lvalues as rvalues in certain cases (to prefer move
11257 /// construction), then falls back to treating them as lvalues if that failed.
11260 const NamedReturnInfo &NRInfo, Expr *Value,
11261 bool SupressSimplerImplicitMoves = false);
11262
11264
11265 /// Deduce the return type for a function from a returned expression, per
11266 /// C++1y [dcl.spec.auto]p6.
11268 SourceLocation ReturnLoc, Expr *RetExpr,
11269 const AutoType *AT);
11270
11271 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11272 Scope *CurScope);
11273 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11274 bool AllowRecovery = false);
11275
11276 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
11277 /// for capturing scopes.
11279 NamedReturnInfo &NRInfo,
11280 bool SupressSimplerImplicitMoves);
11281
11282 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
11283 /// and creates a proper catch handler from them.
11285 Stmt *HandlerBlock);
11286
11287 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
11288 /// handlers and creates a try statement from them.
11290 ArrayRef<Stmt *> Handlers);
11291
11292 void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry);
11293
11294 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
11295 SourceLocation TryLoc, Stmt *TryBlock,
11296 Stmt *Handler);
11298 Stmt *Block);
11303
11305 bool IsIfExists,
11306 NestedNameSpecifierLoc QualifierLoc,
11307 DeclarationNameInfo NameInfo,
11308 Stmt *Nested);
11310 bool IsIfExists, CXXScopeSpec &SS,
11311 UnqualifiedId &Name, Stmt *Nested);
11312
11313 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11314 CapturedRegionKind Kind, unsigned NumParams);
11315 typedef std::pair<StringRef, QualType> CapturedParamNameType;
11316 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11317 CapturedRegionKind Kind,
11319 unsigned OpenMPCaptureLevel = 0);
11323 SourceLocation Loc,
11324 unsigned NumParams);
11325
11327 VarDecl *RangeVar, ArrayRef<MaterializeTemporaryExpr *> Temporaries);
11328
11329private:
11330 /// Check whether the given statement can have musttail applied to it,
11331 /// issuing a diagnostic and returning false if not.
11332 bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11333
11334 ///@}
11335
11336 //
11337 //
11338 // -------------------------------------------------------------------------
11339 //
11340 //
11341
11342 /// \name `inline asm` Statement
11343 /// Implementations are in SemaStmtAsm.cpp
11344 ///@{
11345
11346public:
11347 ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel);
11348 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
11349 bool IsVolatile, unsigned NumOutputs,
11350 unsigned NumInputs, IdentifierInfo **Names,
11351 MultiExprArg Constraints, MultiExprArg Exprs,
11352 Expr *AsmString, MultiExprArg Clobbers,
11353 unsigned NumLabels, SourceLocation RParenLoc);
11354
11356 llvm::InlineAsmIdentifierInfo &Info);
11358 SourceLocation TemplateKWLoc,
11359 UnqualifiedId &Id,
11360 bool IsUnevaluatedContext);
11361 bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset,
11362 SourceLocation AsmLoc);
11364 SourceLocation AsmLoc);
11366 ArrayRef<Token> AsmToks, StringRef AsmString,
11367 unsigned NumOutputs, unsigned NumInputs,
11368 ArrayRef<StringRef> Constraints,
11369 ArrayRef<StringRef> Clobbers,
11370 ArrayRef<Expr *> Exprs, SourceLocation EndLoc);
11371 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
11372 SourceLocation Location, bool AlwaysCreate);
11373
11374 ///@}
11375
11376 //
11377 //
11378 // -------------------------------------------------------------------------
11379 //
11380 //
11381
11382 /// \name Statement Attribute Handling
11383 /// Implementations are in SemaStmtAttr.cpp
11384 ///@{
11385
11386public:
11387 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11388 const AttributeCommonInfo &A);
11389 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11390 const AttributeCommonInfo &A);
11391
11392 CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E);
11394
11395 /// Process the attributes before creating an attributed statement. Returns
11396 /// the semantic attributes that have been processed.
11397 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
11399
11401 SourceRange Range);
11403 const IdentifierInfo *AttrName,
11404 SourceRange Range);
11405
11406 ///@}
11407
11408 //
11409 //
11410 // -------------------------------------------------------------------------
11411 //
11412 //
11413
11414 /// \name C++ Templates
11415 /// Implementations are in SemaTemplate.cpp
11416 ///@{
11417
11418public:
11419 // Saves the current floating-point pragma stack and clear it in this Sema.
11421 public:
11423 : S(S), SavedStack(std::move(S.FpPragmaStack)) {
11424 S.FpPragmaStack.Stack.clear();
11425 }
11426 ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); }
11429
11430 private:
11431 Sema &S;
11433 };
11434
11436 CurFPFeatures = FPO;
11437 FpPragmaStack.CurrentValue = FPO.getChangesFrom(FPOptions(LangOpts));
11438 }
11439
11445
11450
11451 typedef llvm::MapVector<const FunctionDecl *,
11452 std::unique_ptr<LateParsedTemplate>>
11455
11456 /// Determine the number of levels of enclosing template parameters. This is
11457 /// only usable while parsing. Note that this does not include dependent
11458 /// contexts in which no template parameters have yet been declared, such as
11459 /// in a terse function template or generic lambda before the first 'auto' is
11460 /// encountered.
11461 unsigned getTemplateDepth(Scope *S) const;
11462
11464 bool AllowFunctionTemplates = true,
11465 bool AllowDependent = true);
11467 bool AllowFunctionTemplates = true,
11468 bool AllowDependent = true,
11469 bool AllowNonTemplateFunctions = false);
11470 /// Try to interpret the lookup result D as a template-name.
11471 ///
11472 /// \param D A declaration found by name lookup.
11473 /// \param AllowFunctionTemplates Whether function templates should be
11474 /// considered valid results.
11475 /// \param AllowDependent Whether unresolved using declarations (that might
11476 /// name templates) should be considered valid results.
11478 bool AllowFunctionTemplates = true,
11479 bool AllowDependent = true);
11480
11482 /// Whether and why a template name is required in this lookup.
11484 public:
11485 /// Template name is required if TemplateKWLoc is valid.
11487 : TemplateKW(TemplateKWLoc) {}
11488 /// Template name is unconditionally required.
11490
11492 return TemplateKW.value_or(SourceLocation());
11493 }
11494 bool hasTemplateKeyword() const {
11495 return getTemplateKeywordLoc().isValid();
11496 }
11497 bool isRequired() const { return TemplateKW != SourceLocation(); }
11498 explicit operator bool() const { return isRequired(); }
11499
11500 private:
11501 std::optional<SourceLocation> TemplateKW;
11502 };
11503
11505 /// This is not assumed to be a template name.
11507 /// This is assumed to be a template name because lookup found nothing.
11509 /// This is assumed to be a template name because lookup found one or more
11510 /// functions (but no function templates).
11512 };
11513
11514 bool
11516 QualType ObjectType, bool EnteringContext,
11517 RequiredTemplateKind RequiredTemplate = SourceLocation(),
11518 AssumedTemplateKind *ATK = nullptr,
11519 bool AllowTypoCorrection = true);
11520
11522 bool hasTemplateKeyword,
11523 const UnqualifiedId &Name,
11524 ParsedType ObjectType, bool EnteringContext,
11526 bool &MemberOfUnknownSpecialization,
11527 bool AllowTypoCorrection = true);
11528
11529 /// Try to resolve an undeclared template name as a type template.
11530 ///
11531 /// Sets II to the identifier corresponding to the template name, and updates
11532 /// Name to a corresponding (typo-corrected) type template name and TNK to
11533 /// the corresponding kind, if possible.
11535 TemplateNameKind &TNK,
11536 SourceLocation NameLoc,
11537 IdentifierInfo *&II);
11538
11539 /// Determine whether a particular identifier might be the name in a C++1z
11540 /// deduction-guide declaration.
11541 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
11542 SourceLocation NameLoc, CXXScopeSpec &SS,
11543 ParsedTemplateTy *Template = nullptr);
11544
11546 SourceLocation IILoc, Scope *S,
11547 const CXXScopeSpec *SS,
11548 TemplateTy &SuggestedTemplate,
11549 TemplateNameKind &SuggestedKind);
11550
11551 /// Determine whether we would be unable to instantiate this template (because
11552 /// it either has no definition, or is in the process of being instantiated).
11554 SourceLocation PointOfInstantiation, NamedDecl *Instantiation,
11555 bool InstantiatedFromMember, const NamedDecl *Pattern,
11556 const NamedDecl *PatternDef, TemplateSpecializationKind TSK,
11557 bool Complain = true, bool *Unreachable = nullptr);
11558
11559 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
11560 /// that the template parameter 'PrevDecl' is being shadowed by a new
11561 /// declaration at location Loc. Returns true to indicate that this is
11562 /// an error, and false otherwise.
11563 ///
11564 /// \param Loc The location of the declaration that shadows a template
11565 /// parameter.
11566 ///
11567 /// \param PrevDecl The template parameter that the declaration shadows.
11568 ///
11569 /// \param SupportedForCompatibility Whether to issue the diagnostic as
11570 /// a warning for compatibility with older versions of clang.
11571 /// Ignored when MSVC compatibility is enabled.
11573 bool SupportedForCompatibility = false);
11574
11575 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
11576 /// the parameter D to reference the templated declaration and return a
11577 /// pointer to the template declaration. Otherwise, do nothing to D and return
11578 /// null.
11580
11581 /// ActOnTypeParameter - Called when a C++ template type parameter
11582 /// (e.g., "typename T") has been parsed. Typename specifies whether
11583 /// the keyword "typename" was used to declare the type parameter
11584 /// (otherwise, "class" was used), and KeyLoc is the location of the
11585 /// "class" or "typename" keyword. ParamName is the name of the
11586 /// parameter (NULL indicates an unnamed template parameter) and
11587 /// ParamNameLoc is the location of the parameter name (if any).
11588 /// If the type parameter has a default argument, it will be added
11589 /// later via ActOnTypeParameterDefault.
11591 SourceLocation EllipsisLoc,
11592 SourceLocation KeyLoc,
11593 IdentifierInfo *ParamName,
11594 SourceLocation ParamNameLoc, unsigned Depth,
11595 unsigned Position, SourceLocation EqualLoc,
11596 ParsedType DefaultArg, bool HasTypeConstraint);
11597
11599
11600 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
11602 TemplateTypeParmDecl *ConstrainedParameter,
11603 SourceLocation EllipsisLoc);
11604 bool BuildTypeConstraint(const CXXScopeSpec &SS,
11606 TemplateTypeParmDecl *ConstrainedParameter,
11607 SourceLocation EllipsisLoc,
11608 bool AllowUnexpandedPack);
11609
11610 /// Attach a type-constraint to a template parameter.
11611 /// \returns true if an error occurred. This can happen if the
11612 /// immediately-declared constraint could not be formed (e.g. incorrect number
11613 /// of arguments for the named concept).
11615 DeclarationNameInfo NameInfo,
11616 TemplateDecl *NamedConcept, NamedDecl *FoundDecl,
11617 const TemplateArgumentListInfo *TemplateArgs,
11618 TemplateTypeParmDecl *ConstrainedParameter,
11619 SourceLocation EllipsisLoc);
11620
11622 NonTypeTemplateParmDecl *NewConstrainedParm,
11623 NonTypeTemplateParmDecl *OrigConstrainedParm,
11624 SourceLocation EllipsisLoc);
11625
11626 /// Require the given type to be a structural type, and diagnose if it is not.
11627 ///
11628 /// \return \c true if an error was produced.
11630
11631 /// Check that the type of a non-type template parameter is
11632 /// well-formed.
11633 ///
11634 /// \returns the (possibly-promoted) parameter type if valid;
11635 /// otherwise, produces a diagnostic and returns a NULL type.
11637 SourceLocation Loc);
11639
11641 unsigned Depth, unsigned Position,
11642 SourceLocation EqualLoc,
11643 Expr *DefaultArg);
11644
11645 /// ActOnTemplateTemplateParameter - Called when a C++ template template
11646 /// parameter (e.g. T in template <template <typename> class T> class array)
11647 /// has been parsed. S is the current scope.
11649 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind,
11650 bool TypenameKeyword, TemplateParameterList *Params,
11651 SourceLocation EllipsisLoc, IdentifierInfo *ParamName,
11652 SourceLocation ParamNameLoc, unsigned Depth, unsigned Position,
11653 SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg);
11654
11655 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
11656 /// constrained by RequiresClause, that contains the template parameters in
11657 /// Params.
11659 unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc,
11660 SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params,
11661 SourceLocation RAngleLoc, Expr *RequiresClause);
11662
11663 /// The context in which we are checking a template parameter list.
11665 // For this context, Class, Variable, TypeAlias, and non-pack Template
11666 // Template Parameters are treated uniformly.
11668
11675 };
11676
11677 /// Checks the validity of a template parameter list, possibly
11678 /// considering the template parameter list from a previous
11679 /// declaration.
11680 ///
11681 /// If an "old" template parameter list is provided, it must be
11682 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
11683 /// template parameter list.
11684 ///
11685 /// \param NewParams Template parameter list for a new template
11686 /// declaration. This template parameter list will be updated with any
11687 /// default arguments that are carried through from the previous
11688 /// template parameter list.
11689 ///
11690 /// \param OldParams If provided, template parameter list from a
11691 /// previous declaration of the same template. Default template
11692 /// arguments will be merged from the old template parameter list to
11693 /// the new template parameter list.
11694 ///
11695 /// \param TPC Describes the context in which we are checking the given
11696 /// template parameter list.
11697 ///
11698 /// \param SkipBody If we might have already made a prior merged definition
11699 /// of this template visible, the corresponding body-skipping information.
11700 /// Default argument redefinition is not an error when skipping such a body,
11701 /// because (under the ODR) we can assume the default arguments are the same
11702 /// as the prior merged definition.
11703 ///
11704 /// \returns true if an error occurred, false otherwise.
11706 TemplateParameterList *OldParams,
11708 SkipBodyInfo *SkipBody = nullptr);
11709
11710 /// Match the given template parameter lists to the given scope
11711 /// specifier, returning the template parameter list that applies to the
11712 /// name.
11713 ///
11714 /// \param DeclStartLoc the start of the declaration that has a scope
11715 /// specifier or a template parameter list.
11716 ///
11717 /// \param DeclLoc The location of the declaration itself.
11718 ///
11719 /// \param SS the scope specifier that will be matched to the given template
11720 /// parameter lists. This scope specifier precedes a qualified name that is
11721 /// being declared.
11722 ///
11723 /// \param TemplateId The template-id following the scope specifier, if there
11724 /// is one. Used to check for a missing 'template<>'.
11725 ///
11726 /// \param ParamLists the template parameter lists, from the outermost to the
11727 /// innermost template parameter lists.
11728 ///
11729 /// \param IsFriend Whether to apply the slightly different rules for
11730 /// matching template parameters to scope specifiers in friend
11731 /// declarations.
11732 ///
11733 /// \param IsMemberSpecialization will be set true if the scope specifier
11734 /// denotes a fully-specialized type, and therefore this is a declaration of
11735 /// a member specialization.
11736 ///
11737 /// \returns the template parameter list, if any, that corresponds to the
11738 /// name that is preceded by the scope specifier @p SS. This template
11739 /// parameter list may have template parameters (if we're declaring a
11740 /// template) or may have no template parameters (if we're declaring a
11741 /// template specialization), or may be NULL (if what we're declaring isn't
11742 /// itself a template).
11744 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
11745 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
11746 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
11747 bool &IsMemberSpecialization, bool &Invalid,
11748 bool SuppressDiagnostic = false);
11749
11750 /// Returns the template parameter list with all default template argument
11751 /// information.
11753
11755 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11756 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
11757 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
11758 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
11759 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
11760 TemplateParameterList **OuterTemplateParamLists,
11761 bool IsMemberSpecialization, SkipBodyInfo *SkipBody = nullptr);
11762
11763 /// Translates template arguments as provided by the parser
11764 /// into template arguments used by semantic analysis.
11767
11768 /// Convert a parsed type into a parsed template argument. This is mostly
11769 /// trivial, except that we may have parsed a C++17 deduced class template
11770 /// specialization type, in which case we should form a template template
11771 /// argument instead of a type template argument.
11773
11775
11778 SourceLocation TemplateLoc,
11779 TemplateArgumentListInfo &TemplateArgs,
11780 Scope *Scope, bool ForNestedNameSpecifier);
11781
11783 ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
11784 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
11785 SourceLocation TemplateKWLoc, TemplateTy Template,
11786 const IdentifierInfo *TemplateII,
11787 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11788 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
11789 bool IsCtorOrDtorName = false, bool IsClassName = false,
11790 ImplicitTypenameContext AllowImplicitTypename =
11792
11793 /// Parsed an elaborated-type-specifier that refers to a template-id,
11794 /// such as \c class T::template apply<U>.
11796 TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc,
11797 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD,
11798 SourceLocation TemplateLoc, SourceLocation LAngleLoc,
11799 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc);
11800
11803 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
11805
11806 /// Get the specialization of the given variable template corresponding to
11807 /// the specified argument list, or a null-but-valid result if the arguments
11808 /// are dependent.
11810 SourceLocation TemplateLoc,
11811 SourceLocation TemplateNameLoc,
11812 const TemplateArgumentListInfo &TemplateArgs,
11813 bool SetWrittenArgs);
11814
11815 /// Form a reference to the specialization of the given variable template
11816 /// corresponding to the specified argument list, or a null-but-valid result
11817 /// if the arguments are dependent.
11819 const DeclarationNameInfo &NameInfo,
11821 SourceLocation TemplateLoc,
11822 const TemplateArgumentListInfo *TemplateArgs);
11823
11826 const TemplateArgumentListInfo *TemplateArgs);
11827
11829 CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11830 const DeclarationNameInfo &ConceptNameInfo,
11831 NamedDecl *FoundDecl, TemplateDecl *NamedConcept,
11832 const TemplateArgumentListInfo *TemplateArgs,
11833 bool DoCheckConstraintSatisfaction = true);
11834
11837 bool TemplateKeyword, TemplateDecl *TD,
11838 SourceLocation Loc);
11839
11841 SourceLocation TemplateKWLoc, LookupResult &R,
11842 bool RequiresADL,
11843 const TemplateArgumentListInfo *TemplateArgs);
11844
11845 // We actually only call this from template instantiation.
11848 const DeclarationNameInfo &NameInfo,
11849 const TemplateArgumentListInfo *TemplateArgs,
11850 bool IsAddressOfOperand);
11851
11853 return Pack.pack_size() - 1 - *ArgPackSubstIndex;
11854 }
11855
11858 Arg = Arg.pack_elements()[*ArgPackSubstIndex];
11859 if (Arg.isPackExpansion())
11860 Arg = Arg.getPackExpansionPattern();
11861 return Arg;
11862 }
11863
11865 BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
11866 QualType ParamType, SourceLocation loc,
11867 TemplateArgument Replacement,
11868 UnsignedOrNone PackIndex, bool Final);
11869
11870 /// Form a template name from a name that is syntactically required to name a
11871 /// template, either due to use of the 'template' keyword or because a name in
11872 /// this syntactic context is assumed to name a template (C++
11873 /// [temp.names]p2-4).
11874 ///
11875 /// This action forms a template name given the name of the template and its
11876 /// optional scope specifier. This is used when the 'template' keyword is used
11877 /// or when the parsing context unambiguously treats a following '<' as
11878 /// introducing a template argument list. Note that this may produce a
11879 /// non-dependent template name if we can perform the lookup now and identify
11880 /// the named template.
11881 ///
11882 /// For example, given "x.MetaFun::template apply", the scope specifier
11883 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
11884 /// of the "template" keyword, and "apply" is the \p Name.
11886 SourceLocation TemplateKWLoc,
11887 const UnqualifiedId &Name,
11888 ParsedType ObjectType,
11889 bool EnteringContext, TemplateTy &Template,
11890 bool AllowInjectedClassName = false);
11891
11893 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11894 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
11896 MultiTemplateParamsArg TemplateParameterLists,
11897 SkipBodyInfo *SkipBody = nullptr);
11898
11899 /// Check the non-type template arguments of a class template
11900 /// partial specialization according to C++ [temp.class.spec]p9.
11901 ///
11902 /// \param TemplateNameLoc the location of the template name.
11903 /// \param PrimaryTemplate the template parameters of the primary class
11904 /// template.
11905 /// \param NumExplicit the number of explicitly-specified template arguments.
11906 /// \param TemplateArgs the template arguments of the class template
11907 /// partial specialization.
11908 ///
11909 /// \returns \c true if there was an error, \c false otherwise.
11911 TemplateDecl *PrimaryTemplate,
11912 unsigned NumExplicitArgs,
11918
11920 MultiTemplateParamsArg TemplateParameterLists,
11921 Declarator &D);
11922
11923 /// Diagnose cases where we have an explicit template specialization
11924 /// before/after an explicit template instantiation, producing diagnostics
11925 /// for those cases where they are required and determining whether the
11926 /// new specialization/instantiation will have any effect.
11927 ///
11928 /// \param NewLoc the location of the new explicit specialization or
11929 /// instantiation.
11930 ///
11931 /// \param NewTSK the kind of the new explicit specialization or
11932 /// instantiation.
11933 ///
11934 /// \param PrevDecl the previous declaration of the entity.
11935 ///
11936 /// \param PrevTSK the kind of the old explicit specialization or
11937 /// instantiatin.
11938 ///
11939 /// \param PrevPointOfInstantiation if valid, indicates where the previous
11940 /// declaration was instantiated (either implicitly or explicitly).
11941 ///
11942 /// \param HasNoEffect will be set to true to indicate that the new
11943 /// specialization or instantiation has no effect and should be ignored.
11944 ///
11945 /// \returns true if there was an error that should prevent the introduction
11946 /// of the new declaration into the AST, false otherwise.
11948 SourceLocation NewLoc,
11949 TemplateSpecializationKind ActOnExplicitInstantiationNewTSK,
11950 NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK,
11951 SourceLocation PrevPtOfInstantiation, bool &SuppressNew);
11952
11953 /// Perform semantic analysis for the given dependent function
11954 /// template specialization.
11955 ///
11956 /// The only possible way to get a dependent function template specialization
11957 /// is with a friend declaration, like so:
11958 ///
11959 /// \code
11960 /// template <class T> void foo(T);
11961 /// template <class T> class A {
11962 /// friend void foo<>(T);
11963 /// };
11964 /// \endcode
11965 ///
11966 /// There really isn't any useful analysis we can do here, so we
11967 /// just store the information.
11969 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
11971
11972 /// Perform semantic analysis for the given function template
11973 /// specialization.
11974 ///
11975 /// This routine performs all of the semantic analysis required for an
11976 /// explicit function template specialization. On successful completion,
11977 /// the function declaration \p FD will become a function template
11978 /// specialization.
11979 ///
11980 /// \param FD the function declaration, which will be updated to become a
11981 /// function template specialization.
11982 ///
11983 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
11984 /// if any. Note that this may be valid info even when 0 arguments are
11985 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
11986 /// as it anyway contains info on the angle brackets locations.
11987 ///
11988 /// \param Previous the set of declarations that may be specialized by
11989 /// this function specialization.
11990 ///
11991 /// \param QualifiedFriend whether this is a lookup for a qualified friend
11992 /// declaration with no explicit template argument list that might be
11993 /// befriending a function template specialization.
11995 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
11996 LookupResult &Previous, bool QualifiedFriend = false);
11997
11998 /// Perform semantic analysis for the given non-template member
11999 /// specialization.
12000 ///
12001 /// This routine performs all of the semantic analysis required for an
12002 /// explicit member function specialization. On successful completion,
12003 /// the function declaration \p FD will become a member function
12004 /// specialization.
12005 ///
12006 /// \param Member the member declaration, which will be updated to become a
12007 /// specialization.
12008 ///
12009 /// \param Previous the set of declarations, one of which may be specialized
12010 /// by this function specialization; the set will be modified to contain the
12011 /// redeclared member.
12014
12015 // Explicit instantiation of a class template specialization
12017 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
12018 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
12019 TemplateTy Template, SourceLocation TemplateNameLoc,
12020 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
12021 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
12022
12023 // Explicit instantiation of a member class of a class template.
12025 SourceLocation TemplateLoc,
12026 unsigned TagSpec, SourceLocation KWLoc,
12027 CXXScopeSpec &SS, IdentifierInfo *Name,
12028 SourceLocation NameLoc,
12029 const ParsedAttributesView &Attr);
12030
12032 SourceLocation TemplateLoc,
12033 Declarator &D);
12034
12035 /// If the given template parameter has a default template
12036 /// argument, substitute into that default template argument and
12037 /// return the corresponding template argument.
12039 TemplateDecl *Template, SourceLocation TemplateKWLoc,
12040 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
12041 ArrayRef<TemplateArgument> SugaredConverted,
12042 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
12043
12044 /// Returns the top most location responsible for the definition of \p N.
12045 /// If \p N is a a template specialization, this is the location
12046 /// of the top of the instantiation stack.
12047 /// Otherwise, the location of \p N is returned.
12049
12050 /// Specifies the context in which a particular template
12051 /// argument is being checked.
12053 /// The template argument was specified in the code or was
12054 /// instantiated with some deduced template arguments.
12056
12057 /// The template argument was deduced via template argument
12058 /// deduction.
12060
12061 /// The template argument was deduced from an array bound
12062 /// via template argument deduction.
12064 };
12065
12073
12074 /// The checked, converted argument will be added to the
12075 /// end of these vectors.
12077
12078 /// The check is being performed in the context of partial ordering.
12080
12081 /// If true, assume these template arguments are
12082 /// the injected template arguments for a template template parameter.
12083 /// This will relax the requirement that all its possible uses are valid:
12084 /// TTP checking is loose, and assumes that invalid uses will be diagnosed
12085 /// during instantiation.
12087
12088 /// Is set to true when, in the context of TTP matching, a pack parameter
12089 /// matches non-pack arguments.
12090 bool StrictPackMatch = false;
12091 };
12092
12093 /// Check that the given template argument corresponds to the given
12094 /// template parameter.
12095 ///
12096 /// \param Param The template parameter against which the argument will be
12097 /// checked.
12098 ///
12099 /// \param Arg The template argument, which may be updated due to conversions.
12100 ///
12101 /// \param Template The template in which the template argument resides.
12102 ///
12103 /// \param TemplateLoc The location of the template name for the template
12104 /// whose argument list we're matching.
12105 ///
12106 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
12107 /// the template argument list.
12108 ///
12109 /// \param ArgumentPackIndex The index into the argument pack where this
12110 /// argument will be placed. Only valid if the parameter is a parameter pack.
12111 ///
12112 /// \param CTAK Describes how we arrived at this particular template argument:
12113 /// explicitly written, deduced, etc.
12114 ///
12115 /// \returns true on error, false otherwise.
12117 NamedDecl *Template, SourceLocation TemplateLoc,
12118 SourceLocation RAngleLoc,
12119 unsigned ArgumentPackIndex,
12122
12123 /// Check that the given template arguments can be provided to
12124 /// the given template, converting the arguments along the way.
12125 ///
12126 /// \param Template The template to which the template arguments are being
12127 /// provided.
12128 ///
12129 /// \param TemplateLoc The location of the template name in the source.
12130 ///
12131 /// \param TemplateArgs The list of template arguments. If the template is
12132 /// a template template parameter, this function may extend the set of
12133 /// template arguments to also include substituted, defaulted template
12134 /// arguments.
12135 ///
12136 /// \param PartialTemplateArgs True if the list of template arguments is
12137 /// intentionally partial, e.g., because we're checking just the initial
12138 /// set of template arguments.
12139 ///
12140 /// \param Converted Will receive the converted, canonicalized template
12141 /// arguments.
12142 ///
12143 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
12144 /// contain the converted forms of the template arguments as written.
12145 /// Otherwise, \p TemplateArgs will not be modified.
12146 ///
12147 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
12148 /// receive true if the cause for the error is the associated constraints of
12149 /// the template not being satisfied by the template arguments.
12150 ///
12151 /// \param DefaultArgs any default arguments from template specialization
12152 /// deduction.
12153 ///
12154 /// \returns true if an error occurred, false otherwise.
12156 SourceLocation TemplateLoc,
12157 TemplateArgumentListInfo &TemplateArgs,
12158 const DefaultArguments &DefaultArgs,
12159 bool PartialTemplateArgs,
12161 bool UpdateArgsWithConversions = true,
12162 bool *ConstraintsNotSatisfied = nullptr);
12163
12166 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
12167 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
12168 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions = true,
12169 bool *ConstraintsNotSatisfied = nullptr);
12170
12173 SmallVectorImpl<TemplateArgument> &SugaredConverted,
12174 SmallVectorImpl<TemplateArgument> &CanonicalConverted);
12175
12176 /// Check a template argument against its corresponding
12177 /// template type parameter.
12178 ///
12179 /// This routine implements the semantics of C++ [temp.arg.type]. It
12180 /// returns true if an error occurred, and false otherwise.
12182
12183 /// Check a template argument against its corresponding
12184 /// non-type template parameter.
12185 ///
12186 /// This routine implements the semantics of C++ [temp.arg.nontype].
12187 /// If an error occurred, it returns ExprError(); otherwise, it
12188 /// returns the converted template argument. \p ParamType is the
12189 /// type of the non-type template parameter after it has been instantiated.
12191 QualType InstantiatedParamType, Expr *Arg,
12192 TemplateArgument &SugaredConverted,
12193 TemplateArgument &CanonicalConverted,
12194 bool StrictCheck,
12196
12197 /// Check a template argument against its corresponding
12198 /// template template parameter.
12199 ///
12200 /// This routine implements the semantics of C++ [temp.arg.template].
12201 /// It returns true if an error occurred, and false otherwise.
12203 TemplateParameterList *Params,
12205 bool PartialOrdering,
12206 bool *StrictPackMatch);
12207
12210 const TemplateArgumentLoc &Arg);
12211
12213 std::optional<SourceRange> ParamRange = {});
12215
12216 /// Given a non-type template argument that refers to a
12217 /// declaration and the type of its corresponding non-type template
12218 /// parameter, produce an expression that properly refers to that
12219 /// declaration.
12220 /// FIXME: This is used in some contexts where the resulting expression
12221 /// doesn't need to live too long. It would be useful if this function
12222 /// could return a temporary expression.
12224 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc);
12227 SourceLocation Loc);
12228
12229 /// Enumeration describing how template parameter lists are compared
12230 /// for equality.
12232 /// We are matching the template parameter lists of two templates
12233 /// that might be redeclarations.
12234 ///
12235 /// \code
12236 /// template<typename T> struct X;
12237 /// template<typename T> struct X;
12238 /// \endcode
12240
12241 /// We are matching the template parameter lists of two template
12242 /// template parameters as part of matching the template parameter lists
12243 /// of two templates that might be redeclarations.
12244 ///
12245 /// \code
12246 /// template<template<int I> class TT> struct X;
12247 /// template<template<int Value> class Other> struct X;
12248 /// \endcode
12250
12251 /// We are determining whether the template-parameters are equivalent
12252 /// according to C++ [temp.over.link]/6. This comparison does not consider
12253 /// constraints.
12254 ///
12255 /// \code
12256 /// template<C1 T> void f(T);
12257 /// template<C2 T> void f(T);
12258 /// \endcode
12260 };
12261
12262 // A struct to represent the 'new' declaration, which is either itself just
12263 // the named decl, or the important information we need about it in order to
12264 // do constraint comparisons.
12266 const NamedDecl *ND = nullptr;
12267 const DeclContext *DC = nullptr;
12268 const DeclContext *LexicalDC = nullptr;
12269 SourceLocation Loc;
12270
12271 public:
12274 const DeclContext *LexicalDeclCtx,
12275 SourceLocation Loc)
12276
12277 : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) {
12278 assert(DC && LexicalDC &&
12279 "Constructor only for cases where we have the information to put "
12280 "in here");
12281 }
12282
12283 // If this was constructed with no information, we cannot do substitution
12284 // for constraint comparison, so make sure we can check that.
12285 bool isInvalid() const { return !ND && !DC; }
12286
12287 const NamedDecl *getDecl() const { return ND; }
12288
12289 bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; }
12290
12292 return ND ? ND->getLexicalDeclContext() : LexicalDC;
12293 }
12294
12296 return ND ? ND->getDeclContext() : DC;
12297 }
12298
12299 SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; }
12300 };
12301
12302 /// Determine whether the given template parameter lists are
12303 /// equivalent.
12304 ///
12305 /// \param New The new template parameter list, typically written in the
12306 /// source code as part of a new template declaration.
12307 ///
12308 /// \param Old The old template parameter list, typically found via
12309 /// name lookup of the template declared with this template parameter
12310 /// list.
12311 ///
12312 /// \param Complain If true, this routine will produce a diagnostic if
12313 /// the template parameter lists are not equivalent.
12314 ///
12315 /// \param Kind describes how we are to match the template parameter lists.
12316 ///
12317 /// \param TemplateArgLoc If this source location is valid, then we
12318 /// are actually checking the template parameter list of a template
12319 /// argument (New) against the template parameter list of its
12320 /// corresponding template template parameter (Old). We produce
12321 /// slightly different diagnostics in this scenario.
12322 ///
12323 /// \returns True if the template parameter lists are equal, false
12324 /// otherwise.
12326 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
12327 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
12329 SourceLocation TemplateArgLoc = SourceLocation());
12330
12332 TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
12334 SourceLocation TemplateArgLoc = SourceLocation()) {
12335 return TemplateParameterListsAreEqual(nullptr, New, nullptr, Old, Complain,
12336 Kind, TemplateArgLoc);
12337 }
12338
12339 /// Check whether a template can be declared within this scope.
12340 ///
12341 /// If the template declaration is valid in this scope, returns
12342 /// false. Otherwise, issues a diagnostic and returns true.
12343 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
12344
12345 /// Called when the parser has parsed a C++ typename
12346 /// specifier, e.g., "typename T::type".
12347 ///
12348 /// \param S The scope in which this typename type occurs.
12349 /// \param TypenameLoc the location of the 'typename' keyword
12350 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12351 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
12352 /// \param IdLoc the location of the identifier.
12353 /// \param IsImplicitTypename context where T::type refers to a type.
12355 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
12356 const IdentifierInfo &II, SourceLocation IdLoc,
12358
12359 /// Called when the parser has parsed a C++ typename
12360 /// specifier that ends in a template-id, e.g.,
12361 /// "typename MetaFun::template apply<T1, T2>".
12362 ///
12363 /// \param S The scope in which this typename type occurs.
12364 /// \param TypenameLoc the location of the 'typename' keyword
12365 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12366 /// \param TemplateLoc the location of the 'template' keyword, if any.
12367 /// \param TemplateName The template name.
12368 /// \param TemplateII The identifier used to name the template.
12369 /// \param TemplateIILoc The location of the template name.
12370 /// \param LAngleLoc The location of the opening angle bracket ('<').
12371 /// \param TemplateArgs The template arguments.
12372 /// \param RAngleLoc The location of the closing angle bracket ('>').
12374 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
12375 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
12376 TemplateTy TemplateName, const IdentifierInfo *TemplateII,
12377 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
12378 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc);
12379
12381 SourceLocation KeywordLoc,
12382 NestedNameSpecifierLoc QualifierLoc,
12383 const IdentifierInfo &II, SourceLocation IILoc,
12384 TypeSourceInfo **TSI, bool DeducedTSTContext);
12385
12387 SourceLocation KeywordLoc,
12388 NestedNameSpecifierLoc QualifierLoc,
12389 const IdentifierInfo &II, SourceLocation IILoc,
12390 bool DeducedTSTContext = true);
12391
12392 /// Rebuilds a type within the context of the current instantiation.
12393 ///
12394 /// The type \p T is part of the type of an out-of-line member definition of
12395 /// a class template (or class template partial specialization) that was
12396 /// parsed and constructed before we entered the scope of the class template
12397 /// (or partial specialization thereof). This routine will rebuild that type
12398 /// now that we have entered the declarator's scope, which may produce
12399 /// different canonical types, e.g.,
12400 ///
12401 /// \code
12402 /// template<typename T>
12403 /// struct X {
12404 /// typedef T* pointer;
12405 /// pointer data();
12406 /// };
12407 ///
12408 /// template<typename T>
12409 /// typename X<T>::pointer X<T>::data() { ... }
12410 /// \endcode
12411 ///
12412 /// Here, the type "typename X<T>::pointer" will be created as a
12413 /// DependentNameType, since we do not know that we can look into X<T> when we
12414 /// parsed the type. This function will rebuild the type, performing the
12415 /// lookup of "pointer" in X<T> and returning an ElaboratedType whose
12416 /// canonical type is the same as the canonical type of T*, allowing the
12417 /// return types of the out-of-line definition and the declaration to match.
12419 SourceLocation Loc,
12420 DeclarationName Name);
12422
12424
12425 /// Rebuild the template parameters now that we know we're in a current
12426 /// instantiation.
12427 bool
12429
12430 /// Produces a formatted string that describes the binding of
12431 /// template parameters to template arguments.
12432 std::string
12434 const TemplateArgumentList &Args);
12435
12436 std::string
12438 const TemplateArgument *Args,
12439 unsigned NumArgs);
12440
12444
12445 /// ActOnDependentIdExpression - Handle a dependent id-expression that
12446 /// was just parsed. This is only possible with an explicit scope
12447 /// specifier naming a dependent type.
12449 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
12450 const DeclarationNameInfo &NameInfo, bool isAddressOfOperand,
12451 const TemplateArgumentListInfo *TemplateArgs);
12452
12455 SourceLocation TemplateKWLoc,
12456 const DeclarationNameInfo &NameInfo,
12457 const TemplateArgumentListInfo *TemplateArgs);
12458
12459 // Calculates whether the expression Constraint depends on an enclosing
12460 // template, for the purposes of [temp.friend] p9.
12461 // TemplateDepth is the 'depth' of the friend function, which is used to
12462 // compare whether a declaration reference is referring to a containing
12463 // template, or just the current friend function. A 'lower' TemplateDepth in
12464 // the AST refers to a 'containing' template. As the constraint is
12465 // uninstantiated, this is relative to the 'top' of the TU.
12466 bool
12468 unsigned TemplateDepth,
12469 const Expr *Constraint);
12470
12471 /// Find the failed Boolean condition within a given Boolean
12472 /// constant expression, and describe it with a string.
12473 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
12474
12476
12478 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
12479 const IdentifierInfo *Name, SourceLocation NameLoc);
12480
12482 Expr *ConstraintExpr,
12483 const ParsedAttributesView &Attrs);
12484
12486 bool &AddToScope);
12488
12489 TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12490 const CXXScopeSpec &SS,
12491 const IdentifierInfo *Name,
12492 SourceLocation TagLoc, SourceLocation NameLoc);
12493
12495 CachedTokens &Toks);
12498
12499 /// We've found a use of a templated declaration that would trigger an
12500 /// implicit instantiation. Check that any relevant explicit specializations
12501 /// and partial specializations are visible/reachable, and diagnose if not.
12504
12505 ///@}
12506
12507 //
12508 //
12509 // -------------------------------------------------------------------------
12510 //
12511 //
12512
12513 /// \name C++ Template Argument Deduction
12514 /// Implementations are in SemaTemplateDeduction.cpp
12515 ///@{
12516
12517public:
12518 class SFINAETrap;
12519
12522 : S(S), Prev(std::exchange(S.CurrentSFINAEContext, Cur)) {}
12523
12524 protected:
12526 ~SFINAEContextBase() { S.CurrentSFINAEContext = Prev; }
12529
12530 private:
12531 SFINAETrap *Prev;
12532 };
12533
12537
12538 /// RAII class used to determine whether SFINAE has
12539 /// trapped any errors that occur during template argument
12540 /// deduction.
12541 class SFINAETrap : SFINAEContextBase {
12542 bool HasErrorOcurred = false;
12543 bool WithAccessChecking = false;
12544 bool PrevLastDiagnosticIgnored =
12545 S.getDiagnostics().isLastDiagnosticIgnored();
12546 sema::TemplateDeductionInfo *DeductionInfo = nullptr;
12547
12548 SFINAETrap(Sema &S, sema::TemplateDeductionInfo *Info,
12549 bool WithAccessChecking)
12550 : SFINAEContextBase(S, this), WithAccessChecking(WithAccessChecking),
12551 DeductionInfo(Info) {}
12552
12553 public:
12554 /// \param WithAccessChecking If true, discard all diagnostics (from the
12555 /// immediate context) instead of adding them to the currently active
12556 /// \ref TemplateDeductionInfo.
12557 explicit SFINAETrap(Sema &S, bool WithAccessChecking = false)
12558 : SFINAETrap(S, /*Info=*/nullptr, WithAccessChecking) {}
12559
12561 : SFINAETrap(S, &Info, /*WithAccessChecking=*/false) {}
12562
12564 S.getDiagnostics().setLastDiagnosticIgnored(PrevLastDiagnosticIgnored);
12565 }
12566
12567 SFINAETrap(const SFINAETrap &) = delete;
12568 SFINAETrap &operator=(const SFINAETrap &) = delete;
12569
12571 return DeductionInfo;
12572 }
12573
12574 /// Determine whether any SFINAE errors have been trapped.
12575 bool hasErrorOccurred() const { return HasErrorOcurred; }
12576 void setErrorOccurred() { HasErrorOcurred = true; }
12577
12578 bool withAccessChecking() const { return WithAccessChecking; }
12579 };
12580
12581 /// RAII class used to indicate that we are performing provisional
12582 /// semantic analysis to determine the validity of a construct, so
12583 /// typo-correction and diagnostics in the immediate context (not within
12584 /// implicitly-instantiated templates) should be suppressed.
12586 Sema &SemaRef;
12587 // FIXME: Using a SFINAETrap for this is a hack.
12588 SFINAETrap Trap;
12589 bool PrevDisableTypoCorrection;
12590
12591 public:
12592 explicit TentativeAnalysisScope(Sema &SemaRef)
12593 : SemaRef(SemaRef), Trap(SemaRef, /*ForValidityCheck=*/true),
12594 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
12595 SemaRef.DisableTypoCorrection = true;
12596 }
12598 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
12599 }
12600
12603 };
12604
12605 /// For each declaration that involved template argument deduction, the
12606 /// set of diagnostics that were suppressed during that template argument
12607 /// deduction.
12608 ///
12609 /// FIXME: Serialize this structure to the AST file.
12610 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1>>
12613
12614 /// Compare types for equality with respect to possibly compatible
12615 /// function types (noreturn adjustment, implicit calling conventions). If any
12616 /// of parameter and argument is not a function, just perform type comparison.
12617 ///
12618 /// \param P the template parameter type.
12619 ///
12620 /// \param A the argument type.
12622
12623 /// Allocate a TemplateArgumentLoc where all locations have
12624 /// been initialized to the given location.
12625 ///
12626 /// \param Arg The template argument we are producing template argument
12627 /// location information for.
12628 ///
12629 /// \param NTTPType For a declaration template argument, the type of
12630 /// the non-type template parameter that corresponds to this template
12631 /// argument. Can be null if no type sugar is available to add to the
12632 /// type from the template argument.
12633 ///
12634 /// \param Loc The source location to use for the resulting template
12635 /// argument.
12637 QualType NTTPType,
12638 SourceLocation Loc);
12639
12640 /// Get a template argument mapping the given template parameter to itself,
12641 /// e.g. for X in \c template<int X>, this would return an expression template
12642 /// argument referencing X.
12644 SourceLocation Location);
12645
12646 /// Adjust the type \p ArgFunctionType to match the calling convention,
12647 /// noreturn, and optionally the exception specification of \p FunctionType.
12648 /// Deduction often wants to ignore these properties when matching function
12649 /// types.
12651 bool AdjustExceptionSpec = false);
12652
12655 ArrayRef<TemplateArgument> TemplateArgs,
12657
12660 ArrayRef<TemplateArgument> TemplateArgs,
12662
12663 /// Deduce the template arguments of the given template from \p FromType.
12664 /// Used to implement the IsDeducible constraint for alias CTAD per C++
12665 /// [over.match.class.deduct]p4.
12666 ///
12667 /// It only supports class or type alias templates.
12671
12676 bool NumberOfArgumentsMustMatch);
12677
12678 /// Substitute the explicitly-provided template arguments into the
12679 /// given function template according to C++ [temp.arg.explicit].
12680 ///
12681 /// \param FunctionTemplate the function template into which the explicit
12682 /// template arguments will be substituted.
12683 ///
12684 /// \param ExplicitTemplateArgs the explicitly-specified template
12685 /// arguments.
12686 ///
12687 /// \param Deduced the deduced template arguments, which will be populated
12688 /// with the converted and checked explicit template arguments.
12689 ///
12690 /// \param ParamTypes will be populated with the instantiated function
12691 /// parameters.
12692 ///
12693 /// \param FunctionType if non-NULL, the result type of the function template
12694 /// will also be instantiated and the pointed-to value will be updated with
12695 /// the instantiated function type.
12696 ///
12697 /// \param Info if substitution fails for any reason, this object will be
12698 /// populated with more information about the failure.
12699 ///
12700 /// \returns TemplateDeductionResult::Success if substitution was successful,
12701 /// or some failure condition.
12704 TemplateArgumentListInfo &ExplicitTemplateArgs,
12708
12709 /// brief A function argument from which we performed template argument
12710 // deduction for a call.
12723
12724 /// Finish template argument deduction for a function template,
12725 /// checking the deduced template arguments for completeness and forming
12726 /// the function template specialization.
12727 ///
12728 /// \param OriginalCallArgs If non-NULL, the original call arguments against
12729 /// which the deduced argument types should be compared.
12730 /// \param CheckNonDependent Callback before substituting into the declaration
12731 /// with the deduced template arguments.
12732 /// \param OnlyInitializeNonUserDefinedConversions is used as a workaround for
12733 /// some breakages introduced by CWG2369, where non-user-defined conversions
12734 /// are checked first before the constraints.
12738 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
12740 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
12741 bool PartialOverloading, bool PartialOrdering,
12742 bool ForOverloadSetAddressResolution,
12743 llvm::function_ref<bool(bool)> CheckNonDependent =
12744 [](bool /*OnlyInitializeNonUserDefinedConversions*/) {
12745 return false;
12746 });
12747
12748 /// Perform [temp.friend] p5 template argument deduction for a dependent
12749 /// friend declaration and a candidate class template specialization.
12751 ClassTemplateDecl *PatternCTD,
12752 ClassTemplateDecl *CandidateCTD,
12754 ArrayRef<TemplateArgument> PatternArgs,
12755 ArrayRef<TemplateArgument> CandidateArgs,
12756 SourceLocation Loc,
12757 TemplateSpecCandidateSet *FailedTSC,
12758 MultiLevelTemplateArgumentList &DeducedArgs);
12759
12760 /// Perform template argument deduction from a function call
12761 /// (C++ [temp.deduct.call]).
12762 ///
12763 /// \param FunctionTemplate the function template for which we are performing
12764 /// template argument deduction.
12765 ///
12766 /// \param ExplicitTemplateArgs the explicit template arguments provided
12767 /// for this call.
12768 ///
12769 /// \param Args the function call arguments
12770 ///
12771 /// \param Specialization if template argument deduction was successful,
12772 /// this will be set to the function template specialization produced by
12773 /// template argument deduction.
12774 ///
12775 /// \param Info the argument will be updated to provide additional information
12776 /// about template argument deduction.
12777 ///
12778 /// \param CheckNonDependent A callback to invoke to check conversions for
12779 /// non-dependent parameters, between deduction and substitution, per DR1391.
12780 /// If this returns true, substitution will be skipped and we return
12781 /// TemplateDeductionResult::NonDependentConversionFailure. The callback is
12782 /// passed the parameter types (after substituting explicit template
12783 /// arguments).
12784 ///
12785 /// \returns the result of template argument deduction.
12788 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12790 bool PartialOverloading, bool AggregateDeductionCandidate,
12791 bool PartialOrdering, QualType ObjectType,
12792 Expr::Classification ObjectClassification,
12793 bool ForOverloadSetAddressResolution,
12794 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent);
12795
12796 /// Deduce template arguments when taking the address of a function
12797 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
12798 /// a template.
12799 ///
12800 /// \param FunctionTemplate the function template for which we are performing
12801 /// template argument deduction.
12802 ///
12803 /// \param ExplicitTemplateArgs the explicitly-specified template
12804 /// arguments.
12805 ///
12806 /// \param ArgFunctionType the function type that will be used as the
12807 /// "argument" type (A) when performing template argument deduction from the
12808 /// function template's function type. This type may be NULL, if there is no
12809 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
12810 ///
12811 /// \param Specialization if template argument deduction was successful,
12812 /// this will be set to the function template specialization produced by
12813 /// template argument deduction.
12814 ///
12815 /// \param Info the argument will be updated to provide additional information
12816 /// about template argument deduction.
12817 ///
12818 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12819 /// the address of a function template per [temp.deduct.funcaddr] and
12820 /// [over.over]. If \c false, we are looking up a function template
12821 /// specialization based on its signature, per [temp.deduct.decl].
12822 ///
12823 /// \returns the result of template argument deduction.
12826 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
12828 bool IsAddressOfFunction = false);
12829
12830 /// Deduce template arguments for a templated conversion
12831 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
12832 /// conversion function template specialization.
12835 Expr::Classification ObjectClassification, QualType ToType,
12837
12838 /// Deduce template arguments for a function template when there is
12839 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
12840 ///
12841 /// \param FunctionTemplate the function template for which we are performing
12842 /// template argument deduction.
12843 ///
12844 /// \param ExplicitTemplateArgs the explicitly-specified template
12845 /// arguments.
12846 ///
12847 /// \param Specialization if template argument deduction was successful,
12848 /// this will be set to the function template specialization produced by
12849 /// template argument deduction.
12850 ///
12851 /// \param Info the argument will be updated to provide additional information
12852 /// about template argument deduction.
12853 ///
12854 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12855 /// the address of a function template in a context where we do not have a
12856 /// target type, per [over.over]. If \c false, we are looking up a function
12857 /// template specialization based on its signature, which only happens when
12858 /// deducing a function parameter type from an argument that is a template-id
12859 /// naming a function template specialization.
12860 ///
12861 /// \returns the result of template argument deduction.
12864 TemplateArgumentListInfo *ExplicitTemplateArgs,
12867 bool IsAddressOfFunction = false);
12868
12869 /// Substitute Replacement for \p auto in \p TypeWithAuto
12870 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
12871 /// Substitute Replacement for auto in TypeWithAuto
12873 QualType Replacement);
12874
12875 // Substitute auto in TypeWithAuto for a Dependent auto type
12877
12878 // Substitute auto in TypeWithAuto for a Dependent auto type
12881
12882 /// Completely replace the \c auto in \p TypeWithAuto by
12883 /// \p Replacement. This does not retain any \c auto type sugar.
12884 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
12886 QualType Replacement);
12887
12888 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
12889 ///
12890 /// Note that this is done even if the initializer is dependent. (This is
12891 /// necessary to support partial ordering of templates using 'auto'.)
12892 /// A dependent type will be produced when deducing from a dependent type.
12893 ///
12894 /// \param Type the type pattern using the auto type-specifier.
12895 /// \param Init the initializer for the variable whose type is to be deduced.
12896 /// \param Result if type deduction was successful, this will be set to the
12897 /// deduced type.
12898 /// \param Info the argument will be updated to provide additional information
12899 /// about template argument deduction.
12900 /// \param DependentDeduction Set if we should permit deduction in
12901 /// dependent cases. This is necessary for template partial ordering
12902 /// with 'auto' template parameters. The template parameter depth to be
12903 /// used should be specified in the 'Info' parameter.
12904 /// \param IgnoreConstraints Set if we should not fail if the deduced type
12905 /// does not satisfy the type-constraint in the auto
12906 /// type.
12910 bool DependentDeduction = false,
12911 bool IgnoreConstraints = false,
12912 TemplateSpecCandidateSet *FailedTSC = nullptr);
12913 void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init);
12915 bool Diagnose = true);
12916
12918 SourceLocation Loc);
12919
12920 /// Returns the more specialized class template partial specialization
12921 /// according to the rules of partial ordering of class template partial
12922 /// specializations (C++ [temp.class.order]).
12923 ///
12924 /// \param PS1 the first class template partial specialization
12925 ///
12926 /// \param PS2 the second class template partial specialization
12927 ///
12928 /// \returns the more specialized class template partial specialization. If
12929 /// neither partial specialization is more specialized, returns NULL.
12934
12937
12941
12944
12946 TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
12947 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
12948 bool PartialOrdering, bool *StrictPackMatch);
12949
12950 /// Mark which template parameters are used in a given expression.
12951 ///
12952 /// \param E the expression from which template parameters will be deduced.
12953 ///
12954 /// \param Used a bit vector whose elements will be set to \c true
12955 /// to indicate when the corresponding template parameter will be
12956 /// deduced.
12957 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
12958 unsigned Depth, llvm::SmallBitVector &Used);
12959
12960 /// Mark which template parameters are named in a given expression.
12961 ///
12962 /// Unlike MarkUsedTemplateParameters, this excludes parameter that
12963 /// are used but not directly named by an expression - i.e. it excludes
12964 /// any template parameter that denotes the type of a referenced NTTP.
12965 ///
12966 /// \param Used a bit vector whose elements will be set to \c true
12967 /// to indicate when the corresponding template parameter will be
12968 /// deduced.
12970 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used);
12971
12972 /// Mark which template parameters can be deduced from a given
12973 /// template argument list.
12974 ///
12975 /// \param TemplateArgs the template argument list from which template
12976 /// parameters will be deduced.
12977 ///
12978 /// \param Used a bit vector whose elements will be set to \c true
12979 /// to indicate when the corresponding template parameter will be
12980 /// deduced.
12981 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
12982 bool OnlyDeduced, unsigned Depth,
12983 llvm::SmallBitVector &Used);
12984
12986 bool OnlyDeduced, unsigned Depth,
12987 llvm::SmallBitVector &Used);
12988
12990 unsigned Depth, llvm::SmallBitVector &Used);
12991
12992 void
12997
12998 /// Marks all of the template parameters that will be deduced by a
12999 /// call to the given function template.
13000 static void
13003 llvm::SmallBitVector &Deduced);
13004
13005 /// Returns the more specialized function template according
13006 /// to the rules of function template partial ordering (C++
13007 /// [temp.func.order]).
13008 ///
13009 /// \param FT1 the first function template
13010 ///
13011 /// \param FT2 the second function template
13012 ///
13013 /// \param TPOC the context in which we are performing partial ordering of
13014 /// function templates.
13015 ///
13016 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
13017 /// only when \c TPOC is \c TPOC_Call. Does not include the object argument
13018 /// when calling a member function.
13019 ///
13020 /// \param RawObj1Ty The type of the object parameter of FT1 if a member
13021 /// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function
13022 /// template from a member function
13023 ///
13024 /// \param RawObj2Ty The type of the object parameter of FT2 if a member
13025 /// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function
13026 /// template from a member function
13027 ///
13028 /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
13029 /// candidate with a reversed parameter order. In this case, the corresponding
13030 /// P/A pairs between FT1 and FT2 are reversed.
13031 ///
13032 /// \returns the more specialized function template. If neither
13033 /// template is more specialized, returns NULL.
13036 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
13037 QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false,
13038 bool PartialOverloading = false);
13039
13040 /// Retrieve the most specialized of the given function template
13041 /// specializations.
13042 ///
13043 /// \param SpecBegin the start iterator of the function template
13044 /// specializations that we will be comparing.
13045 ///
13046 /// \param SpecEnd the end iterator of the function template
13047 /// specializations, paired with \p SpecBegin.
13048 ///
13049 /// \param Loc the location where the ambiguity or no-specializations
13050 /// diagnostic should occur.
13051 ///
13052 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
13053 /// no matching candidates.
13054 ///
13055 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
13056 /// occurs.
13057 ///
13058 /// \param CandidateDiag partial diagnostic used for each function template
13059 /// specialization that is a candidate in the ambiguous ordering. One
13060 /// parameter in this diagnostic should be unbound, which will correspond to
13061 /// the string describing the template arguments for the function template
13062 /// specialization.
13063 ///
13064 /// \returns the most specialized function template specialization, if
13065 /// found. Otherwise, returns SpecEnd.
13066 UnresolvedSetIterator
13067 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
13068 TemplateSpecCandidateSet &FailedCandidates,
13069 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
13070 const PartialDiagnostic &AmbigDiag,
13071 const PartialDiagnostic &CandidateDiag,
13072 bool Complain = true, QualType TargetType = QualType());
13073
13074 /// Returns the more constrained function according to the rules of
13075 /// partial ordering by constraints (C++ [temp.constr.order]).
13076 ///
13077 /// \param FD1 the first function
13078 ///
13079 /// \param FD2 the second function
13080 ///
13081 /// \returns the more constrained function. If neither function is
13082 /// more constrained, returns NULL.
13083 FunctionDecl *getMoreConstrainedFunction(FunctionDecl *FD1,
13084 FunctionDecl *FD2);
13085
13086 ///@}
13087
13088 //
13089 //
13090 // -------------------------------------------------------------------------
13091 //
13092 //
13093
13094 /// \name C++ Template Deduction Guide
13095 /// Implementations are in SemaTemplateDeductionGuide.cpp
13096 ///@{
13097
13098 /// Declare implicit deduction guides for a class template if we've
13099 /// not already done so.
13100 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
13101 SourceLocation Loc);
13102
13103 CXXDeductionGuideDecl *DeclareAggregateDeductionGuideFromInitList(
13104 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
13105 SourceLocation Loc);
13106
13107 ///@}
13108
13109 //
13110 //
13111 // -------------------------------------------------------------------------
13112 //
13113 //
13114
13115 /// \name C++ Template Instantiation
13116 /// Implementations are in SemaTemplateInstantiate.cpp
13117 ///@{
13118
13119public:
13120 /// A helper class for building up ExtParameterInfos.
13123 bool HasInteresting = false;
13124
13125 public:
13126 /// Set the ExtParameterInfo for the parameter at the given index,
13127 ///
13129 assert(Infos.size() <= index);
13130 Infos.resize(index);
13131 Infos.push_back(info);
13132
13133 if (!HasInteresting)
13134 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
13135 }
13136
13137 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
13138 /// ExtParameterInfo array we've built up.
13140 getPointerOrNull(unsigned numParams) {
13141 if (!HasInteresting)
13142 return nullptr;
13143 Infos.resize(numParams);
13144 return Infos.data();
13145 }
13146 };
13147
13148 /// The current instantiation scope used to store local
13149 /// variables.
13151
13152 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
13154
13155 /// A mapping from parameters with unparsed default arguments to the
13156 /// set of instantiations of each parameter.
13157 ///
13158 /// This mapping is a temporary data structure used when parsing
13159 /// nested class templates or nested classes of class templates,
13160 /// where we might end up instantiating an inner class before the
13161 /// default arguments of its methods have been parsed.
13163
13164 using InstantiatingSpecializationsKey = llvm::PointerIntPair<Decl *, 2>;
13165
13172
13174 : S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
13175 auto [_, Created] = S.InstantiatingSpecializations.insert(Key);
13176 if (!Created)
13177 Key = {};
13178 }
13179
13181 if (Key.getOpaqueValue()) {
13182 [[maybe_unused]] bool Erased =
13183 S.InstantiatingSpecializations.erase(Key);
13184 assert(Erased);
13185 }
13186 }
13187
13190
13191 operator bool() const { return Key.getOpaqueValue() == nullptr; }
13192
13193 private:
13194 Sema &S;
13196 };
13197
13198 /// A context in which code is being synthesized (where a source location
13199 /// alone is not sufficient to identify the context). This covers template
13200 /// instantiation and various forms of implicitly-generated functions.
13202 /// The kind of template instantiation we are performing
13204 /// We are instantiating a template declaration. The entity is
13205 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
13207
13208 /// We are instantiating a default argument for a template
13209 /// parameter. The Entity is the template parameter whose argument is
13210 /// being instantiated, the Template is the template, and the
13211 /// TemplateArgs/NumTemplateArguments provide the template arguments as
13212 /// specified.
13214
13215 /// We are instantiating a default argument for a function.
13216 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
13217 /// provides the template arguments as specified.
13219
13220 /// We are substituting explicit template arguments provided for
13221 /// a function template. The entity is a FunctionTemplateDecl.
13223
13224 /// We are substituting template argument determined as part of
13225 /// template argument deduction for either a class template
13226 /// partial specialization or a function template. The
13227 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
13228 /// a TemplateDecl.
13230
13231 /// We are substituting into a lambda expression.
13233
13234 /// We are substituting prior template arguments into a new
13235 /// template parameter. The template parameter itself is either a
13236 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
13238
13239 /// We are checking the validity of a default template argument that
13240 /// has been used when naming a template-id.
13242
13243 /// We are computing the exception specification for a defaulted special
13244 /// member function.
13246
13247 /// We are instantiating the exception specification for a function
13248 /// template which was deferred until it was needed.
13250
13251 /// We are instantiating a requirement of a requires expression.
13253
13254 /// We are checking the satisfaction of a nested requirement of a requires
13255 /// expression.
13257
13258 /// We are declaring an implicit special member function.
13260
13261 /// We are declaring an implicit 'operator==' for a defaulted
13262 /// 'operator<=>'.
13264
13265 /// We are defining a synthesized function (such as a defaulted special
13266 /// member).
13268
13269 // We are checking the constraints associated with a constrained entity or
13270 // the constraint expression of a concept. This includes the checks that
13271 // atomic constraints have the type 'bool' and that they can be constant
13272 // evaluated.
13274
13275 // We are substituting template arguments into a constraint expression.
13277
13278 // Instantiating a Requires Expression parameter clause.
13280
13281 // We are substituting into the parameter mapping of an atomic constraint
13282 // during normalization.
13284
13285 /// We are rewriting a comparison operator in terms of an operator<=>.
13287
13288 /// We are initializing a structured binding.
13290
13291 /// We are marking a class as __dllexport.
13293
13294 /// We are building an implied call from __builtin_dump_struct. The
13295 /// arguments are in CallArgs.
13297
13298 /// Added for Template instantiation observation.
13299 /// Memoization means we are _not_ instantiating a template because
13300 /// it is already instantiated (but we entered a context where we
13301 /// would have had to if it was not already instantiated).
13303
13304 /// We are building deduction guides for a class.
13306
13307 /// We are instantiating a type alias template declaration.
13309
13310 /// We are performing partial ordering for template template parameters.
13312
13313 /// We are performing name lookup for a function template or variable
13314 /// template named 'sycl_kernel_launch'.
13316
13317 /// We are performing overload resolution for a call to a function
13318 /// template or variable template named 'sycl_kernel_launch'.
13320
13321 /// We are instantiating an expansion statement.
13323 } Kind;
13324
13325 /// Whether we're substituting into constraints.
13327
13328 /// Whether we're substituting into the parameter mapping of a constraint.
13330
13331 /// The point of instantiation or synthesis within the source code.
13333
13334 /// The entity that is being synthesized.
13336
13337 /// The template (or partial specialization) in which we are
13338 /// performing the instantiation, for substitutions of prior template
13339 /// arguments.
13341
13342 union {
13343 /// The list of template arguments we are substituting, if they
13344 /// are not part of the entity.
13346
13347 /// The list of argument expressions in a synthesized call.
13348 const Expr *const *CallArgs;
13349 };
13350
13351 // FIXME: Wrap this union around more members, or perhaps store the
13352 // kind-specific members in the RAII object owning the context.
13353 union {
13354 /// The number of template arguments in TemplateArgs.
13356
13357 /// The number of expressions in CallArgs.
13358 unsigned NumCallArgs;
13359
13360 /// The special member being declared or defined.
13362 };
13363
13368
13369 /// The source range that covers the construct that cause
13370 /// the instantiation, e.g., the template-id that causes a class
13371 /// template instantiation.
13373
13378
13379 /// Determines whether this template is an actual instantiation
13380 /// that should be counted toward the maximum instantiation depth.
13381 bool isInstantiationRecord() const;
13382 };
13383
13384 /// A stack object to be created when performing template
13385 /// instantiation.
13386 ///
13387 /// Construction of an object of type \c InstantiatingTemplate
13388 /// pushes the current instantiation onto the stack of active
13389 /// instantiations. If the size of this stack exceeds the maximum
13390 /// number of recursive template instantiations, construction
13391 /// produces an error and evaluates true.
13392 ///
13393 /// Destruction of this object will pop the named instantiation off
13394 /// the stack.
13396 /// Note that we are instantiating a class template,
13397 /// function template, variable template, alias template,
13398 /// or a member thereof.
13399 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13400 Decl *Entity,
13401 SourceRange InstantiationRange = SourceRange());
13402
13404 /// Note that we are instantiating an exception specification
13405 /// of a function template.
13406 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13408 SourceRange InstantiationRange = SourceRange());
13409
13410 /// Note that we are instantiating a type alias template declaration.
13411 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13412 TypeAliasTemplateDecl *Entity,
13413 ArrayRef<TemplateArgument> TemplateArgs,
13414 SourceRange InstantiationRange = SourceRange());
13415
13416 /// Note that we are instantiating a default argument in a
13417 /// template-id.
13418 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13420 ArrayRef<TemplateArgument> TemplateArgs,
13421 SourceRange InstantiationRange = SourceRange());
13422
13423 /// Note that we are substituting either explicitly-specified or
13424 /// deduced template arguments during function template argument deduction.
13425 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13427 ArrayRef<TemplateArgument> TemplateArgs,
13429 SourceRange InstantiationRange = SourceRange());
13430
13431 /// Note that we are instantiating as part of template
13432 /// argument deduction for a class template declaration.
13433 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13435 ArrayRef<TemplateArgument> TemplateArgs,
13436 SourceRange InstantiationRange = SourceRange());
13437
13438 /// Note that we are instantiating as part of template
13439 /// argument deduction for a class template partial
13440 /// specialization.
13441 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13443 ArrayRef<TemplateArgument> TemplateArgs,
13444 SourceRange InstantiationRange = SourceRange());
13445
13446 /// Note that we are instantiating as part of template
13447 /// argument deduction for a variable template partial
13448 /// specialization.
13449 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13451 ArrayRef<TemplateArgument> TemplateArgs,
13452 SourceRange InstantiationRange = SourceRange());
13453
13454 /// Note that we are instantiating a default argument for a function
13455 /// parameter.
13456 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13457 ParmVarDecl *Param,
13458 ArrayRef<TemplateArgument> TemplateArgs,
13459 SourceRange InstantiationRange = SourceRange());
13460
13461 /// Note that we are substituting prior template arguments into a
13462 /// non-type parameter.
13463 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13465 ArrayRef<TemplateArgument> TemplateArgs,
13466 SourceRange InstantiationRange);
13467
13468 /// Note that we are substituting prior template arguments into a
13469 /// template template parameter.
13470 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13472 ArrayRef<TemplateArgument> TemplateArgs,
13473 SourceRange InstantiationRange);
13474
13475 /// Note that we are checking the default template argument
13476 /// against the template parameter for a given template-id.
13477 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13479 ArrayRef<TemplateArgument> TemplateArgs,
13480 SourceRange InstantiationRange);
13481
13483 /// \brief Note that we are checking the constraints associated with some
13484 /// constrained entity (a concept declaration or a template with associated
13485 /// constraints).
13486 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13488 ArrayRef<TemplateArgument> TemplateArgs,
13489 SourceRange InstantiationRange);
13490
13492 /// \brief Note that we are checking a constraint expression associated
13493 /// with a template declaration or as part of the satisfaction check of a
13494 /// concept.
13495 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13497 SourceRange InstantiationRange);
13498
13500 /// \brief Note that we are subtituting into the parameter mapping of an
13501 /// atomic constraint during constraint normalization.
13502 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13504 SourceRange InstantiationRange);
13505
13506 /// \brief Note that we are substituting template arguments into a part of
13507 /// a requirement of a requires expression.
13508 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13510 SourceRange InstantiationRange = SourceRange());
13511
13512 /// \brief Note that we are substituting the body of an expansion statement.
13513 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13514 CXXExpansionStmtPattern *ExpansionStmt,
13516 SourceRange InstantiationRange);
13517
13518 /// \brief Note that we are checking the satisfaction of the constraint
13519 /// expression inside of a nested requirement.
13520 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13522 SourceRange InstantiationRange = SourceRange());
13523
13524 /// \brief Note that we are checking a requires clause.
13525 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13526 const RequiresExpr *E,
13527 SourceRange InstantiationRange);
13528
13530 /// \brief Note that we are building deduction guides.
13531 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13533 SourceRange InstantiationRange = SourceRange());
13534
13536 /// \brief Note that we are partial ordering template template parameters.
13537 InstantiatingTemplate(Sema &SemaRef, SourceLocation ArgLoc,
13539 SourceRange InstantiationRange = SourceRange());
13540
13541 /// Note that we have finished instantiating this template.
13542 void Clear();
13543
13545
13546 /// Determines whether we have exceeded the maximum
13547 /// recursive template instantiations.
13548 bool isInvalid() const { return Invalid; }
13549
13550 private:
13551 Sema &SemaRef;
13552 bool Invalid;
13553
13556 SourceLocation PointOfInstantiation,
13557 SourceRange InstantiationRange, Decl *Entity,
13558 NamedDecl *Template = nullptr,
13559 ArrayRef<TemplateArgument> TemplateArgs = {});
13560
13562
13563 InstantiatingTemplate &operator=(const InstantiatingTemplate &) = delete;
13564 };
13565
13566 bool SubstTemplateArgument(const TemplateArgumentLoc &Input,
13567 const MultiLevelTemplateArgumentList &TemplateArgs,
13568 TemplateArgumentLoc &Output,
13569 SourceLocation Loc = {},
13570 const DeclarationName &Entity = {});
13571 bool
13572 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
13573 const MultiLevelTemplateArgumentList &TemplateArgs,
13574 TemplateArgumentListInfo &Outputs);
13575
13576 /// Substitute concept template arguments in the constraint expression
13577 /// of a concept-id. This is used to implement [temp.constr.normal].
13579 SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE,
13580 const Expr *ConstraintExpr,
13581 const MultiLevelTemplateArgumentList &MLTAL);
13582
13584 ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,
13585 const MultiLevelTemplateArgumentList &TemplateArgs,
13586 TemplateArgumentListInfo &Out);
13587
13588 /// Retrieve the template argument list(s) that should be used to
13589 /// instantiate the definition of the given declaration.
13590 ///
13591 /// \param ND the declaration for which we are computing template
13592 /// instantiation arguments.
13593 ///
13594 /// \param DC In the event we don't HAVE a declaration yet, we instead provide
13595 /// the decl context where it will be created. In this case, the `Innermost`
13596 /// should likely be provided. If ND is non-null, this is ignored.
13597 ///
13598 /// \param Innermost if non-NULL, specifies a template argument list for the
13599 /// template declaration passed as ND.
13600 ///
13601 /// \param RelativeToPrimary true if we should get the template
13602 /// arguments relative to the primary template, even when we're
13603 /// dealing with a specialization. This is only relevant for function
13604 /// template specializations.
13605 ///
13606 /// \param Pattern If non-NULL, indicates the pattern from which we will be
13607 /// instantiating the definition of the given declaration, \p ND. This is
13608 /// used to determine the proper set of template instantiation arguments for
13609 /// friend function template specializations.
13610 ///
13611 /// \param ForConstraintInstantiation when collecting arguments,
13612 /// ForConstraintInstantiation indicates we should continue looking when
13613 /// encountering a lambda generic call operator, and continue looking for
13614 /// arguments on an enclosing class template.
13615 ///
13616 /// \param SkipForSpecialization when specified, any template specializations
13617 /// in a traversal would be ignored.
13618 ///
13619 /// \param ForDefaultArgumentSubstitution indicates we should continue looking
13620 /// when encountering a specialized member function template, rather than
13621 /// returning immediately.
13622 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
13623 const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
13624 std::optional<ArrayRef<TemplateArgument>> Innermost = std::nullopt,
13625 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr,
13626 bool ForConstraintInstantiation = false,
13627 bool SkipForSpecialization = false,
13628 bool ForDefaultArgumentSubstitution = false);
13629
13630 /// RAII object to handle the state changes required to synthesize
13631 /// a function body.
13633 Sema &S;
13634 Sema::ContextRAII SavedContext;
13635 bool PushedCodeSynthesisContext = false;
13636
13637 public:
13639 : S(S), SavedContext(S, DC) {
13640 auto *FD = dyn_cast<FunctionDecl>(DC);
13641 S.PushFunctionScope();
13642 S.PushExpressionEvaluationContextForFunction(
13644 if (FD)
13645 FD->setWillHaveBody(true);
13646 else
13647 assert(isa<ObjCMethodDecl>(DC));
13648 }
13649
13651 assert(!PushedCodeSynthesisContext);
13652
13655 Ctx.PointOfInstantiation = UseLoc;
13656 Ctx.Entity = cast<Decl>(S.CurContext);
13657 S.pushCodeSynthesisContext(Ctx);
13658
13659 PushedCodeSynthesisContext = true;
13660 }
13661
13663 if (PushedCodeSynthesisContext)
13664 S.popCodeSynthesisContext();
13665 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
13666 FD->setWillHaveBody(false);
13667 S.CheckImmediateEscalatingFunctionDefinition(FD, S.getCurFunction());
13668 }
13669 S.PopExpressionEvaluationContext();
13670 S.PopFunctionScopeInfo();
13671 }
13672
13676 };
13677
13678 /// RAII object to ensure that a code synthesis context is popped on scope
13679 /// exit.
13681 Sema &S;
13682
13683 public:
13685 : S(S) {
13686 S.pushCodeSynthesisContext(Ctx);
13687 }
13688
13689 ~ScopedCodeSynthesisContext() { S.popCodeSynthesisContext(); }
13693 };
13694
13695 /// List of active code synthesis contexts.
13696 ///
13697 /// This vector is treated as a stack. As synthesis of one entity requires
13698 /// synthesis of another, additional contexts are pushed onto the stack.
13700
13701 /// Specializations whose definitions are currently being instantiated.
13702 llvm::DenseSet<InstantiatingSpecializationsKey> InstantiatingSpecializations;
13703
13704 /// Non-dependent types used in templates that have already been instantiated
13705 /// by some template instantiation.
13706 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
13707
13708 /// Extra modules inspected when performing a lookup during a template
13709 /// instantiation. Computed lazily.
13711
13712 /// Cache of additional modules that should be used for name lookup
13713 /// within the current template instantiation. Computed lazily; use
13714 /// getLookupModules() to get a complete set.
13715 llvm::DenseSet<Module *> LookupModulesCache;
13716
13717 /// Map from the most recent declaration of a namespace to the most
13718 /// recent visible declaration of that namespace.
13719 llvm::DenseMap<NamedDecl *, NamedDecl *> VisibleNamespaceCache;
13720
13722
13723 /// The number of \p CodeSynthesisContexts that are not template
13724 /// instantiations and, therefore, should not be counted as part of the
13725 /// instantiation depth.
13726 ///
13727 /// When the instantiation depth reaches the user-configurable limit
13728 /// \p LangOptions::InstantiationDepth we will abort instantiation.
13729 // FIXME: Should we have a similar limit for other forms of synthesis?
13731
13732 /// The depth of the context stack at the point when the most recent
13733 /// error or warning was produced.
13734 ///
13735 /// This value is used to suppress printing of redundant context stacks
13736 /// when there are multiple errors or warnings in the same instantiation.
13737 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
13739
13740 /// The current index into pack expansion arguments that will be
13741 /// used for substitution of parameter packs.
13742 ///
13743 /// The pack expansion index will be none to indicate that parameter packs
13744 /// should be instantiated as themselves. Otherwise, the index specifies
13745 /// which argument within the parameter pack will be used for substitution.
13747
13748 /// RAII object used to change the argument pack substitution index
13749 /// within a \c Sema object.
13750 ///
13751 /// See \c ArgPackSubstIndex for more information.
13753 Sema &Self;
13754 UnsignedOrNone OldSubstIndex;
13755
13756 public:
13758 : Self(Self),
13759 OldSubstIndex(std::exchange(Self.ArgPackSubstIndex, NewSubstIndex)) {}
13760
13761 ~ArgPackSubstIndexRAII() { Self.ArgPackSubstIndex = OldSubstIndex; }
13764 };
13765
13768
13779 /// Prints the current instantiation stack through a series of
13780 /// notes.
13785
13786 /// Returns a pointer to the current SFINAE context, if any.
13787 [[nodiscard]] SFINAETrap *getSFINAEContext() const {
13788 return CurrentSFINAEContext;
13789 }
13790 [[nodiscard]] bool isSFINAEContext() const {
13791 return CurrentSFINAEContext != nullptr;
13792 }
13793
13794 /// Perform substitution on the type T with a given set of template
13795 /// arguments.
13796 ///
13797 /// This routine substitutes the given template arguments into the
13798 /// type T and produces the instantiated type.
13799 ///
13800 /// \param T the type into which the template arguments will be
13801 /// substituted. If this type is not dependent, it will be returned
13802 /// immediately.
13803 ///
13804 /// \param Args the template arguments that will be
13805 /// substituted for the top-level template parameters within T.
13806 ///
13807 /// \param Loc the location in the source code where this substitution
13808 /// is being performed. It will typically be the location of the
13809 /// declarator (if we're instantiating the type of some declaration)
13810 /// or the location of the type in the source code (if, e.g., we're
13811 /// instantiating the type of a cast expression).
13812 ///
13813 /// \param Entity the name of the entity associated with a declaration
13814 /// being instantiated (if any). May be empty to indicate that there
13815 /// is no such entity (if, e.g., this is a type that occurs as part of
13816 /// a cast expression) or that the entity has no name (e.g., an
13817 /// unnamed function parameter).
13818 ///
13819 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
13820 /// acceptable as the top level type of the result.
13821 ///
13822 /// \param IsIncompleteSubstitution If provided, the pointee will be set
13823 /// whenever substitution would perform a replacement with a null or
13824 /// non-existent template argument.
13825 ///
13826 /// \returns If the instantiation succeeds, the instantiated
13827 /// type. Otherwise, produces diagnostics and returns a NULL type.
13829 const MultiLevelTemplateArgumentList &TemplateArgs,
13830 SourceLocation Loc, DeclarationName Entity,
13831 bool AllowDeducedTST = false);
13832
13834 const MultiLevelTemplateArgumentList &TemplateArgs,
13835 SourceLocation Loc, DeclarationName Entity,
13836 bool *IsIncompleteSubstitution = nullptr);
13837
13839 const MultiLevelTemplateArgumentList &TemplateArgs,
13840 SourceLocation Loc, DeclarationName Entity);
13841
13844 const MultiLevelTemplateArgumentList &TemplateArgs,
13845 SourceLocation Loc, DeclarationName Entity);
13846
13847 /// A form of SubstType intended specifically for instantiating the
13848 /// type of a FunctionDecl. Its purpose is solely to force the
13849 /// instantiation of default-argument expressions and to avoid
13850 /// instantiating an exception-specification.
13852 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
13853 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
13854 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
13856 const MultiLevelTemplateArgumentList &Args);
13859 SmallVectorImpl<QualType> &ExceptionStorage,
13860 const MultiLevelTemplateArgumentList &Args);
13861 ParmVarDecl *
13863 const MultiLevelTemplateArgumentList &TemplateArgs,
13864 int indexAdjustment, UnsignedOrNone NumExpansions,
13865 bool ExpectParameterPack, bool EvaluateConstraints = true);
13866
13867 /// Substitute the given template arguments into the given set of
13868 /// parameters, producing the set of parameter types that would be generated
13869 /// from such a substitution.
13871 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
13872 const MultiLevelTemplateArgumentList &TemplateArgs,
13873 SmallVectorImpl<QualType> &ParamTypes,
13875 ExtParameterInfoBuilder &ParamInfos);
13876
13877 /// Substitute the given template arguments into the default argument.
13879 const MultiLevelTemplateArgumentList &TemplateArgs,
13880 bool ForCallExpr = false);
13882 const MultiLevelTemplateArgumentList &TemplateArgs);
13883 /// Substitute an expression as if it is a address-of-operand, which makes it
13884 /// act like a CXXIdExpression rather than an attempt to call.
13886 const MultiLevelTemplateArgumentList &TemplateArgs);
13887
13888 // Must be used instead of SubstExpr at 'constraint checking' time.
13891 const MultiLevelTemplateArgumentList &TemplateArgs);
13892 // Unlike the above, this does not evaluate constraints.
13894 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs);
13895
13896 /// Substitute the given template arguments into a list of
13897 /// expressions, expanding pack expansions if required.
13898 ///
13899 /// \param Exprs The list of expressions to substitute into.
13900 ///
13901 /// \param IsCall Whether this is some form of call, in which case
13902 /// default arguments will be dropped.
13903 ///
13904 /// \param TemplateArgs The set of template arguments to substitute.
13905 ///
13906 /// \param Outputs Will receive all of the substituted arguments.
13907 ///
13908 /// \returns true if an error occurred, false otherwise.
13909 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
13910 const MultiLevelTemplateArgumentList &TemplateArgs,
13911 SmallVectorImpl<Expr *> &Outputs);
13912
13914 const MultiLevelTemplateArgumentList &TemplateArgs);
13915
13918 bool CXXDirectInit);
13919
13920 /// Perform substitution on the base class specifiers of the
13921 /// given class template specialization.
13922 ///
13923 /// Produces a diagnostic and returns true on error, returns false and
13924 /// attaches the instantiated base classes to the class template
13925 /// specialization if successful.
13926 bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13927 const MultiLevelTemplateArgumentList &TemplateArgs);
13928
13929 /// Instantiate the definition of a class from a given pattern.
13930 ///
13931 /// \param PointOfInstantiation The point of instantiation within the
13932 /// source code.
13933 ///
13934 /// \param Instantiation is the declaration whose definition is being
13935 /// instantiated. This will be either a class template specialization
13936 /// or a member class of a class template specialization.
13937 ///
13938 /// \param Pattern is the pattern from which the instantiation
13939 /// occurs. This will be either the declaration of a class template or
13940 /// the declaration of a member class of a class template.
13941 ///
13942 /// \param TemplateArgs The template arguments to be substituted into
13943 /// the pattern.
13944 ///
13945 /// \param TSK the kind of implicit or explicit instantiation to perform.
13946 ///
13947 /// \param Complain whether to complain if the class cannot be instantiated
13948 /// due to the lack of a definition.
13949 ///
13950 /// \returns true if an error occurred, false otherwise.
13951 bool InstantiateClass(SourceLocation PointOfInstantiation,
13952 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13953 const MultiLevelTemplateArgumentList &TemplateArgs,
13954 TemplateSpecializationKind TSK, bool Complain = true);
13955
13956private:
13957 bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
13958 CXXRecordDecl *Instantiation,
13959 CXXRecordDecl *Pattern,
13960 const MultiLevelTemplateArgumentList &TemplateArgs,
13961 TemplateSpecializationKind TSK, bool Complain);
13962
13963public:
13964 /// Instantiate the definition of an enum from a given pattern.
13965 ///
13966 /// \param PointOfInstantiation The point of instantiation within the
13967 /// source code.
13968 /// \param Instantiation is the declaration whose definition is being
13969 /// instantiated. This will be a member enumeration of a class
13970 /// temploid specialization, or a local enumeration within a
13971 /// function temploid specialization.
13972 /// \param Pattern The templated declaration from which the instantiation
13973 /// occurs.
13974 /// \param TemplateArgs The template arguments to be substituted into
13975 /// the pattern.
13976 /// \param TSK The kind of implicit or explicit instantiation to perform.
13977 ///
13978 /// \return \c true if an error occurred, \c false otherwise.
13979 bool InstantiateEnum(SourceLocation PointOfInstantiation,
13980 EnumDecl *Instantiation, EnumDecl *Pattern,
13981 const MultiLevelTemplateArgumentList &TemplateArgs,
13983
13984 /// Instantiate the definition of a field from the given pattern.
13985 ///
13986 /// \param PointOfInstantiation The point of instantiation within the
13987 /// source code.
13988 /// \param Instantiation is the declaration whose definition is being
13989 /// instantiated. This will be a class of a class temploid
13990 /// specialization, or a local enumeration within a function temploid
13991 /// specialization.
13992 /// \param Pattern The templated declaration from which the instantiation
13993 /// occurs.
13994 /// \param TemplateArgs The template arguments to be substituted into
13995 /// the pattern.
13996 ///
13997 /// \return \c true if an error occurred, \c false otherwise.
13999 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
14000 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
14001
14003 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
14004
14006 SourceLocation PointOfInstantiation,
14007 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14008 TemplateSpecializationKind TSK, bool Complain,
14009 bool PrimaryStrictPackMatch);
14010
14011 /// Instantiates the definitions of all of the member
14012 /// of the given class, which is an instantiation of a class template
14013 /// or a member class of a template.
14014 void
14015 InstantiateClassMembers(SourceLocation PointOfInstantiation,
14016 CXXRecordDecl *Instantiation,
14017 const MultiLevelTemplateArgumentList &TemplateArgs,
14019
14020 /// Instantiate the definitions of all of the members of the
14021 /// given class template specialization, which was named as part of an
14022 /// explicit instantiation.
14024 SourceLocation PointOfInstantiation,
14025 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14027
14030 const MultiLevelTemplateArgumentList &TemplateArgs);
14031
14032 /// Do template substitution on declaration name info.
14035 const MultiLevelTemplateArgumentList &TemplateArgs);
14037 SubstTemplateName(SourceLocation TemplateKWLoc,
14038 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
14039 SourceLocation NameLoc,
14040 const MultiLevelTemplateArgumentList &TemplateArgs);
14041
14043 const MultiLevelTemplateArgumentList &TemplateArgs,
14044 bool EvaluateConstraint);
14045
14046 /// Determine whether we are currently performing template instantiation.
14049 }
14050
14051 /// Determine whether we are currently performing constraint substitution.
14053 return !CodeSynthesisContexts.empty() &&
14054 CodeSynthesisContexts.back().InConstraintSubstitution;
14055 }
14056
14058 return !CodeSynthesisContexts.empty() &&
14059 CodeSynthesisContexts.back().InParameterMappingSubstitution &&
14061 }
14062
14063 using EntityPrinter = llvm::function_ref<void(llvm::raw_ostream &)>;
14064
14065 /// \brief create a Requirement::SubstitutionDiagnostic with only a
14066 /// SubstitutedEntity and DiagLoc using ASTContext's allocator.
14069
14070 ///@}
14071
14072 //
14073 //
14074 // -------------------------------------------------------------------------
14075 //
14076 //
14077
14078 /// \name C++ Template Declaration Instantiation
14079 /// Implementations are in SemaTemplateInstantiateDecl.cpp
14080 ///@{
14081
14082public:
14083 /// An entity for which implicit template instantiation is required.
14084 ///
14085 /// The source location associated with the declaration is the first place in
14086 /// the source code where the declaration was "used". It is not necessarily
14087 /// the point of instantiation (which will be either before or after the
14088 /// namespace-scope declaration that triggered this implicit instantiation),
14089 /// However, it is the location that diagnostics should generally refer to,
14090 /// because users will need to know what code triggered the instantiation.
14091 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
14092
14093 /// The queue of implicit template instantiations that are required
14094 /// but have not yet been performed.
14095 std::deque<PendingImplicitInstantiation> PendingInstantiations;
14096
14097 /// Queue of implicit template instantiations that cannot be performed
14098 /// eagerly.
14100
14104
14105 /// The queue of implicit template instantiations that are required
14106 /// and must be performed within the current local scope.
14107 ///
14108 /// This queue is only used for member functions of local classes in
14109 /// templates, which must be instantiated in the same scope as their
14110 /// enclosing function, so that they can reference function-local
14111 /// types, static variables, enumerators, etc.
14112 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
14113
14115 public:
14117 : S(S), AtEndOfTU(AtEndOfTU) {
14118 SavedPendingLocalImplicitInstantiations.swap(
14119 S.PendingLocalImplicitInstantiations);
14120 }
14121
14122 void perform() {
14123 S.PerformPendingInstantiations(/*LocalOnly=*/true,
14124 /*AtEndOfTU=*/AtEndOfTU);
14125 }
14126
14128 assert(S.PendingLocalImplicitInstantiations.empty() &&
14129 "there shouldn't be any pending local implicit instantiations");
14130 SavedPendingLocalImplicitInstantiations.swap(
14131 S.PendingLocalImplicitInstantiations);
14132 }
14133
14137
14138 private:
14139 Sema &S;
14140 bool AtEndOfTU;
14141 std::deque<PendingImplicitInstantiation>
14142 SavedPendingLocalImplicitInstantiations;
14143 };
14144
14145 /// Records and restores the CurFPFeatures state on entry/exit of compound
14146 /// statements.
14148 public:
14153 FPOptionsOverride getOverrides() { return OldOverrides; }
14154
14155 private:
14156 Sema &S;
14157 FPOptions OldFPFeaturesState;
14158 FPOptionsOverride OldOverrides;
14159 LangOptions::FPEvalMethodKind OldEvalMethod;
14160 SourceLocation OldFPPragmaLocation;
14161 };
14162
14164 public:
14165 GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
14166 : S(S), Enabled(Enabled), AtEndOfTU(AtEndOfTU) {
14167 if (!Enabled)
14168 return;
14169
14170 S.SavedPendingInstantiations.emplace_back();
14171 S.SavedPendingInstantiations.back().swap(S.PendingInstantiations);
14172
14173 S.SavedVTableUses.emplace_back();
14174 S.SavedVTableUses.back().swap(S.VTableUses);
14175 }
14176
14177 void perform() {
14178 if (Enabled) {
14179 S.DefineUsedVTables();
14180 S.PerformPendingInstantiations(/*LocalOnly=*/false,
14181 /*AtEndOfTU=*/AtEndOfTU);
14182 }
14183 }
14184
14186 if (!Enabled)
14187 return;
14188
14189 // Restore the set of pending vtables.
14190 assert(S.VTableUses.empty() &&
14191 "VTableUses should be empty before it is discarded.");
14192 S.VTableUses.swap(S.SavedVTableUses.back());
14193 S.SavedVTableUses.pop_back();
14194
14195 // Restore the set of pending implicit instantiations.
14196 if ((S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) &&
14197 AtEndOfTU) {
14198 assert(S.PendingInstantiations.empty() &&
14199 "PendingInstantiations should be empty before it is discarded.");
14200 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
14201 S.SavedPendingInstantiations.pop_back();
14202 } else {
14203 // Template instantiations in the PCH may be delayed until the TU.
14204 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
14205 S.PendingInstantiations.insert(
14206 S.PendingInstantiations.end(),
14207 S.SavedPendingInstantiations.back().begin(),
14208 S.SavedPendingInstantiations.back().end());
14209 S.SavedPendingInstantiations.pop_back();
14210 }
14211 }
14212
14214 delete;
14217
14218 private:
14219 Sema &S;
14220 bool Enabled;
14221 bool AtEndOfTU;
14222 };
14223
14225 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES);
14226
14237
14238 /// Recheck instantiated thread-safety attributes that could not be validated
14239 /// on the dependent pattern declaration.
14240 bool checkInstantiatedThreadSafetyAttrs(const Decl *D, const Attr *A);
14241
14242 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
14243 const Decl *Pattern, Decl *Inst,
14244 LateInstantiatedAttrVec *LateAttrs = nullptr,
14245 LocalInstantiationScope *OuterMostScope = nullptr);
14246
14247 /// Update instantiation attributes after template was late parsed.
14248 ///
14249 /// Some attributes are evaluated based on the body of template. If it is
14250 /// late parsed, such attributes cannot be evaluated when declaration is
14251 /// instantiated. This function is used to update instantiation attributes
14252 /// when template definition is ready.
14253 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
14254
14255 void
14257 const Decl *Pattern, Decl *Inst,
14258 LateInstantiatedAttrVec *LateAttrs = nullptr,
14259 LocalInstantiationScope *OuterMostScope = nullptr);
14260
14262 bool IsCopy = false);
14263
14265 ParmVarDecl *Param);
14266 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
14268
14269 /// Instantiate (or find existing instantiation of) a function template with a
14270 /// given set of template arguments.
14271 ///
14272 /// Usually this should not be used, and template argument deduction should be
14273 /// used in its place.
14276 SourceLocation Loc,
14279
14280 /// Instantiate the definition of the given function from its
14281 /// template.
14282 ///
14283 /// \param PointOfInstantiation the point at which the instantiation was
14284 /// required. Note that this is not precisely a "point of instantiation"
14285 /// for the function, but it's close.
14286 ///
14287 /// \param Function the already-instantiated declaration of a
14288 /// function template specialization or member function of a class template
14289 /// specialization.
14290 ///
14291 /// \param Recursive if true, recursively instantiates any functions that
14292 /// are required by this instantiation.
14293 ///
14294 /// \param DefinitionRequired if true, then we are performing an explicit
14295 /// instantiation where the body of the function is required. Complain if
14296 /// there is no such body.
14297 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
14299 bool Recursive = false,
14300 bool DefinitionRequired = false,
14301 bool AtEndOfTU = false);
14304 const TemplateArgumentList *PartialSpecArgs,
14306 SourceLocation PointOfInstantiation,
14307 LateInstantiatedAttrVec *LateAttrs = nullptr,
14308 LocalInstantiationScope *StartingScope = nullptr);
14309
14310 /// Instantiates a variable template specialization by completing it
14311 /// with appropriate type information and initializer.
14313 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
14314 const MultiLevelTemplateArgumentList &TemplateArgs);
14315
14316 /// BuildVariableInstantiation - Used after a new variable has been created.
14317 /// Sets basic variable data and decides whether to postpone the
14318 /// variable instantiation.
14319 void
14321 const MultiLevelTemplateArgumentList &TemplateArgs,
14322 LateInstantiatedAttrVec *LateAttrs,
14323 DeclContext *Owner,
14324 LocalInstantiationScope *StartingScope,
14325 bool InstantiatingVarTemplate = false,
14326 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
14327
14328 /// Instantiate the initializer of a variable.
14330 VarDecl *Var, VarDecl *OldVar,
14331 const MultiLevelTemplateArgumentList &TemplateArgs);
14332
14333 /// Instantiate the definition of the given variable from its
14334 /// template.
14335 ///
14336 /// \param PointOfInstantiation the point at which the instantiation was
14337 /// required. Note that this is not precisely a "point of instantiation"
14338 /// for the variable, but it's close.
14339 ///
14340 /// \param Var the already-instantiated declaration of a templated variable.
14341 ///
14342 /// \param Recursive if true, recursively instantiates any functions that
14343 /// are required by this instantiation.
14344 ///
14345 /// \param DefinitionRequired if true, then we are performing an explicit
14346 /// instantiation where a definition of the variable is required. Complain
14347 /// if there is no such definition.
14348 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
14349 VarDecl *Var, bool Recursive = false,
14350 bool DefinitionRequired = false,
14351 bool AtEndOfTU = false);
14352
14355 const MultiLevelTemplateArgumentList &TemplateArgs);
14356
14357 /// Find the instantiation of the given declaration within the
14358 /// current instantiation.
14359 ///
14360 /// This routine is intended to be used when \p D is a declaration
14361 /// referenced from within a template, that needs to mapped into the
14362 /// corresponding declaration within an instantiation. For example,
14363 /// given:
14364 ///
14365 /// \code
14366 /// template<typename T>
14367 /// struct X {
14368 /// enum Kind {
14369 /// KnownValue = sizeof(T)
14370 /// };
14371 ///
14372 /// bool getKind() const { return KnownValue; }
14373 /// };
14374 ///
14375 /// template struct X<int>;
14376 /// \endcode
14377 ///
14378 /// In the instantiation of X<int>::getKind(), we need to map the \p
14379 /// EnumConstantDecl for \p KnownValue (which refers to
14380 /// X<T>::<Kind>::KnownValue) to its instantiation
14381 /// (X<int>::<Kind>::KnownValue).
14382 /// \p FindInstantiatedDecl performs this mapping from within the
14383 /// instantiation of X<int>.
14384 NamedDecl *
14386 const MultiLevelTemplateArgumentList &TemplateArgs,
14387 bool FindingInstantiatedContext = false);
14388
14389 /// Finds the instantiation of the given declaration context
14390 /// within the current instantiation.
14391 ///
14392 /// \returns NULL if there was an error
14393 DeclContext *
14395 const MultiLevelTemplateArgumentList &TemplateArgs);
14396
14397 Decl *SubstDecl(Decl *D, DeclContext *Owner,
14398 const MultiLevelTemplateArgumentList &TemplateArgs);
14399
14400 /// Substitute the name and return type of a defaulted 'operator<=>' to form
14401 /// an implicit 'operator=='.
14403 FunctionDecl *Spaceship);
14404
14405 /// Performs template instantiation for all implicit template
14406 /// instantiations we have seen until this point.
14407 void PerformPendingInstantiations(bool LocalOnly = false,
14408 bool AtEndOfTU = true);
14409
14412 const MultiLevelTemplateArgumentList &TemplateArgs,
14413 bool EvaluateConstraints = true);
14414
14416 const DeclContext *Pattern,
14417 const MultiLevelTemplateArgumentList &TemplateArgs);
14418
14419private:
14420 /// Introduce the instantiated local variables into the local
14421 /// instantiation scope.
14422 void addInstantiatedLocalVarsToScope(FunctionDecl *Function,
14423 const FunctionDecl *PatternDecl,
14425 /// Introduce the instantiated function parameters into the local
14426 /// instantiation scope, and set the parameter names to those used
14427 /// in the template.
14428 bool addInstantiatedParametersToScope(
14429 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14431 const MultiLevelTemplateArgumentList &TemplateArgs);
14432
14433 /// Introduce the instantiated captures of the lambda into the local
14434 /// instantiation scope.
14435 bool addInstantiatedCapturesToScope(
14436 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14438 const MultiLevelTemplateArgumentList &TemplateArgs);
14439
14440 int ParsingClassDepth = 0;
14441
14442 class SavePendingParsedClassStateRAII {
14443 public:
14444 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
14445
14446 ~SavePendingParsedClassStateRAII() {
14447 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
14448 "there shouldn't be any pending delayed exception spec checks");
14449 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
14450 "there shouldn't be any pending delayed exception spec checks");
14451 swapSavedState();
14452 }
14453
14454 SavePendingParsedClassStateRAII(const SavePendingParsedClassStateRAII &) =
14455 delete;
14456 SavePendingParsedClassStateRAII &
14457 operator=(const SavePendingParsedClassStateRAII &) = delete;
14458
14459 private:
14460 Sema &S;
14462 SavedOverridingExceptionSpecChecks;
14464 SavedEquivalentExceptionSpecChecks;
14465
14466 void swapSavedState() {
14467 SavedOverridingExceptionSpecChecks.swap(
14468 S.DelayedOverridingExceptionSpecChecks);
14469 SavedEquivalentExceptionSpecChecks.swap(
14470 S.DelayedEquivalentExceptionSpecChecks);
14471 }
14472 };
14473
14474 ///@}
14475
14476 //
14477 //
14478 // -------------------------------------------------------------------------
14479 //
14480 //
14481
14482 /// \name C++ Variadic Templates
14483 /// Implementations are in SemaTemplateVariadic.cpp
14484 ///@{
14485
14486public:
14487 /// Determine whether an unexpanded parameter pack might be permitted in this
14488 /// location. Useful for error recovery.
14490
14491 /// The context in which an unexpanded parameter pack is
14492 /// being diagnosed.
14493 ///
14494 /// Note that the values of this enumeration line up with the first
14495 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
14497 /// An arbitrary expression.
14499
14500 /// The base type of a class type.
14502
14503 /// The type of an arbitrary declaration.
14505
14506 /// The type of a data member.
14508
14509 /// The size of a bit-field.
14511
14512 /// The expression in a static assertion.
14514
14515 /// The fixed underlying type of an enumeration.
14517
14518 /// The enumerator value.
14520
14521 /// A using declaration.
14523
14524 /// A friend declaration.
14526
14527 /// A declaration qualifier.
14529
14530 /// An initializer.
14532
14533 /// A default argument.
14535
14536 /// The type of a non-type template parameter.
14538
14539 /// The type of an exception.
14541
14542 /// Explicit specialization.
14544
14545 /// Partial specialization.
14547
14548 /// Microsoft __if_exists.
14550
14551 /// Microsoft __if_not_exists.
14553
14554 /// Lambda expression.
14556
14557 /// Block expression.
14559
14560 /// A type constraint.
14562
14563 // A requirement in a requires-expression.
14565
14566 // A requires-clause.
14568 };
14569
14570 /// Diagnose unexpanded parameter packs.
14571 ///
14572 /// \param Loc The location at which we should emit the diagnostic.
14573 ///
14574 /// \param UPPC The context in which we are diagnosing unexpanded
14575 /// parameter packs.
14576 ///
14577 /// \param Unexpanded the set of unexpanded parameter packs.
14578 ///
14579 /// \returns true if an error occurred, false otherwise.
14583
14584 /// If the given type contains an unexpanded parameter pack,
14585 /// diagnose the error.
14586 ///
14587 /// \param Loc The source location where a diagnostc should be emitted.
14588 ///
14589 /// \param T The type that is being checked for unexpanded parameter
14590 /// packs.
14591 ///
14592 /// \returns true if an error occurred, false otherwise.
14595
14596 /// If the given expression contains an unexpanded parameter
14597 /// pack, diagnose the error.
14598 ///
14599 /// \param E The expression that is being checked for unexpanded
14600 /// parameter packs.
14601 ///
14602 /// \returns true if an error occurred, false otherwise.
14605
14606 /// If the given requirees-expression contains an unexpanded reference to one
14607 /// of its own parameter packs, diagnose the error.
14608 ///
14609 /// \param RE The requiress-expression that is being checked for unexpanded
14610 /// parameter packs.
14611 ///
14612 /// \returns true if an error occurred, false otherwise.
14614
14615 /// If the given nested-name-specifier contains an unexpanded
14616 /// parameter pack, diagnose the error.
14617 ///
14618 /// \param SS The nested-name-specifier that is being checked for
14619 /// unexpanded parameter packs.
14620 ///
14621 /// \returns true if an error occurred, false otherwise.
14624
14625 /// If the given name contains an unexpanded parameter pack,
14626 /// diagnose the error.
14627 ///
14628 /// \param NameInfo The name (with source location information) that
14629 /// is being checked for unexpanded parameter packs.
14630 ///
14631 /// \returns true if an error occurred, false otherwise.
14634
14635 /// If the given template name contains an unexpanded parameter pack,
14636 /// diagnose the error.
14637 ///
14638 /// \param Loc The location of the template name.
14639 ///
14640 /// \param Template The template name that is being checked for unexpanded
14641 /// parameter packs.
14642 ///
14643 /// \returns true if an error occurred, false otherwise.
14647
14648 /// If the given template argument contains an unexpanded parameter
14649 /// pack, diagnose the error.
14650 ///
14651 /// \param Arg The template argument that is being checked for unexpanded
14652 /// parameter packs.
14653 ///
14654 /// \returns true if an error occurred, false otherwise.
14657
14658 /// Collect the set of unexpanded parameter packs within the given
14659 /// template argument.
14660 ///
14661 /// \param Arg The template argument that will be traversed to find
14662 /// unexpanded parameter packs.
14664 TemplateArgument Arg,
14666
14667 /// Collect the set of unexpanded parameter packs within the given
14668 /// template argument.
14669 ///
14670 /// \param Arg The template argument that will be traversed to find
14671 /// unexpanded parameter packs.
14675
14676 /// Collect the set of unexpanded parameter packs within the given
14677 /// type.
14678 ///
14679 /// \param T The type that will be traversed to find
14680 /// unexpanded parameter packs.
14683
14684 /// Collect the set of unexpanded parameter packs within the given
14685 /// type.
14686 ///
14687 /// \param TL The type that will be traversed to find
14688 /// unexpanded parameter packs.
14691
14692 /// Collect the set of unexpanded parameter packs within the given
14693 /// nested-name-specifier.
14694 ///
14695 /// \param NNS The nested-name-specifier that will be traversed to find
14696 /// unexpanded parameter packs.
14700
14701 /// Collect the set of unexpanded parameter packs within the given
14702 /// name.
14703 ///
14704 /// \param NameInfo The name that will be traversed to find
14705 /// unexpanded parameter packs.
14707 const DeclarationNameInfo &NameInfo,
14709
14710 /// Collect the set of unexpanded parameter packs within the given
14711 /// expression.
14714
14715 /// Invoked when parsing a template argument.
14716 ///
14717 /// \param Arg the template argument, which may already be invalid.
14718 ///
14719 /// If it is followed by ellipsis, this function is called before
14720 /// `ActOnPackExpansion`.
14723
14724 /// Invoked when parsing a template argument followed by an
14725 /// ellipsis, which creates a pack expansion.
14726 ///
14727 /// \param Arg The template argument preceding the ellipsis, which
14728 /// may already be invalid.
14729 ///
14730 /// \param EllipsisLoc The location of the ellipsis.
14732 SourceLocation EllipsisLoc);
14733
14734 /// Invoked when parsing a type followed by an ellipsis, which
14735 /// creates a pack expansion.
14736 ///
14737 /// \param Type The type preceding the ellipsis, which will become
14738 /// the pattern of the pack expansion.
14739 ///
14740 /// \param EllipsisLoc The location of the ellipsis.
14742
14743 /// Construct a pack expansion type from the pattern of the pack
14744 /// expansion.
14746 SourceLocation EllipsisLoc,
14747 UnsignedOrNone NumExpansions);
14748
14749 /// Construct a pack expansion type from the pattern of the pack
14750 /// expansion.
14751 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
14752 SourceLocation EllipsisLoc,
14753 UnsignedOrNone NumExpansions);
14754
14755 /// Invoked when parsing an expression followed by an ellipsis, which
14756 /// creates a pack expansion.
14757 ///
14758 /// \param Pattern The expression preceding the ellipsis, which will become
14759 /// the pattern of the pack expansion.
14760 ///
14761 /// \param EllipsisLoc The location of the ellipsis.
14762 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
14763
14764 /// Invoked when parsing an expression followed by an ellipsis, which
14765 /// creates a pack expansion.
14766 ///
14767 /// \param Pattern The expression preceding the ellipsis, which will become
14768 /// the pattern of the pack expansion.
14769 ///
14770 /// \param EllipsisLoc The location of the ellipsis.
14771 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
14772 UnsignedOrNone NumExpansions);
14773
14774 /// Determine whether we could expand a pack expansion with the
14775 /// given set of parameter packs into separate arguments by repeatedly
14776 /// transforming the pattern.
14777 ///
14778 /// \param EllipsisLoc The location of the ellipsis that identifies the
14779 /// pack expansion.
14780 ///
14781 /// \param PatternRange The source range that covers the entire pattern of
14782 /// the pack expansion.
14783 ///
14784 /// \param Unexpanded The set of unexpanded parameter packs within the
14785 /// pattern.
14786 ///
14787 /// \param ShouldExpand Will be set to \c true if the transformer should
14788 /// expand the corresponding pack expansions into separate arguments. When
14789 /// set, \c NumExpansions must also be set.
14790 ///
14791 /// \param RetainExpansion Whether the caller should add an unexpanded
14792 /// pack expansion after all of the expanded arguments. This is used
14793 /// when extending explicitly-specified template argument packs per
14794 /// C++0x [temp.arg.explicit]p9.
14795 ///
14796 /// \param NumExpansions The number of separate arguments that will be in
14797 /// the expanded form of the corresponding pack expansion. This is both an
14798 /// input and an output parameter, which can be set by the caller if the
14799 /// number of expansions is known a priori (e.g., due to a prior substitution)
14800 /// and will be set by the callee when the number of expansions is known.
14801 /// The callee must set this value when \c ShouldExpand is \c true; it may
14802 /// set this value in other cases.
14803 ///
14804 /// \returns true if an error occurred (e.g., because the parameter packs
14805 /// are to be instantiated with arguments of different lengths), false
14806 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
14807 /// must be set.
14809 SourceLocation EllipsisLoc, SourceRange PatternRange,
14811 const MultiLevelTemplateArgumentList &TemplateArgs,
14812 bool FailOnPackProducingTemplates, bool &ShouldExpand,
14813 bool &RetainExpansion, UnsignedOrNone &NumExpansions,
14814 bool Diagnose = true);
14815
14816 /// Determine the number of arguments in the given pack expansion
14817 /// type.
14818 ///
14819 /// This routine assumes that the number of arguments in the expansion is
14820 /// consistent across all of the unexpanded parameter packs in its pattern.
14821 ///
14822 /// Returns an empty Optional if the type can't be expanded.
14824 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
14825
14828 const MultiLevelTemplateArgumentList &TemplateArgs);
14829
14830 /// Determine whether the given declarator contains any unexpanded
14831 /// parameter packs.
14832 ///
14833 /// This routine is used by the parser to disambiguate function declarators
14834 /// with an ellipsis prior to the ')', e.g.,
14835 ///
14836 /// \code
14837 /// void f(T...);
14838 /// \endcode
14839 ///
14840 /// To determine whether we have an (unnamed) function parameter pack or
14841 /// a variadic function.
14842 ///
14843 /// \returns true if the declarator contains any unexpanded parameter packs,
14844 /// false otherwise.
14846
14847 /// Returns the pattern of the pack expansion for a template argument.
14848 ///
14849 /// \param OrigLoc The template argument to expand.
14850 ///
14851 /// \param Ellipsis Will be set to the location of the ellipsis.
14852 ///
14853 /// \param NumExpansions Will be set to the number of expansions that will
14854 /// be generated from this pack expansion, if known a priori.
14857 SourceLocation &Ellipsis,
14858 UnsignedOrNone &NumExpansions) const;
14859
14860 /// Given a template argument that contains an unexpanded parameter pack, but
14861 /// which has already been substituted, attempt to determine the number of
14862 /// elements that will be produced once this argument is fully-expanded.
14863 ///
14864 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
14865 /// avoid actually expanding the pack where possible.
14867
14868 /// Called when an expression computing the size of a parameter pack
14869 /// is parsed.
14870 ///
14871 /// \code
14872 /// template<typename ...Types> struct count {
14873 /// static const unsigned value = sizeof...(Types);
14874 /// };
14875 /// \endcode
14876 ///
14877 //
14878 /// \param OpLoc The location of the "sizeof" keyword.
14879 /// \param Name The name of the parameter pack whose size will be determined.
14880 /// \param NameLoc The source location of the name of the parameter pack.
14881 /// \param RParenLoc The location of the closing parentheses.
14883 IdentifierInfo &Name,
14884 SourceLocation NameLoc,
14885 SourceLocation RParenLoc);
14886
14887 ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression,
14888 SourceLocation EllipsisLoc,
14889 SourceLocation LSquareLoc, Expr *IndexExpr,
14890 SourceLocation RSquareLoc);
14891
14892 ExprResult BuildPackIndexingExpr(Expr *PackExpression,
14893 SourceLocation EllipsisLoc, Expr *IndexExpr,
14894 SourceLocation RSquareLoc,
14895 ArrayRef<Expr *> ExpandedExprs = {},
14896 bool FullySubstituted = false);
14897
14898 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
14899 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
14900 tok::TokenKind Operator,
14901 SourceLocation EllipsisLoc, Expr *RHS,
14902 SourceLocation RParenLoc);
14903 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
14904 SourceLocation LParenLoc, Expr *LHS,
14905 BinaryOperatorKind Operator,
14906 SourceLocation EllipsisLoc, Expr *RHS,
14907 SourceLocation RParenLoc,
14908 UnsignedOrNone NumExpansions);
14909 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
14910 BinaryOperatorKind Operator);
14911
14912 ///@}
14913
14914 //
14915 //
14916 // -------------------------------------------------------------------------
14917 //
14918 //
14919
14920 /// \name Constraints and Concepts
14921 /// Implementations are in SemaConcept.cpp
14922 ///@{
14923
14924public:
14925 ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI);
14926
14927 ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc,
14928 TypeSourceInfo *TSI);
14929
14930public:
14932 const llvm::FoldingSetNodeID &ID) {
14933 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
14934 SatisfactionStack.emplace_back(Can, ID);
14935 }
14936
14937 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
14938
14940 const llvm::FoldingSetNodeID &ID) const {
14941 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
14942 return llvm::is_contained(SatisfactionStack,
14943 SatisfactionStackEntryTy{Can, ID});
14944 }
14945
14947 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
14948
14949 // Resets the current SatisfactionStack for cases where we are instantiating
14950 // constraints as a 'side effect' of normal instantiation in a way that is not
14951 // indicative of recursive definition.
14954 Sema &SemaRef;
14955
14956 public:
14958 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
14959 }
14960
14962 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
14963 }
14964
14968 };
14969
14972 SatisfactionStack.swap(NewSS);
14973 }
14974
14976 llvm::PointerUnion<const NamedDecl *,
14978
14979 /// Check whether the given expression is a valid constraint expression.
14980 /// A diagnostic is emitted if it is not, false is returned, and
14981 /// PossibleNonPrimary will be set to true if the failure might be due to a
14982 /// non-primary expression being used as an atomic constraint.
14983 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
14984 bool *PossibleNonPrimary = nullptr,
14985 bool IsTrailingRequiresClause = false);
14986
14987 /// \brief Check whether the given list of constraint expressions are
14988 /// satisfied (as if in a 'conjunction') given template arguments.
14989 /// \param Template the template-like entity that triggered the constraints
14990 /// check (either a concept or a constrained entity).
14991 /// \param ConstraintExprs a list of constraint expressions, treated as if
14992 /// they were 'AND'ed together.
14993 /// \param TemplateArgLists the list of template arguments to substitute into
14994 /// the constraint expression.
14995 /// \param TemplateIDRange The source range of the template id that
14996 /// caused the constraints check.
14997 /// \param Satisfaction if true is returned, will contain details of the
14998 /// satisfaction, with enough information to diagnose an unsatisfied
14999 /// expression.
15000 /// \returns true if an error occurred and satisfaction could not be checked,
15001 /// false otherwise.
15004 ArrayRef<AssociatedConstraint> AssociatedConstraints,
15005 const MultiLevelTemplateArgumentList &TemplateArgLists,
15006 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction,
15007 const ConceptReference *TopLevelConceptId = nullptr,
15008 Expr **ConvertedExpr = nullptr);
15009
15010 /// Check whether the given function decl's trailing requires clause is
15011 /// satisfied, if any. Returns false and updates Satisfaction with the
15012 /// satisfaction verdict if successful, emits a diagnostic and returns true if
15013 /// an error occurred and satisfaction could not be determined.
15014 ///
15015 /// \returns true if an error occurred, false otherwise.
15017 ConstraintSatisfaction &Satisfaction,
15018 SourceLocation UsageLoc = SourceLocation(),
15019 bool ForOverloadResolution = false);
15020
15021 // Calculates whether two constraint expressions are equal irrespective of a
15022 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
15023 // 'New', which are the "source" of the constraint, since this is necessary
15024 // for figuring out the relative 'depth' of the constraint. The depth of the
15025 // 'primary template' and the 'instantiated from' templates aren't necessarily
15026 // the same, such as a case when one is a 'friend' defined in a class.
15028 const Expr *OldConstr,
15030 const Expr *NewConstr);
15031
15032 // Calculates whether the friend function depends on an enclosing template for
15033 // the purposes of [temp.friend] p9.
15035
15036 /// \brief Ensure that the given template arguments satisfy the constraints
15037 /// associated with the given template, emitting a diagnostic if they do not.
15038 ///
15039 /// \param Template The template to which the template arguments are being
15040 /// provided.
15041 ///
15042 /// \param TemplateArgs The converted, canonicalized template arguments.
15043 ///
15044 /// \param TemplateIDRange The source range of the template id that
15045 /// caused the constraints check.
15046 ///
15047 /// \returns true if the constrains are not satisfied or could not be checked
15048 /// for satisfaction, false if the constraints are satisfied.
15051 const MultiLevelTemplateArgumentList &TemplateArgs,
15052 SourceRange TemplateIDRange);
15053
15054 bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation,
15056 ArrayRef<TemplateArgument> TemplateArgs,
15057 ConstraintSatisfaction &Satisfaction);
15058
15059 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15060 /// unsatisfied.
15061 /// \param First whether this is the first time an unsatisfied constraint is
15062 /// diagnosed for this error.
15064 SourceLocation Loc = {},
15065 bool First = true);
15066
15067 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15068 /// unsatisfied.
15069 void
15071 bool First = true);
15072
15075 ArrayRef<AssociatedConstraint> AssociatedConstraints);
15076
15077 /// \brief Check whether the given declaration's associated constraints are
15078 /// at least as constrained than another declaration's according to the
15079 /// partial ordering of constraints.
15080 ///
15081 /// \param Result If no error occurred, receives the result of true if D1 is
15082 /// at least constrained than D2, and false otherwise.
15083 ///
15084 /// \returns true if an error occurred, false otherwise.
15085 bool IsAtLeastAsConstrained(const NamedDecl *D1,
15087 const NamedDecl *D2,
15089 bool &Result);
15090
15091 /// If D1 was not at least as constrained as D2, but would've been if a pair
15092 /// of atomic constraints involved had been declared in a concept and not
15093 /// repeated in two separate places in code.
15094 /// \returns true if such a diagnostic was emitted, false otherwise.
15098
15099 /// Cache the satisfaction of an atomic constraint.
15100 /// The key is based on the unsubstituted expression and the parameter
15101 /// mapping. This lets us not substituting the mapping more than once,
15102 /// which is (very!) expensive.
15103 /// FIXME: this should be private.
15104 llvm::DenseMap<llvm::FoldingSetNodeID,
15107
15108 /// Cache the instantiation results of template parameter mappings within
15109 /// concepts. Substituting into normalized concepts can be extremely expensive
15110 /// due to the redundancy of template parameters. This cache is intended for
15111 /// use by TemplateInstantiator to avoid redundant semantic checking.
15112 llvm::DenseMap<llvm::FoldingSetNodeID, TemplateArgumentLoc>
15114
15115private:
15116 /// Caches pairs of template-like decls whose associated constraints were
15117 /// checked for subsumption and whether or not the first's constraints did in
15118 /// fact subsume the second's.
15119 llvm::DenseMap<std::pair<const NamedDecl *, const NamedDecl *>, bool>
15120 SubsumptionCache;
15121 /// Caches the normalized associated constraints of declarations (concepts or
15122 /// constrained declarations). If an error occurred while normalizing the
15123 /// associated constraints of the template or concept, nullptr will be cached
15124 /// here.
15125 llvm::DenseMap<ConstrainedDeclOrNestedRequirement, NormalizedConstraint *>
15126 NormalizationCache;
15127
15128 /// Cache whether the associated constraint of a declaration
15129 /// is satisfied.
15130 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
15131 SatisfactionCache;
15132
15133 // The current stack of constraint satisfactions, so we can exit-early.
15135
15136 /// Used by SetupConstraintCheckingTemplateArgumentsAndScope to set up the
15137 /// LocalInstantiationScope of the current non-lambda function. For lambdas,
15138 /// use LambdaScopeForCallOperatorInstantiationRAII.
15139 bool
15140 SetupConstraintScope(FunctionDecl *FD,
15141 std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15142 const MultiLevelTemplateArgumentList &MLTAL,
15144
15145 /// Used during constraint checking, sets up the constraint template argument
15146 /// lists, and calls SetupConstraintScope to set up the
15147 /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
15148 std::optional<MultiLevelTemplateArgumentList>
15149 SetupConstraintCheckingTemplateArgumentsAndScope(
15150 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15152
15153 ///@}
15154
15155 //
15156 //
15157 // -------------------------------------------------------------------------
15158 //
15159 //
15160
15161 /// \name Types
15162 /// Implementations are in SemaType.cpp
15163 ///@{
15164
15165public:
15166 /// A mapping that describes the nullability we've seen in each header file.
15168
15169 static int getPrintable(int I) { return I; }
15170 static unsigned getPrintable(unsigned I) { return I; }
15171 static bool getPrintable(bool B) { return B; }
15172 static const char *getPrintable(const char *S) { return S; }
15173 static StringRef getPrintable(StringRef S) { return S; }
15174 static const std::string &getPrintable(const std::string &S) { return S; }
15175 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
15176 return II;
15177 }
15179 static QualType getPrintable(QualType T) { return T; }
15180 static SourceRange getPrintable(SourceRange R) { return R; }
15182 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
15184
15185 enum class CompleteTypeKind {
15186 /// Apply the normal rules for complete types. In particular,
15187 /// treat all sizeless types as incomplete.
15189
15190 /// Relax the normal rules for complete types so that they include
15191 /// sizeless built-in types.
15193
15194 // FIXME: Eventually we should flip the default to Normal and opt in
15195 // to AcceptSizeless rather than opt out of it.
15197 };
15198
15200 const DeclSpec *DS = nullptr);
15202 const DeclSpec *DS = nullptr);
15203
15204 /// Build a pointer type.
15205 ///
15206 /// \param T The type to which we'll be building a pointer.
15207 ///
15208 /// \param Loc The location of the entity whose type involves this
15209 /// pointer type or, if there is no such entity, the location of the
15210 /// type that will have pointer type.
15211 ///
15212 /// \param Entity The name of the entity that involves the pointer
15213 /// type, if known.
15214 ///
15215 /// \returns A suitable pointer type, if there are no
15216 /// errors. Otherwise, returns a NULL type.
15218 DeclarationName Entity);
15219
15220 /// Build a reference type.
15221 ///
15222 /// \param T The type to which we'll be building a reference.
15223 ///
15224 /// \param Loc The location of the entity whose type involves this
15225 /// reference type or, if there is no such entity, the location of the
15226 /// type that will have reference type.
15227 ///
15228 /// \param Entity The name of the entity that involves the reference
15229 /// type, if known.
15230 ///
15231 /// \returns A suitable reference type, if there are no
15232 /// errors. Otherwise, returns a NULL type.
15234 DeclarationName Entity);
15235
15236 /// Build an array type.
15237 ///
15238 /// \param T The type of each element in the array.
15239 ///
15240 /// \param ASM C99 array size modifier (e.g., '*', 'static').
15241 ///
15242 /// \param ArraySize Expression describing the size of the array.
15243 ///
15244 /// \param Brackets The range from the opening '[' to the closing ']'.
15245 ///
15246 /// \param Entity The name of the entity that involves the array
15247 /// type, if known.
15248 ///
15249 /// \returns A suitable array type, if there are no errors. Otherwise,
15250 /// returns a NULL type.
15252 unsigned Quals, SourceRange Brackets,
15253 DeclarationName Entity);
15255
15256 /// Build an ext-vector type.
15257 ///
15258 /// Run the required checks for the extended vector type.
15260 SourceLocation AttrLoc);
15261 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
15262 SourceLocation AttrLoc);
15263
15265 Expr *CountExpr,
15266 bool CountInBytes,
15267 bool OrNull);
15268
15269 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an
15270 /// expression is uninstantiated. If instantiated it will apply the
15271 /// appropriate address space to the type. This function allows dependent
15272 /// template variables to be used in conjunction with the address_space
15273 /// attribute
15274 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
15275 SourceLocation AttrLoc);
15276
15277 /// Same as above, but constructs the AddressSpace index if not provided.
15279 SourceLocation AttrLoc);
15280
15282
15284
15285 /// Build a function type.
15286 ///
15287 /// This routine checks the function type according to C++ rules and
15288 /// under the assumption that the result type and parameter types have
15289 /// just been instantiated from a template. It therefore duplicates
15290 /// some of the behavior of GetTypeForDeclarator, but in a much
15291 /// simpler form that is only suitable for this narrow use case.
15292 ///
15293 /// \param T The return type of the function.
15294 ///
15295 /// \param ParamTypes The parameter types of the function. This array
15296 /// will be modified to account for adjustments to the types of the
15297 /// function parameters.
15298 ///
15299 /// \param Loc The location of the entity whose type involves this
15300 /// function type or, if there is no such entity, the location of the
15301 /// type that will have function type.
15302 ///
15303 /// \param Entity The name of the entity that involves the function
15304 /// type, if known.
15305 ///
15306 /// \param EPI Extra information about the function type. Usually this will
15307 /// be taken from an existing function with the same prototype.
15308 ///
15309 /// \returns A suitable function type, if there are no errors. The
15310 /// unqualified type will always be a FunctionProtoType.
15311 /// Otherwise, returns a NULL type.
15313 SourceLocation Loc, DeclarationName Entity,
15315
15316 /// Build a member pointer type \c T Class::*.
15317 ///
15318 /// \param T the type to which the member pointer refers.
15319 /// \param Class the class type into which the member pointer points.
15320 /// \param Loc the location where this type begins
15321 /// \param Entity the name of the entity that will have this member pointer
15322 /// type
15323 ///
15324 /// \returns a member pointer type, if successful, or a NULL type if there was
15325 /// an error.
15327 CXXRecordDecl *Cls, SourceLocation Loc,
15328 DeclarationName Entity);
15329
15330 /// Build a block pointer type.
15331 ///
15332 /// \param T The type to which we'll be building a block pointer.
15333 ///
15334 /// \param Loc The source location, used for diagnostics.
15335 ///
15336 /// \param Entity The name of the entity that involves the block pointer
15337 /// type, if known.
15338 ///
15339 /// \returns A suitable block pointer type, if there are no
15340 /// errors. Otherwise, returns a NULL type.
15342 DeclarationName Entity);
15343
15344 /// Build a paren type including \p T.
15347
15348 /// Build a Read-only Pipe type.
15349 ///
15350 /// \param T The type to which we'll be building a Pipe.
15351 ///
15352 /// \param Loc We do not use it for now.
15353 ///
15354 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15355 /// a NULL type.
15357
15358 /// Build a Write-only Pipe type.
15359 ///
15360 /// \param T The type to which we'll be building a Pipe.
15361 ///
15362 /// \param Loc We do not use it for now.
15363 ///
15364 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15365 /// a NULL type.
15367
15368 /// Build a bit-precise integer type.
15369 ///
15370 /// \param IsUnsigned Boolean representing the signedness of the type.
15371 ///
15372 /// \param BitWidth Size of this int type in bits, or an expression
15373 /// representing that.
15374 ///
15375 /// \param Loc Location of the keyword.
15376 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
15377
15378 /// GetTypeForDeclarator - Convert the type for the specified
15379 /// declarator to Type instances.
15380 ///
15381 /// The result of this call will never be null, but the associated
15382 /// type may be a null type if there's an unrecoverable error.
15385
15386 /// Package the given type and TSI into a ParsedType.
15389 TypeSourceInfo **TInfo = nullptr);
15390
15392
15393 // Check whether the size of array element of type \p EltTy is a multiple of
15394 // its alignment and return false if it isn't.
15396
15397 void
15398 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
15399 SourceLocation FallbackLoc,
15400 SourceLocation ConstQualLoc = SourceLocation(),
15401 SourceLocation VolatileQualLoc = SourceLocation(),
15402 SourceLocation RestrictQualLoc = SourceLocation(),
15403 SourceLocation AtomicQualLoc = SourceLocation(),
15404 SourceLocation UnalignedQualLoc = SourceLocation());
15405
15406 /// Retrieve the keyword associated
15408
15409 /// Adjust the calling convention of a method to be the ABI default if it
15410 /// wasn't specified explicitly. This handles method types formed from
15411 /// function type typedefs and typename template arguments.
15412 void adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
15413 bool IsCtorOrDtor, SourceLocation Loc);
15414
15415 // Check if there is an explicit attribute, but only look through parens.
15416 // The intent is to look for an attribute on the current declarator, but not
15417 // one that came from a typedef.
15419
15420 /// Check whether a nullability type specifier can be added to the given
15421 /// type through some means not written in source (e.g. API notes).
15422 ///
15423 /// \param Type The type to which the nullability specifier will be
15424 /// added. On success, this type will be updated appropriately.
15425 ///
15426 /// \param Nullability The nullability specifier to add.
15427 ///
15428 /// \param DiagLoc The location to use for diagnostics.
15429 ///
15430 /// \param AllowArrayTypes Whether to accept nullability specifiers on an
15431 /// array type (e.g., because it will decay to a pointer).
15432 ///
15433 /// \param OverrideExisting Whether to override an existing, locally-specified
15434 /// nullability specifier rather than complaining about the conflict.
15435 ///
15436 /// \returns true if nullability cannot be applied, false otherwise.
15438 NullabilityKind Nullability,
15439 SourceLocation DiagLoc,
15440 bool AllowArrayTypes,
15441 bool OverrideExisting);
15442
15443 /// Check whether the given variable declaration has a size that fits within
15444 /// the address space it is declared in. This issues a diagnostic if not.
15445 ///
15446 /// \param VD The variable declaration to check the size of.
15447 ///
15448 /// \param AS The address space to check the size of \p VD against.
15449 ///
15450 /// \returns true if the variable's size fits within the address space, false
15451 /// otherwise.
15452 bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS);
15453
15454 /// Get the type of expression E, triggering instantiation to complete the
15455 /// type if necessary -- that is, if the expression refers to a templated
15456 /// static data member of incomplete array type.
15457 ///
15458 /// May still return an incomplete type if instantiation was not possible or
15459 /// if the type is incomplete for a different reason. Use
15460 /// RequireCompleteExprType instead if a diagnostic is expected for an
15461 /// incomplete expression type.
15463
15465
15466 /// Ensure that the type of the given expression is complete.
15467 ///
15468 /// This routine checks whether the expression \p E has a complete type. If
15469 /// the expression refers to an instantiable construct, that instantiation is
15470 /// performed as needed to complete its type. Furthermore
15471 /// Sema::RequireCompleteType is called for the expression's type (or in the
15472 /// case of a reference type, the referred-to type).
15473 ///
15474 /// \param E The expression whose type is required to be complete.
15475 /// \param Kind Selects which completeness rules should be applied.
15476 /// \param Diagnoser The object that will emit a diagnostic if the type is
15477 /// incomplete.
15478 ///
15479 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
15480 /// otherwise.
15482 TypeDiagnoser &Diagnoser);
15483 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
15484
15485 template <typename... Ts>
15486 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
15487 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15489 }
15490
15491 // Returns the underlying type of a decltype with the given expression.
15493
15495 /// If AsUnevaluated is false, E is treated as though it were an evaluated
15496 /// context, such as when building a type for decltype(auto).
15497 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
15498
15499 QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr,
15500 SourceLocation Loc,
15501 SourceLocation EllipsisLoc);
15502 QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr,
15503 SourceLocation Loc, SourceLocation EllipsisLoc,
15504 bool FullySubstituted = false,
15505 ArrayRef<QualType> Expansions = {});
15506
15507 using UTTKind = UnaryTransformType::UTTKind;
15509 SourceLocation Loc);
15515 SourceLocation Loc);
15517 SourceLocation Loc);
15519 SourceLocation Loc);
15520
15522 return BuiltinRemoveReference(BaseType, UTTKind::RemoveCVRef, Loc);
15523 }
15524
15526 SourceLocation Loc);
15528 SourceLocation Loc);
15529
15530 bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT);
15531
15532 /// Ensure that the type T is a literal type.
15533 ///
15534 /// This routine checks whether the type @p T is a literal type. If @p T is an
15535 /// incomplete type, an attempt is made to complete it. If @p T is a literal
15536 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
15537 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
15538 /// it the type @p T), along with notes explaining why the type is not a
15539 /// literal type, and returns true.
15540 ///
15541 /// @param Loc The location in the source that the non-literal type
15542 /// diagnostic should refer to.
15543 ///
15544 /// @param T The type that this routine is examining for literalness.
15545 ///
15546 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
15547 ///
15548 /// @returns @c true if @p T is not a literal type and a diagnostic was
15549 /// emitted, @c false otherwise.
15551 TypeDiagnoser &Diagnoser);
15552 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
15553
15554 template <typename... Ts>
15555 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
15556 const Ts &...Args) {
15557 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15558 return RequireLiteralType(Loc, T, Diagnoser);
15559 }
15560
15563 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
15564 }
15565
15566 /// Ensure that the type T is a complete type.
15567 ///
15568 /// This routine checks whether the type @p T is complete in any
15569 /// context where a complete type is required. If @p T is a complete
15570 /// type, returns false. If @p T is a class template specialization,
15571 /// this routine then attempts to perform class template
15572 /// instantiation. If instantiation fails, or if @p T is incomplete
15573 /// and cannot be completed, issues the diagnostic @p diag (giving it
15574 /// the type @p T) and returns true.
15575 ///
15576 /// @param Loc The location in the source that the incomplete type
15577 /// diagnostic should refer to.
15578 ///
15579 /// @param T The type that this routine is examining for completeness.
15580 ///
15581 /// @param Kind Selects which completeness rules should be applied.
15582 ///
15583 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
15584 /// @c false otherwise.
15586 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
15588 CompleteTypeKind Kind, unsigned DiagID);
15589
15591 TypeDiagnoser &Diagnoser) {
15592 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
15593 }
15594 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
15595 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
15596 }
15597
15598 template <typename... Ts>
15599 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
15600 const Ts &...Args) {
15601 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15602 return RequireCompleteType(Loc, T, Diagnoser);
15603 }
15604
15605 /// Determine whether a declaration is visible to name lookup.
15606 bool isVisible(const NamedDecl *D) {
15607 return D->isUnconditionallyVisible() ||
15608 isAcceptableSlow(D, AcceptableKind::Visible);
15609 }
15610
15611 /// Determine whether a declaration is reachable.
15612 bool isReachable(const NamedDecl *D) {
15613 // All visible declarations are reachable.
15614 return D->isUnconditionallyVisible() ||
15615 isAcceptableSlow(D, AcceptableKind::Reachable);
15616 }
15617
15618 /// Determine whether a declaration is acceptable (visible/reachable).
15620 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
15621 }
15622
15623 /// Determine if \p D and \p Suggested have a structurally compatible
15624 /// layout as described in C11 6.2.7/1.
15625 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
15626
15627 /// Determine if \p D has a visible definition. If not, suggest a declaration
15628 /// that should be made visible to expose the definition.
15629 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
15630 bool OnlyNeedComplete = false);
15632 NamedDecl *Hidden;
15633 return hasVisibleDefinition(const_cast<NamedDecl *>(D), &Hidden);
15634 }
15635 /// Determine if \p D has a definition which allows we redefine it in current
15636 /// TU. \p Suggested is the definition that should be made visible to expose
15637 /// the definition.
15638 bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,
15639 bool &Visible);
15641 NamedDecl *Hidden;
15642 return isRedefinitionAllowedFor(const_cast<NamedDecl *>(D), &Hidden,
15643 Visible);
15644 }
15645
15646 /// Determine if \p D has a reachable definition. If not, suggest a
15647 /// declaration that should be made reachable to expose the definition.
15648 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
15649 bool OnlyNeedComplete = false);
15651 NamedDecl *Hidden;
15652 return hasReachableDefinition(D, &Hidden);
15653 }
15654
15655 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
15656 AcceptableKind Kind,
15657 bool OnlyNeedComplete = false);
15659 NamedDecl *Hidden;
15660 return hasAcceptableDefinition(D, &Hidden, Kind);
15661 }
15662
15663 /// Try to parse the conditional expression attached to an effect attribute
15664 /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty
15665 /// optional on error.
15666 std::optional<FunctionEffectMode>
15667 ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName);
15668
15669 void ActOnCleanupAttr(Decl *D, const Attr *A);
15670 void ActOnInitPriorityAttr(Decl *D, const Attr *A);
15671
15672private:
15673 /// The implementation of RequireCompleteType
15674 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
15675 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
15676
15677 /// Nullability type specifiers.
15678 IdentifierInfo *Ident__Nonnull = nullptr;
15679 IdentifierInfo *Ident__Nullable = nullptr;
15680 IdentifierInfo *Ident__Nullable_result = nullptr;
15681 IdentifierInfo *Ident__Null_unspecified = nullptr;
15682
15683 ///@}
15684
15685 //
15686 //
15687 // -------------------------------------------------------------------------
15688 //
15689 //
15690
15691 /// \name FixIt Helpers
15692 /// Implementations are in SemaFixItUtils.cpp
15693 ///@{
15694
15695public:
15696 /// Get a string to suggest for zero-initialization of a type.
15698 SourceLocation Loc) const;
15699 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
15700
15701 ///@}
15702
15703 //
15704 //
15705 // -------------------------------------------------------------------------
15706 //
15707 //
15708
15709 /// \name Function Effects
15710 /// Implementations are in SemaFunctionEffects.cpp
15711 ///@{
15712public:
15715
15718 std::optional<FunctionEffectWithCondition>
15719 Old; // Invalid when 'Kind' is 'Added'.
15720 std::optional<FunctionEffectWithCondition>
15721 New; // Invalid when 'Kind' is 'Removed'.
15722
15723 StringRef effectName() const {
15724 if (Old)
15725 return Old.value().Effect.name();
15726 return New.value().Effect.name();
15727 }
15728
15729 /// Describes the result of effects differing between a base class's virtual
15730 /// method and an overriding method in a subclass.
15731 enum class OverrideResult {
15734 Merge // Merge missing effect from base to derived.
15735 };
15736
15737 /// Return true if adding or removing the effect as part of a type
15738 /// conversion should generate a diagnostic.
15740 const FunctionEffectsRef &SrcFX,
15741 QualType DstType,
15742 const FunctionEffectsRef &DstFX) const;
15743
15744 /// Return true if adding or removing the effect in a redeclaration should
15745 /// generate a diagnostic.
15746 bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction,
15747 const FunctionEffectsRef &OldFX,
15748 const FunctionDecl &NewFunction,
15749 const FunctionEffectsRef &NewFX) const;
15750
15751 /// Return true if adding or removing the effect in a C++ virtual method
15752 /// override should generate a diagnostic.
15754 const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,
15755 const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const;
15756 };
15757
15758 struct FunctionEffectDiffVector : public SmallVector<FunctionEffectDiff> {
15759 /// Caller should short-circuit by checking for equality first.
15761 const FunctionEffectsRef &New);
15762 };
15763
15764 /// All functions/lambdas/blocks which have bodies and which have a non-empty
15765 /// FunctionEffectsRef to be verified.
15767
15768 /// The union of all effects present on DeclsWithEffectsToVerify. Conditions
15769 /// are all null.
15771
15772public:
15773 /// Warn and return true if adding a function effect to a set would create a
15774 /// conflict.
15777 SourceLocation NewAttrLoc);
15778
15779 // Report a failure to merge function effects between declarations due to a
15780 // conflict.
15781 void
15783 SourceLocation NewLoc,
15784 SourceLocation OldLoc);
15785
15786 /// Inline checks from the start of maybeAddDeclWithEffects, to
15787 /// minimize performance impact on code not using effects.
15788 template <class FuncOrBlockDecl>
15789 void maybeAddDeclWithEffects(FuncOrBlockDecl *D) {
15790 if (Context.hasAnyFunctionEffects())
15791 if (FunctionEffectsRef FX = D->getFunctionEffects(); !FX.empty())
15793 }
15794
15795 /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify.
15796 void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15797
15798 /// Unconditionally add a Decl to DeclsWithEfffectsToVerify.
15799 void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15800
15802
15803 ///@}
15804
15805 //
15806 //
15807 // -------------------------------------------------------------------------
15808 //
15809 //
15810
15811 /// \name Expansion Statements
15812 /// Implementations are in SemaExpand.cpp
15813 ///@{
15814public:
15815 CXXExpansionStmtDecl *ActOnCXXExpansionStmtDecl(unsigned TemplateDepth,
15816 SourceLocation TemplateKWLoc);
15817
15821
15823 SourceLocation LBraceLoc,
15824 SourceLocation RBraceLoc);
15825
15827 CXXExpansionStmtDecl *ESD, Stmt *Init, Stmt *ExpansionVarStmt,
15828 Expr *ExpansionInitializer, SourceLocation LParenLoc,
15829 SourceLocation ColonLoc, SourceLocation RParenLoc,
15830 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps);
15831
15832 StmtResult FinishCXXExpansionStmt(Stmt *Expansion, Stmt *Body);
15833
15835 Stmt *ExpansionVar,
15836 SourceLocation LParenLoc,
15837 SourceLocation ColonLoc,
15838 SourceLocation RParenLoc);
15839
15841 CXXExpansionStmtDecl *ESD, Stmt *Init, DeclStmt *ExpansionVarStmt,
15842 Expr *ExpansionInitializer, SourceLocation LParenLoc,
15843 SourceLocation ColonLoc, SourceLocation RParenLoc,
15844 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
15845
15846 ExprResult BuildCXXExpansionSelectExpr(InitListExpr *Range, Expr *Idx);
15847
15848 std::optional<uint64_t>
15849 ComputeExpansionSize(CXXExpansionStmtPattern *Expansion);
15850 ///@}
15851};
15852
15856
15857/// Contains a late templated function.
15858/// Will be parsed at the end of the translation unit, used by Sema & Parser.
15861 /// The template function declaration to be late parsed.
15863 /// Floating-point options in the point of definition.
15865};
15866
15867template <>
15869 PragmaMsStackAction Action,
15870 llvm::StringRef StackSlotLabel,
15872
15873} // end namespace clang
15874
15875#endif
#define V(N, I)
Forward declaration of all AST node types.
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enumerations for traits support.
Defines enum values for all the target-independent builtin functions.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines Expressions and AST nodes for C++2a concepts.
Token Tok
The Token.
FormatToken * Previous
The previous token in the unwrapped line.
static const Decl * getCanonicalDecl(const Decl *D)
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines several types used to describe C++ lambda expressions that are shared between the parser and ...
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::Module class, which describes a module in the source code.
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
llvm::json::Object Object
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
@ NotForRedeclaration
The lookup is a reference to this name that is not for the purpose of redeclaring the name.
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
AccessResult
A copy of Sema's enum without AR_delayed.
CastType
Definition SemaCast.cpp: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.
C Language Family Type Representation.
Represents a member of a struct/union/class.
Definition Decl.h:3294
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:2732
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3836
Attr - This represents one attribute.
Definition Attr.h:46
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3521
A binding in a decomposition declaration.
Definition DeclCXX.h:4210
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4806
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:2637
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2972
Represents a C++ base or member initializer.
Definition DeclCXX.h:2402
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2629
Represents a C++ destructor within a class.
Definition DeclCXX.h:2902
Represents a C++26 expansion statement declaration.
CXXExpansionStmtPattern - Represents an unexpanded C++ expansion statement.
Definition StmtCXX.h:675
CXXFieldCollector - Used to keep track of CXXFieldDecls during parsing of C++ classes.
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h: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:1157
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:70
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2954
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition Decl.h:5078
CaseStmt - Represent a case statement.
Definition Stmt.h:1929
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3687
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:3702
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:1281
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1640
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:4274
Captures a template argument whose value has been deduced via c++ template argument deduction.
Definition Template.h:339
A dependently-generated diagnostic.
Designation - Represent a full designation, which is a sequence of designators.
Definition Designator.h:221
A little helper class used to produce diagnostics.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3557
Represents an enum.
Definition Decl.h:4145
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, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:813
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:3294
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:266
FileNullability & operator[](FileID file)
Definition Sema.h:277
FileNullability Nullability
Definition Sema.h:273
Declaration of a friend template.
Represents a function declaration or definition.
Definition Decl.h:2058
A mutable set of FunctionEffect::Kind.
Definition TypeBase.h:5275
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5389
Kind
Identifies the particular effect.
Definition TypeBase.h:5037
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5221
Represents a reference to a function parameter pack, init-capture pack, or binding pack that has been...
Definition ExprCXX.h:4881
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5421
Declaration of a template function.
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4643
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4617
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:623
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3601
Describes an C or C++ initializer list.
Definition Expr.h:5319
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:377
Represents the results of name lookup.
Definition Lookup.h:147
A global _GUID constant.
Definition DeclCXX.h:4428
An instance of this class represents the declaration of a property member.
Definition DeclCXX.h:4374
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:4960
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3375
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3767
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:1160
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:8122
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:1161
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:2193
Represents a parameter to a function.
Definition Decl.h:1819
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:300
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:336
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:2697
A (possibly-)qualified type.
Definition TypeBase.h:938
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
Represents a struct/union/class.
Definition Decl.h:4459
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:1876
bool operator==(const AlignPackInfo &Info) const
Definition Sema.h:1936
static AlignPackInfo getFromRawEncoding(unsigned Encoding)
Definition Sema.h:1908
unsigned getPackNumber() const
Definition Sema.h:1926
bool IsXLStack() const
Definition Sema.h:1934
bool IsPackSet() const
Definition Sema.h:1928
AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
Definition Sema.h:1882
bool IsAlignAttr() const
Definition Sema.h:1922
bool IsPackAttr() const
Definition Sema.h:1920
bool operator!=(const AlignPackInfo &Info) const
Definition Sema.h:1942
AlignPackInfo(bool IsXL)
Definition Sema.h:1886
static uint32_t getRawEncoding(const AlignPackInfo &Info)
Definition Sema.h:1893
Mode getAlignMode() const
Definition Sema.h:1924
ArgPackSubstIndexRAII(Sema &Self, UnsignedOrNone NewSubstIndex)
Definition Sema.h:13757
ArgPackSubstIndexRAII & operator=(const ArgPackSubstIndexRAII &)=delete
ArgPackSubstIndexRAII(const ArgPackSubstIndexRAII &)=delete
BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
Definition Sema.h:8295
void diagnose(Sema &S, SourceLocation Loc, QualType T) override
Definition Sema.h:8300
void emit(const SemaDiagnosticBuilder &DB, std::index_sequence< Is... >) const
Definition Sema.h:8287
std::tuple< const Ts &... > Args
Definition Sema.h:8284
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:1316
CompoundScopeRAII(const CompoundScopeRAII &)=delete
std::pair< VarDecl *, Expr * > get() const
Definition Sema.h:7835
std::optional< bool > getKnownValue() const
Definition Sema.h:7839
A RAII object to temporarily push a declaration context.
Definition Sema.h:3533
ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext=true)
Definition Sema.h:3543
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:10353
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:10358
virtual bool match(QualType T)=0
Determine whether the specified type is a valid destination type for this conversion.
virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when the expression has incomplete class type.
DeferDiagsRAII(Sema &S, bool DeferDiags)
Definition Sema.h:10081
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:1385
DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool)
Enter a new scope.
Definition Sema.h:1404
void popUndelayed(DelayedDiagnosticsState state)
Undo a previous pushUndelayed().
Definition Sema.h:1428
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1397
sema::DelayedDiagnosticPool * getCurrentPool() const
Returns the current delayed-diagnostics pool.
Definition Sema.h:1400
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:1414
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1420
A helper class for building up ExtParameterInfos.
Definition Sema.h:13121
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:13140
void set(unsigned index, FunctionProtoType::ExtParameterInfo info)
Set the ExtParameterInfo for the parameter at the given index,.
Definition Sema.h:13128
FPFeaturesStateRAII(const FPFeaturesStateRAII &)=delete
FPOptionsOverride getOverrides()
Definition Sema.h:14153
FPFeaturesStateRAII & operator=(const FPFeaturesStateRAII &)=delete
FpPragmaStackSaveRAII(const FpPragmaStackSaveRAII &)=delete
FpPragmaStackSaveRAII & operator=(const FpPragmaStackSaveRAII &)=delete
FullExprArg(Sema &actions)
Definition Sema.h:7779
ExprResult release()
Definition Sema.h:7781
friend class Sema
Definition Sema.h:7790
Expr * get() const
Definition Sema.h:7783
GlobalEagerInstantiationScope(const GlobalEagerInstantiationScope &)=delete
GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
Definition Sema.h:14165
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:10417
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:10409
unsigned size() const
The number of exceptions in the exception specification.
Definition Sema.h:5581
ExceptionSpecificationType getExceptionSpecType() const
Get the computed exception specification type.
Definition Sema.h:5574
const QualType * data() const
The set of exceptions in the exception specification.
Definition Sema.h:5584
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:5590
FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const
Overwrite an EPI's exception specification with this computed exception specification.
Definition Sema.h:5597
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:14116
LocalEagerInstantiationScope(const LocalEagerInstantiationScope &)=delete
static NameClassification DependentNonType()
Definition Sema.h:3759
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3769
ExprResult getExpression() const
Definition Sema.h:3795
NameClassification(const IdentifierInfo *Keyword)
Definition Sema.h:3732
static NameClassification Unknown()
Definition Sema.h:3739
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3743
NameClassificationKind getKind() const
Definition Sema.h:3793
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3787
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3775
NamedDecl * getNonTypeDecl() const
Definition Sema.h:3805
NameClassification(ParsedType Type)
Definition Sema.h:3729
TemplateName getTemplateName() const
Definition Sema.h:3810
ParsedType getType() const
Definition Sema.h:3800
TemplateNameKind getTemplateNameKind() const
Definition Sema.h:3819
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3749
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3781
static NameClassification UndeclaredNonType()
Definition Sema.h:3755
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3763
static NameClassification Error()
Definition Sema.h:3735
void operator()(sema::FunctionScopeInfo *Scope) const
Definition Sema.cpp:2618
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:11489
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11491
RequiredTemplateKind(SourceLocation TemplateKWLoc=SourceLocation())
Template name is required if TemplateKWLoc is valid.
Definition Sema.h:11486
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12541
SFINAETrap & operator=(const SFINAETrap &)=delete
SFINAETrap(const SFINAETrap &)=delete
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12575
SFINAETrap(Sema &S, bool WithAccessChecking=false)
Definition Sema.h:12557
bool withAccessChecking() const
Definition Sema.h:12578
sema::TemplateDeductionInfo * getDeductionInfo() const
Definition Sema.h:12570
SFINAETrap(Sema &S, sema::TemplateDeductionInfo &Info)
Definition Sema.h:12560
SatisfactionStackResetRAII(const SatisfactionStackResetRAII &)=delete
SatisfactionStackResetRAII & operator=(const SatisfactionStackResetRAII &)=delete
ScopedCodeSynthesisContext(Sema &S, const CodeSynthesisContext &Ctx)
Definition Sema.h:13684
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:8312
void diagnose(Sema &S, SourceLocation Loc, QualType T) override
Definition Sema.h:8317
SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
Definition Sema.h:8314
SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
Definition Sema.h:9342
SpecialMemberOverloadResult(CXXMethodDecl *MD)
Definition Sema.h:9329
CXXMethodDecl * getMethod() const
Definition Sema.h:9332
void setMethod(CXXMethodDecl *MD)
Definition Sema.h:9333
void addContextNote(SourceLocation UseLoc)
Definition Sema.h:13650
SynthesizedFunctionScope(const SynthesizedFunctionScope &)=delete
SynthesizedFunctionScope(Sema &S, DeclContext *DC)
Definition Sema.h:13638
SynthesizedFunctionScope & operator=(const SynthesizedFunctionScope &)=delete
SourceLocation getLocation() const
Definition Sema.h:12299
bool ContainsDecl(const NamedDecl *ND) const
Definition Sema.h:12289
const DeclContext * getDeclContext() const
Definition Sema.h:12295
TemplateCompareNewDeclInfo(const DeclContext *DeclCtx, const DeclContext *LexicalDeclCtx, SourceLocation Loc)
Definition Sema.h:12273
const NamedDecl * getDecl() const
Definition Sema.h:12287
TemplateCompareNewDeclInfo(const NamedDecl *ND)
Definition Sema.h:12272
const DeclContext * getLexicalDeclContext() const
Definition Sema.h:12291
TentativeAnalysisScope(Sema &SemaRef)
Definition Sema.h:12592
TentativeAnalysisScope & operator=(const TentativeAnalysisScope &)=delete
TentativeAnalysisScope(const TentativeAnalysisScope &)=delete
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
VerifyICEDiagnoser(bool Suppress=false)
Definition Sema.h:7738
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:864
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:1447
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:3637
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:13715
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:8221
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:13699
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:11007
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13150
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2691
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:1138
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:1590
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:14101
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
void PopParsingClass(ParsingClassState state)
Definition Sema.h:6579
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:10094
void LoadExternalWeakUndeclaredIdentifiers()
Load weak undeclared identifiers from the external source.
Definition Sema.cpp:1102
bool containsUnexpandedParameterPacks(Declarator &D)
Determine whether the given declarator contains any unexpanded parameter packs.
std::optional< QualType > BuiltinVectorMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
std::optional< uint64_t > ComputeExpansionSize(CXXExpansionStmtPattern *Expansion)
bool CheckExplicitObjectOverride(CXXMethodDecl *New, const CXXMethodDecl *Old)
llvm::SmallPtrSet< SpecialMemberDecl, 4 > SpecialMembersBeingDeclared
The C++ special members which we are currently in the process of declaring.
Definition Sema.h:6568
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc)
void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc, Scope *curScope)
ActonPragmaExport - called on well-formed '#pragma export'.
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs, SmallVectorImpl< const Attr * > &OutAttrs)
Process the attributes before creating an attributed statement.
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8267
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:8189
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:970
bool isAttrContext() const
Definition Sema.h:6975
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:8260
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition Sema.cpp:2791
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9358
@ LookupLabel
Label name lookup.
Definition Sema.h:9367
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9362
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9389
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9381
@ LookupOMPReductionName
Look up the name of an OpenMP user-defined reduction operation.
Definition Sema.h:9403
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9397
@ LookupObjCProtocolName
Look up the name of an Objective-C protocol.
Definition Sema.h:9399
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9394
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9374
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition Sema.h:9401
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition Sema.h:9385
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9370
@ LookupDestructorName
Look up a name following ~ in a destructor name.
Definition Sema.h:9377
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9365
@ LookupOMPMapperName
Look up the name of an OpenMP user-defined mapper.
Definition Sema.h:9405
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9407
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:9308
LazyVector< TypedefNameDecl *, ExternalSemaSource, &ExternalSemaSource::ReadExtVectorDecls, 2, 2 > ExtVectorDeclsType
Definition Sema.h:4962
UnaryTransformType::UTTKind UTTKind
Definition Sema.h:15507
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:6320
SemaM68k & M68k()
Definition Sema.h:1497
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:13769
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:1380
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:2144
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:9798
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:4907
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:5136
OpaquePtr< QualType > TypeTy
Definition Sema.h:1298
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.
TypeSourceInfo * SubstFriendType(TypeSourceInfo *TSI, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity)
void ActOnFinishDelayedMemberInitializers(Decl *Record)
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
bool CheckCXXThisType(SourceLocation Loc, QualType Type)
Check whether the type of 'this' is valid in the current context.
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class)
Perform qualified name lookup into all base classes of the given class.
void addImplicitTypedef(StringRef Name, QualType T)
Definition Sema.cpp:370
void PrintContextStack()
Definition Sema.h:13778
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:657
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
SemaOpenMP & OpenMP()
Definition Sema.h:1532
void CheckDelegatingCtorCycles()
llvm::SmallSet< SourceLocation, 2 > SrcLocSet
Definition Sema.h:9307
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:2319
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition Sema.h:6358
bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is visible.
Definition Sema.h:9674
bool FormatStringHasSArg(const StringLiteral *FExpr)
StmtResult BuildCXXForRangeRangeVar(Scope *S, Expr *Range, QualType Type, bool IsConstexpr=false)
Build the range variable of a range-based for loop or iterating expansion statement and return its De...
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec)
Emit a warning for all pending noderef expressions that we recorded.
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis)
void ActOnStmtExprError()
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false, ArrayRef< const Expr * > StopAt={})
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
bool IsLastErrorImmediate
Is the last error level diagnostic immediate.
Definition Sema.h:1368
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:3588
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:15175
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:1259
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:4809
void CheckFloatComparison(SourceLocation Loc, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1848
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:15631
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:6541
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:5235
void emitAndClearUnusedLocalTypedefWarnings()
Definition Sema.cpp:1216
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:6522
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:1248
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:1472
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:376
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
Definition Sema.h:7855
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7857
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7856
void LateTemplateParserCB(void *P, LateParsedTemplate &LPT)
Callback to the parser to parse templated functions when needed.
Definition Sema.h:1349
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:15590
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
static SourceRange getPrintable(SourceLocation L)
Definition Sema.h:15181
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:8209
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:9912
@ Interface
'export module X;'
Definition Sema.h:9909
@ Implementation
'module X;'
Definition Sema.h:9910
@ PartitionInterface
'export module X:Y;'
Definition Sema.h:9911
SourceLocation LocationOfExcessPrecisionNotSatisfied
Definition Sema.h:8347
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1241
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:9621
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition Sema.h:10436
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10439
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10445
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10443
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:1806
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
@ AR_dependent
Definition Sema.h:1691
@ AR_accessible
Definition Sema.h:1689
@ AR_inaccessible
Definition Sema.h:1690
@ AR_delayed
Definition Sema.h:1692
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:15188
@ AcceptSizeless
Relax the normal rules for complete types so that they include sizeless built-in types.
Definition Sema.h:15192
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:686
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc)
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
Adds a conversion function template specialization candidate to the overload set, using template argu...
Preprocessor & getPreprocessor() const
Definition Sema.h:935
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:6953
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2463
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:8336
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl)
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2079
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...
void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, StringLiteral *DeletedMessage=nullptr)
static SourceRange getPrintable(const Expr *E)
Definition Sema.h:15182
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2073
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:15770
void setFunctionHasBranchIntoScope()
Definition Sema.cpp:2644
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:4967
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:2153
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:6782
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, StringRef Arg)
ActOnPragmaMSComment - Called on well formed #pragma comment(kind, "arg").
Definition SemaAttr.cpp:663
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc)
Build an ext-vector type.
StmtResult BuildNonEnumeratingCXXExpansionStmtPattern(CXXExpansionStmtDecl *ESD, Stmt *Init, DeclStmt *ExpansionVarStmt, Expr *ExpansionInitializer, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation RParenLoc, ArrayRef< MaterializeTemporaryExpr * > LifetimeExtendTemps={})
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
SmallVector< AlignPackIncludeState, 8 > AlignPackIncludeStack
Definition Sema.h:2068
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:11209
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:2743
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:4210
@ Default
= default ;
Definition Sema.h:4212
@ Delete
deleted-function-body
Definition Sema.h:4218
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:14063
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:1297
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:2080
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:1487
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:15106
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
void ActOnTranslationUnitScope(Scope *S)
Scope actions.
Definition Sema.cpp:173
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD, bool Diagnose, bool LookForGlobal, DeclarationName Name)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
void ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt)
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand, Expr *Awaiter, bool IsImplicit=false)
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, const Designation &Desig, SourceLocation RParenLoc)
SemaSYCL & SYCL()
Definition Sema.h:1557
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:3018
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:6965
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:1758
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:842
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
LateParsedTemplateMapT LateParsedTemplateMap
Definition Sema.h:11454
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
QualType CheckMatrixCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:12052
@ CTAK_DeducedFromArrayBound
The template argument was deduced from an array bound via template argument deduction.
Definition Sema.h:12063
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12055
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12059
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:9302
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:1577
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:13719
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:1305
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:8176
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:701
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:9313
FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC)
Definition Sema.h:7800
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:2361
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:933
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:4436
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:15555
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
bool CheckCaseExpression(Expr *E)
void resetFPOptions(FPOptions FPO)
Definition Sema.h:11435
bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind)
Definition Sema.h:15658
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:9895
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:15171
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1517
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1372
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:2973
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:1442
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:3206
bool captureSwiftVersionIndependentAPINotes()
Whether APINotes should be gathered for all applicable Swift language versions, without being applied...
Definition Sema.h:1672
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:2076
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void PrintInstantiationStack()
Definition Sema.h:13782
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:3627
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:763
bool isImmediateFunctionContext() const
Definition Sema.h:8201
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:936
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1078
void addExternalSource(IntrusiveRefCntPtr< ExternalSemaSource > E)
Registers an external source.
Definition Sema.cpp:676
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition SemaExpr.cpp:773
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:6548
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:1434
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:6632
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:2072
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:777
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:892
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth)
Called before parsing a function declarator belonging to a function declaration.
void LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded unary operator.
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName)
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition SemaDecl.cpp:713
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2640
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:6575
@ FRS_Success
Definition Sema.h:10824
@ FRS_DiagnosticIssued
Definition Sema.h:10826
@ FRS_NoViableFunction
Definition Sema.h:10825
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:14236
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:986
void mergeVisibilityType(Decl *D, SourceLocation Loc, VisibilityAttr::VisibilityType Type)
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9355
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:9305
bool BuiltinVectorToScalarMath(CallExpr *TheCall)
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD=nullptr, CUDAFunctionTarget CFT=CUDAFunctionTarget::InvalidTarget)
Check validaty of calling convention attribute attr.
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen)
ActOnArrayTypeTrait - Parsed one of the binary type trait support pseudo-functions.
QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType)
llvm::SmallVector< QualType, 4 > CurrentParameterCopyTypes
Stack of types that correspond to the parameter entities that are currently being copy-initialized.
Definition Sema.h:9044
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:15766
@ Conversions
Allow explicit conversion functions but not explicit constructors.
Definition Sema.h:10145
@ All
Allow both explicit conversion functions and explicit constructors.
Definition Sema.h:10147
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:1231
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMemberKind > SpecialMemberDecl
Definition Sema.h:6563
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:1209
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:14975
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:3650
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:1763
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:2734
unsigned InventedParameterInfosStart
The index of the first InventedParameterInfo that refers to the current context.
Definition Sema.h:3530
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:2654
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:12231
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12249
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12239
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12259
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:4958
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:1777
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:8378
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:11504
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11511
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11508
bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Target, bool SkipTargetFirstParameter, SourceLocation TargetLoc, const FunctionProtoType *Source, bool SkipSourceFirstParameter, SourceLocation SourceLoc)
CheckParamExceptionSpec - Check if the parameter and return types of the two functions have equivalen...
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, OverloadCandidateParamOrder PO={})
Add a C++ member function template as a candidate to the candidate set, using template argument deduc...
bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl)
Definition SemaAttr.cpp:838
StmtResult ActOnCXXExpansionStmtPattern(CXXExpansionStmtDecl *ESD, Stmt *Init, Stmt *ExpansionVarStmt, Expr *ExpansionInitializer, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation RParenLoc, ArrayRef< MaterializeTemporaryExpr * > LifetimeExtendTemps)
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, CheckTemplateArgumentInfo &CTAI, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
MergeVarDeclTypes - We parsed a variable 'New' which has the same name and scope as a previous declar...
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg)
Compare types for equality with respect to possibly compatible function types (noreturn adjustment,...
StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body)
AtomicArgumentOrder
Definition Sema.h:2747
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2482
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:514
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:11440
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:3623
std::optional< ExpressionEvaluationContextRecord::InitializationContext > OutermostDeclarationWithDelayedImmediateInvocations() const
Definition Sema.h:8236
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:15178
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition Sema.h:4647
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:1588
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:931
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition Sema.h:8330
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:277
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:2500
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:2633
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:15599
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:14496
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition Sema.h:14516
@ UPPC_RequiresClause
Definition Sema.h:14567
@ UPPC_UsingDeclaration
A using declaration.
Definition Sema.h:14522
@ UPPC_IfExists
Microsoft __if_exists.
Definition Sema.h:14549
@ UPPC_Requirement
Definition Sema.h:14564
@ UPPC_ExceptionType
The type of an exception.
Definition Sema.h:14540
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14519
@ UPPC_Lambda
Lambda expression.
Definition Sema.h:14555
@ UPPC_IfNotExists
Microsoft __if_not_exists.
Definition Sema.h:14552
@ UPPC_PartialSpecialization
Partial specialization.
Definition Sema.h:14546
@ UPPC_Initializer
An initializer.
Definition Sema.h:14531
@ UPPC_BaseType
The base type of a class type.
Definition Sema.h:14501
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14525
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14534
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14504
@ UPPC_Expression
An arbitrary expression.
Definition Sema.h:14498
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14543
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14528
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14507
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition Sema.h:14513
@ UPPC_Block
Block expression.
Definition Sema.h:14558
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14510
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14537
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14561
api_notes::APINotesManager APINotes
Definition Sema.h:1309
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:12611
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:929
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:13164
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:5950
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:2594
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:2115
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:1467
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:3644
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:1522
void SwapSatisfactionStack(llvm::SmallVectorImpl< SatisfactionStackEntryTy > &NewSS)
Definition Sema.h:14970
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:7044
@ ReuseLambdaContextDecl
Definition Sema.h:7044
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:937
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:1462
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:1351
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:1304
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:2162
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:1346
SmallVector< PragmaAttributeGroup, 2 > PragmaAttributeStack
Definition Sema.h:2140
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:2269
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:3631
SemaDirectX & DirectX()
Definition Sema.h:1477
llvm::SmallSetVector< const NamedDecl *, 16 > NamedDeclSetType
Definition Sema.h:6524
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:1507
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:1589
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:1303
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:1237
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2709
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:1232
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
llvm::DenseMap< unsigned, CXXDeductionGuideDecl * > AggregateDeductionCandidates
Definition Sema.h:9047
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:961
void ActOnStartOfCompoundStmt(bool IsStmtExpr)
Definition SemaStmt.cpp:417
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:15612
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:6526
SemaHLSL & HLSL()
Definition Sema.h:1482
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:11453
bool CollectStats
Flag indicating whether or not to collect detailed statistics.
Definition Sema.h:1235
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9354
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:1237
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:6959
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:1849
void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1502
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:1547
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:15789
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
SourceLocation ImplicitMSInheritanceAttrLoc
Source location for newly created implicit MSInheritanceAttrs.
Definition Sema.h:1838
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:5956
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:5330
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
Definition Sema.h:5333
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
Definition Sema.h:5337
MemberPointerConversionDirection
Definition Sema.h:10277
SmallVector< PendingImplicitInstantiation, 1 > LateParsedInstantiations
Queue of implicit template instantiations that cannot be performed eagerly.
Definition Sema.h:14099
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6519
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:2813
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:15173
SemaSwift & Swift()
Definition Sema.h:1562
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:2061
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:6624
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:6989
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6556
StmtResult ActOnExprStmtError()
Definition SemaStmt.cpp:66
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2071
ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef< TypeSourceInfo * > Args, SourceLocation RParenLoc)
const VarDecl * getCopyElisionCandidate(NamedReturnInfo &Info, QualType ReturnType)
Updates given NamedReturnInfo's move-eligible and copy-elidable statuses, considering the function re...
CXXRecordDecl * getCurrentInstantiationOf(NestedNameSpecifier NNS)
If the given nested name specifier refers to the current instantiation, return the declaration that c...
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD)
Mark the exception specifications of all virtual member functions in the given class as needed.
StmtResult BuildCXXEnumeratingExpansionStmtPattern(Decl *ESD, Stmt *Init, Stmt *ExpansionVar, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation RParenLoc)
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
void completeExprArrayBound(Expr *E)
DeclContext * getCurLexicalContext() const
Definition Sema.h:1142
std::function< TypeResult(StringRef, StringRef, SourceLocation)> ParseTypeFromStringCallback
Callback to the parser to parse a type expressed as a string.
Definition Sema.h:1360
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:2118
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:1770
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:1300
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:11857
ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand, UnresolvedLookupExpr *Lookup)
SmallVector< std::deque< PendingImplicitInstantiation >, 8 > SavedPendingInstantiations
Definition Sema.h:14103
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:2165
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:884
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:4824
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:10464
FileNullabilityMap NullabilityMap
A mapping that describes the nullability we've seen in each header file.
Definition Sema.h:15167
ProcessingContextState ParsingClassState
Definition Sema.h:6574
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:1340
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:2628
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
MemberPointerConversionResult CheckMemberPointerConversion(QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind, CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange, bool IgnoreBaseAccess, MemberPointerConversionDirection Direction)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx, StringEvaluationContext EvalContext, bool ErrorOnInvalidMessage)
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
ExprResult ActOnCXXExpansionInitList(MultiExprArg SubExprs, SourceLocation LBraceLoc, SourceLocation RBraceLoc)
ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, StringLiteral *BinaryData, StringRef FileName)
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
bool isDeclaratorFunctionLike(Declarator &D)
Determine whether.
Definition Sema.cpp:3062
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:3896
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition Sema.h:2720
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:15521
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:15113
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...
bool DiagnosePackIndexingInFriendNNS(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc)
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition Sema.h:6986
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:2446
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:11852
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:13162
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:4918
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:5946
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:647
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:15606
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition Sema.h:8205
llvm::MapVector< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3610
StringLiteral * CurInitSeg
Last section used with pragma init_seg.
Definition Sema.h:2114
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9890
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:2575
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:8072
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:2664
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:7001
void ApplyForRangeOrExpansionStatementLifetimeExtension(VarDecl *RangeVar, ArrayRef< MaterializeTemporaryExpr * > Temporaries)
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, ADLResult &Functions)
void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl)
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition Sema.h:6533
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:1445
auto getDefaultDiagFunc()
Definition Sema.h:2321
void ActOnInitPriorityAttr(Decl *D, const Attr *A)
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
VarDecl * BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id)
Perform semantic analysis for the variable declaration that occurs within a C++ catch clause,...
bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount)
Checks that a call expression's argument count is at least the desired number.
bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypePromotion - Determines whether the conversion from FromType to ToType involves ...
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path)
Check a cast of an unknown-any type.
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc)
ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const,addrspace}_cast's.
Definition SemaCast.cpp: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:12612
ClassTemplateDecl * StdTypeIdentity
The C++ "std::type_identity" template, which is defined in <type_traits>.
Definition Sema.h:6552
SemaOpenCL & OpenCL()
Definition Sema.h:1527
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:14112
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:2245
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:15183
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:2650
@ FAPK_Elsewhere
Definition Sema.h:2654
@ FAPK_Fixed
Definition Sema.h:2651
@ FAPK_Variadic
Definition Sema.h:2652
@ FAPK_VAList
Definition Sema.h:2653
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:8197
ObjCMethodDecl * SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl< ObjCMethodDecl * > &Methods)
llvm::DenseMap< ParmVarDecl *, llvm::TinyPtrVector< ParmVarDecl * > > UnparsedDefaultArgInstantiationsMap
Definition Sema.h:13153
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1737
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:15619
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:14946
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:8389
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:3641
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition Sema.h:6785
ExprResult BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index, QualType ParamType, SourceLocation loc, TemplateArgument Replacement, UnsignedOrNone PackIndex, bool Final)
bool MSStructPragmaOn
Definition Sema.h:1835
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:13730
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:14047
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID)
Definition Sema.h:15594
SourceManager & getSourceManager() const
Definition Sema.h:934
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:8460
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:4896
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:651
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:3584
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:987
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:717
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:12331
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:2333
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:9348
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:14052
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:6066
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
CXXExpansionStmtDecl * ActOnCXXExpansionStmtDecl(unsigned TemplateDepth, SourceLocation TemplateKWLoc)
bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc)
PragmaClangSection PragmaClangTextSection
Definition Sema.h:1850
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:7498
bool BoundsSafetyCheckInitialization(const InitializedEntity &Entity, const InitializationKind &Kind, AssignmentAction Action, QualType LHSType, Expr *RHSExpr)
Perform Bounds Safety Semantic checks for initializing a Bounds Safety pointer.
NonTrivialCUnionKind
Definition Sema.h:4149
@ NTCUK_Destruct
Definition Sema.h:4151
@ NTCUK_Init
Definition Sema.h:4150
@ NTCUK_Copy
Definition Sema.h:4152
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:1381
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:8346
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1847
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:9143
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
CXXExpansionStmtDecl * BuildCXXExpansionStmtDecl(DeclContext *Ctx, SourceLocation TemplateKWLoc, NonTypeTemplateParmDecl *NTTP)
bool anyAltivecTypes(QualType srcType, QualType destType)
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc)
PushNamespaceVisibilityAttr - Note that we've entered a namespace with a visibility attribute.
ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, SourceLocation AsmLoc)
std::pair< AvailabilityResult, const NamedDecl * > ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message, ObjCInterfaceDecl *ClassReceiver)
The diagnostic we should emit for D, and the declaration that originated it, or AR_Available.
ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc)
Act on the result of classifying a name as an undeclared (ADL-only) non-type declaration.
StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind, ArrayRef< MaterializeTemporaryExpr * > LifetimeExtendTemps={})
ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition Sema.cpp:2494
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:2060
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:6783
void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro, SourceLocation MutableLoc)
ExternalSemaSource * getExternalSource() const
Definition Sema.h:939
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:1245
void * VisContext
VisContext - Manages the stack for #pragma GCC visibility.
Definition Sema.h:2121
SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const
Returns the top most location responsible for the definition of N.
bool isSFINAEContext() const
Definition Sema.h:13790
FunctionDecl * BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl, QualType AllocType, SourceLocation)
QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs=true)
Definition Sema.h:8815
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:15180
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:13746
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:14931
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:15561
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, const PartialDiagnostic &PD, const FunctionDecl *FD=nullptr)
Definition Sema.h:1148
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:3024
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:2134
void setFunctionHasMustTail()
Definition Sema.cpp:2659
ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType)
void checkUnusedDeclAttributes(Declarator &D)
checkUnusedDeclAttributes - Given a declarator which is not being used to build a declaration,...
bool hasReachableMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is a member specialization declaration (as op...
LabelDecl * LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc=SourceLocation(), bool IsLabelStmt=false)
LookupOrCreateLabel - Do a name lookup of a label with the specified name.
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind)
RecordDecl * CXXTypeInfoDecl
The C++ "type_info" declaration, which is defined in <typeinfo>.
Definition Sema.h:8385
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:14937
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:2649
RedeclarationKind forRedeclarationInCurContext() const
bool hasReachableDefinition(NamedDecl *D)
Definition Sema.h:15650
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:2642
bool CheckAttrTarget(const ParsedAttr &CurrAttr)
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition Sema.h:6544
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:1231
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:1586
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:11315
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:1583
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:1306
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:4710
bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount)
Checks that a call expression's argument count is the desired number.
PragmaAlignPackDiagnoseKind
Definition Sema.h:2223
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:6993
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:1345
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:1884
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14095
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:9918
@ PrivateFragmentImportFinished
after 'module :private;' but a non-import decl has already been seen.
Definition Sema.h:9925
@ ImportFinished
after any non-import decl.
Definition Sema.h:9922
@ PrivateFragmentImportAllowed
after 'module :private;' but before any non-import decl.
Definition Sema.h:9923
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:9919
@ GlobalFragment
after 'module;' but before 'module X;'
Definition Sema.h:9920
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
Definition Sema.h:9927
@ ImportAllowed
after 'module X;' but before any non-import decl.
Definition Sema.h:9921
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:15179
bool checkInstantiatedThreadSafetyAttrs(const Decl *D, const Attr *A)
Recheck instantiated thread-safety attributes that could not be validated on the dependent pattern de...
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
CUDALaunchBoundsAttr * CreateLaunchBoundsAttr(const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks, bool IgnoreArch=false)
Create a CUDALaunchBoundsAttr attribute.
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with the preprocessor.
Definition Sema.cpp:110
VarDecl * BuildForRangeVarDecl(SourceLocation Loc, QualType Type, IdentifierInfo *Name, bool IsConstexpr)
Helper used by the expansion statements and for-range code to build a variable declaration for e....
StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested)
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl)
void incrementMSManglingNumber() const
Definition Sema.h:1266
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:6727
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6749
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6739
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6754
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6744
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6764
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6733
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6759
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6774
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:13738
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:4872
@ AP_InferredFromAnyAppleOS
The availability attribute was inferred from an 'anyAppleOS' availability attribute.
Definition Sema.h:4886
@ AP_PragmaClangAttribute
The availability attribute was applied using 'pragma clang attribute'.
Definition Sema.h:4878
@ AP_InferredFromOtherPlatform
The availability attribute for a specific platform was inferred from an availability attribute for an...
Definition Sema.h:4882
@ AP_PragmaClangAttribute_InferredFromAnyAppleOS
The availability attribute was inferred from an 'anyAppleOS' availability attribute that was applied ...
Definition Sema.h:4891
@ AP_Explicit
The availability attribute was specified explicitly next to the declaration.
Definition Sema.h:4875
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:985
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:14057
SemaPPC & PPC()
Definition Sema.h:1537
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:2507
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:4955
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:1264
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:14939
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:1350
bool CheckDependentFriend(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc, ArrayRef< TemplateParameterList * > TPLs, bool IsInstantiation)
void DiagnoseAmbiguousLookup(LookupResult &Result)
Produce a diagnostic describing the ambiguity that resulted from name lookup.
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void CheckExplicitObjectLambda(Declarator &D)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope.
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD)
Only called on function definitions; if there is a MSVC pragma optimize in scope, consider changing t...
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc)
PopPragmaVisibility - Pop the top element of the visibility stack; used for '#pragma GCC visibility' ...
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
llvm::MapVector< FieldDecl *, DeleteLocs > DeleteExprs
Delete-expressions to be analyzed at the end of translation unit.
Definition Sema.h:8396
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:3634
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:10073
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,...
ExprResult CheckVarOrConceptTemplateTemplateId(const DeclarationNameInfo &NameInfo, TemplateTemplateParmDecl *Template, const TemplateArgumentListInfo *TemplateArgs)
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition Sema.h:8187
SemaSystemZ & SystemZ()
Definition Sema.h:1567
DarwinSDKInfo * getDarwinSDKInfoForAvailabilityChecking()
Definition Sema.cpp:124
bool isRedefinitionAllowedFor(const NamedDecl *D, bool &Visible)
Definition Sema.h:15640
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:3046
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind, SourceLocation Loc)
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
llvm::SmallPtrSet< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3614
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8333
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:10269
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:9904
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:674
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:1308
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:11481
@ TemplateNameIsRequired
Definition Sema.h:11481
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:792
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:6537
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:1307
CXXMethodDecl * CreateLambdaCallOperator(SourceRange IntroducerRange, CXXRecordDecl *Class)
void DiagnoseUnterminatedPragmaAlignPack()
Definition SemaAttr.cpp:632
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition Sema.h:7804
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:930
FPOptions CurFPFeatures
Definition Sema.h:1301
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:1353
QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc)
llvm::SmallPtrSet< const CXXRecordDecl *, 8 > RecordDeclSetTy
Definition Sema.h:6528
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.
ExprResult BuildCXXExpansionSelectExpr(InitListExpr *Range, Expr *Idx)
void addLifetimeBoundToImplicitThis(CXXMethodDecl *MD)
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
void LoadExternalExtnameUndeclaredIdentifiers()
Load pragma redefine_extname'd undeclared identifiers from the external source.
Definition Sema.cpp:1112
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:523
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2070
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:3085
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc, bool IsExplicit)
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
std::unique_ptr< APINotesSelectorDiagnosticState > APINotesSelectorDiagnostics
Definition Sema.h:1311
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef< ParsedType > Args, SourceLocation RParenLoc)
Parsed one of the type trait support pseudo-functions.
StmtResult FinishCXXExpansionStmt(Stmt *Expansion, Stmt *Body)
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition Sema.h:11664
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11674
@ TPC_FriendFunctionTemplate
Definition Sema.h:11672
@ TPC_ClassTemplateMember
Definition Sema.h:11670
@ TPC_FunctionTemplate
Definition Sema.h:11669
@ TPC_FriendClassTemplate
Definition Sema.h:11671
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11673
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:1457
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:1587
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:2149
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:979
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:7763
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:6560
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition Sema.h:13710
void PrintStats() const
Print out statistics about the semantic analysis.
Definition Sema.cpp:691
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:15170
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:1833
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:1250
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:11101
@ BFRK_Check
Determining whether a for-range statement could be built.
Definition Sema.h:11109
@ BFRK_Build
Initial building of a for-range statement.
Definition Sema.h:11103
@ BFRK_Rebuild
Instantiation or recovery rebuild of a for-range statement.
Definition Sema.h:11106
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
SemaNVPTX & NVPTX()
Definition Sema.h:1512
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:586
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:2090
@ PSK_ConstSeg
Definition Sema.h:2093
@ PSK_DataSeg
Definition Sema.h:2091
@ PSK_CodeSeg
Definition Sema.h:2094
@ PSK_BSSSeg
Definition Sema.h:2092
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:646
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:6357
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
ActOnField - Each field of a C struct/union is passed into this in order to create a FieldDecl object...
bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum)
BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a constant expression representing ...
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
CodeAlignAttr * BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E)
ExprResult ActOnStmtExprResult(ExprResult E)
void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate=false, VarTemplateSpecializationDecl *PrevVTSD=nullptr)
BuildVariableInstantiation - Used after a new variable has been created.
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc)
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition Sema.h:3603
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2252
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:1846
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:1364
QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel)
AbstractDiagSelID
Definition Sema.h:6303
@ AbstractSynthesizedIvarType
Definition Sema.h:6310
@ AbstractVariableType
Definition Sema.h:6307
@ AbstractReturnType
Definition Sema.h:6305
@ AbstractNone
Definition Sema.h:6304
@ AbstractFieldType
Definition Sema.h:6308
@ AbstractArrayType
Definition Sema.h:6311
@ AbstractParamType
Definition Sema.h:6306
@ AbstractIvarType
Definition Sema.h:6309
StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
Definition SemaStmt.cpp:976
MSPropertyDecl * HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr)
HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiate the definition of an enum from a given pattern.
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
ExprResult SubstCXXIdExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
Substitute an expression as if it is a address-of-operand, which makes it act like a CXXIdExpression ...
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
void CheckAlignasUnderalignment(Decl *D)
SemaSPIRV & SPIRV()
Definition Sema.h:1552
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:8382
ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand)
Act on the result of classifying a name as an undeclared member of a dependent base class.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
void getSortedUnusedLocalTypedefNameCandidates(SmallVectorImpl< const TypedefNameDecl * > &Sorted) const
Store UnusedLocalTypedefNameCandidates in Sorted in a deterministic order.
Definition Sema.cpp:1203
ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder=AtomicArgumentOrder::API)
Decl * ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc)
Complete the definition of an export declaration.
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI)
Note that we have finished the explicit captures for the given lambda.
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind, SourceLocation Loc)
void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC)
ActOnPragmaFPContract - Called on well formed #pragma {STDC,OPENCL} FP_CONTRACT and #pragma clang fp ...
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
std::optional< ResolvedAllocation > FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, const ImplicitAllocationParameters &IAP, MultiExprArg PlaceArgs, bool Diagnose=true)
Finds the overloads of operator new and delete that are appropriate for the allocation.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
void DiagnoseUnusedAPINotesSelectors()
Diagnose exact API notes selectors that were not matched by any declaration processed in this transla...
DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, SourceLocation EllipsisLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists, TemplateIdAnnotation *TemplateId)
Handle a friend tag declaration where the scope specifier was templated.
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc)
Called on well formed #pragma clang optimize.
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange)
ActOnUnaryExprOrTypeTraitExpr - Handle sizeof(type) and sizeof expr and the same for alignof and __al...
QualType PreferredConditionType(ConditionKind K) const
Definition Sema.h:7995
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:9411
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition Sema.h:9415
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition Sema.h:9421
@ LOLR_Error
The lookup resulted in an error.
Definition Sema.h:9413
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition Sema.h:9418
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition Sema.h:9429
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition Sema.h:9425
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:2679
const ExpressionEvaluationContextRecord & parentEvaluationContext() const
Definition Sema.h:6971
SemaLoongArch & LoongArch()
Definition Sema.h:1492
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:6439
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6444
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6441
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:14091
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:3038
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1297
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:729
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:3580
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:1783
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:15486
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:7841
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:1572
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:3526
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:13706
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:1542
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:2640
StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt)
Definition SemaStmt.cpp:614
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11446
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:7797
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:8341
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1296
static int getPrintable(int I)
Definition Sema.h:15169
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply.
void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName)
Called on well formed #pragma section().
Definition SemaAttr.cpp:926
void ActOnDependentForRangeInitializer(VarDecl *LoopVar, BuildForRangeKind BFRK)
Set the type of a for-range declaration whose for-range or expansion initialiser is dependent.
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition Sema.h:9683
bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling)
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:12993
StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope)
Definition SemaStmt.cpp:591
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:3882
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:15174
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:552
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:8213
ForRangeBeginEndInfo BuildCXXForRangeBeginEndVars(Scope *S, VarDecl *RangeVar, SourceLocation ColonLoc, SourceLocation CoawaitLoc, ArrayRef< MaterializeTemporaryExpr * > LifetimeExtendTemps, BuildForRangeKind Kind, bool IsConstexpr, StmtResult *RebuildResult=nullptr, llvm::function_ref< StmtResult()> RebuildWithDereference={}, IdentifierInfo *BeginName=nullptr, IdentifierInfo *EndName=nullptr)
Determine begin-expr and end-expr and build variable declarations for them as per [stmt....
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
SFINAETrap * CurrentSFINAEContext
Definition Sema.h:13721
SemaARM & ARM()
Definition Sema.h:1452
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:13702
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:15172
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:11011
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:672
QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a block pointer type.
PragmaMsStackAction
Definition Sema.h:1852
@ PSK_Push_Set
Definition Sema.h:1858
@ PSK_Reset
Definition Sema.h:1853
@ PSK_Pop_Set
Definition Sema.h:1859
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:8677
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:13787
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:85
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1810
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3851
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.).
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:4769
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:3647
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:8475
The base class of the type hierarchy.
Definition TypeBase.h:1879
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3801
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3696
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:3361
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4166
A set of unresolved declarations.
The iterator over UnresolvedSets.
Represents a C++ using-declaration.
Definition DeclCXX.h:3616
Represents C++ using-directive.
Definition DeclCXX.h:3121
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3424
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:4289
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:791
Retains information about a captured region.
Definition ScopeInfo.h:817
Contains information about the compound statement currently being parsed.
Definition ScopeInfo.h:67
A collection of diagnostics which were delayed.
A diagnostic message which has been conditionally emitted pending the complete parsing of the current...
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
Provides information about an attempted template argument deduction, whose success or failure was des...
#define UINT_MAX
Definition limits.h:64
Definition SPIR.cpp:47
Enums for the diagnostics of target, target_version and target_clones.
Definition Sema.h:850
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
llvm::DenseMap< int, SourceRange > ParsedSubjectMatchRuleSet
bool operator==(const ValueType &a, const ValueType &b)
void threadSafetyCleanup(BeforeSet *Cache)
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
Top level wrappers for InstallAPI frontend operations.
PragmaClangSectionAction
Definition Sema.h:471
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:818
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:829
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:825
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:821
bool isa(CodeGen::Address addr)
Definition Address.h:330
OpaquePtr< TemplateName > ParsedTemplateTy
Definition Ownership.h:256
@ CPlusPlus
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
VariadicCallType
Definition Sema.h:508
FunctionEffectMode
Used with attributes/effects with a boolean condition, e.g. nonblocking.
Definition Sema.h:454
CUDAFunctionTarget
Definition Cuda.h:65
CanThrowResult
Possible results from evaluation of a noexcept expression.
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
AllocationFunctionScope
The scope in which to find allocation functions.
Definition Sema.h:786
@ Both
Look for allocation functions in both the global scope and in the scope of the allocated class.
Definition Sema.h:794
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:648
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:656
@ BitwiseOp
A bitwise operation.
Definition Sema.h:660
@ Arithmetic
An arithmetic operation.
Definition Sema.h:658
@ Conditional
A conditional (?:) operator.
Definition Sema.h:664
@ CompAssign
A compound assignment expression.
Definition Sema.h:666
@ Comparison
A comparison.
Definition Sema.h:662
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:347
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:1543
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:589
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:599
@ TemplateTemplateArgument
Definition Sema.h:608
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition Overload.h:84
NonTrivialCUnionContext
Definition Sema.h:527
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition Sema.h:623
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:631
@ OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition Sema.h:637
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:628
@ ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition Sema.h:634
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:244
@ Private
'private' clause, allowed on 'parallel', 'serial', 'loop', 'parallel loop', and 'serial loop' constru...
TypeOfKind
The kind of 'typeof' expression we're after.
Definition TypeBase.h:919
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h: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:930
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
bool isFunctionOrMethodOrBlockForAttrSubject(const Decl *D)
Return true if the given decl has function type (function or function-typed variable) or an Objective...
Definition Attr.h:41
OverloadCandidateRewriteKind
The kinds of rewrite we perform on overload candidates.
Definition Overload.h:89
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
LambdaCaptureInitKind
Definition DeclSpec.h: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:473
@ Undefined
Keep undefined.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OffsetOfKind
Definition Sema.h:611
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3833
SmallVector< ImplicitAllocationArguments, 3 > AllocationArgumentSet
Definition Sema.h:231
CorrectTypoKind
Definition Sema.h:813
ActionResult< CXXCtorInitializer * > MemInitResult
Definition Ownership.h:253
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
bool isFunctionOrMethodVariadic(const Decl *D)
Definition Attr.h:144
@ 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:684
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:707
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition Sema.h:782
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition Sema.h:699
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition Sema.h:754
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition Sema.h:744
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition Sema.h:771
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition Sema.h:758
@ CompatibleOBTDiscards
CompatibleOBTDiscards - Assignment discards overflow behavior.
Definition Sema.h:778
@ IncompatibleOBTKinds
IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType kinds, e....
Definition Sema.h:775
@ CompatibleVoidPtrToNonVoidPtr
CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because a void * can implicitly convert...
Definition Sema.h:691
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition Sema.h:733
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:728
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition Sema.h:767
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:686
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition Sema.h:718
@ IncompatiblePointerDiscardsOverflowBehavior
IncompatiblePointerDiscardsOverflowBehavior - The assignment discards overflow behavior annotations b...
Definition Sema.h:738
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition Sema.h:695
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition Sema.h:703
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition Sema.h:750
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition Sema.h:712
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:724
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition Sema.h:762
TagUseKind
Definition Sema.h:446
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:462
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6045
TUFragmentKind
Definition Sema.h:482
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:550
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:582
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:557
@ DependentNonType
The name denotes a member of a dependent type that could not be resolved.
Definition Sema.h:571
@ UndeclaredTemplate
The name was classified as an ADL-only function template name.
Definition Sema.h:584
@ NonType
The name was classified as a specific non-type, non-template declaration.
Definition Sema.h:563
@ Unknown
This name is not a type or template in this context, but might be something else.
Definition Sema.h:553
@ Error
Classification failed; an error has been produced.
Definition Sema.h:555
@ Type
The name was classified as a type.
Definition Sema.h:559
@ TypeTemplate
The name was classified as a template whose specializations are types.
Definition Sema.h:578
@ Concept
The name was classified as a concept name.
Definition Sema.h:586
@ OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
Definition Sema.h:576
@ UndeclaredNonType
The name was classified as an ADL-only function name.
Definition Sema.h:567
@ VarTemplate
The name was classified as a variable template name.
Definition Sema.h:580
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Decl.h:2029
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:494
CastKind
CastKind - The kind of operation required for a conversion.
AllowFoldKind
Definition Sema.h:650
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:671
PragmaMSStructKind
Definition PragmaKinds.h:24
AssignmentAction
Definition Sema.h:218
@ Deduced
The normal deduced case.
Definition TypeBase.h:1818
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Decl.h:2018
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:516
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:158
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:2254
IfExistsResult
Describes the result of an "if-exists" condition check.
Definition Sema.h:798
@ Exists
The symbol exists.
Definition Sema.h:800
@ DoesNotExist
The symbol does not exist.
Definition Sema.h:803
MSInheritanceModel
Assigned inheritance model for a class in the MS C++ ABI.
Definition Specifiers.h:411
bool hasFunctionProto(const Decl *D)
hasFunctionProto - Return true if the given decl has a argument information.
Definition Attr.h:56
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
unsigned getFunctionOrMethodNumParams(const Decl *D)
getFunctionOrMethodNumParams - Return number of function or method parameters.
Definition Attr.h:65
TPOC
The context in which partial ordering of function templates occurs.
Definition Template.h:310
TrivialABIHandling
Definition Sema.h:640
@ ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition Sema.h:645
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:642
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:375
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:425
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:420
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:423
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:396
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:382
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:418
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:427
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:415
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:385
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:399
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:388
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:402
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:391
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:412
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:429
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:406
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:409
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:833
@ CaseValue
Expression in a case label.
Definition Sema.h:834
@ StaticAssertMessageData
Call to data() in a static assert message.
Definition Sema.h:844
@ Enumerator
Enumerator value with fixed underlying type.
Definition Sema.h:835
@ StaticAssertMessageSize
Call to size() in a static assert message.
Definition Sema.h:842
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:841
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:839
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:837
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:846
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:840
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
SourceLocIdentKind
Definition Expr.h:5024
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:6020
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6031
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6034
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6038
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2248
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:2000
CheckedConversionKind
The kind of conversion being performed.
Definition Sema.h:433
@ Implicit
An implicit conversion.
Definition Sema.h:435
@ CStyleCast
A C-style cast.
Definition Sema.h:437
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
Definition Sema.h:443
@ OtherCast
A cast other than a C-style cast.
Definition Sema.h:441
@ FunctionalCast
A functional-style cast.
Definition Sema.h:439
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
Selector diagnostic state for all API notes readers used by one Sema.
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:248
SourceLocation PointerEndLoc
The end location for the first pointer declarator in the file.
Definition Sema.h:255
SourceLocation PointerLoc
The first pointer declarator (of any pointer kind) in the file that does not have a corresponding nul...
Definition Sema.h:251
bool SawTypeNullability
Whether we saw any type nullability annotations in the given file.
Definition Sema.h:261
uint8_t PointerKind
Which kind of pointer declarator we saw.
Definition Sema.h:258
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition TypeBase.h:5158
Holds information about the various types of exception specification.
Definition TypeBase.h:5478
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5480
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5483
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5486
Extra information about a function prototype.
Definition TypeBase.h:5506
Represents a complete lambda introducer.
Definition DeclSpec.h:2884
Contains a late templated function.
Definition Sema.h:15859
FPOptions FPO
Floating-point options in the point of definition.
Definition Sema.h:15864
Decl * D
The template function declaration to be late parsed.
Definition Sema.h:15862
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:934
Describes how types, statements, expressions, and declarations should be printed.
SourceLocation CurrentPragmaLocation
Definition Sema.h:2065
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10556
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10563
CheckNonDependentConversionsFlag(bool SuppressUserConversions, bool OnlyInitializeNonUserDefinedConversions)
Definition Sema.h:10565
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:12090
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12086
CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &)=delete
CheckTemplateArgumentInfo(bool PartialOrdering=false, bool MatchingTTP=false)
Definition Sema.h:12067
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12079
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12076
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12076
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:13201
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition Sema.h:13372
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
bool InParameterMappingSubstitution
Whether we're substituting into the parameter mapping of a constraint.
Definition Sema.h:13329
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition Sema.h:13345
ArrayRef< TemplateArgument > template_arguments() const
Definition Sema.h:13364
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation,...
Definition Sema.h:13340
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13332
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13358
bool InConstraintSubstitution
Whether we're substituting into constraints.
Definition Sema.h:13326
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13348
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition Sema.h:13355
SynthesisKind
The kind of template instantiation we are performing.
Definition Sema.h:13203
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13292
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition Sema.h:13213
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition Sema.h:13222
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition Sema.h:13241
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13289
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition Sema.h:13249
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition Sema.h:13256
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13296
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition Sema.h:13267
@ Memoization
Added for Template instantiation observation.
Definition Sema.h:13302
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition Sema.h:13232
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition Sema.h:13308
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13305
@ PartialOrderingTTP
We are performing partial ordering for template template parameters.
Definition Sema.h:13311
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13229
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition Sema.h:13237
@ SYCLKernelLaunchOverloadResolution
We are performing overload resolution for a call to a function template or variable template named 's...
Definition Sema.h:13319
@ ExpansionStmtInstantiation
We are instantiating an expansion statement.
Definition Sema.h:13322
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13245
@ TemplateInstantiation
We are instantiating a template declaration.
Definition Sema.h:13206
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition Sema.h:13259
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13263
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13218
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13286
@ SYCLKernelLaunchLookup
We are performing name lookup for a function template or variable template named 'sycl_kernel_launch'...
Definition Sema.h:13315
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition Sema.h:13252
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13335
CXXSpecialMemberKind SpecialMember
The special member being declared or defined.
Definition Sema.h:13361
bool isInstantiationRecord() const
Determines whether this template is an actual instantiation that should be counted toward the maximum...
InitializationContext(SourceLocation Loc, ValueDecl *Decl, DeclContext *Context)
Definition Sema.h:6888
Data structure used to record current or nested expression evaluation contexts.
Definition Sema.h:6789
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:6822
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition Sema.h:6824
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6875
Decl * ManglingContextDecl
The declaration that provides context for lambda expressions and block literals if the normal declara...
Definition Sema.h:6809
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:6818
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition Sema.h:6829
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:6837
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition Sema.h:6833
bool IsCaseExpr
Whether evaluating an expression for a switch case label.
Definition Sema.h:6878
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6843
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:6804
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition Sema.h:6851
bool RebuildDefaultArgOrDefaultInit
Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
Definition Sema.h:6881
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6847
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition Sema.h:6794
VarDecl * DeclForInitializer
Declaration for initializer if one is currently being parsed.
Definition Sema.h:6814
std::optional< InitializationContext > DelayedDefaultInitializationContext
Definition Sema.h:6898
ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext)
Definition Sema.h:6900
ExpressionEvaluationContext Context
The expression evaluation context.
Definition Sema.h:6791
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition Sema.h:6798
Holds the 'begin' and 'end' variables of a range-based for loop or expansion statement; begin-expr an...
Definition Sema.h:11152
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2662
FunctionEffectDiffVector(const FunctionEffectsRef &Old, const FunctionEffectsRef &New)
Caller should short-circuit by checking for equality first.
std::optional< FunctionEffectWithCondition > Old
Definition Sema.h:15719
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:15723
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:15731
std::optional< FunctionEffectWithCondition > New
Definition Sema.h:15721
FunctionEffect::Kind EffectKind
Definition Sema.h:15716
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13548
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:14229
LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, Decl *D)
Definition Sema.h:14232
bool isMoveEligible() const
Definition Sema.h:11206
bool isCopyElidable() const
Definition Sema.h:11207
const VarDecl * Candidate
Definition Sema.h:11201
IdentifierInfo * Identifier
The identifier preceding the '::'.
Definition Sema.h:3339
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType=ParsedType())
Creates info object for the most typical case.
Definition Sema.h:3348
SourceLocation IdentifierLoc
The location of the identifier.
Definition Sema.h:3342
SourceLocation CCLoc
The location of the '::'.
Definition Sema.h:3345
ParsedType ObjectType
The type of the object, if we're parsing nested-name-specifier in a member access expression.
Definition Sema.h:3336
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType)
Definition Sema.h:3354
OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType)
Definition Sema.h:12712
Information from a C++ pragma export, for a symbol that we haven't seen the declaration for yet.
Definition Sema.h:2356
This an attribute introduced by #pragma clang attribute.
Definition Sema.h:2124
SmallVector< attr::SubjectMatchRule, 4 > MatchRules
Definition Sema.h:2127
A push'd group of PragmaAttributeEntries.
Definition Sema.h:2132
SourceLocation Loc
The location of the push attribute.
Definition Sema.h:2134
SmallVector< PragmaAttributeEntry, 2 > Entries
Definition Sema.h:2137
const IdentifierInfo * Namespace
The namespace of this push group.
Definition Sema.h:2136
SourceLocation PragmaLocation
Definition Sema.h:1843
PragmaMsStackAction Action
Definition Sema.h:1863
Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
Definition Sema.h:1976
llvm::StringRef StackSlotLabel
Definition Sema.h:1972
SourceLocation PragmaLocation
Definition Sema.h:1974
SourceLocation PragmaPushLocation
Definition Sema.h:1975
ValueType CurrentValue
Definition Sema.h:2046
void SentinelAction(PragmaMsStackAction Action, StringRef Label)
Definition Sema.h:2032
bool hasValue() const
Definition Sema.h:2042
SmallVector< Slot, 2 > Stack
Definition Sema.h:2044
ValueType DefaultValue
Definition Sema.h:2045
SourceLocation CurrentPragmaLocation
Definition Sema.h:2047
PragmaStack(const ValueType &Default)
Definition Sema.h:2039
void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value)
Definition Sema.h:1983
ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val)
Definition Sema.h:5170
ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val)
Definition Sema.h:5164
RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
Definition Sema.h:13173
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:10453
SFINAEContextBase & operator=(const SFINAEContextBase &)=delete
SFINAEContextBase(Sema &S, SFINAETrap *Cur)
Definition Sema.h:12521
SFINAEContextBase(const SFINAEContextBase &)=delete
Abstract class used to diagnose incomplete types.
Definition Sema.h:8274
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull)
Definition Sema.h:2704
unsigned LayoutCompatible
If true, Type should be compared with other expression's types for layout-compatibility.
Definition Sema.h:2713
bool CheckSameAsPrevious
Definition Sema.h:361
NamedDecl * Previous
Definition Sema.h:362
SkipBodyInfo()=default
NamedDecl * New
Definition Sema.h:363
Information about a template-id annotation token.