clang 19.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
19#include "clang/AST/ASTFwd.h"
20#include "clang/AST/Attr.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
28#include "clang/AST/ExprObjC.h"
32#include "clang/AST/NSAPI.h"
34#include "clang/AST/StmtCXX.h"
35#include "clang/AST/TypeLoc.h"
39#include "clang/Basic/Cuda.h"
42#include "clang/Basic/Module.h"
50#include "clang/Sema/DeclSpec.h"
56#include "clang/Sema/Scope.h"
57#include "clang/Sema/SemaBase.h"
61#include "clang/Sema/Weak.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/STLForwardCompat.h"
64#include "llvm/ADT/SetVector.h"
65#include "llvm/ADT/SmallBitVector.h"
66#include "llvm/ADT/SmallPtrSet.h"
67#include "llvm/ADT/SmallSet.h"
68#include "llvm/ADT/SmallVector.h"
69#include "llvm/ADT/TinyPtrVector.h"
70#include <deque>
71#include <memory>
72#include <optional>
73#include <string>
74#include <tuple>
75#include <vector>
76
77namespace llvm {
78class APSInt;
79template <typename ValueT, typename ValueInfoT> class DenseSet;
80class SmallBitVector;
81struct InlineAsmIdentifierInfo;
82} // namespace llvm
83
84namespace clang {
85class ADLResult;
86class ASTConsumer;
87class ASTContext;
88class ASTMutationListener;
89class ASTReader;
90class ASTWriter;
91class ArrayType;
92class ParsedAttr;
93class BindingDecl;
94class BlockDecl;
95class CapturedDecl;
96class CXXBasePath;
97class CXXBasePaths;
98class CXXBindTemporaryExpr;
100class CXXConstructorDecl;
101class CXXConversionDecl;
102class CXXDeleteExpr;
103class CXXDestructorDecl;
104class CXXFieldCollector;
105class CXXMemberCallExpr;
106class CXXMethodDecl;
107class CXXScopeSpec;
108class CXXTemporary;
109class CXXTryStmt;
110class CallExpr;
111class ClassTemplateDecl;
112class ClassTemplatePartialSpecializationDecl;
113class ClassTemplateSpecializationDecl;
114class VarTemplatePartialSpecializationDecl;
115class CodeCompleteConsumer;
116class CodeCompletionAllocator;
117class CodeCompletionTUInfo;
118class CodeCompletionResult;
119class CoroutineBodyStmt;
120class Decl;
121class DeclAccessPair;
122class DeclContext;
123class DeclRefExpr;
124class DeclaratorDecl;
125class DeducedTemplateArgument;
126class DependentDiagnostic;
127class DesignatedInitExpr;
128class Designation;
129class EnableIfAttr;
130class EnumConstantDecl;
131class Expr;
132class ExtVectorType;
133class FormatAttr;
134class FriendDecl;
135class FunctionDecl;
136class FunctionProtoType;
137class FunctionTemplateDecl;
138class ImplicitConversionSequence;
140class InitListExpr;
141class InitializationKind;
142class InitializationSequence;
143class InitializedEntity;
144class IntegerLiteral;
145class LabelStmt;
146class LambdaExpr;
147class LangOptions;
148class LocalInstantiationScope;
149class LookupResult;
150class MacroInfo;
152class ModuleLoader;
153class MultiLevelTemplateArgumentList;
154class NamedDecl;
155class ObjCImplementationDecl;
156class ObjCInterfaceDecl;
157class ObjCMethodDecl;
158class ObjCProtocolDecl;
159struct OverloadCandidate;
160enum class OverloadCandidateParamOrder : char;
162class OverloadCandidateSet;
163class OverloadExpr;
164class ParenListExpr;
165class ParmVarDecl;
166class Preprocessor;
167class PseudoDestructorTypeStorage;
168class PseudoObjectExpr;
169class QualType;
170class SemaCodeCompletion;
171class SemaCUDA;
172class SemaHLSL;
173class SemaObjC;
174class SemaOpenACC;
175class SemaOpenMP;
176class SemaSYCL;
177class StandardConversionSequence;
178class Stmt;
179class StringLiteral;
180class SwitchStmt;
181class TemplateArgument;
182class TemplateArgumentList;
183class TemplateArgumentLoc;
184class TemplateDecl;
185class TemplateInstantiationCallback;
186class TemplateParameterList;
187class TemplatePartialOrderingContext;
188class TemplateTemplateParmDecl;
189class Token;
190class TypeAliasDecl;
191class TypedefDecl;
192class TypedefNameDecl;
193class TypeLoc;
194class TypoCorrectionConsumer;
195class UnqualifiedId;
196class UnresolvedLookupExpr;
197class UnresolvedMemberExpr;
198class UnresolvedSetImpl;
199class UnresolvedSetIterator;
200class UsingDecl;
201class UsingShadowDecl;
202class ValueDecl;
203class VarDecl;
204class VarTemplateSpecializationDecl;
205class VisibilityAttr;
206class VisibleDeclConsumer;
207class IndirectFieldDecl;
208struct DeductionFailureInfo;
209class TemplateSpecCandidateSet;
210
211namespace sema {
212class AccessedEntity;
213class BlockScopeInfo;
214class Capture;
215class CapturedRegionScopeInfo;
216class CapturingScopeInfo;
217class CompoundScopeInfo;
218class DelayedDiagnostic;
219class DelayedDiagnosticPool;
220class FunctionScopeInfo;
221class LambdaScopeInfo;
222class PossiblyUnreachableDiag;
223class RISCVIntrinsicManager;
224class SemaPPCallbacks;
225class TemplateDeductionInfo;
226} // namespace sema
227
228namespace threadSafety {
229class BeforeSet;
230void threadSafetyCleanup(BeforeSet *Cache);
231} // namespace threadSafety
232
233// FIXME: No way to easily map from TemplateTypeParmTypes to
234// TemplateTypeParmDecls, so we have this horrible PointerUnion.
235typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *>,
236 SourceLocation>
238
239/// Describes whether we've seen any nullability information for the given
240/// file.
242 /// The first pointer declarator (of any pointer kind) in the file that does
243 /// not have a corresponding nullability annotation.
245
246 /// The end location for the first pointer declarator in the file. Used for
247 /// placing fix-its.
249
250 /// Which kind of pointer declarator we saw.
251 uint8_t PointerKind;
252
253 /// Whether we saw any type nullability annotations in the given file.
254 bool SawTypeNullability = false;
255};
256
257/// A mapping from file IDs to a record of whether we've seen nullability
258/// information in that file.
260 /// A mapping from file IDs to the nullability information for each file ID.
261 llvm::DenseMap<FileID, FileNullability> Map;
262
263 /// A single-element cache based on the file ID.
264 struct {
267 } Cache;
268
269public:
271 // Check the single-element cache.
272 if (file == Cache.File)
273 return Cache.Nullability;
274
275 // It's not in the single-element cache; flush the cache if we have one.
276 if (!Cache.File.isInvalid()) {
277 Map[Cache.File] = Cache.Nullability;
278 }
279
280 // Pull this entry into the cache.
281 Cache.File = file;
282 Cache.Nullability = Map[file];
283 return Cache.Nullability;
284 }
285};
286
287/// Tracks expected type during expression parsing, for use in code completion.
288/// The type is tied to a particular token, all functions that update or consume
289/// the type take a start location of the token they are looking at as a
290/// parameter. This avoids updating the type on hot paths in the parser.
292public:
293 PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
294
295 void enterCondition(Sema &S, SourceLocation Tok);
296 void enterReturn(Sema &S, SourceLocation Tok);
298 /// Handles e.g. BaseType{ .D = Tok...
300 const Designation &D);
301 /// Computing a type for the function argument may require running
302 /// overloading, so we postpone its computation until it is actually needed.
303 ///
304 /// Clients should be very careful when using this function, as it stores a
305 /// function_ref, clients should make sure all calls to get() with the same
306 /// location happen while function_ref is alive.
307 ///
308 /// The callback should also emit signature help as a side-effect, but only
309 /// if the completion point has been reached.
311 llvm::function_ref<QualType()> ComputeType);
312
314 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
315 SourceLocation OpLoc);
316 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
318 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
319 /// Handles all type casts, including C-style cast, C++ casts, etc.
321
322 /// Get the expected type associated with this location, if any.
323 ///
324 /// If the location is a function argument, determining the expected type
325 /// involves considering all function overloads and the arguments so far.
326 /// In this case, signature help for these function overloads will be reported
327 /// as a side-effect (only if the completion point has been reached).
329 if (!Enabled || Tok != ExpectedLoc)
330 return QualType();
331 if (!Type.isNull())
332 return Type;
333 if (ComputeType)
334 return ComputeType();
335 return QualType();
336 }
337
338private:
339 bool Enabled;
340 /// Start position of a token for which we store expected type.
341 SourceLocation ExpectedLoc;
342 /// Expected type for a token starting at ExpectedLoc.
344 /// A function to compute expected type at ExpectedLoc. It is only considered
345 /// if Type is null.
346 llvm::function_ref<QualType()> ComputeType;
347};
348
350 SkipBodyInfo() = default;
351 bool ShouldSkip = false;
353 NamedDecl *Previous = nullptr;
354 NamedDecl *New = nullptr;
355};
356
357/// Describes the result of template argument deduction.
358///
359/// The TemplateDeductionResult enumeration describes the result of
360/// template argument deduction, as returned from
361/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
362/// structure provides additional information about the results of
363/// template argument deduction, e.g., the deduced template argument
364/// list (if successful) or the specific template parameters or
365/// deduced arguments that were involved in the failure.
367 /// Template argument deduction was successful.
368 Success = 0,
369 /// The declaration was invalid; do nothing.
370 Invalid,
371 /// Template argument deduction exceeded the maximum template
372 /// instantiation depth (which has already been diagnosed).
374 /// Template argument deduction did not deduce a value
375 /// for every template parameter.
377 /// Template argument deduction did not deduce a value for every
378 /// expansion of an expanded template parameter pack.
380 /// Template argument deduction produced inconsistent
381 /// deduced values for the given template parameter.
383 /// Template argument deduction failed due to inconsistent
384 /// cv-qualifiers on a template parameter type that would
385 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
386 /// but were given a non-const "X".
388 /// Substitution of the deduced template argument values
389 /// resulted in an error.
391 /// After substituting deduced template arguments, a dependent
392 /// parameter type did not match the corresponding argument.
394 /// After substituting deduced template arguments, an element of
395 /// a dependent parameter type did not match the corresponding element
396 /// of the corresponding argument (when deducing from an initializer list).
398 /// A non-depnedent component of the parameter did not match the
399 /// corresponding component of the argument.
401 /// When performing template argument deduction for a function
402 /// template, there were too many call arguments.
404 /// When performing template argument deduction for a function
405 /// template, there were too few call arguments.
407 /// The explicitly-specified template arguments were not valid
408 /// template arguments for the given template.
410 /// Checking non-dependent argument conversions failed.
412 /// The deduced arguments did not satisfy the constraints associated
413 /// with the template.
415 /// Deduction failed; that's all we know.
417 /// CUDA Target attributes do not match.
419 /// Some error which was already diagnosed.
421};
422
423/// Kinds of C++ special members.
431 Invalid
432};
433
434/// The kind of conversion being performed.
436 /// An implicit conversion.
437 Implicit,
438 /// A C-style cast.
440 /// A functional-style cast.
442 /// A cast other than a C-style cast.
443 OtherCast,
444 /// A conversion for an operand of a builtin overloaded operator.
446};
447
448/// Sema - This implements semantic analysis and AST building for C.
449/// \nosubgrouping
450class Sema final : public SemaBase {
451 // Table of Contents
452 // -----------------
453 // 1. Semantic Analysis (Sema.cpp)
454 // 2. C++ Access Control (SemaAccess.cpp)
455 // 3. Attributes (SemaAttr.cpp)
456 // 4. Availability Attribute Handling (SemaAvailability.cpp)
457 // 5. Casts (SemaCast.cpp)
458 // 6. Extra Semantic Checking (SemaChecking.cpp)
459 // 7. C++ Coroutines (SemaCoroutine.cpp)
460 // 8. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
461 // 9. Declarations (SemaDecl.cpp)
462 // 10. Declaration Attribute Handling (SemaDeclAttr.cpp)
463 // 11. C++ Declarations (SemaDeclCXX.cpp)
464 // 12. C++ Exception Specifications (SemaExceptionSpec.cpp)
465 // 13. Expressions (SemaExpr.cpp)
466 // 14. C++ Expressions (SemaExprCXX.cpp)
467 // 15. Member Access Expressions (SemaExprMember.cpp)
468 // 16. Initializers (SemaInit.cpp)
469 // 17. C++ Lambda Expressions (SemaLambda.cpp)
470 // 18. Name Lookup (SemaLookup.cpp)
471 // 19. Modules (SemaModule.cpp)
472 // 20. C++ Overloading (SemaOverload.cpp)
473 // 21. Pseudo-Object (SemaPseudoObject.cpp)
474 // 22. Statements (SemaStmt.cpp)
475 // 23. `inline asm` Statement (SemaStmtAsm.cpp)
476 // 24. Statement Attribute Handling (SemaStmtAttr.cpp)
477 // 25. C++ Templates (SemaTemplate.cpp)
478 // 26. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
479 // 27. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
480 // 28. C++ Template Declaration Instantiation
481 // (SemaTemplateInstantiateDecl.cpp)
482 // 29. C++ Variadic Templates (SemaTemplateVariadic.cpp)
483 // 30. Constraints and Concepts (SemaConcept.cpp)
484 // 31. Types (SemaType.cpp)
485 // 32. FixIt Helpers (SemaFixItUtils.cpp)
486 // 33. Name Lookup for RISC-V Vector Intrinsic (SemaRISCVVectorLookup.cpp)
487
488 /// \name Semantic Analysis
489 /// Implementations are in Sema.cpp
490 ///@{
491
492public:
493 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
495 CodeCompleteConsumer *CompletionConsumer = nullptr);
496 ~Sema();
497
498 /// Perform initialization that occurs after the parser has been
499 /// initialized but before it parses anything.
500 void Initialize();
501
502 /// This virtual key function only exists to limit the emission of debug info
503 /// describing the Sema class. GCC and Clang only emit debug info for a class
504 /// with a vtable when the vtable is emitted. Sema is final and not
505 /// polymorphic, but the debug info size savings are so significant that it is
506 /// worth adding a vtable just to take advantage of this optimization.
507 virtual void anchor();
508
509 const LangOptions &getLangOpts() const { return LangOpts; }
512
515 Preprocessor &getPreprocessor() const { return PP; }
516 ASTContext &getASTContext() const { return Context; }
520
522 StringRef Platform);
524
525 /// Registers an external source. If an external source already exists,
526 /// creates a multiplex external source and appends to it.
527 ///
528 ///\param[in] E - A non-null external sema source.
529 ///
531
532 void PrintStats() const;
533
534 /// Warn that the stack is nearly exhausted.
536
537 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
538 /// guaranteed). Produces a warning if we're low on stack space and allocates
539 /// more in that case. Use this in code that may recurse deeply (for example,
540 /// in template instantiation) to avoid stack overflow.
542 llvm::function_ref<void()> Fn);
543
544 /// Returns default addr space for method qualifiers.
546
547 /// Load weak undeclared identifiers from the external source.
549
550 /// Determine if VD, which must be a variable or function, is an external
551 /// symbol that nonetheless can't be referenced from outside this translation
552 /// unit because its type has no linkage and it's not extern "C".
553 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
554
555 /// Obtain a sorted list of functions that are undefined but ODR-used.
557 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined);
558
559 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
561 /// Retrieves list of suspicious delete-expressions that will be checked at
562 /// the end of translation unit.
563 const llvm::MapVector<FieldDecl *, DeleteLocs> &
565
566 /// Cause the active diagnostic on the DiagosticsEngine to be
567 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
568 /// should not be used elsewhere.
569 void EmitCurrentDiagnostic(unsigned DiagID);
570
571 void addImplicitTypedef(StringRef Name, QualType T);
572
573 /// Whether uncompilable error has occurred. This includes error happens
574 /// in deferred diagnostics.
575 bool hasUncompilableErrorOccurred() const;
576
577 bool findMacroSpelling(SourceLocation &loc, StringRef name);
578
579 /// Calls \c Lexer::getLocForEndOfToken()
581
582 /// Retrieve the module loader associated with the preprocessor.
584
585 /// Invent a new identifier for parameters of abbreviated templates.
588 unsigned Index);
589
591
592 // Emit all deferred diagnostics.
593 void emitDeferredDiags();
594
596 /// The global module fragment, between 'module;' and a module-declaration.
598 /// A normal translation unit fragment. For a non-module unit, this is the
599 /// entire translation unit. Otherwise, it runs from the module-declaration
600 /// to the private-module-fragment (if any) or the end of the TU (if not).
602 /// The private module fragment, between 'module :private;' and the end of
603 /// the translation unit.
604 Private
605 };
606
610
612
613 void PushFunctionScope();
614 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
616
617 /// This is used to inform Sema what the current TemplateParameterDepth
618 /// is during Parsing. Currently it is used to pass on the depth
619 /// when parsing generic lambda 'auto' parameters.
620 void RecordParsingTemplateParameterDepth(unsigned Depth);
621
622 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
624 unsigned OpenMPCaptureLevel = 0);
625
626 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
627 /// time after they've been popped.
629 Sema *Self;
630
631 public:
632 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
634 };
635
637 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
638
641 const Decl *D = nullptr,
642 QualType BlockType = QualType());
643
645
650
651 void PushCompoundScope(bool IsStmtExpr);
652 void PopCompoundScope();
653
655
656 /// Retrieve the current block, if any.
658
659 /// Get the innermost lambda enclosing the current location, if any. This
660 /// looks through intervening non-lambda scopes such as local functions and
661 /// blocks.
663
664 /// Retrieve the current lambda scope info, if any.
665 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
666 /// lambda scope info ignoring all inner capturing scopes that are not
667 /// lambda scopes.
669 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
670
671 /// Retrieve the current generic lambda info, if any.
673
674 /// Retrieve the current captured region, if any.
676
677 void ActOnComment(SourceRange Comment);
678
679 /// Retrieve the parser's current scope.
680 ///
681 /// This routine must only be used when it is certain that semantic analysis
682 /// and the parser are in precisely the same context, which is not the case
683 /// when, e.g., we are performing any kind of template instantiation.
684 /// Therefore, the only safe places to use this scope are in the parser
685 /// itself and in routines directly invoked from the parser and *never* from
686 /// template substitution or instantiation.
687 Scope *getCurScope() const { return CurScope; }
688
690
693 }
694
695 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
696 const FunctionDecl *FD = nullptr);
698 const PartialDiagnostic &PD,
699 const FunctionDecl *FD = nullptr) {
700 return targetDiag(Loc, PD.getDiagID(), FD) << PD;
701 }
702
703 /// Check if the type is allowed to be used for the current target.
705 ValueDecl *D = nullptr);
706
707 // /// The kind of conversion being performed.
708 // enum CheckedConversionKind {
709 // /// An implicit conversion.
710 // CCK_ImplicitConversion,
711 // /// A C-style cast.
712 // CCK_CStyleCast,
713 // /// A functional-style cast.
714 // CCK_FunctionalCast,
715 // /// A cast other than a C-style cast.
716 // CCK_OtherCast,
717 // /// A conversion for an operand of a builtin overloaded operator.
718 // CCK_ForBuiltinOverloadedOp
719 // };
720
721 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
722 /// cast. If there is already an implicit cast, merge into the existing one.
723 /// If isLvalue, the result of the cast is an lvalue.
726 const CXXCastPath *BasePath = nullptr,
728
729 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
730 /// to the conversion from scalar type ScalarTy to the Boolean type.
732
733 /// If \p AllowLambda is true, treat lambda as function.
734 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
735
736 /// Returns a pointer to the innermost enclosing function, or nullptr if the
737 /// current context is not inside a function. If \p AllowLambda is true,
738 /// this can return the call operator of an enclosing lambda, otherwise
739 /// lambdas are skipped when looking for an enclosing function.
740 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
741
742 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
743 /// the method decl for the method being parsed. If we're currently
744 /// in a 'block', this returns the containing context.
746
747 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
748 /// or C function we're in, otherwise return null. If we're currently
749 /// in a 'block', this returns the containing context.
751
752 /// Warn if we're implicitly casting from a _Nullable pointer type to a
753 /// _Nonnull one.
756
757 /// Warn when implicitly casting 0 to nullptr.
758 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
759
761 UnavailableAttr::ImplicitReason reason);
762
763 /// Retrieve a suitable printing policy for diagnostics.
766 }
767
768 /// Retrieve a suitable printing policy for diagnostics.
770 const Preprocessor &PP);
771
772 /// Scope actions.
774
775 /// Determine whether \param D is function like (function or function
776 /// template) for parsing.
778
779 /// The maximum alignment, same as in llvm::Value. We duplicate them here
780 /// because that allows us not to duplicate the constants in clang code,
781 /// which we must to since we can't directly use the llvm constants.
782 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
783 ///
784 /// This is the greatest alignment value supported by load, store, and alloca
785 /// instructions, and global values.
786 static const unsigned MaxAlignmentExponent = 32;
787 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
788
789 /// Flag indicating whether or not to collect detailed statistics.
791
792 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
793
794 /// Stack containing information about each of the nested
795 /// function, block, and method scopes that are currently active.
797
798 /// The index of the first FunctionScope that corresponds to the current
799 /// context.
801
802 /// Track the number of currently active capturing scopes.
804
805 llvm::BumpPtrAllocator BumpAlloc;
806
807 /// The kind of translation unit we are processing.
808 ///
809 /// When we're processing a complete translation unit, Sema will perform
810 /// end-of-translation-unit semantic tasks (such as creating
811 /// initializers for tentative definitions in C) once parsing has
812 /// completed. Modules and precompiled headers perform different kinds of
813 /// checks.
815
816 /// Translation Unit Scope - useful to Objective-C actions that need
817 /// to lookup file scope declarations in the "ordinary" C decl namespace.
818 /// For example, user-defined classes, built-in "id" type, etc.
820
822
824 return CurScope->incrementMSManglingNumber();
825 }
826
827 /// Try to recover by turning the given expression into a
828 /// call. Returns true if recovery was attempted or an error was
829 /// emitted; this may also leave the ExprResult invalid.
831 bool ForceComplain = false,
832 bool (*IsPlausibleResult)(QualType) = nullptr);
833
834 /// Figure out if an expression could be turned into a call.
835 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
836 UnresolvedSetImpl &NonTemplateOverloads);
837
841
844
852
853 /// A RAII object to enter scope of a compound statement.
855 public:
856 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
857 S.ActOnStartOfCompoundStmt(IsStmtExpr);
858 }
859
861
862 private:
863 Sema &S;
864 };
865
866 /// An RAII helper that pops function a function scope on exit.
869 bool Active;
872 if (Active)
874 }
875 void disable() { Active = false; }
876 };
877
878 /// Build a partial diagnostic.
879 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
880
882 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
883 }
884
885 /// Worker object for performing CFG-based warnings.
888
889 /// Callback to the parser to parse templated functions when needed.
890 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
891 typedef void LateTemplateParserCleanupCB(void *P);
895
897 LateTemplateParserCleanupCB *LTPCleanup, void *P) {
898 LateTemplateParser = LTP;
899 LateTemplateParserCleanup = LTPCleanup;
900 OpaqueParser = P;
901 }
902
903 /// Callback to the parser to parse a type expressed as a string.
904 std::function<TypeResult(StringRef, StringRef, SourceLocation)>
906
907 /// VAListTagName - The declaration name corresponding to __va_list_tag.
908 /// This is used as part of a hack to omit that class from ADL results.
910
911 /// Is the last error level diagnostic immediate. This is used to determined
912 /// whether the next info diagnostic should be immediate.
914
915 class DelayedDiagnostics;
916
918 sema::DelayedDiagnosticPool *SavedPool = nullptr;
920 };
923
924 /// A class which encapsulates the logic for delaying diagnostics
925 /// during parsing and other processing.
927 /// The current pool of diagnostics into which delayed
928 /// diagnostics should go.
929 sema::DelayedDiagnosticPool *CurPool = nullptr;
930
931 public:
933
934 /// Adds a delayed diagnostic.
935 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
936
937 /// Determines whether diagnostics should be delayed.
938 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
939
940 /// Returns the current delayed-diagnostics pool.
941 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
942
943 /// Enter a new scope. Access and deprecation diagnostics will be
944 /// collected in this pool.
947 state.SavedPool = CurPool;
948 CurPool = &pool;
949 return state;
950 }
951
952 /// Leave a delayed-diagnostic state that was previously pushed.
953 /// Do not emit any of the diagnostics. This is performed as part
954 /// of the bookkeeping of popping a pool "properly".
956 CurPool = state.SavedPool;
957 }
958
959 /// Enter a new scope where access and deprecation diagnostics are
960 /// not delayed.
963 state.SavedPool = CurPool;
964 CurPool = nullptr;
965 return state;
966 }
967
968 /// Undo a previous pushUndelayed().
970 assert(CurPool == nullptr);
971 CurPool = state.SavedPool;
972 }
973 } DelayedDiagnostics;
974
976 return DelayedDiagnostics.push(pool);
977 }
978
979 /// Diagnostics that are emitted only if we discover that the given function
980 /// must be codegen'ed. Because handling these correctly adds overhead to
981 /// compilation, this is currently only enabled for CUDA compilations.
982 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
983
984 /// CurContext - This is the current declaration context of parsing.
986
988 assert(CodeCompletionPtr);
989 return *CodeCompletionPtr;
990 }
991
993 assert(CUDAPtr);
994 return *CUDAPtr;
995 }
996
998 assert(HLSLPtr);
999 return *HLSLPtr;
1000 }
1001
1003 assert(ObjCPtr);
1004 return *ObjCPtr;
1005 }
1006
1008 assert(OpenACCPtr);
1009 return *OpenACCPtr;
1010 }
1011
1013 assert(OpenMPPtr && "SemaOpenMP is dead");
1014 return *OpenMPPtr;
1015 }
1016
1018 assert(SYCLPtr);
1019 return *SYCLPtr;
1020 }
1021
1022 /// Source of additional semantic information.
1024
1025protected:
1026 friend class Parser;
1028 friend class ASTReader;
1029 friend class ASTDeclReader;
1030 friend class ASTWriter;
1031
1032private:
1033 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1034 bool WarnedDarwinSDKInfoMissing = false;
1035
1036 Sema(const Sema &) = delete;
1037 void operator=(const Sema &) = delete;
1038
1039 /// The handler for the FileChanged preprocessor events.
1040 ///
1041 /// Used for diagnostics that implement custom semantic analysis for #include
1042 /// directives, like -Wpragma-pack.
1043 sema::SemaPPCallbacks *SemaPPCallbackHandler;
1044
1045 /// The parser's current scope.
1046 ///
1047 /// The parser maintains this state here.
1048 Scope *CurScope;
1049
1050 mutable IdentifierInfo *Ident_super;
1051
1052 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1053 std::unique_ptr<SemaCUDA> CUDAPtr;
1054 std::unique_ptr<SemaHLSL> HLSLPtr;
1055 std::unique_ptr<SemaObjC> ObjCPtr;
1056 std::unique_ptr<SemaOpenACC> OpenACCPtr;
1057 std::unique_ptr<SemaOpenMP> OpenMPPtr;
1058 std::unique_ptr<SemaSYCL> SYCLPtr;
1059
1060 ///@}
1061
1062 //
1063 //
1064 // -------------------------------------------------------------------------
1065 //
1066 //
1067
1068 /// \name C++ Access Control
1069 /// Implementations are in SemaAccess.cpp
1070 ///@{
1071
1072public:
1079
1080 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1081 NamedDecl *PrevMemberDecl,
1082 AccessSpecifier LexicalAS);
1083
1085 DeclAccessPair FoundDecl);
1087 DeclAccessPair FoundDecl);
1089 SourceRange PlacementRange,
1090 CXXRecordDecl *NamingClass,
1091 DeclAccessPair FoundDecl,
1092 bool Diagnose = true);
1094 DeclAccessPair FoundDecl,
1095 const InitializedEntity &Entity,
1096 bool IsCopyBindingRefToTemp = false);
1098 DeclAccessPair FoundDecl,
1099 const InitializedEntity &Entity,
1100 const PartialDiagnostic &PDiag);
1102 CXXDestructorDecl *Dtor,
1103 const PartialDiagnostic &PDiag,
1104 QualType objectType = QualType());
1107 CXXRecordDecl *NamingClass,
1108 DeclAccessPair Found);
1111 CXXRecordDecl *DecomposedClass,
1112 DeclAccessPair Field);
1114 const SourceRange &,
1115 DeclAccessPair FoundDecl);
1117 Expr *ArgExpr,
1118 DeclAccessPair FoundDecl);
1120 ArrayRef<Expr *> ArgExprs,
1121 DeclAccessPair FoundDecl);
1123 DeclAccessPair FoundDecl);
1125 QualType Derived, const CXXBasePath &Path,
1126 unsigned DiagID, bool ForceCheck = false,
1127 bool ForceUnprivileged = false);
1128 void CheckLookupAccess(const LookupResult &R);
1129 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1130 QualType BaseType);
1132 DeclAccessPair Found, QualType ObjectType,
1134 const PartialDiagnostic &Diag);
1136 DeclAccessPair Found,
1137 QualType ObjectType) {
1138 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1139 SourceLocation(), PDiag());
1140 }
1141
1143 const DependentDiagnostic &DD,
1144 const MultiLevelTemplateArgumentList &TemplateArgs);
1146
1147 ///@}
1148
1149 //
1150 //
1151 // -------------------------------------------------------------------------
1152 //
1153 //
1154
1155 /// \name Attributes
1156 /// Implementations are in SemaAttr.cpp
1157 ///@{
1158
1159public:
1160 /// Controls member pointer representation format under the MS ABI.
1163
1164 bool MSStructPragmaOn; // True when \#pragma ms_struct on
1165
1166 /// Source location for newly created implicit MSInheritanceAttrs
1168
1169 /// pragma clang section kind
1176 PCSK_Relro = 5
1178
1180
1182 std::string SectionName;
1183 bool Valid = false;
1185 };
1186
1192
1194 PSK_Reset = 0x0, // #pragma ()
1195 PSK_Set = 0x1, // #pragma (value)
1196 PSK_Push = 0x2, // #pragma (push[, id])
1197 PSK_Pop = 0x4, // #pragma (pop[, id])
1198 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
1199 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1200 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
1201 };
1202
1205 StringRef SlotLabel;
1207 };
1208
1209 // #pragma pack and align.
1211 public:
1212 // `Native` represents default align mode, which may vary based on the
1213 // platform.
1214 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1215
1216 // #pragma pack info constructor
1217 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1218 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1219 assert(Num == PackNumber && "The pack number has been truncated.");
1220 }
1221
1222 // #pragma align info constructor
1224 : PackAttr(false), AlignMode(M),
1225 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1226
1227 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1228
1230
1231 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1232 // integer encoding for it. This should only be passed to
1233 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
1234 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
1235 std::uint32_t Encoding{};
1236 if (Info.IsXLStack())
1237 Encoding |= IsXLMask;
1238
1239 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1240
1241 if (Info.IsPackAttr())
1242 Encoding |= PackAttrMask;
1243
1244 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1245
1246 return Encoding;
1247 }
1248
1249 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1250 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1252 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1253 int PackNumber = (Encoding & PackNumMask) >> 4;
1254
1255 if (Encoding & PackAttrMask)
1256 return AlignPackInfo(M, PackNumber, IsXL);
1257
1258 return AlignPackInfo(M, IsXL);
1259 }
1260
1261 bool IsPackAttr() const { return PackAttr; }
1262
1263 bool IsAlignAttr() const { return !PackAttr; }
1264
1265 Mode getAlignMode() const { return AlignMode; }
1266
1267 unsigned getPackNumber() const { return PackNumber; }
1268
1269 bool IsPackSet() const {
1270 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1271 // attriute on a decl.
1272 return PackNumber != UninitPackVal && PackNumber != 0;
1273 }
1274
1275 bool IsXLStack() const { return XLStack; }
1276
1277 bool operator==(const AlignPackInfo &Info) const {
1278 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
1279 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
1280 Info.XLStack);
1281 }
1282
1283 bool operator!=(const AlignPackInfo &Info) const {
1284 return !(*this == Info);
1285 }
1286
1287 private:
1288 /// \brief True if this is a pragma pack attribute,
1289 /// not a pragma align attribute.
1290 bool PackAttr;
1291
1292 /// \brief The alignment mode that is in effect.
1293 Mode AlignMode;
1294
1295 /// \brief The pack number of the stack.
1296 unsigned char PackNumber;
1297
1298 /// \brief True if it is a XL #pragma align/pack stack.
1299 bool XLStack;
1300
1301 /// \brief Uninitialized pack value.
1302 static constexpr unsigned char UninitPackVal = -1;
1303
1304 // Masks to encode and decode an AlignPackInfo.
1305 static constexpr uint32_t IsXLMask{0x0000'0001};
1306 static constexpr uint32_t AlignModeMask{0x0000'0006};
1307 static constexpr uint32_t PackAttrMask{0x00000'0008};
1308 static constexpr uint32_t PackNumMask{0x0000'01F0};
1309 };
1310
1311 template <typename ValueType> struct PragmaStack {
1312 struct Slot {
1313 llvm::StringRef StackSlotLabel;
1314 ValueType Value;
1317 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
1322 };
1323
1324 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
1325 llvm::StringRef StackSlotLabel, ValueType Value) {
1326 if (Action == PSK_Reset) {
1328 CurrentPragmaLocation = PragmaLocation;
1329 return;
1330 }
1331 if (Action & PSK_Push)
1332 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
1333 PragmaLocation);
1334 else if (Action & PSK_Pop) {
1335 if (!StackSlotLabel.empty()) {
1336 // If we've got a label, try to find it and jump there.
1337 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
1338 return x.StackSlotLabel == StackSlotLabel;
1339 });
1340 // If we found the label so pop from there.
1341 if (I != Stack.rend()) {
1342 CurrentValue = I->Value;
1343 CurrentPragmaLocation = I->PragmaLocation;
1344 Stack.erase(std::prev(I.base()), Stack.end());
1345 }
1346 } else if (!Stack.empty()) {
1347 // We do not have a label, just pop the last entry.
1348 CurrentValue = Stack.back().Value;
1349 CurrentPragmaLocation = Stack.back().PragmaLocation;
1350 Stack.pop_back();
1351 }
1352 }
1353 if (Action & PSK_Set) {
1355 CurrentPragmaLocation = PragmaLocation;
1356 }
1357 }
1358
1359 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
1360 // method body to restore the stacks on exit, so it works like this:
1361 //
1362 // struct S {
1363 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
1364 // void Method {}
1365 // #pragma <name>(pop, InternalPragmaSlot)
1366 // };
1367 //
1368 // It works even with #pragma vtordisp, although MSVC doesn't support
1369 // #pragma vtordisp(push [, id], n)
1370 // syntax.
1371 //
1372 // Push / pop a named sentinel slot.
1373 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
1374 assert((Action == PSK_Push || Action == PSK_Pop) &&
1375 "Can only push / pop #pragma stack sentinels!");
1377 }
1378
1379 // Constructors.
1380 explicit PragmaStack(const ValueType &Default)
1382
1383 bool hasValue() const { return CurrentValue != DefaultValue; }
1384
1386 ValueType DefaultValue; // Value used for PSK_Reset action.
1387 ValueType CurrentValue;
1389 };
1390 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
1391 // we shouldn't do so if they're in a module).
1392
1393 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
1394 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
1395 ///
1396 /// 0: Suppress all vtordisps
1397 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
1398 /// structors
1399 /// 2: Always insert vtordisps to support RTTI on partially constructed
1400 /// objects
1403 // The current #pragma align/pack values and locations at each #include.
1408 };
1410 // Segment #pragmas.
1415
1416 // #pragma strict_gs_check.
1418
1419 // This stack tracks the current state of Sema.CurFPFeatures.
1422 FPOptionsOverride result;
1423 if (!FpPragmaStack.hasValue()) {
1424 result = FPOptionsOverride();
1425 } else {
1426 result = FpPragmaStack.CurrentValue;
1427 }
1428 return result;
1429 }
1430
1436 };
1437
1438 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
1439 // Actions should be performed only if we enter / exit a C++ method body.
1441 public:
1442 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
1444
1445 private:
1446 Sema &S;
1447 StringRef SlotLabel;
1448 bool ShouldAct;
1449 };
1450
1451 /// Last section used with #pragma init_seg.
1454
1455 /// Sections used with #pragma alloc_text.
1456 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
1457
1458 /// VisContext - Manages the stack for \#pragma GCC visibility.
1459 void *VisContext; // Really a "PragmaVisStack*"
1460
1461 /// This an attribute introduced by \#pragma clang attribute.
1467 };
1468
1469 /// A push'd group of PragmaAttributeEntries.
1471 /// The location of the push attribute.
1473 /// The namespace of this push group.
1476 };
1477
1479
1480 /// The declaration that is currently receiving an attribute from the
1481 /// #pragma attribute stack.
1483
1484 /// This represents the last location of a "#pragma clang optimize off"
1485 /// directive if such a directive has not been closed by an "on" yet. If
1486 /// optimizations are currently "on", this is set to an invalid location.
1488
1489 /// Get the location for the currently active "\#pragma clang optimize
1490 /// off". If this location is invalid, then the state of the pragma is "on".
1493 }
1494
1495 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
1496 /// whether the optimizations in the list passed to the pragma should be
1497 /// turned off or on. This boolean is true by default because command line
1498 /// options are honored when `#pragma optimize("", on)`.
1499 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
1501
1502 /// Set of no-builtin functions listed by \#pragma function.
1504
1505 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
1506 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
1508
1509 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
1511
1512 /// Add gsl::Pointer attribute to std::container::iterator
1513 /// \param ND The declaration that introduces the name
1514 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
1515 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
1516
1517 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
1519
1520 /// Add [[gsl::Pointer]] attributes for std:: types.
1522
1523 /// Add _Nullable attributes for std:: types.
1525
1527 POAK_Native, // #pragma options align=native
1528 POAK_Natural, // #pragma options align=natural
1529 POAK_Packed, // #pragma options align=packed
1530 POAK_Power, // #pragma options align=power
1531 POAK_Mac68k, // #pragma options align=mac68k
1532 POAK_Reset // #pragma options align=reset
1534
1535 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
1538 PragmaClangSectionKind SecKind,
1539 StringRef SecName);
1540
1541 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
1543 SourceLocation PragmaLoc);
1544
1545 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
1546 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
1547 StringRef SlotLabel, Expr *Alignment);
1548
1549 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
1550 /// (unless they are value dependent or type dependent). Returns false
1551 /// and emits a diagnostic if one or more of the arguments could not be
1552 /// folded into a constant.
1555
1559 };
1560
1562 SourceLocation IncludeLoc);
1564
1565 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
1567
1568 /// ActOnPragmaMSComment - Called on well formed
1569 /// \#pragma comment(kind, "arg").
1571 StringRef Arg);
1572
1573 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
1574 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
1575 StringRef Value);
1576
1577 /// Are precise floating point semantics currently enabled?
1579 return !CurFPFeatures.getAllowFPReassociate() &&
1580 !CurFPFeatures.getNoSignedZero() &&
1581 !CurFPFeatures.getAllowReciprocal() &&
1582 !CurFPFeatures.getAllowApproxFunc();
1583 }
1584
1587
1588 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
1591
1592 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
1593 /// pointers_to_members(representation method[, general purpose
1594 /// representation]).
1597 SourceLocation PragmaLoc);
1598
1599 /// Called on well formed \#pragma vtordisp().
1602
1603 bool UnifySection(StringRef SectionName, int SectionFlags,
1604 NamedDecl *TheDecl);
1605 bool UnifySection(StringRef SectionName, int SectionFlags,
1606 SourceLocation PragmaSectionLocation);
1607
1608 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
1609 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
1610 PragmaMsStackAction Action,
1611 llvm::StringRef StackSlotLabel,
1612 StringLiteral *SegmentName, llvm::StringRef PragmaName);
1613
1614 /// Called on well formed \#pragma section().
1615 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
1616 StringLiteral *SegmentName);
1617
1618 /// Called on well-formed \#pragma init_seg().
1619 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
1620 StringLiteral *SegmentName);
1621
1622 /// Called on well-formed \#pragma alloc_text().
1624 SourceLocation PragmaLocation, StringRef Section,
1625 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
1626 &Functions);
1627
1628 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
1629 /// strict_gs_check.
1631 PragmaMsStackAction Action,
1632 bool Value);
1633
1634 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
1635 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
1636 SourceLocation PragmaLoc);
1637
1639 SourceLocation PragmaLoc,
1642 const IdentifierInfo *Namespace);
1643
1644 /// Called on well-formed '\#pragma clang attribute pop'.
1646 const IdentifierInfo *Namespace);
1647
1648 /// Adds the attributes that have been specified using the
1649 /// '\#pragma clang attribute push' directives to the given declaration.
1650 void AddPragmaAttributes(Scope *S, Decl *D);
1651
1653
1655
1656 /// Called on well formed \#pragma clang optimize.
1657 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
1658
1659 /// #pragma optimize("[optimization-list]", on | off).
1660 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
1661
1662 /// Call on well formed \#pragma function.
1663 void
1665 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
1666
1667 /// Only called on function definitions; if there is a pragma in scope
1668 /// with the effect of a range-based optnone, consider marking the function
1669 /// with attribute optnone.
1671
1672 /// Only called on function definitions; if there is a `#pragma alloc_text`
1673 /// that decides which code section the function should be in, add
1674 /// attribute section to the function.
1676
1677 /// Adds the 'optnone' attribute to the function declaration if there
1678 /// are no conflicts; Loc represents the location causing the 'optnone'
1679 /// attribute to be added (usually because of a pragma).
1681
1682 /// Only called on function definitions; if there is a MSVC #pragma optimize
1683 /// in scope, consider changing the function's attributes based on the
1684 /// optimization list passed to the pragma.
1686
1687 /// Only called on function definitions; if there is a pragma in scope
1688 /// with the effect of a range-based no_builtin, consider marking the function
1689 /// with attribute no_builtin.
1691
1692 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
1693 /// add an appropriate visibility attribute.
1695
1696 /// FreeVisContext - Deallocate and null out VisContext.
1697 void FreeVisContext();
1698
1699 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
1700 void ActOnPragmaVisibility(const IdentifierInfo *VisType,
1701 SourceLocation PragmaLoc);
1702
1703 /// ActOnPragmaFPContract - Called on well formed
1704 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
1705 /// \#pragma clang fp contract
1707
1708 /// Called on well formed
1709 /// \#pragma clang fp reassociate
1710 /// or
1711 /// \#pragma clang fp reciprocal
1713 bool IsEnabled);
1714
1715 /// ActOnPragmaFenvAccess - Called on well formed
1716 /// \#pragma STDC FENV_ACCESS
1717 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
1718
1719 /// ActOnPragmaCXLimitedRange - Called on well formed
1720 /// \#pragma STDC CX_LIMITED_RANGE
1723
1724 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
1727
1728 /// Called to set constant rounding mode for floating point operations.
1729 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
1730
1731 /// Called to set exception behavior for floating point operations.
1733
1734 /// PushNamespaceVisibilityAttr - Note that we've entered a
1735 /// namespace with a visibility attribute.
1736 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
1738
1739 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
1740 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
1741 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
1742
1743 /// Handles semantic checking for features that are common to all attributes,
1744 /// such as checking whether a parameter was properly specified, or the
1745 /// correct number of arguments were passed, etc. Returns true if the
1746 /// attribute has been diagnosed.
1747 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
1748 bool SkipArgCountCheck = false);
1749 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
1750 bool SkipArgCountCheck = false);
1751
1752 ///@}
1753
1754 //
1755 //
1756 // -------------------------------------------------------------------------
1757 //
1758 //
1759
1760 /// \name Availability Attribute Handling
1761 /// Implementations are in SemaAvailability.cpp
1762 ///@{
1763
1764public:
1765 /// Issue any -Wunguarded-availability warnings in \c FD
1767
1769
1770 /// Retrieve the current function, if any, that should be analyzed for
1771 /// potential availability violations.
1773
1775 const ObjCInterfaceDecl *UnknownObjCClass,
1776 bool ObjCPropertyAccess,
1777 bool AvoidPartialAvailabilityChecks = false,
1778 ObjCInterfaceDecl *ClassReceiver = nullptr);
1779
1780 ///@}
1781
1782 //
1783 //
1784 // -------------------------------------------------------------------------
1785 //
1786 //
1787
1788 /// \name Casts
1789 /// Implementations are in SemaCast.cpp
1790 ///@{
1791
1792public:
1794 return CCK == CheckedConversionKind::CStyleCast ||
1797 }
1798
1799 /// ActOnCXXNamedCast - Parse
1800 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
1802 SourceLocation LAngleBracketLoc, Declarator &D,
1803 SourceLocation RAngleBracketLoc,
1804 SourceLocation LParenLoc, Expr *E,
1805 SourceLocation RParenLoc);
1806
1808 TypeSourceInfo *Ty, Expr *E,
1809 SourceRange AngleBrackets, SourceRange Parens);
1810
1812 ExprResult Operand,
1813 SourceLocation RParenLoc);
1814
1816 Expr *Operand, SourceLocation RParenLoc);
1817
1818 // Checks that reinterpret casts don't have undefined behavior.
1819 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1820 bool IsDereference, SourceRange Range);
1821
1822 // Checks that the vector type should be initialized from a scalar
1823 // by splatting the value rather than populating a single element.
1824 // This is the case for AltiVecVector types as well as with
1825 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
1826 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
1827
1828 // Checks if the -faltivec-src-compat=gcc option is specified.
1829 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
1830 // treated the same way as they are when trying to initialize
1831 // these vectors on gcc (an error is emitted).
1833 QualType SrcTy);
1834
1836 SourceLocation RParenLoc, Expr *Op);
1837
1839 SourceLocation LParenLoc,
1840 Expr *CastExpr,
1841 SourceLocation RParenLoc);
1842
1843 ///@}
1844
1845 //
1846 //
1847 // -------------------------------------------------------------------------
1848 //
1849 //
1850
1851 /// \name Extra Semantic Checking
1852 /// Implementations are in SemaChecking.cpp
1853 ///@{
1854
1855public:
1856 /// Used to change context to isConstantEvaluated without pushing a heavy
1857 /// ExpressionEvaluationContextRecord object.
1859
1863 }
1864
1866 unsigned ByteNo) const;
1867
1869 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
1870 FAPK_Variadic, // values to format are passed as variadic arguments
1871 FAPK_VAList, // values to format are passed in a va_list
1872 };
1873
1874 // Used to grab the relevant information from a FormatAttr and a
1875 // FunctionDeclaration.
1877 unsigned FormatIdx;
1880 };
1881
1882 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1883 bool IsVariadic, FormatStringInfo *FSI);
1884
1885 // Used by C++ template instantiation.
1888 SourceLocation BuiltinLoc,
1889 SourceLocation RParenLoc);
1890
1903 static FormatStringType GetFormatStringType(const FormatAttr *Format);
1904
1905 bool FormatStringHasSArg(const StringLiteral *FExpr);
1906
1907 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
1908
1910 BinaryOperatorKind Opcode);
1911
1912 /// Register a magic integral constant to be used as a type tag.
1913 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
1914 uint64_t MagicValue, QualType Type,
1915 bool LayoutCompatible, bool MustBeNull);
1916
1919
1923
1925
1926 /// If true, \c Type should be compared with other expression's types for
1927 /// layout-compatibility.
1928 LLVM_PREFERRED_TYPE(bool)
1930 LLVM_PREFERRED_TYPE(bool)
1931 unsigned MustBeNull : 1;
1932 };
1933
1934 /// A pair of ArgumentKind identifier and magic value. This uniquely
1935 /// identifies the magic value.
1936 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
1937
1938 /// Diagnoses the current set of gathered accesses. This typically
1939 /// happens at full expression level. The set is cleared after emitting the
1940 /// diagnostics.
1942
1943 /// This function checks if the expression is in the sef of potentially
1944 /// misaligned members and it is converted to some pointer type T with lower
1945 /// or equal alignment requirements. If so it removes it. This is used when
1946 /// we do not want to diagnose such misaligned access (e.g. in conversions to
1947 /// void*).
1948 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
1949
1950 /// This function calls Action when it determines that E designates a
1951 /// misaligned member due to the packed attribute. This is used to emit
1952 /// local diagnostics like in reference binding.
1954 Expr *E,
1955 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
1956 Action);
1957
1958 enum class AtomicArgumentOrder { API, AST };
1960 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
1961 SourceLocation RParenLoc, MultiExprArg Args,
1964
1965 /// Check to see if a given expression could have '.c_str()' called on it.
1966 bool hasCStrMethod(const Expr *E);
1967
1970 bool IsEqual, SourceRange Range);
1971
1973 bool CheckParameterNames);
1974
1975 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1976
1977 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
1978 /// to weak/__unsafe_unretained type.
1980
1981 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
1982 /// to weak/__unsafe_unretained expression.
1984
1985 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
1986 /// statement as a \p Body, and it is located on the same line.
1987 ///
1988 /// This helps prevent bugs due to typos, such as:
1989 /// if (condition);
1990 /// do_stuff();
1991 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
1992 unsigned DiagID);
1993
1994 /// Warn if a for/while loop statement \p S, which is followed by
1995 /// \p PossibleBody, has a suspicious null statement as a body.
1996 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
1997
1998 /// Warn if a value is moved to itself.
1999 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2000 SourceLocation OpLoc);
2001
2002 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
2010
2011 bool IsLayoutCompatible(QualType T1, QualType T2) const;
2013 const TypeSourceInfo *Derived);
2014
2015 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2016 const FunctionProtoType *Proto);
2017
2018 bool BuiltinVectorMath(CallExpr *TheCall, QualType &Res);
2019 bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2020
2021 bool CheckHLSLBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
2022
2023 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2024 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2025 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2026 VariadicCallType CallType);
2027
2028 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2029 const NamedDecl *Callee);
2030
2031 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2032
2033private:
2034 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
2035 const ArraySubscriptExpr *ASE = nullptr,
2036 bool AllowOnePastEnd = true, bool IndexNegated = false);
2037 void CheckArrayAccess(const Expr *E);
2038
2039 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2040 const FunctionProtoType *Proto);
2041 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
2042 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
2044 const FunctionProtoType *Proto, SourceLocation Loc);
2045
2046 void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg);
2047
2048 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
2049 StringRef ParamName, QualType ArgTy, QualType ParamTy);
2050
2051 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
2052
2053 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2054 CallExpr *TheCall);
2055
2056 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2057 CallExpr *TheCall);
2058
2059 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
2060
2061 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2062 unsigned MaxWidth);
2063 bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2064 CallExpr *TheCall);
2065 bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
2066 bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
2067 bool ParseSVEImmChecks(CallExpr *TheCall,
2068 SmallVector<std::tuple<int, int, int>, 3> &ImmChecks);
2069 bool CheckSMEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
2070 bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2071 CallExpr *TheCall);
2072 bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg,
2073 bool WantCDE);
2074 bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2075 CallExpr *TheCall);
2076
2077 bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2078 CallExpr *TheCall);
2079 bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
2080 bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
2081 bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
2082 bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2083 CallExpr *TheCall);
2084 bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2085 CallExpr *TheCall);
2086 bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
2087 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
2088 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
2089 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
2090 bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall);
2091 bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
2092 ArrayRef<int> ArgNums);
2093 bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums);
2094 bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
2095 ArrayRef<int> ArgNums);
2096 bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2097 CallExpr *TheCall);
2098 bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2099 CallExpr *TheCall);
2100 bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
2101 bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum);
2102 bool CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2103 CallExpr *TheCall);
2104 void checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D,
2105 const llvm::StringMap<bool> &FeatureMap);
2106 bool CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI,
2107 unsigned BuiltinID, CallExpr *TheCall);
2108 bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI,
2109 unsigned BuiltinID,
2110 CallExpr *TheCall);
2111 bool CheckNVPTXBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2112 CallExpr *TheCall);
2113
2114 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
2115 bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
2116 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
2117 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
2118 unsigned BuiltinID);
2119 bool BuiltinComplex(CallExpr *TheCall);
2120 bool BuiltinVSX(CallExpr *TheCall);
2121 bool BuiltinOSLogFormat(CallExpr *TheCall);
2122 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
2123
2124 bool BuiltinPrefetch(CallExpr *TheCall);
2125 bool BuiltinAllocaWithAlign(CallExpr *TheCall);
2126 bool BuiltinArithmeticFence(CallExpr *TheCall);
2127 bool BuiltinAssume(CallExpr *TheCall);
2128 bool BuiltinAssumeAligned(CallExpr *TheCall);
2129 bool BuiltinLongjmp(CallExpr *TheCall);
2130 bool BuiltinSetjmp(CallExpr *TheCall);
2131 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
2132 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
2133 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
2135 bool BuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result);
2136 bool BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High,
2137 bool RangeIsError = true);
2138 bool BuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
2139 unsigned Multiple);
2140 bool BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
2141 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
2142 unsigned ArgBits);
2143 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
2144 unsigned ArgBits);
2145 bool BuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, int ArgNum,
2146 unsigned ExpectedFieldNum, bool AllowName);
2147 bool BuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
2148 bool BuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
2149 const char *TypeDesc);
2150
2151 bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc);
2152
2153 bool BuiltinElementwiseMath(CallExpr *TheCall);
2154 bool BuiltinElementwiseTernaryMath(CallExpr *TheCall,
2155 bool CheckForFloatArgs = true);
2156 bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall);
2157 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
2158
2159 bool BuiltinNonDeterministicValue(CallExpr *TheCall);
2160
2161 // Matrix builtin handling.
2162 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
2163 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
2164 ExprResult CallResult);
2165 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
2166 ExprResult CallResult);
2167
2168 // WebAssembly builtin handling.
2169 bool BuiltinWasmRefNullExtern(CallExpr *TheCall);
2170 bool BuiltinWasmRefNullFunc(CallExpr *TheCall);
2171 bool BuiltinWasmTableGet(CallExpr *TheCall);
2172 bool BuiltinWasmTableSet(CallExpr *TheCall);
2173 bool BuiltinWasmTableSize(CallExpr *TheCall);
2174 bool BuiltinWasmTableGrow(CallExpr *TheCall);
2175 bool BuiltinWasmTableFill(CallExpr *TheCall);
2176 bool BuiltinWasmTableCopy(CallExpr *TheCall);
2177
2178 bool CheckFormatArguments(const FormatAttr *Format,
2179 ArrayRef<const Expr *> Args, bool IsCXXMember,
2182 llvm::SmallBitVector &CheckedVarArgs);
2183 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
2184 FormatArgumentPassingKind FAPK, unsigned format_idx,
2185 unsigned firstDataArg, FormatStringType Type,
2187 SourceRange range,
2188 llvm::SmallBitVector &CheckedVarArgs);
2189
2190 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
2191
2192 void CheckAbsoluteValueFunction(const CallExpr *Call,
2193 const FunctionDecl *FDecl);
2194
2195 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
2196
2197 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
2198 IdentifierInfo *FnName);
2199
2200 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
2201
2202 void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName);
2203
2204 void CheckFreeArguments(const CallExpr *E);
2205
2206 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
2207 SourceLocation ReturnLoc, bool isObjCMethod = false,
2208 const AttrVec *Attrs = nullptr,
2209 const FunctionDecl *FD = nullptr);
2210
2211 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
2212 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
2213 void CheckForIntOverflow(const Expr *E);
2214 void CheckUnsequencedOperations(const Expr *E);
2215
2216 /// Perform semantic checks on a completed expression. This will either
2217 /// be a full-expression or a default argument expression.
2218 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
2219 bool IsConstexpr = false);
2220
2221 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
2222 Expr *Init);
2223
2224 /// A map from magic value to type information.
2225 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
2226 TypeTagForDatatypeMagicValues;
2227
2228 /// Peform checks on a call of a function with argument_with_type_tag
2229 /// or pointer_with_type_tag attributes.
2230 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
2231 const ArrayRef<const Expr *> ExprArgs,
2232 SourceLocation CallSiteLoc);
2233
2234 /// Check if we are taking the address of a packed field
2235 /// as this may be a problem if the pointer value is dereferenced.
2236 void CheckAddressOfPackedMember(Expr *rhs);
2237
2238 /// Helper class that collects misaligned member designations and
2239 /// their location info for delayed diagnostics.
2240 struct MisalignedMember {
2241 Expr *E;
2242 RecordDecl *RD;
2243 ValueDecl *MD;
2244 CharUnits Alignment;
2245
2246 MisalignedMember() : E(), RD(), MD() {}
2247 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
2248 CharUnits Alignment)
2249 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
2250 explicit MisalignedMember(Expr *E)
2251 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
2252
2253 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
2254 };
2255 /// Small set of gathered accesses to potentially misaligned members
2256 /// due to the packed attribute.
2257 SmallVector<MisalignedMember, 4> MisalignedMembers;
2258
2259 /// Adds an expression to the set of gathered misaligned members.
2260 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
2261 CharUnits Alignment);
2262 ///@}
2263
2264 //
2265 //
2266 // -------------------------------------------------------------------------
2267 //
2268 //
2269
2270 /// \name C++ Coroutines
2271 /// Implementations are in SemaCoroutine.cpp
2272 ///@{
2273
2274public:
2275 /// The C++ "std::coroutine_traits" template, which is defined in
2276 /// <coroutine_traits>
2278
2280 StringRef Keyword);
2284
2287 UnresolvedLookupExpr *Lookup);
2289 Expr *Awaiter, bool IsImplicit = false);
2291 UnresolvedLookupExpr *Lookup);
2294 bool IsImplicit = false);
2299
2300 // As a clang extension, enforces that a non-coroutine function must be marked
2301 // with [[clang::coro_wrapper]] if it returns a type marked with
2302 // [[clang::coro_return_type]].
2303 // Expects that FD is not a coroutine.
2305 /// Lookup 'coroutine_traits' in std namespace and std::experimental
2306 /// namespace. The namespace found is recorded in Namespace.
2308 SourceLocation FuncLoc);
2309 /// Check that the expression co_await promise.final_suspend() shall not be
2310 /// potentially-throwing.
2311 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
2312
2313 ///@}
2314
2315 //
2316 //
2317 // -------------------------------------------------------------------------
2318 //
2319 //
2320
2321 /// \name C++ Scope Specifiers
2322 /// Implementations are in SemaCXXScopeSpec.cpp
2323 ///@{
2324
2325public:
2326 // Marks SS invalid if it represents an incomplete type.
2328 // Complete an enum decl, maybe without a scope spec.
2330 CXXScopeSpec *SS = nullptr);
2331
2334 bool EnteringContext = false);
2337
2338 /// The parser has parsed a global nested-name-specifier '::'.
2339 ///
2340 /// \param CCLoc The location of the '::'.
2341 ///
2342 /// \param SS The nested-name-specifier, which will be updated in-place
2343 /// to reflect the parsed nested-name-specifier.
2344 ///
2345 /// \returns true if an error occurred, false otherwise.
2347
2348 /// The parser has parsed a '__super' nested-name-specifier.
2349 ///
2350 /// \param SuperLoc The location of the '__super' keyword.
2351 ///
2352 /// \param ColonColonLoc The location of the '::'.
2353 ///
2354 /// \param SS The nested-name-specifier, which will be updated in-place
2355 /// to reflect the parsed nested-name-specifier.
2356 ///
2357 /// \returns true if an error occurred, false otherwise.
2359 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
2360
2362 bool *CanCorrect = nullptr);
2364
2365 /// Keeps information about an identifier in a nested-name-spec.
2366 ///
2368 /// The type of the object, if we're parsing nested-name-specifier in
2369 /// a member access expression.
2371
2372 /// The identifier preceding the '::'.
2374
2375 /// The location of the identifier.
2377
2378 /// The location of the '::'.
2380
2381 /// Creates info object for the most typical case.
2383 SourceLocation ColonColonLoc,
2384 ParsedType ObjectType = ParsedType())
2385 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
2386 CCLoc(ColonColonLoc) {}
2387
2389 SourceLocation ColonColonLoc, QualType ObjectType)
2390 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
2391 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
2392 };
2393
2394 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
2395 bool EnteringContext, CXXScopeSpec &SS,
2396 NamedDecl *ScopeLookupResult,
2397 bool ErrorRecoveryLookup,
2398 bool *IsCorrectedToColon = nullptr,
2399 bool OnlyNamespace = false);
2400
2401 /// The parser has parsed a nested-name-specifier 'identifier::'.
2402 ///
2403 /// \param S The scope in which this nested-name-specifier occurs.
2404 ///
2405 /// \param IdInfo Parser information about an identifier in the
2406 /// nested-name-spec.
2407 ///
2408 /// \param EnteringContext Whether we're entering the context nominated by
2409 /// this nested-name-specifier.
2410 ///
2411 /// \param SS The nested-name-specifier, which is both an input
2412 /// parameter (the nested-name-specifier before this type) and an
2413 /// output parameter (containing the full nested-name-specifier,
2414 /// including this new type).
2415 ///
2416 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
2417 /// are allowed. The bool value pointed by this parameter is set to 'true'
2418 /// if the identifier is treated as if it was followed by ':', not '::'.
2419 ///
2420 /// \param OnlyNamespace If true, only considers namespaces in lookup.
2421 ///
2422 /// \returns true if an error occurred, false otherwise.
2423 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
2424 bool EnteringContext, CXXScopeSpec &SS,
2425 bool *IsCorrectedToColon = nullptr,
2426 bool OnlyNamespace = false);
2427
2428 /// The parser has parsed a nested-name-specifier
2429 /// 'template[opt] template-name < template-args >::'.
2430 ///
2431 /// \param S The scope in which this nested-name-specifier occurs.
2432 ///
2433 /// \param SS The nested-name-specifier, which is both an input
2434 /// parameter (the nested-name-specifier before this type) and an
2435 /// output parameter (containing the full nested-name-specifier,
2436 /// including this new type).
2437 ///
2438 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
2439 /// \param TemplateName the template name.
2440 /// \param TemplateNameLoc The location of the template name.
2441 /// \param LAngleLoc The location of the opening angle bracket ('<').
2442 /// \param TemplateArgs The template arguments.
2443 /// \param RAngleLoc The location of the closing angle bracket ('>').
2444 /// \param CCLoc The location of the '::'.
2445 ///
2446 /// \param EnteringContext Whether we're entering the context of the
2447 /// nested-name-specifier.
2448 ///
2449 ///
2450 /// \returns true if an error occurred, false otherwise.
2452 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2453 TemplateTy TemplateName, SourceLocation TemplateNameLoc,
2454 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
2455 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
2456
2458 SourceLocation ColonColonLoc);
2459
2461 const DeclSpec &DS,
2462 SourceLocation ColonColonLoc,
2463 QualType Type);
2464
2466 NestedNameSpecInfo &IdInfo,
2467 bool EnteringContext);
2468
2469 /// Given a C++ nested-name-specifier, produce an annotation value
2470 /// that the parser can use later to reconstruct the given
2471 /// nested-name-specifier.
2472 ///
2473 /// \param SS A nested-name-specifier.
2474 ///
2475 /// \returns A pointer containing all of the information in the
2476 /// nested-name-specifier \p SS.
2478
2479 /// Given an annotation pointer for a nested-name-specifier, restore
2480 /// the nested-name-specifier structure.
2481 ///
2482 /// \param Annotation The annotation pointer, produced by
2483 /// \c SaveNestedNameSpecifierAnnotation().
2484 ///
2485 /// \param AnnotationRange The source range corresponding to the annotation.
2486 ///
2487 /// \param SS The nested-name-specifier that will be updated with the contents
2488 /// of the annotation pointer.
2489 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
2490 SourceRange AnnotationRange,
2491 CXXScopeSpec &SS);
2492
2493 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
2494
2495 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
2496 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
2497 /// After this method is called, according to [C++ 3.4.3p3], names should be
2498 /// looked up in the declarator-id's scope, until the declarator is parsed and
2499 /// ActOnCXXExitDeclaratorScope is called.
2500 /// The 'SS' should be a non-empty valid CXXScopeSpec.
2502
2503 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
2504 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
2505 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
2506 /// Used to indicate that names should revert to being looked up in the
2507 /// defining scope.
2509
2510 ///@}
2511
2512 //
2513 //
2514 // -------------------------------------------------------------------------
2515 //
2516 //
2517
2518 /// \name Declarations
2519 /// Implementations are in SemaDecl.cpp
2520 ///@{
2521
2522public:
2524
2525 /// The index of the first InventedParameterInfo that refers to the current
2526 /// context.
2528
2529 /// A RAII object to temporarily push a declaration context.
2531 private:
2532 Sema &S;
2533 DeclContext *SavedContext;
2534 ProcessingContextState SavedContextState;
2535 QualType SavedCXXThisTypeOverride;
2536 unsigned SavedFunctionScopesStart;
2537 unsigned SavedInventedParameterInfosStart;
2538
2539 public:
2540 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
2541 : S(S), SavedContext(S.CurContext),
2542 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
2543 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
2544 SavedFunctionScopesStart(S.FunctionScopesStart),
2545 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
2546 assert(ContextToPush && "pushing null context");
2547 S.CurContext = ContextToPush;
2548 if (NewThisContext)
2549 S.CXXThisTypeOverride = QualType();
2550 // Any saved FunctionScopes do not refer to this context.
2551 S.FunctionScopesStart = S.FunctionScopes.size();
2552 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
2553 }
2554
2555 void pop() {
2556 if (!SavedContext)
2557 return;
2558 S.CurContext = SavedContext;
2559 S.DelayedDiagnostics.popUndelayed(SavedContextState);
2560 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
2561 S.FunctionScopesStart = SavedFunctionScopesStart;
2562 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
2563 SavedContext = nullptr;
2564 }
2565
2566 ~ContextRAII() { pop(); }
2567 };
2568
2569 void DiagnoseInvalidJumps(Stmt *Body);
2570
2571 /// The function definitions which were renamed as part of typo-correction
2572 /// to match their respective declarations. We want to keep track of them
2573 /// to ensure that we don't emit a "redefinition" error if we encounter a
2574 /// correctly named definition after the renamed definition.
2576
2577 /// A cache of the flags available in enumerations with the flag_bits
2578 /// attribute.
2579 mutable llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
2580
2581 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
2582 /// declared. Rare. May alias another identifier, declared or undeclared.
2583 ///
2584 /// For aliases, the target identifier is used as a key for eventual
2585 /// processing when the target is declared. For the single-identifier form,
2586 /// the sole identifier is used as the key. Each entry is a `SetVector`
2587 /// (ordered by parse order) of aliases (identified by the alias name) in case
2588 /// of multiple aliases to the same undeclared identifier.
2589 llvm::MapVector<
2591 llvm::SetVector<
2593 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
2595
2596 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
2597 /// \#pragma redefine_extname before declared. Used in Solaris system headers
2598 /// to define functions that occur in multiple standards to call the version
2599 /// in the currently selected standard.
2600 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *> ExtnameUndeclaredIdentifiers;
2601
2602 /// Set containing all typedefs that are likely unused.
2605
2609
2610 /// The set of file scoped decls seen so far that have not been used
2611 /// and must warn if not used. Only contains the first declaration.
2613
2617
2618 /// All the tentative definitions encountered in the TU.
2620
2621 /// All the external declarations encoutered and used in the TU.
2623
2624 /// Generally null except when we temporarily switch decl contexts,
2625 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
2627
2628 /// Is the module scope we are in a C++ Header Unit?
2630 return ModuleScopes.empty() ? false
2631 : ModuleScopes.back().Module->isHeaderUnit();
2632 }
2633
2634 /// Get the module owning an entity.
2635 Module *getOwningModule(const Decl *Entity) {
2636 return Entity->getOwningModule();
2637 }
2638
2639 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2640
2642 Scope *S, CXXScopeSpec *SS = nullptr,
2643 bool isClassName = false, bool HasTrailingDot = false,
2644 ParsedType ObjectType = nullptr,
2645 bool IsCtorOrDtorName = false,
2646 bool WantNontrivialTypeSourceInfo = false,
2647 bool IsClassTemplateDeductionContext = true,
2648 ImplicitTypenameContext AllowImplicitTypename =
2650 IdentifierInfo **CorrectedII = nullptr);
2652 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2654 Scope *S, CXXScopeSpec *SS,
2655 ParsedType &SuggestedType,
2656 bool IsTemplateName = false);
2657
2658 /// Attempt to behave like MSVC in situations where lookup of an unqualified
2659 /// type name has failed in a dependent context. In these situations, we
2660 /// automatically form a DependentTypeName that will retry lookup in a related
2661 /// scope during instantiation.
2663 SourceLocation NameLoc,
2664 bool IsTemplateTypeArg);
2665
2666 /// Describes the result of the name lookup and resolution performed
2667 /// by \c ClassifyName().
2669 /// This name is not a type or template in this context, but might be
2670 /// something else.
2672 /// Classification failed; an error has been produced.
2674 /// The name has been typo-corrected to a keyword.
2676 /// The name was classified as a type.
2678 /// The name was classified as a specific non-type, non-template
2679 /// declaration. ActOnNameClassifiedAsNonType should be called to
2680 /// convert the declaration to an expression.
2682 /// The name was classified as an ADL-only function name.
2683 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2684 /// result to an expression.
2686 /// The name denotes a member of a dependent type that could not be
2687 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2688 /// convert the result to an expression.
2690 /// The name was classified as an overload set, and an expression
2691 /// representing that overload set has been formed.
2692 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2693 /// expression referencing the overload set.
2695 /// The name was classified as a template whose specializations are types.
2697 /// The name was classified as a variable template name.
2699 /// The name was classified as a function template name.
2701 /// The name was classified as an ADL-only function template name.
2703 /// The name was classified as a concept name.
2705 };
2706
2709 union {
2714 };
2715
2716 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2717
2718 public:
2720
2721 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2722
2723 static NameClassification Error() { return NameClassification(NC_Error); }
2724
2726 return NameClassification(NC_Unknown);
2727 }
2728
2730 NameClassification Result(NC_OverloadSet);
2731 Result.Expr = E;
2732 return Result;
2733 }
2734
2736 NameClassification Result(NC_NonType);
2737 Result.NonTypeDecl = D;
2738 return Result;
2739 }
2740
2742 return NameClassification(NC_UndeclaredNonType);
2743 }
2744
2746 return NameClassification(NC_DependentNonType);
2747 }
2748
2750 NameClassification Result(NC_TypeTemplate);
2751 Result.Template = Name;
2752 return Result;
2753 }
2754
2756 NameClassification Result(NC_VarTemplate);
2757 Result.Template = Name;
2758 return Result;
2759 }
2760
2762 NameClassification Result(NC_FunctionTemplate);
2763 Result.Template = Name;
2764 return Result;
2765 }
2766
2768 NameClassification Result(NC_Concept);
2769 Result.Template = Name;
2770 return Result;
2771 }
2772
2774 NameClassification Result(NC_UndeclaredTemplate);
2775 Result.Template = Name;
2776 return Result;
2777 }
2778
2779 NameClassificationKind getKind() const { return Kind; }
2780
2782 assert(Kind == NC_OverloadSet);
2783 return Expr;
2784 }
2785
2787 assert(Kind == NC_Type);
2788 return Type;
2789 }
2790
2792 assert(Kind == NC_NonType);
2793 return NonTypeDecl;
2794 }
2795
2797 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2798 Kind == NC_VarTemplate || Kind == NC_Concept ||
2799 Kind == NC_UndeclaredTemplate);
2800 return Template;
2801 }
2802
2804 switch (Kind) {
2805 case NC_TypeTemplate:
2806 return TNK_Type_template;
2807 case NC_FunctionTemplate:
2808 return TNK_Function_template;
2809 case NC_VarTemplate:
2810 return TNK_Var_template;
2811 case NC_Concept:
2812 return TNK_Concept_template;
2813 case NC_UndeclaredTemplate:
2815 default:
2816 llvm_unreachable("unsupported name classification.");
2817 }
2818 }
2819 };
2820
2821 /// Perform name lookup on the given name, classifying it based on
2822 /// the results of name lookup and the following token.
2823 ///
2824 /// This routine is used by the parser to resolve identifiers and help direct
2825 /// parsing. When the identifier cannot be found, this routine will attempt
2826 /// to correct the typo and classify based on the resulting name.
2827 ///
2828 /// \param S The scope in which we're performing name lookup.
2829 ///
2830 /// \param SS The nested-name-specifier that precedes the name.
2831 ///
2832 /// \param Name The identifier. If typo correction finds an alternative name,
2833 /// this pointer parameter will be updated accordingly.
2834 ///
2835 /// \param NameLoc The location of the identifier.
2836 ///
2837 /// \param NextToken The token following the identifier. Used to help
2838 /// disambiguate the name.
2839 ///
2840 /// \param CCC The correction callback, if typo correction is desired.
2841 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2842 IdentifierInfo *&Name, SourceLocation NameLoc,
2843 const Token &NextToken,
2844 CorrectionCandidateCallback *CCC = nullptr);
2845
2846 /// Act on the result of classifying a name as an undeclared (ADL-only)
2847 /// non-type declaration.
2849 SourceLocation NameLoc);
2850 /// Act on the result of classifying a name as an undeclared member of a
2851 /// dependent base class.
2853 IdentifierInfo *Name,
2854 SourceLocation NameLoc,
2855 bool IsAddressOfOperand);
2856 /// Act on the result of classifying a name as a specific non-type
2857 /// declaration.
2859 NamedDecl *Found,
2860 SourceLocation NameLoc,
2861 const Token &NextToken);
2862 /// Act on the result of classifying a name as an overload set.
2864
2865 /// Describes the detailed kind of a template name. Used in diagnostics.
2872 Concept,
2874 };
2877
2878 /// Determine whether it's plausible that E was intended to be a
2879 /// template-name.
2881 if (!getLangOpts().CPlusPlus || E.isInvalid())
2882 return false;
2883 Dependent = false;
2884 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2885 return !DRE->hasExplicitTemplateArgs();
2886 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2887 return !ME->hasExplicitTemplateArgs();
2888 Dependent = true;
2889 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2890 return !DSDRE->hasExplicitTemplateArgs();
2891 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2892 return !DSME->hasExplicitTemplateArgs();
2893 // Any additional cases recognized here should also be handled by
2894 // diagnoseExprIntendedAsTemplateName.
2895 return false;
2896 }
2897
2898 void warnOnReservedIdentifier(const NamedDecl *D);
2899
2901
2903 MultiTemplateParamsArg TemplateParameterLists);
2906 unsigned FailedFoldDiagID);
2911 TemplateIdAnnotation *TemplateId,
2912 bool IsMemberSpecialization);
2913
2914 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
2915
2916 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2918 const LookupResult &R);
2921 const LookupResult &R);
2922 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2923 const LookupResult &R);
2924 void CheckShadow(Scope *S, VarDecl *D);
2925
2926 /// Warn if 'E', which is an expression that is about to be modified, refers
2927 /// to a shadowing declaration.
2929
2931
2932 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2933 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2934 TypedefNameDecl *NewTD);
2937 TypeSourceInfo *TInfo,
2940 LookupResult &Previous, bool &Redeclaration);
2942 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
2943 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
2944 bool &AddToScope, ArrayRef<BindingDecl *> Bindings = std::nullopt);
2945
2946 // Returns true if the variable declaration is a redeclaration
2950
2952 TypeSourceInfo *TInfo,
2954 MultiTemplateParamsArg TemplateParamLists,
2955 bool &AddToScope);
2957
2958 // Returns true if the function declaration is a redeclaration
2961 bool IsMemberSpecialization, bool DeclIsDefn);
2964 QualType NewT, QualType OldT);
2965 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2968 bool IsDefinition);
2971 SourceLocation ExplicitThisLoc = {});
2972 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
2973 QualType T);
2974 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2975 SourceLocation NameLoc,
2976 const IdentifierInfo *Name, QualType T,
2977 TypeSourceInfo *TSInfo, StorageClass SC);
2978
2979 // Contexts where using non-trivial C union types can be disallowed. This is
2980 // passed to err_non_trivial_c_union_in_invalid_context.
2982 // Function parameter.
2984 // Function return.
2986 // Default-initialized object.
2988 // Variable with automatic storage duration.
2990 // Initializer expression that might copy from another object.
2992 // Assignment.
2994 // Compound literal.
2996 // Block capture.
2998 // lvalue-to-rvalue conversion of volatile type.
3000 };
3001
3002 /// Emit diagnostics if the initializer or any of its explicit or
3003 /// implicitly-generated subexpressions require copying or
3004 /// default-initializing a type that is or contains a C union type that is
3005 /// non-trivial to copy or default-initialize.
3007
3008 // These flags are passed to checkNonTrivialCUnion.
3013 };
3014
3015 /// Emit diagnostics if a non-trivial C union type or a struct that contains
3016 /// a non-trivial C union is used in an invalid context.
3018 NonTrivialCUnionContext UseContext,
3019 unsigned NonTrivialKind);
3020
3021 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
3022 void ActOnUninitializedDecl(Decl *dcl);
3023 void ActOnInitializerError(Decl *Dcl);
3024
3025 void ActOnCXXForRangeDecl(Decl *D);
3027 IdentifierInfo *Ident,
3028 ParsedAttributes &Attrs);
3029
3032 void FinalizeDeclaration(Decl *D);
3034 ArrayRef<Decl *> Group);
3036
3037 /// Should be called on all declarations that might have attached
3038 /// documentation comments.
3039 void ActOnDocumentableDecl(Decl *D);
3041
3042 enum class FnBodyKind {
3043 /// C++26 [dcl.fct.def.general]p1
3044 /// function-body:
3045 /// ctor-initializer[opt] compound-statement
3046 /// function-try-block
3047 Other,
3048 /// = default ;
3049 Default,
3050 /// deleted-function-body
3051 ///
3052 /// deleted-function-body:
3053 /// = delete ;
3054 /// = delete ( unevaluated-string ) ;
3055 Delete
3056 };
3057
3059 SourceLocation LocAfterDecls);
3061 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
3062 SkipBodyInfo *SkipBody = nullptr);
3064 MultiTemplateParamsArg TemplateParamLists,
3065 SkipBodyInfo *SkipBody = nullptr,
3066 FnBodyKind BodyKind = FnBodyKind::Other);
3068 SkipBodyInfo *SkipBody = nullptr,
3069 FnBodyKind BodyKind = FnBodyKind::Other);
3071
3072 /// Determine whether we can delay parsing the body of a function or
3073 /// function template until it is used, assuming we don't care about emitting
3074 /// code for that function.
3075 ///
3076 /// This will be \c false if we may need the body of the function in the
3077 /// middle of parsing an expression (where it's impractical to switch to
3078 /// parsing a different function), for instance, if it's constexpr in C++11
3079 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
3080 bool canDelayFunctionBody(const Declarator &D);
3081
3082 /// Determine whether we can skip parsing the body of a function
3083 /// definition, assuming we don't care about analyzing its body or emitting
3084 /// code for that function.
3085 ///
3086 /// This will be \c false only if we may need the body of the function in
3087 /// order to parse the rest of the program (for instance, if it is
3088 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
3089 bool canSkipFunctionBody(Decl *D);
3090
3093 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
3096
3097 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
3098 /// attribute for which parsing is delayed.
3100
3101 /// Diagnose any unused parameters in the given sequence of
3102 /// ParmVarDecl pointers.
3104
3105 /// Diagnose whether the size of parameters or return value of a
3106 /// function or obj-c method definition is pass-by-value and larger than a
3107 /// specified threshold.
3108 void
3110 QualType ReturnTy, NamedDecl *D);
3111
3113 SourceLocation RParenLoc);
3114
3117
3119
3121 const ParsedAttributesView &DeclAttrs,
3122 RecordDecl *&AnonRecord);
3124 const ParsedAttributesView &DeclAttrs,
3125 MultiTemplateParamsArg TemplateParams,
3126 bool IsExplicitInstantiation,
3127 RecordDecl *&AnonRecord);
3128
3131 const PrintingPolicy &Policy);
3132
3133 /// Called once it is known whether
3134 /// a tag declaration is an anonymous union or struct.
3136
3138
3141
3142 /// Common ways to introduce type names without a tag for use in diagnostics.
3143 /// Keep in sync with err_tag_reference_non_tag.
3154 };
3155
3156 /// Given a non-tag type declaration, returns an enum useful for indicating
3157 /// what kind of non-tag type this is.
3159
3161 bool isDefinition, SourceLocation NewTagLoc,
3162 const IdentifierInfo *Name);
3163
3165 TUK_Reference, // Reference to a tag: 'struct foo *X;'
3166 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
3167 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
3168 TUK_Friend // Friend declaration: 'friend struct foo;'
3170
3172 // Not parsing a type within __builtin_offsetof.
3174 // Parsing a type within __builtin_offsetof.
3176 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
3177 // To improve our diagnostic message.
3179 };
3180
3181 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3182 SourceLocation KWLoc, CXXScopeSpec &SS,
3183 IdentifierInfo *Name, SourceLocation NameLoc,
3185 SourceLocation ModulePrivateLoc,
3186 MultiTemplateParamsArg TemplateParameterLists,
3187 bool &OwnedDecl, bool &IsDependent,
3188 SourceLocation ScopedEnumKWLoc,
3189 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3190 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3191 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
3192
3193 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3194 Declarator &D, Expr *BitfieldWidth);
3195
3196 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3197 Declarator &D, Expr *BitfieldWidth,
3198 InClassInitStyle InitStyle, AccessSpecifier AS);
3199
3202 SourceLocation Loc, bool Mutable,
3203 Expr *BitfieldWidth, InClassInitStyle InitStyle,
3205 NamedDecl *PrevDecl, Declarator *D = nullptr);
3206
3208
3209 void ActOnLastBitfield(SourceLocation DeclStart,
3210 SmallVectorImpl<Decl *> &AllIvarDecls);
3211
3212 // This is used for both record definitions and ObjC interface declarations.
3213 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3214 ArrayRef<Decl *> Fields, SourceLocation LBrac,
3215 SourceLocation RBrac, const ParsedAttributesView &AttrList);
3216
3217 /// ActOnTagStartDefinition - Invoked when we have entered the
3218 /// scope of a tag's definition (e.g., for an enumeration, class,
3219 /// struct, or union).
3221
3222 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3223 /// Differently from C++, actually parse the body and reject / error out
3224 /// in case of a structural mismatch.
3225 bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3226
3228
3229 /// Invoked when we enter a tag definition that we're skipping.
3231
3232 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3233 /// C++ record definition's base-specifiers clause and are starting its
3234 /// member declarations.
3236 SourceLocation FinalLoc,
3237 bool IsFinalSpelledSealed,
3238 bool IsAbstract,
3239 SourceLocation LBraceLoc);
3240
3241 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3242 /// the definition of a tag (enumeration, class, struct, or union).
3244 SourceRange BraceRange);
3245
3247
3248 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3249 /// error parsing the definition of a tag.
3251
3253 EnumConstantDecl *LastEnumConst,
3255 Expr *val);
3257 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3258 QualType EnumUnderlyingTy, bool IsFixed,
3259 const EnumDecl *Prev);
3260
3261 /// Determine whether the body of an anonymous enumeration should be skipped.
3262 /// \param II The name of the first enumerator.
3264 SourceLocation IILoc);
3265
3266 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3268 const ParsedAttributesView &Attrs,
3269 SourceLocation EqualLoc, Expr *Val);
3270 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3271 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3272 const ParsedAttributesView &Attr);
3273
3274 /// Set the current declaration context until it gets popped.
3275 void PushDeclContext(Scope *S, DeclContext *DC);
3276 void PopDeclContext();
3277
3278 /// EnterDeclaratorContext - Used when we must lookup names in the context
3279 /// of a declarator's nested name specifier.
3282
3283 /// Enter a template parameter scope, after it's been associated with a
3284 /// particular DeclContext. Causes lookup within the scope to chain through
3285 /// enclosing contexts in the correct order.
3287
3288 /// Push the parameters of D, which must be a function, into scope.
3291
3292 /// Add this decl to the scope shadowed decl chains.
3293 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3294
3295 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3296 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3297 /// true if 'D' belongs to the given declaration context.
3298 ///
3299 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3300 /// enclosing namespace set of the context, rather than contained
3301 /// directly within it.
3302 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3303 bool AllowInlineNamespace = false) const;
3304
3305 /// Finds the scope corresponding to the given decl context, if it
3306 /// happens to be an enclosing scope. Otherwise return NULL.
3308
3309 /// Subroutines of ActOnDeclarator().
3311 TypeSourceInfo *TInfo);
3312 bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New);
3313
3314 /// Describes the kind of merge to perform for availability
3315 /// attributes (including "deprecated", "unavailable", and "availability").
3317 /// Don't merge availability attributes at all.
3319 /// Merge availability attributes for a redeclaration, which requires
3320 /// an exact match.
3322 /// Merge availability attributes for an override, which requires
3323 /// an exact match or a weakening of constraints.
3325 /// Merge availability attributes for an implementation of
3326 /// a protocol requirement.
3328 /// Merge availability attributes for an implementation of
3329 /// an optional protocol requirement.
3332
3333 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3336 LookupResult &OldDecls);
3337 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3338 bool MergeTypeWithOld, bool NewDeclIsDefn);
3340 Scope *S, bool MergeTypeWithOld);
3343 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3344 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3345 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3346
3348 bool ConsiderLinkage, bool AllowInlineNamespace);
3349
3353 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
3354
3356
3357 /// If it's a file scoped decl that must warn if not used, keep track
3358 /// of it.
3360
3361 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
3363
3366 DiagReceiverTy DiagReceiver);
3367 void DiagnoseUnusedDecl(const NamedDecl *ND);
3368 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
3369
3370 /// If VD is set but not otherwise used, diagnose, for a parameter or a
3371 /// variable.
3372 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
3373
3375
3379 bool ForRedeclaration, SourceLocation Loc);
3380
3381 /// Get the outermost AttributedType node that sets a calling convention.
3382 /// Valid types should not have multiple attributes with different CCs.
3384
3387
3388 /// ParsingInitForAutoVars - a set of declarations with auto types for which
3389 /// we are currently parsing the initializer.
3391
3392 /// Look for a locally scoped extern "C" declaration by the given name.
3394
3396
3398
3400
3401 /// Checks if the variant/multiversion functions are compatible.
3403 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
3404 const PartialDiagnostic &NoProtoDiagID,
3405 const PartialDiagnosticAt &NoteCausedDiagIDAt,
3406 const PartialDiagnosticAt &NoSupportDiagIDAt,
3407 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
3408 bool ConstexprSupported, bool CLinkageMayDiffer);
3409
3410 /// type checking declaration initializers (C99 6.7.8)
3412 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
3413
3417 Expr *Init);
3418
3420 Expr *Init);
3421
3423
3424 // Heuristically tells if the function is `get_return_object` member of a
3425 // coroutine promise_type by matching the function name.
3426 static bool CanBeGetReturnObject(const FunctionDecl *FD);
3427 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
3428
3430 Scope *S);
3432 FunctionDecl *FD);
3434
3435 /// VerifyBitField - verifies that a bit field expression is an ICE and has
3436 /// the correct width, and that the field type is valid.
3437 /// Returns false on success.
3439 const IdentifierInfo *FieldName, QualType FieldTy,
3440 bool IsMsStruct, Expr *BitWidth);
3441
3442 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
3443 /// enum. If AllowMask is true, then we also allow the complement of a valid
3444 /// value, to be used as a mask.
3445 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
3446 bool AllowMask) const;
3447
3448 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
3449 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
3450 SourceLocation WeakNameLoc);
3451
3452 /// ActOnPragmaRedefineExtname - Called on well formed
3453 /// \#pragma redefine_extname oldname newname.
3455 IdentifierInfo *AliasName,
3456 SourceLocation PragmaLoc,
3457 SourceLocation WeakNameLoc,
3458 SourceLocation AliasNameLoc);
3459
3460 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
3461 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
3462 SourceLocation PragmaLoc,
3463 SourceLocation WeakNameLoc,
3464 SourceLocation AliasNameLoc);
3465
3466 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
3468 Emitted,
3469 CUDADiscarded, // Discarded due to CUDA/HIP hostness
3470 OMPDiscarded, // Discarded due to OpenMP hostness
3471 TemplateDiscarded, // Discarded due to uninstantiated templates
3472 Unknown,
3473 };
3474 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
3475 bool Final = false);
3476
3477 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
3479
3480private:
3481 /// Function or variable declarations to be checked for whether the deferred
3482 /// diagnostics should be emitted.
3483 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
3484
3485 /// Map of current shadowing declarations to shadowed declarations. Warn if
3486 /// it looks like the user is trying to modify the shadowing declaration.
3487 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
3488
3489 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
3490
3491 ///@}
3492
3493 //
3494 //
3495 // -------------------------------------------------------------------------
3496 //
3497 //
3498
3499 /// \name Declaration Attribute Handling
3500 /// Implementations are in SemaDeclAttr.cpp
3501 ///@{
3502
3503public:
3504 /// Describes the kind of priority given to an availability attribute.
3505 ///
3506 /// The sum of priorities deteremines the final priority of the attribute.
3507 /// The final priority determines how the attribute will be merged.
3508 /// An attribute with a lower priority will always remove higher priority
3509 /// attributes for the specified platform when it is being applied. An
3510 /// attribute with a higher priority will not be applied if the declaration
3511 /// already has an availability attribute with a lower priority for the
3512 /// specified platform. The final prirority values are not expected to match
3513 /// the values in this enumeration, but instead should be treated as a plain
3514 /// integer value. This enumeration just names the priority weights that are
3515 /// used to calculate that final vaue.
3517 /// The availability attribute was specified explicitly next to the
3518 /// declaration.
3520
3521 /// The availability attribute was applied using '#pragma clang attribute'.
3523
3524 /// The availability attribute for a specific platform was inferred from
3525 /// an availability attribute for another platform.
3528
3529 /// Describes the reason a calling convention specification was ignored, used
3530 /// for diagnostics.
3532 ForThisTarget = 0,
3536 };
3537
3538 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
3539 /// \#pragma weak during processing of other Decls.
3540 /// I couldn't figure out a clean way to generate these in-line, so
3541 /// we store them here and handle separately -- which is a hack.
3542 /// It would be best to refactor this.
3544
3545 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
3547
3551
3552 /// ExtVectorDecls - This is a list all the extended vector types. This allows
3553 /// us to associate a raw vector type with one of the ext_vector type names.
3554 /// This is only necessary for issuing pretty diagnostics.
3556
3558 const Expr *E, StringRef &Str,
3559 SourceLocation *ArgLocation = nullptr);
3560 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
3561 StringRef &Str,
3562 SourceLocation *ArgLocation = nullptr);
3563
3564 /// Determine if type T is a valid subject for a nonnull and similar
3565 /// attributes. By default, we look through references (the behavior used by
3566 /// nonnull), but if the second parameter is true, then we treat a reference
3567 /// type as valid.
3568 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3569
3570 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
3571 /// declaration.
3572 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
3573 Expr *OE);
3574
3575 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
3576 /// declaration.
3577 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
3578 Expr *ParamExpr);
3579
3580 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
3581 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
3582
3583 AvailabilityAttr *
3585 IdentifierInfo *Platform, bool Implicit,
3586 VersionTuple Introduced, VersionTuple Deprecated,
3587 VersionTuple Obsoleted, bool IsUnavailable,
3588 StringRef Message, bool IsStrict, StringRef Replacement,
3590 TypeVisibilityAttr *
3592 TypeVisibilityAttr::VisibilityType Vis);
3593 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3594 VisibilityAttr::VisibilityType Vis);
3595 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3596 StringRef Name);
3597
3598 llvm::Error isValidSectionSpecifier(StringRef Str);
3599 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3600 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3601 StringRef Name);
3602
3603 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3604 bool checkTargetVersionAttr(SourceLocation LiteralLoc, Decl *D,
3605 StringRef &Str, bool &isDefault);
3607 SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal,
3608 Decl *D, bool &HasDefault, bool &HasCommas, bool &HasNotDefault,
3609 SmallVectorImpl<SmallString<64>> &StringsBuffer);
3610
3611 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3612 StringRef NewUserDiagnostic);
3613 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3614 IdentifierInfo *Format, int FormatIdx,
3615 int FirstArg);
3616
3617 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
3618 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
3619 bool IsPackExpansion);
3621 bool IsPackExpansion);
3622
3623 /// AddAlignValueAttr - Adds an align_value attribute to a particular
3624 /// declaration.
3625 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
3626
3627 /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D.
3628 void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
3629 StringRef Annot, MutableArrayRef<Expr *> Args);
3630
3632 bool BestCase,
3633 MSInheritanceModel SemanticSpelling);
3634
3636
3637 /// AddModeAttr - Adds a mode attribute to a particular declaration.
3638 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
3639 bool InInstantiation = false);
3640 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3641 const AttributeCommonInfo &CI,
3642 const IdentifierInfo *Ident);
3643 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3644 SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3645 StringRef Name);
3646 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3647 const AttributeCommonInfo &CI);
3648 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3649 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3650 const InternalLinkageAttr &AL);
3651
3652 /// Check validaty of calling convention attribute \p attr. If \p FD
3653 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
3654 /// target. Otherwise, it is specified by \p CFT.
3656 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
3658
3659 void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
3660 ParameterABI ABI);
3661 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
3662
3663 /// Create an CUDALaunchBoundsAttr attribute.
3664 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
3665 Expr *MaxThreads,
3666 Expr *MinBlocks,
3667 Expr *MaxBlocks);
3668
3669 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
3670 /// declaration.
3671 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
3672 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
3673
3674 enum class RetainOwnershipKind { NS, CF, OS };
3675 void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
3676 RetainOwnershipKind K, bool IsTemplateInstantiation);
3677
3679
3680 /// Do a check to make sure \p Name looks like a legal argument for the
3681 /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
3682 /// is invalid for the given declaration.
3683 ///
3684 /// \p AL is used to provide caret diagnostics in case of a malformed name.
3685 ///
3686 /// \returns true if the name is a valid swift name for \p D, false otherwise.
3687 bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
3688 const ParsedAttr &AL, bool IsAsync);
3689
3690 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3691 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3692
3693 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
3694
3695 WebAssemblyImportNameAttr *
3696 mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL);
3697 WebAssemblyImportModuleAttr *
3698 mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL);
3699
3700 /// Create an AMDGPUWavesPerEUAttr attribute.
3701 AMDGPUFlatWorkGroupSizeAttr *
3703 Expr *Max);
3704
3705 /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
3706 /// attribute to a particular declaration.
3708 Expr *Min, Expr *Max);
3709
3710 /// Create an AMDGPUWavesPerEUAttr attribute.
3711 AMDGPUWavesPerEUAttr *
3713 Expr *Max);
3714
3715 /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
3716 /// particular declaration.
3718 Expr *Min, Expr *Max);
3719
3720 /// Create an AMDGPUMaxNumWorkGroupsAttr attribute.
3721 AMDGPUMaxNumWorkGroupsAttr *
3723 Expr *YExpr, Expr *ZExpr);
3724
3725 /// addAMDGPUMaxNumWorkGroupsAttr - Adds an amdgpu_max_num_work_groups
3726 /// attribute to a particular declaration.
3728 Expr *XExpr, Expr *YExpr, Expr *ZExpr);
3729
3730 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3731 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3732 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3733 const AttributeCommonInfo &CI,
3734 bool BestCase,
3735 MSInheritanceModel Model);
3736
3737 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3738 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3739 const EnforceTCBLeafAttr &AL);
3740
3741 // Helper for delayed processing of attributes.
3743 const ParsedAttributesView &AttrList);
3744
3745 // Options for ProcessDeclAttributeList().
3748 : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {}
3749
3751 ProcessDeclAttributeOptions Result = *this;
3752 Result.IncludeCXX11Attributes = Val;
3753 return Result;
3754 }
3755
3757 ProcessDeclAttributeOptions Result = *this;
3758 Result.IgnoreTypeAttributes = Val;
3759 return Result;
3760 }
3761
3762 // Should C++11 attributes be processed?
3764
3765 // Should any type attributes encountered be ignored?
3766 // If this option is false, a diagnostic will be emitted for any type
3767 // attributes of a kind that does not "slide" from the declaration to
3768 // the decl-specifier-seq.
3770 };
3771
3773 const ParsedAttributesView &AttrList,
3774 const ProcessDeclAttributeOptions &Options =
3777 const ParsedAttributesView &AttrList);
3778
3780
3783 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
3784
3785 void ProcessPragmaWeak(Scope *S, Decl *D);
3786 // Decl attributes - this routine is the top level dispatcher.
3787 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3788
3790
3792
3793 ///@}
3794
3795 //
3796 //
3797 // -------------------------------------------------------------------------
3798 //
3799 //
3800
3801 /// \name C++ Declarations
3802 /// Implementations are in SemaDeclCXX.cpp
3803 ///@{
3804
3805public:
3807
3808 /// Called before parsing a function declarator belonging to a function
3809 /// declaration.
3811 unsigned TemplateParameterDepth);
3812
3813 /// Called after parsing a function declarator belonging to a function
3814 /// declaration.
3816
3817 // Act on C++ namespaces
3819 SourceLocation NamespaceLoc,
3820 SourceLocation IdentLoc, IdentifierInfo *Ident,
3821 SourceLocation LBrace,
3822 const ParsedAttributesView &AttrList,
3823 UsingDirectiveDecl *&UsingDecl, bool IsNested);
3824 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
3825
3828
3830 EnumDecl *getStdAlignValT() const;
3831
3833 const IdentifierInfo *MemberOrBase);
3834
3836 /// The '<=>' operator was used in an expression and a builtin operator
3837 /// was selected.
3839 /// A defaulted 'operator<=>' needed the comparison category. This
3840 /// typically only applies to 'std::strong_ordering', due to the implicit
3841 /// fallback return value.
3843 };
3844
3845 /// Lookup the specified comparison category types in the standard
3846 /// library, an check the VarDecls possibly returned by the operator<=>
3847 /// builtins for that type.
3848 ///
3849 /// \return The type of the comparison category type corresponding to the
3850 /// specified Kind, or a null type if an error occurs
3854
3855 /// Tests whether Ty is an instance of std::initializer_list and, if
3856 /// it is and Element is not NULL, assigns the element type to Element.
3857 bool isStdInitializerList(QualType Ty, QualType *Element);
3858
3859 /// Looks for the std::initializer_list template and instantiates it
3860 /// with Element, or emits an error if it's not found.
3861 ///
3862 /// \returns The instantiated template, or null on error.
3864
3865 /// Determine whether Ctor is an initializer-list constructor, as
3866 /// defined in [dcl.init.list]p2.
3867 bool isInitListConstructor(const FunctionDecl *Ctor);
3868
3869 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
3870 SourceLocation NamespcLoc, CXXScopeSpec &SS,
3871 SourceLocation IdentLoc,
3872 IdentifierInfo *NamespcName,
3873 const ParsedAttributesView &AttrList);
3874
3876
3877 Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc,
3878 SourceLocation AliasLoc, IdentifierInfo *Alias,
3879 CXXScopeSpec &SS, SourceLocation IdentLoc,
3880 IdentifierInfo *Ident);
3881
3882 void FilterUsingLookup(Scope *S, LookupResult &lookup);
3883 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
3885 const LookupResult &PreviousDecls,
3886 UsingShadowDecl *&PrevShadow);
3889 UsingShadowDecl *PrevDecl);
3890
3892 bool HasTypenameKeyword,
3893 const CXXScopeSpec &SS,
3894 SourceLocation NameLoc,
3895 const LookupResult &Previous);
3896 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
3897 const CXXScopeSpec &SS,
3898 const DeclarationNameInfo &NameInfo,
3899 SourceLocation NameLoc,
3900 const LookupResult *R = nullptr,
3901 const UsingDecl *UD = nullptr);
3902
3904 SourceLocation UsingLoc,
3905 bool HasTypenameKeyword,
3906 SourceLocation TypenameLoc, CXXScopeSpec &SS,
3907 DeclarationNameInfo NameInfo,
3908 SourceLocation EllipsisLoc,
3909 const ParsedAttributesView &AttrList,
3910 bool IsInstantiation, bool IsUsingIfExists);
3912 SourceLocation UsingLoc,
3913 SourceLocation EnumLoc,
3914 SourceLocation NameLoc,
3916 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
3917 ArrayRef<NamedDecl *> Expansions);
3918
3920
3921 /// Given a derived-class using shadow declaration for a constructor and the
3922 /// correspnding base class constructor, find or create the implicit
3923 /// synthesized derived class constructor to use for this initialization.
3926 ConstructorUsingShadowDecl *DerivedShadow);
3927
3929 SourceLocation UsingLoc,
3930 SourceLocation TypenameLoc, CXXScopeSpec &SS,
3931 UnqualifiedId &Name, SourceLocation EllipsisLoc,
3932 const ParsedAttributesView &AttrList);
3934 SourceLocation UsingLoc,
3935 SourceLocation EnumLoc,
3936 SourceLocation IdentLoc, IdentifierInfo &II,
3937 CXXScopeSpec *SS = nullptr);
3939 MultiTemplateParamsArg TemplateParams,
3940 SourceLocation UsingLoc, UnqualifiedId &Name,
3941 const ParsedAttributesView &AttrList,
3942 TypeResult Type, Decl *DeclFromDeclSpec);
3943
3944 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
3945 /// including handling of its default argument expressions.
3946 ///
3947 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
3949 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
3950 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
3951 bool HadMultipleCandidates, bool IsListInitialization,
3952 bool IsStdInitListInitialization, bool RequiresZeroInit,
3953 CXXConstructionKind ConstructKind, SourceRange ParenRange);
3954
3955 /// Build a CXXConstructExpr whose constructor has already been resolved if
3956 /// it denotes an inherited constructor.
3958 SourceLocation ConstructLoc, QualType DeclInitType,
3959 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
3960 bool HadMultipleCandidates, bool IsListInitialization,
3961 bool IsStdInitListInitialization, bool RequiresZeroInit,
3962 CXXConstructionKind ConstructKind, SourceRange ParenRange);
3963
3964 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
3965 // the constructor can be elidable?
3967 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
3968 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
3969 bool HadMultipleCandidates, bool IsListInitialization,
3970 bool IsStdInitListInitialization, bool RequiresZeroInit,
3971 CXXConstructionKind ConstructKind, SourceRange ParenRange);
3972
3974 SourceLocation InitLoc);
3975
3976 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
3977 /// constructed variable.
3978 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
3979
3980 /// Helper class that collects exception specifications for
3981 /// implicitly-declared special member functions.
3983 // Pointer to allow copying
3984 Sema *Self;
3985 // We order exception specifications thus:
3986 // noexcept is the most restrictive, but is only used in C++11.
3987 // throw() comes next.
3988 // Then a throw(collected exceptions)
3989 // Finally no specification, which is expressed as noexcept(false).
3990 // throw(...) is used instead if any called function uses it.
3991 ExceptionSpecificationType ComputedEST;
3992 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3993 SmallVector<QualType, 4> Exceptions;
3994
3995 void ClearExceptions() {
3996 ExceptionsSeen.clear();
3997 Exceptions.clear();
3998 }
3999
4000 public:
4002 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4003 if (!Self.getLangOpts().CPlusPlus11)
4004 ComputedEST = EST_DynamicNone;
4005 }
4006
4007 /// Get the computed exception specification type.
4009 assert(!isComputedNoexcept(ComputedEST) &&
4010 "noexcept(expr) should not be a possible result");
4011 return ComputedEST;
4012 }
4013
4014 /// The number of exceptions in the exception specification.
4015 unsigned size() const { return Exceptions.size(); }
4016
4017 /// The set of exceptions in the exception specification.
4018 const QualType *data() const { return Exceptions.data(); }
4019
4020 /// Integrate another called method into the collected data.
4021 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4022
4023 /// Integrate an invoked expression into the collected data.
4024 void CalledExpr(Expr *E) { CalledStmt(E); }
4025
4026 /// Integrate an invoked statement into the collected data.
4027 void CalledStmt(Stmt *S);
4028
4029 /// Overwrite an EPI's exception specification with this
4030 /// computed exception specification.
4033 ESI.Type = getExceptionSpecType();
4034 if (ESI.Type == EST_Dynamic) {
4035 ESI.Exceptions = Exceptions;
4036 } else if (ESI.Type == EST_None) {
4037 /// C++11 [except.spec]p14:
4038 /// The exception-specification is noexcept(false) if the set of
4039 /// potential exceptions of the special member function contains "any"
4040 ESI.Type = EST_NoexceptFalse;
4041 ESI.NoexceptExpr =
4042 Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get();
4043 }
4044 return ESI;
4045 }
4046 };
4047
4048 /// Evaluate the implicit exception specification for a defaulted
4049 /// special member function.
4051
4052 /// Check the given exception-specification and update the
4053 /// exception specification information with the results.
4054 void checkExceptionSpecification(bool IsTopLevel,
4056 ArrayRef<ParsedType> DynamicExceptions,
4057 ArrayRef<SourceRange> DynamicExceptionRanges,
4058 Expr *NoexceptExpr,
4059 SmallVectorImpl<QualType> &Exceptions,
4061
4062 /// Add an exception-specification to the given member or friend function
4063 /// (or function template). The exception-specification was parsed
4064 /// after the function itself was declared.
4066 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
4067 ArrayRef<ParsedType> DynamicExceptions,
4068 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr);
4069
4070 class InheritedConstructorInfo;
4071
4072 /// Determine if a special member function should have a deleted
4073 /// definition when it is defaulted.
4075 InheritedConstructorInfo *ICI = nullptr,
4076 bool Diagnose = false);
4077
4078 /// Produce notes explaining why a defaulted function was defined as deleted.
4080
4081 /// Declare the implicit default constructor for the given class.
4082 ///
4083 /// \param ClassDecl The class declaration into which the implicit
4084 /// default constructor will be added.
4085 ///
4086 /// \returns The implicitly-declared default constructor.
4089
4090 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4091 /// defining this constructor as the default constructor.
4093 CXXConstructorDecl *Constructor);
4094
4095 /// Declare the implicit destructor for the given class.
4096 ///
4097 /// \param ClassDecl The class declaration into which the implicit
4098 /// destructor will be added.
4099 ///
4100 /// \returns The implicitly-declared destructor.
4102
4103 /// DefineImplicitDestructor - Checks for feasibility of
4104 /// defining this destructor as the default destructor.
4105 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4107
4108 /// Build an exception spec for destructors that don't have one.
4109 ///
4110 /// C++11 says that user-defined destructors with no exception spec get one
4111 /// that looks as if the destructor was implicitly declared.
4113
4114 /// Define the specified inheriting constructor.
4116 CXXConstructorDecl *Constructor);
4117
4118 /// Declare the implicit copy constructor for the given class.
4119 ///
4120 /// \param ClassDecl The class declaration into which the implicit
4121 /// copy constructor will be added.
4122 ///
4123 /// \returns The implicitly-declared copy constructor.
4125
4126 /// DefineImplicitCopyConstructor - Checks for feasibility of
4127 /// defining this constructor as the copy constructor.
4128 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4129 CXXConstructorDecl *Constructor);
4130
4131 /// Declare the implicit move constructor for the given class.
4132 ///
4133 /// \param ClassDecl The Class declaration into which the implicit
4134 /// move constructor will be added.
4135 ///
4136 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4137 /// declared.
4139
4140 /// DefineImplicitMoveConstructor - Checks for feasibility of
4141 /// defining this constructor as the move constructor.
4142 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4143 CXXConstructorDecl *Constructor);
4144
4145 /// Declare the implicit copy assignment operator for the given class.
4146 ///
4147 /// \param ClassDecl The class declaration into which the implicit
4148 /// copy assignment operator will be added.
4149 ///
4150 /// \returns The implicitly-declared copy assignment operator.
4152
4153 /// Defines an implicitly-declared copy assignment operator.
4154 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4155 CXXMethodDecl *MethodDecl);
4156
4157 /// Declare the implicit move assignment operator for the given class.
4158 ///
4159 /// \param ClassDecl The Class declaration into which the implicit
4160 /// move assignment operator will be added.
4161 ///
4162 /// \returns The implicitly-declared move assignment operator, or NULL if it
4163 /// wasn't declared.
4165
4166 /// Defines an implicitly-declared move assignment operator.
4167 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4168 CXXMethodDecl *MethodDecl);
4169
4170 /// Check a completed declaration of an implicit special member.
4172
4173 /// Determine whether the given function is an implicitly-deleted
4174 /// special member function.
4176
4177 /// Check whether 'this' shows up in the type of a static member
4178 /// function after the (naturally empty) cv-qualifier-seq would be.
4179 ///
4180 /// \returns true if an error occurred.
4182
4183 /// Whether this' shows up in the exception specification of a static
4184 /// member function.
4186
4187 /// Check whether 'this' shows up in the attributes of the given
4188 /// static member function.
4189 ///
4190 /// \returns true if an error occurred.
4192
4194 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI);
4195
4197
4199 QualType DeclInitType, MultiExprArg ArgsPtr,
4201 SmallVectorImpl<Expr *> &ConvertedArgs,
4202 bool AllowExplicit = false,
4203 bool IsListInitialization = false);
4204
4205 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4206 /// initializer for the declaration 'Dcl'.
4207 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4208 /// static data member of class X, names should be looked up in the scope of
4209 /// class X.
4211
4212 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4213 /// initializer for the declaration 'Dcl'.
4214 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
4215
4216 /// Define the "body" of the conversion from a lambda object to a
4217 /// function pointer.
4218 ///
4219 /// This routine doesn't actually define a sensible body; rather, it fills
4220 /// in the initialization expression needed to copy the lambda object into
4221 /// the block, and IR generation actually generates the real body of the
4222 /// block pointer conversion.
4223 void
4225 CXXConversionDecl *Conv);
4226
4227 /// Define the "body" of the conversion from a lambda object to a
4228 /// block pointer.
4229 ///
4230 /// This routine doesn't actually define a sensible body; rather, it fills
4231 /// in the initialization expression needed to copy the lambda object into
4232 /// the block, and IR generation actually generates the real body of the
4233 /// block pointer conversion.
4235 CXXConversionDecl *Conv);
4236
4238 Expr *LangStr, SourceLocation LBraceLoc);
4240 SourceLocation RBraceLoc);
4241
4242 //===--------------------------------------------------------------------===//
4243 // C++ Classes
4244 //
4246 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
4247 const CXXScopeSpec *SS = nullptr);
4249
4251 SourceLocation ColonLoc,
4252 const ParsedAttributesView &Attrs);
4253
4254 NamedDecl *
4256 MultiTemplateParamsArg TemplateParameterLists,
4257 Expr *BitfieldWidth, const VirtSpecifiers &VS,
4258 InClassInitStyle InitStyle);
4259
4262 SourceLocation EqualLoc,
4263 Expr *Init);
4264
4266 ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS,
4267 IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy,
4268 const DeclSpec &DS, SourceLocation IdLoc,
4269 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
4270 SourceLocation RParenLoc, SourceLocation EllipsisLoc);
4271
4272 MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S,
4273 CXXScopeSpec &SS,
4274 IdentifierInfo *MemberOrBase,
4275 ParsedType TemplateTypeTy,
4276 const DeclSpec &DS, SourceLocation IdLoc,
4277 Expr *InitList, SourceLocation EllipsisLoc);
4278
4279 MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S,
4280 CXXScopeSpec &SS,
4281 IdentifierInfo *MemberOrBase,
4282 ParsedType TemplateTypeTy,
4283 const DeclSpec &DS, SourceLocation IdLoc,
4284 Expr *Init, SourceLocation EllipsisLoc);
4285
4287 SourceLocation IdLoc);
4288
4290 TypeSourceInfo *BaseTInfo, Expr *Init,
4291 CXXRecordDecl *ClassDecl,
4292 SourceLocation EllipsisLoc);
4293
4295 CXXRecordDecl *ClassDecl);
4296
4299
4301 CXXConstructorDecl *Constructor, bool AnyErrors,
4302 ArrayRef<CXXCtorInitializer *> Initializers = std::nullopt);
4303
4304 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
4305 /// mark all the non-trivial destructors of its members and bases as
4306 /// referenced.
4309
4310 /// Mark destructors of virtual bases of this class referenced. In the Itanium
4311 /// C++ ABI, this is done when emitting a destructor for any non-abstract
4312 /// class. In the Microsoft C++ ABI, this is done any time a class's
4313 /// destructor is referenced.
4315 SourceLocation Location, CXXRecordDecl *ClassDecl,
4316 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr);
4317
4318 /// Do semantic checks to allow the complete destructor variant to be emitted
4319 /// when the destructor is defined in another translation unit. In the Itanium
4320 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
4321 /// can be emitted in separate TUs. To emit the complete variant, run a subset
4322 /// of the checks performed when emitting a regular destructor.
4324 CXXDestructorDecl *Dtor);
4325
4326 /// The list of classes whose vtables have been used within
4327 /// this translation unit, and the source locations at which the
4328 /// first use occurred.
4329 typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse;
4330
4331 /// The list of vtables that are required but have not yet been
4332 /// materialized.
4334
4335 /// The set of classes whose vtables have been used within
4336 /// this translation unit, and a bit that will be true if the vtable is
4337 /// required to be emitted (otherwise, it should be emitted only if needed
4338 /// by code generation).
4339 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
4340
4341 /// Load any externally-stored vtable uses.
4343
4344 /// Note that the vtable for the given class was used at the
4345 /// given location.
4347 bool DefinitionRequired = false);
4348
4349 /// Mark the exception specifications of all virtual member functions
4350 /// in the given class as needed.
4352 const CXXRecordDecl *RD);
4353
4354 /// MarkVirtualMembersReferenced - Will mark all members of the given
4355 /// CXXRecordDecl referenced.
4357 bool ConstexprOnly = false);
4358
4359 /// Define all of the vtables that have been used in this
4360 /// translation unit and reference any virtual members used by those
4361 /// vtables.
4362 ///
4363 /// \returns true if any work was done, false otherwise.
4364 bool DefineUsedVTables();
4365
4367
4368 void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc,
4370 bool AnyErrors);
4371
4372 /// Check class-level dllimport/dllexport attribute. The caller must
4373 /// ensure that referenceDLLExportedClassMethods is called some point later
4374 /// when all outer classes of Class are complete.
4377
4379
4381 CXXRecordDecl *Class, Attr *ClassAttr,
4382 ClassTemplateSpecializationDecl *BaseTemplateSpec,
4383 SourceLocation BaseLoc);
4384
4386
4387 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
4388 /// conditions that are needed for the attribute to have an effect.
4390
4392 Decl *TagDecl, SourceLocation LBrac,
4393 SourceLocation RBrac,
4394 const ParsedAttributesView &AttrList);
4397
4399 unsigned ActOnReenterTemplateScope(Decl *Template,
4400 llvm::function_ref<Scope *()> EnterScope);
4403 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
4407
4408 bool EvaluateStaticAssertMessageAsString(Expr *Message, std::string &Result,
4409 ASTContext &Ctx,
4410 bool ErrorOnInvalidMessage);
4412 Expr *AssertExpr, Expr *AssertMessageExpr,
4413 SourceLocation RParenLoc);
4415 Expr *AssertExpr, Expr *AssertMessageExpr,
4416 SourceLocation RParenLoc, bool Failed);
4417 void DiagnoseStaticAssertDetails(const Expr *E);
4418
4419 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
4420 MultiTemplateParamsArg TemplateParams);
4422 MultiTemplateParamsArg TemplateParams);
4423
4425 StorageClass &SC);
4426 void CheckConstructor(CXXConstructorDecl *Constructor);
4428 StorageClass &SC);
4433 StorageClass &SC);
4434
4436
4439 SourceLocation DefaultLoc);
4441
4442 /// Kinds of defaulted comparison operator functions.
4443 enum class DefaultedComparisonKind : unsigned char {
4444 /// This is not a defaultable comparison operator.
4445 None,
4446 /// This is an operator== that should be implemented as a series of
4447 /// subobject comparisons.
4448 Equal,
4449 /// This is an operator<=> that should be implemented as a series of
4450 /// subobject comp