clang 20.0.0git
Sema.h
Go to the documentation of this file.
1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/Attr.h"
21#include "clang/AST/CharUnits.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
32#include "clang/AST/StmtCXX.h"
33#include "clang/AST/Type.h"
34#include "clang/AST/TypeLoc.h"
38#include "clang/Basic/Cuda.h"
42#include "clang/Basic/LLVM.h"
43#include "clang/Basic/Lambda.h"
45#include "clang/Basic/Module.h"
56#include "clang/Sema/Attr.h"
58#include "clang/Sema/DeclSpec.h"
64#include "clang/Sema/Scope.h"
65#include "clang/Sema/SemaBase.h"
67#include "clang/Sema/Weak.h"
68#include "llvm/ADT/APInt.h"
69#include "llvm/ADT/ArrayRef.h"
70#include "llvm/ADT/BitmaskEnum.h"
71#include "llvm/ADT/DenseMap.h"
72#include "llvm/ADT/DenseSet.h"
73#include "llvm/ADT/FloatingPointMode.h"
74#include "llvm/ADT/FoldingSet.h"
75#include "llvm/ADT/MapVector.h"
76#include "llvm/ADT/PointerIntPair.h"
77#include "llvm/ADT/PointerUnion.h"
78#include "llvm/ADT/STLExtras.h"
79#include "llvm/ADT/STLForwardCompat.h"
80#include "llvm/ADT/STLFunctionalExtras.h"
81#include "llvm/ADT/SetVector.h"
82#include "llvm/ADT/SmallBitVector.h"
83#include "llvm/ADT/SmallPtrSet.h"
84#include "llvm/ADT/SmallSet.h"
85#include "llvm/ADT/SmallVector.h"
86#include "llvm/ADT/StringExtras.h"
87#include "llvm/ADT/StringMap.h"
88#include "llvm/ADT/TinyPtrVector.h"
89#include "llvm/Support/Allocator.h"
90#include "llvm/Support/Compiler.h"
91#include "llvm/Support/Error.h"
92#include "llvm/Support/ErrorHandling.h"
93#include <cassert>
94#include <climits>
95#include <cstddef>
96#include <cstdint>
97#include <deque>
98#include <functional>
99#include <iterator>
100#include <memory>
101#include <optional>
102#include <string>
103#include <tuple>
104#include <type_traits>
105#include <utility>
106#include <vector>
107
108namespace llvm {
109struct InlineAsmIdentifierInfo;
110} // namespace llvm
111
112namespace clang {
113class ADLResult;
114class APValue;
115struct ASTConstraintSatisfaction;
116class ASTConsumer;
117class ASTContext;
118class ASTDeclReader;
119class ASTMutationListener;
120class ASTReader;
121class ASTWriter;
122class CXXBasePath;
123class CXXBasePaths;
124class CXXFieldCollector;
125class CodeCompleteConsumer;
126enum class ComparisonCategoryType : unsigned char;
127class ConstraintSatisfaction;
128class DarwinSDKInfo;
129class DeclGroupRef;
130class DeducedTemplateArgument;
131struct DeductionFailureInfo;
132class DependentDiagnostic;
133class Designation;
134class IdentifierInfo;
135class ImplicitConversionSequence;
136typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
137class InitializationKind;
138class InitializationSequence;
139class InitializedEntity;
140enum class LangAS : unsigned int;
141class LocalInstantiationScope;
142class LookupResult;
143class MangleNumberingContext;
144typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
145class ModuleLoader;
146class MultiLevelTemplateArgumentList;
147struct NormalizedConstraint;
148class ObjCInterfaceDecl;
149class ObjCMethodDecl;
150struct OverloadCandidate;
151enum class OverloadCandidateParamOrder : char;
153class OverloadCandidateSet;
154class Preprocessor;
155class SemaAMDGPU;
156class SemaARM;
157class SemaAVR;
158class SemaBPF;
159class SemaCodeCompletion;
160class SemaCUDA;
161class SemaHLSL;
162class SemaHexagon;
163class SemaLoongArch;
164class SemaM68k;
165class SemaMIPS;
166class SemaMSP430;
167class SemaNVPTX;
168class SemaObjC;
169class SemaOpenACC;
170class SemaOpenCL;
171class SemaOpenMP;
172class SemaPPC;
173class SemaPseudoObject;
174class SemaRISCV;
175class SemaSYCL;
176class SemaSwift;
177class SemaSystemZ;
178class SemaWasm;
179class SemaX86;
180class StandardConversionSequence;
181class TemplateArgument;
182class TemplateArgumentLoc;
183class TemplateInstantiationCallback;
184class TemplatePartialOrderingContext;
185class TemplateSpecCandidateSet;
186class Token;
187class TypeConstraint;
188class TypoCorrectionConsumer;
189class UnresolvedSetImpl;
190class UnresolvedSetIterator;
191class VisibleDeclConsumer;
192
193namespace sema {
194class BlockScopeInfo;
195class Capture;
196class CapturedRegionScopeInfo;
197class CapturingScopeInfo;
198class CompoundScopeInfo;
199class DelayedDiagnostic;
200class DelayedDiagnosticPool;
201class FunctionScopeInfo;
202class LambdaScopeInfo;
203class SemaPPCallbacks;
204class TemplateDeductionInfo;
205} // namespace sema
206
207namespace threadSafety {
208class BeforeSet;
209void threadSafetyCleanup(BeforeSet *Cache);
210} // namespace threadSafety
211
212// FIXME: No way to easily map from TemplateTypeParmTypes to
213// TemplateTypeParmDecls, so we have this horrible PointerUnion.
214typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *>,
215 SourceLocation>
217
218/// Describes whether we've seen any nullability information for the given
219/// file.
221 /// The first pointer declarator (of any pointer kind) in the file that does
222 /// not have a corresponding nullability annotation.
224
225 /// The end location for the first pointer declarator in the file. Used for
226 /// placing fix-its.
228
229 /// Which kind of pointer declarator we saw.
230 uint8_t PointerKind;
231
232 /// Whether we saw any type nullability annotations in the given file.
233 bool SawTypeNullability = false;
234};
235
236/// A mapping from file IDs to a record of whether we've seen nullability
237/// information in that file.
239 /// A mapping from file IDs to the nullability information for each file ID.
240 llvm::DenseMap<FileID, FileNullability> Map;
241
242 /// A single-element cache based on the file ID.
243 struct {
246 } Cache;
247
248public:
250 // Check the single-element cache.
251 if (file == Cache.File)
252 return Cache.Nullability;
253
254 // It's not in the single-element cache; flush the cache if we have one.
255 if (!Cache.File.isInvalid()) {
256 Map[Cache.File] = Cache.Nullability;
257 }
258
259 // Pull this entry into the cache.
260 Cache.File = file;
261 Cache.Nullability = Map[file];
262 return Cache.Nullability;
263 }
264};
265
266/// Tracks expected type during expression parsing, for use in code completion.
267/// The type is tied to a particular token, all functions that update or consume
268/// the type take a start location of the token they are looking at as a
269/// parameter. This avoids updating the type on hot paths in the parser.
271public:
272 PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
273
274 void enterCondition(Sema &S, SourceLocation Tok);
275 void enterReturn(Sema &S, SourceLocation Tok);
277 /// Handles e.g. BaseType{ .D = Tok...
279 const Designation &D);
280 /// Computing a type for the function argument may require running
281 /// overloading, so we postpone its computation until it is actually needed.
282 ///
283 /// Clients should be very careful when using this function, as it stores a
284 /// function_ref, clients should make sure all calls to get() with the same
285 /// location happen while function_ref is alive.
286 ///
287 /// The callback should also emit signature help as a side-effect, but only
288 /// if the completion point has been reached.
290 llvm::function_ref<QualType()> ComputeType);
291
293 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
294 SourceLocation OpLoc);
295 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
297 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
298 /// Handles all type casts, including C-style cast, C++ casts, etc.
300
301 /// Get the expected type associated with this location, if any.
302 ///
303 /// If the location is a function argument, determining the expected type
304 /// involves considering all function overloads and the arguments so far.
305 /// In this case, signature help for these function overloads will be reported
306 /// as a side-effect (only if the completion point has been reached).
308 if (!Enabled || Tok != ExpectedLoc)
309 return QualType();
310 if (!Type.isNull())
311 return Type;
312 if (ComputeType)
313 return ComputeType();
314 return QualType();
315 }
316
317private:
318 bool Enabled;
319 /// Start position of a token for which we store expected type.
320 SourceLocation ExpectedLoc;
321 /// Expected type for a token starting at ExpectedLoc.
323 /// A function to compute expected type at ExpectedLoc. It is only considered
324 /// if Type is null.
325 llvm::function_ref<QualType()> ComputeType;
326};
327
329 SkipBodyInfo() = default;
330 bool ShouldSkip = false;
332 NamedDecl *Previous = nullptr;
333 NamedDecl *New = nullptr;
334};
335
336/// Describes the result of template argument deduction.
337///
338/// The TemplateDeductionResult enumeration describes the result of
339/// template argument deduction, as returned from
340/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
341/// structure provides additional information about the results of
342/// template argument deduction, e.g., the deduced template argument
343/// list (if successful) or the specific template parameters or
344/// deduced arguments that were involved in the failure.
346 /// Template argument deduction was successful.
347 Success = 0,
348 /// The declaration was invalid; do nothing.
349 Invalid,
350 /// Template argument deduction exceeded the maximum template
351 /// instantiation depth (which has already been diagnosed).
353 /// Template argument deduction did not deduce a value
354 /// for every template parameter.
356 /// Template argument deduction did not deduce a value for every
357 /// expansion of an expanded template parameter pack.
359 /// Template argument deduction produced inconsistent
360 /// deduced values for the given template parameter.
362 /// Template argument deduction failed due to inconsistent
363 /// cv-qualifiers on a template parameter type that would
364 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
365 /// but were given a non-const "X".
367 /// Substitution of the deduced template argument values
368 /// resulted in an error.
370 /// After substituting deduced template arguments, a dependent
371 /// parameter type did not match the corresponding argument.
373 /// After substituting deduced template arguments, an element of
374 /// a dependent parameter type did not match the corresponding element
375 /// of the corresponding argument (when deducing from an initializer list).
377 /// A non-depnedent component of the parameter did not match the
378 /// corresponding component of the argument.
380 /// When performing template argument deduction for a function
381 /// template, there were too many call arguments.
383 /// When performing template argument deduction for a function
384 /// template, there were too few call arguments.
386 /// The explicitly-specified template arguments were not valid
387 /// template arguments for the given template.
389 /// Checking non-dependent argument conversions failed.
391 /// The deduced arguments did not satisfy the constraints associated
392 /// with the template.
394 /// Deduction failed; that's all we know.
396 /// CUDA Target attributes do not match.
398 /// Some error which was already diagnosed.
400};
401
402/// Kinds of C++ special members.
410 Invalid
411};
412
413/// The kind of conversion being performed.
415 /// An implicit conversion.
416 Implicit,
417 /// A C-style cast.
419 /// A functional-style cast.
421 /// A cast other than a C-style cast.
422 OtherCast,
423 /// A conversion for an operand of a builtin overloaded operator.
425};
426
427enum class TagUseKind {
428 Reference, // Reference to a tag: 'struct foo *X;'
429 Declaration, // Fwd decl of a tag: 'struct foo;'
430 Definition, // Definition of a tag: 'struct foo { int X; } Y;'
431 Friend // Friend declaration: 'friend struct foo;'
432};
433
434/// Used with attributes/effects with a boolean condition, e.g. `nonblocking`.
435enum class FunctionEffectMode : uint8_t {
436 None, // effect is not present.
437 False, // effect(false).
438 True, // effect(true).
439 Dependent // effect(expr) where expr is dependent.
440};
441
444
447 FunctionEffectWithCondition Old; // invalid when Added.
448 FunctionEffectWithCondition New; // invalid when Removed.
449
450 StringRef effectName() const {
452 return Old.Effect.name();
453 return New.Effect.name();
454 }
455
456 /// Describes the result of effects differing between a base class's virtual
457 /// method and an overriding method in a subclass.
458 enum class OverrideResult {
459 NoAction,
460 Warn,
461 Merge // Merge missing effect from base to derived.
462 };
463
464 /// Return true if adding or removing the effect as part of a type conversion
465 /// should generate a diagnostic.
467 const FunctionEffectsRef &SrcFX,
468 QualType DstType,
469 const FunctionEffectsRef &DstFX) const;
470
471 /// Return true if adding or removing the effect in a redeclaration should
472 /// generate a diagnostic.
473 bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction,
474 const FunctionEffectsRef &OldFX,
475 const FunctionDecl &NewFunction,
476 const FunctionEffectsRef &NewFX) const;
477
478 /// Return true if adding or removing the effect in a C++ virtual method
479 /// override should generate a diagnostic.
481 const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,
482 const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const;
483};
484
485struct FunctionEffectDifferences : public SmallVector<FunctionEffectDiff> {
486 /// Caller should short-circuit by checking for equality first.
488 const FunctionEffectsRef &New);
489};
490
491/// Sema - This implements semantic analysis and AST building for C.
492/// \nosubgrouping
493class Sema final : public SemaBase {
494 // Table of Contents
495 // -----------------
496 // 1. Semantic Analysis (Sema.cpp)
497 // 2. API Notes (SemaAPINotes.cpp)
498 // 3. C++ Access Control (SemaAccess.cpp)
499 // 4. Attributes (SemaAttr.cpp)
500 // 5. Availability Attribute Handling (SemaAvailability.cpp)
501 // 6. Bounds Safety (SemaBoundsSafety.cpp)
502 // 7. Casts (SemaCast.cpp)
503 // 8. Extra Semantic Checking (SemaChecking.cpp)
504 // 9. C++ Coroutines (SemaCoroutine.cpp)
505 // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
506 // 11. Declarations (SemaDecl.cpp)
507 // 12. Declaration Attribute Handling (SemaDeclAttr.cpp)
508 // 13. C++ Declarations (SemaDeclCXX.cpp)
509 // 14. C++ Exception Specifications (SemaExceptionSpec.cpp)
510 // 15. Expressions (SemaExpr.cpp)
511 // 16. C++ Expressions (SemaExprCXX.cpp)
512 // 17. Member Access Expressions (SemaExprMember.cpp)
513 // 18. Initializers (SemaInit.cpp)
514 // 19. C++ Lambda Expressions (SemaLambda.cpp)
515 // 20. Name Lookup (SemaLookup.cpp)
516 // 21. Modules (SemaModule.cpp)
517 // 22. C++ Overloading (SemaOverload.cpp)
518 // 23. Statements (SemaStmt.cpp)
519 // 24. `inline asm` Statement (SemaStmtAsm.cpp)
520 // 25. Statement Attribute Handling (SemaStmtAttr.cpp)
521 // 26. C++ Templates (SemaTemplate.cpp)
522 // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
523 // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp)
524 // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
525 // 30. C++ Template Declaration Instantiation
526 // (SemaTemplateInstantiateDecl.cpp)
527 // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp)
528 // 32. Constraints and Concepts (SemaConcept.cpp)
529 // 33. Types (SemaType.cpp)
530 // 34. FixIt Helpers (SemaFixItUtils.cpp)
531
532 /// \name Semantic Analysis
533 /// Implementations are in Sema.cpp
534 ///@{
535
536public:
537 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
539 CodeCompleteConsumer *CompletionConsumer = nullptr);
540 ~Sema();
541
542 /// Perform initialization that occurs after the parser has been
543 /// initialized but before it parses anything.
544 void Initialize();
545
546 /// This virtual key function only exists to limit the emission of debug info
547 /// describing the Sema class. GCC and Clang only emit debug info for a class
548 /// with a vtable when the vtable is emitted. Sema is final and not
549 /// polymorphic, but the debug info size savings are so significant that it is
550 /// worth adding a vtable just to take advantage of this optimization.
551 virtual void anchor();
552
553 const LangOptions &getLangOpts() const { return LangOpts; }
556
559 Preprocessor &getPreprocessor() const { return PP; }
560 ASTContext &getASTContext() const { return Context; }
564
566 StringRef Platform);
568
569 /// Registers an external source. If an external source already exists,
570 /// creates a multiplex external source and appends to it.
571 ///
572 ///\param[in] E - A non-null external sema source.
573 ///
575
576 /// Print out statistics about the semantic analysis.
577 void PrintStats() const;
578
579 /// Warn that the stack is nearly exhausted.
581
582 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
583 /// guaranteed). Produces a warning if we're low on stack space and allocates
584 /// more in that case. Use this in code that may recurse deeply (for example,
585 /// in template instantiation) to avoid stack overflow.
587 llvm::function_ref<void()> Fn);
588
589 /// Returns default addr space for method qualifiers.
591
592 /// Load weak undeclared identifiers from the external source.
594
595 /// Determine if VD, which must be a variable or function, is an external
596 /// symbol that nonetheless can't be referenced from outside this translation
597 /// unit because its type has no linkage and it's not extern "C".
598 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
599
600 /// Obtain a sorted list of functions that are undefined but ODR-used.
602 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined);
603
604 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
606 /// Retrieves list of suspicious delete-expressions that will be checked at
607 /// the end of translation unit.
608 const llvm::MapVector<FieldDecl *, DeleteLocs> &
610
611 /// Cause the active diagnostic on the DiagosticsEngine to be
612 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
613 /// should not be used elsewhere.
614 void EmitCurrentDiagnostic(unsigned DiagID);
615
616 void addImplicitTypedef(StringRef Name, QualType T);
617
618 /// Whether uncompilable error has occurred. This includes error happens
619 /// in deferred diagnostics.
620 bool hasUncompilableErrorOccurred() const;
621
622 /// Looks through the macro-expansion chain for the given
623 /// location, looking for a macro expansion with the given name.
624 /// If one is found, returns true and sets the location to that
625 /// expansion loc.
626 bool findMacroSpelling(SourceLocation &loc, StringRef name);
627
628 /// Calls \c Lexer::getLocForEndOfToken()
630
631 /// Retrieve the module loader associated with the preprocessor.
633
634 /// Invent a new identifier for parameters of abbreviated templates.
637 unsigned Index);
638
640
641 // Emit all deferred diagnostics.
642 void emitDeferredDiags();
643
645 /// The global module fragment, between 'module;' and a module-declaration.
647 /// A normal translation unit fragment. For a non-module unit, this is the
648 /// entire translation unit. Otherwise, it runs from the module-declaration
649 /// to the private-module-fragment (if any) or the end of the TU (if not).
651 /// The private module fragment, between 'module :private;' and the end of
652 /// the translation unit.
653 Private
654 };
655
656 /// This is called before the very first declaration in the translation unit
657 /// is parsed. Note that the ASTContext may have already injected some
658 /// declarations.
660 /// ActOnEndOfTranslationUnit - This is called at the very end of the
661 /// translation unit when EOF is reached and all but the top-level scope is
662 /// popped.
665
666 /// Determines the active Scope associated with the given declaration
667 /// context.
668 ///
669 /// This routine maps a declaration context to the active Scope object that
670 /// represents that declaration context in the parser. It is typically used
671 /// from "scope-less" code (e.g., template instantiation, lazy creation of
672 /// declarations) that injects a name for name-lookup purposes and, therefore,
673 /// must update the Scope.
674 ///
675 /// \returns The scope corresponding to the given declaraion context, or NULL
676 /// if no such scope is open.
678
679 void PushFunctionScope();
680 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
682
683 /// This is used to inform Sema what the current TemplateParameterDepth
684 /// is during Parsing. Currently it is used to pass on the depth
685 /// when parsing generic lambda 'auto' parameters.
686 void RecordParsingTemplateParameterDepth(unsigned Depth);
687
688 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
690 unsigned OpenMPCaptureLevel = 0);
691
692 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
693 /// time after they've been popped.
695 Sema *Self;
696
697 public:
698 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
700 };
701
703 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
704
705 /// Pop a function (or block or lambda or captured region) scope from the
706 /// stack.
707 ///
708 /// \param WP The warning policy to use for CFG-based warnings, or null if
709 /// such warnings should not be produced.
710 /// \param D The declaration corresponding to this function scope, if
711 /// producing CFG-based warnings.
712 /// \param BlockType The type of the block expression, if D is a BlockDecl.
715 const Decl *D = nullptr,
716 QualType BlockType = QualType());
717
719
724
725 void PushCompoundScope(bool IsStmtExpr);
726 void PopCompoundScope();
727
728 /// Determine whether any errors occurred within this function/method/
729 /// block.
731
732 /// Retrieve the current block, if any.
734
735 /// Get the innermost lambda enclosing the current location, if any. This
736 /// looks through intervening non-lambda scopes such as local functions and
737 /// blocks.
739
740 /// Retrieve the current lambda scope info, if any.
741 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
742 /// lambda scope info ignoring all inner capturing scopes that are not
743 /// lambda scopes.
745 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
746
747 /// Retrieve the current generic lambda info, if any.
749
750 /// Retrieve the current captured region, if any.
752
753 void ActOnComment(SourceRange Comment);
754
755 /// Retrieve the parser's current scope.
756 ///
757 /// This routine must only be used when it is certain that semantic analysis
758 /// and the parser are in precisely the same context, which is not the case
759 /// when, e.g., we are performing any kind of template instantiation.
760 /// Therefore, the only safe places to use this scope are in the parser
761 /// itself and in routines directly invoked from the parser and *never* from
762 /// template substitution or instantiation.
763 Scope *getCurScope() const { return CurScope; }
764
766
769 }
770
771 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
772 const FunctionDecl *FD = nullptr);
774 const PartialDiagnostic &PD,
775 const FunctionDecl *FD = nullptr) {
776 return targetDiag(Loc, PD.getDiagID(), FD) << PD;
777 }
778
779 /// Check if the type is allowed to be used for the current target.
781 ValueDecl *D = nullptr);
782
783 // /// The kind of conversion being performed.
784 // enum CheckedConversionKind {
785 // /// An implicit conversion.
786 // CCK_ImplicitConversion,
787 // /// A C-style cast.
788 // CCK_CStyleCast,
789 // /// A functional-style cast.
790 // CCK_FunctionalCast,
791 // /// A cast other than a C-style cast.
792 // CCK_OtherCast,
793 // /// A conversion for an operand of a builtin overloaded operator.
794 // CCK_ForBuiltinOverloadedOp
795 // };
796
797 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
798 /// cast. If there is already an implicit cast, merge into the existing one.
799 /// If isLvalue, the result of the cast is an lvalue.
802 const CXXCastPath *BasePath = nullptr,
804
805 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
806 /// to the conversion from scalar type ScalarTy to the Boolean type.
808
809 /// If \p AllowLambda is true, treat lambda as function.
810 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
811
812 /// Returns a pointer to the innermost enclosing function, or nullptr if the
813 /// current context is not inside a function. If \p AllowLambda is true,
814 /// this can return the call operator of an enclosing lambda, otherwise
815 /// lambdas are skipped when looking for an enclosing function.
816 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
817
818 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
819 /// the method decl for the method being parsed. If we're currently
820 /// in a 'block', this returns the containing context.
822
823 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
824 /// or C function we're in, otherwise return null. If we're currently
825 /// in a 'block', this returns the containing context.
827
828 /// Warn if we're implicitly casting from a _Nullable pointer type to a
829 /// _Nonnull one.
832
833 /// Warn when implicitly casting 0 to nullptr.
835
836 // ----- function effects ---
837
838 /// Warn when implicitly changing function effects.
841
842 /// Warn and return true if adding an effect to a set would create a conflict.
845 SourceLocation NewAttrLoc);
846
847 // Report a failure to merge function effects between declarations due to a
848 // conflict.
849 void
851 SourceLocation NewLoc,
852 SourceLocation OldLoc);
853
854 /// Try to parse the conditional expression attached to an effect attribute
855 /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty
856 /// optional on error.
857 std::optional<FunctionEffectMode>
858 ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName);
859
860 /// makeUnavailableInSystemHeader - There is an error in the current
861 /// context. If we're still in a system header, and we can plausibly
862 /// make the relevant declaration unavailable instead of erroring, do
863 /// so and return true.
865 UnavailableAttr::ImplicitReason reason);
866
867 /// Retrieve a suitable printing policy for diagnostics.
870 }
871
872 /// Retrieve a suitable printing policy for diagnostics.
874 const Preprocessor &PP);
875
876 /// Scope actions.
878
879 /// Determine whether \param D is function like (function or function
880 /// template) for parsing.
882
883 /// The maximum alignment, same as in llvm::Value. We duplicate them here
884 /// because that allows us not to duplicate the constants in clang code,
885 /// which we must to since we can't directly use the llvm constants.
886 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
887 ///
888 /// This is the greatest alignment value supported by load, store, and alloca
889 /// instructions, and global values.
890 static const unsigned MaxAlignmentExponent = 32;
891 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
892
893 /// Flag indicating whether or not to collect detailed statistics.
895
896 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
897
898 /// Stack containing information about each of the nested
899 /// function, block, and method scopes that are currently active.
901
902 /// The index of the first FunctionScope that corresponds to the current
903 /// context.
905
906 /// Track the number of currently active capturing scopes.
908
909 llvm::BumpPtrAllocator BumpAlloc;
910
911 /// The kind of translation unit we are processing.
912 ///
913 /// When we're processing a complete translation unit, Sema will perform
914 /// end-of-translation-unit semantic tasks (such as creating
915 /// initializers for tentative definitions in C) once parsing has
916 /// completed. Modules and precompiled headers perform different kinds of
917 /// checks.
919
920 /// Translation Unit Scope - useful to Objective-C actions that need
921 /// to lookup file scope declarations in the "ordinary" C decl namespace.
922 /// For example, user-defined classes, built-in "id" type, etc.
924
926
928 return CurScope->incrementMSManglingNumber();
929 }
930
931 /// Try to recover by turning the given expression into a
932 /// call. Returns true if recovery was attempted or an error was
933 /// emitted; this may also leave the ExprResult invalid.
935 bool ForceComplain = false,
936 bool (*IsPlausibleResult)(QualType) = nullptr);
937
938 /// Figure out if an expression could be turned into a call.
939 ///
940 /// Use this when trying to recover from an error where the programmer may
941 /// have written just the name of a function instead of actually calling it.
942 ///
943 /// \param E - The expression to examine.
944 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
945 /// with no arguments, this parameter is set to the type returned by such a
946 /// call; otherwise, it is set to an empty QualType.
947 /// \param OverloadSet - If the expression is an overloaded function
948 /// name, this parameter is populated with the decls of the various
949 /// overloads.
950 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
951 UnresolvedSetImpl &NonTemplateOverloads);
952
956
959
967
968 /// A RAII object to enter scope of a compound statement.
970 public:
971 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
972 S.ActOnStartOfCompoundStmt(IsStmtExpr);
973 }
974
976
977 private:
978 Sema &S;
979 };
980
981 /// An RAII helper that pops function a function scope on exit.
984 bool Active;
987 if (Active)
989 }
990 void disable() { Active = false; }
991 };
992
994 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
995 }
996
997 /// Worker object for performing CFG-based warnings.
1000
1001 /// Callback to the parser to parse templated functions when needed.
1002 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
1003 typedef void LateTemplateParserCleanupCB(void *P);
1007
1009 LateTemplateParserCleanupCB *LTPCleanup, void *P) {
1010 LateTemplateParser = LTP;
1011 LateTemplateParserCleanup = LTPCleanup;
1012 OpaqueParser = P;
1013 }
1014
1015 /// Callback to the parser to parse a type expressed as a string.
1016 std::function<TypeResult(StringRef, StringRef, SourceLocation)>
1018
1019 /// VAListTagName - The declaration name corresponding to __va_list_tag.
1020 /// This is used as part of a hack to omit that class from ADL results.
1022
1023 /// Is the last error level diagnostic immediate. This is used to determined
1024 /// whether the next info diagnostic should be immediate.
1026
1027 class DelayedDiagnostics;
1028
1030 sema::DelayedDiagnosticPool *SavedPool = nullptr;
1032 };
1035
1036 /// A class which encapsulates the logic for delaying diagnostics
1037 /// during parsing and other processing.
1039 /// The current pool of diagnostics into which delayed
1040 /// diagnostics should go.
1041 sema::DelayedDiagnosticPool *CurPool = nullptr;
1042
1043 public:
1045
1046 /// Adds a delayed diagnostic.
1047 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
1048
1049 /// Determines whether diagnostics should be delayed.
1050 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
1051
1052 /// Returns the current delayed-diagnostics pool.
1053 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
1054
1055 /// Enter a new scope. Access and deprecation diagnostics will be
1056 /// collected in this pool.
1059 state.SavedPool = CurPool;
1060 CurPool = &pool;
1061 return state;
1062 }
1063
1064 /// Leave a delayed-diagnostic state that was previously pushed.
1065 /// Do not emit any of the diagnostics. This is performed as part
1066 /// of the bookkeeping of popping a pool "properly".
1068 CurPool = state.SavedPool;
1069 }
1070
1071 /// Enter a new scope where access and deprecation diagnostics are
1072 /// not delayed.
1075 state.SavedPool = CurPool;
1076 CurPool = nullptr;
1077 return state;
1078 }
1079
1080 /// Undo a previous pushUndelayed().
1082 assert(CurPool == nullptr);
1083 CurPool = state.SavedPool;
1084 }
1085 } DelayedDiagnostics;
1086
1088 return DelayedDiagnostics.push(pool);
1089 }
1090
1091 /// Diagnostics that are emitted only if we discover that the given function
1092 /// must be codegen'ed. Because handling these correctly adds overhead to
1093 /// compilation, this is currently only enabled for CUDA compilations.
1094 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
1095
1096 /// CurContext - This is the current declaration context of parsing.
1098
1100 assert(AMDGPUPtr);
1101 return *AMDGPUPtr;
1102 }
1103
1105 assert(ARMPtr);
1106 return *ARMPtr;
1107 }
1108
1110 assert(AVRPtr);
1111 return *AVRPtr;
1112 }
1113
1115 assert(BPFPtr);
1116 return *BPFPtr;
1117 }
1118
1120 assert(CodeCompletionPtr);
1121 return *CodeCompletionPtr;
1122 }
1123
1125 assert(CUDAPtr);
1126 return *CUDAPtr;
1127 }
1128
1130 assert(HLSLPtr);
1131 return *HLSLPtr;
1132 }
1133
1135 assert(HexagonPtr);
1136 return *HexagonPtr;
1137 }
1138
1140 assert(LoongArchPtr);
1141 return *LoongArchPtr;
1142 }
1143
1145 assert(M68kPtr);
1146 return *M68kPtr;
1147 }
1148
1150 assert(MIPSPtr);
1151 return *MIPSPtr;
1152 }
1153
1155 assert(MSP430Ptr);
1156 return *MSP430Ptr;
1157 }
1158
1160 assert(NVPTXPtr);
1161 return *NVPTXPtr;
1162 }
1163
1165 assert(ObjCPtr);
1166 return *ObjCPtr;
1167 }
1168
1170 assert(OpenACCPtr);
1171 return *OpenACCPtr;
1172 }
1173
1175 assert(OpenCLPtr);
1176 return *OpenCLPtr;
1177 }
1178
1180 assert(OpenMPPtr && "SemaOpenMP is dead");
1181 return *OpenMPPtr;
1182 }
1183
1185 assert(PPCPtr);
1186 return *PPCPtr;
1187 }
1188
1190 assert(PseudoObjectPtr);
1191 return *PseudoObjectPtr;
1192 }
1193
1195 assert(RISCVPtr);
1196 return *RISCVPtr;
1197 }
1198
1200 assert(SYCLPtr);
1201 return *SYCLPtr;
1202 }
1203
1205 assert(SwiftPtr);
1206 return *SwiftPtr;
1207 }
1208
1210 assert(SystemZPtr);
1211 return *SystemZPtr;
1212 }
1213
1215 assert(WasmPtr);
1216 return *WasmPtr;
1217 }
1218
1220 assert(X86Ptr);
1221 return *X86Ptr;
1222 }
1223
1224 /// Source of additional semantic information.
1226
1227protected:
1228 friend class Parser;
1230 friend class ASTReader;
1231 friend class ASTDeclReader;
1232 friend class ASTWriter;
1233
1234private:
1235 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1236 bool WarnedDarwinSDKInfoMissing = false;
1237
1238 Sema(const Sema &) = delete;
1239 void operator=(const Sema &) = delete;
1240
1241 /// The handler for the FileChanged preprocessor events.
1242 ///
1243 /// Used for diagnostics that implement custom semantic analysis for #include
1244 /// directives, like -Wpragma-pack.
1245 sema::SemaPPCallbacks *SemaPPCallbackHandler;
1246
1247 /// The parser's current scope.
1248 ///
1249 /// The parser maintains this state here.
1250 Scope *CurScope;
1251
1252 mutable IdentifierInfo *Ident_super;
1253
1254 std::unique_ptr<SemaAMDGPU> AMDGPUPtr;
1255 std::unique_ptr<SemaARM> ARMPtr;
1256 std::unique_ptr<SemaAVR> AVRPtr;
1257 std::unique_ptr<SemaBPF> BPFPtr;
1258 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1259 std::unique_ptr<SemaCUDA> CUDAPtr;
1260 std::unique_ptr<SemaHLSL> HLSLPtr;
1261 std::unique_ptr<SemaHexagon> HexagonPtr;
1262 std::unique_ptr<SemaLoongArch> LoongArchPtr;
1263 std::unique_ptr<SemaM68k> M68kPtr;
1264 std::unique_ptr<SemaMIPS> MIPSPtr;
1265 std::unique_ptr<SemaMSP430> MSP430Ptr;
1266 std::unique_ptr<SemaNVPTX> NVPTXPtr;
1267 std::unique_ptr<SemaObjC> ObjCPtr;
1268 std::unique_ptr<SemaOpenACC> OpenACCPtr;
1269 std::unique_ptr<SemaOpenCL> OpenCLPtr;
1270 std::unique_ptr<SemaOpenMP> OpenMPPtr;
1271 std::unique_ptr<SemaPPC> PPCPtr;
1272 std::unique_ptr<SemaPseudoObject> PseudoObjectPtr;
1273 std::unique_ptr<SemaRISCV> RISCVPtr;
1274 std::unique_ptr<SemaSYCL> SYCLPtr;
1275 std::unique_ptr<SemaSwift> SwiftPtr;
1276 std::unique_ptr<SemaSystemZ> SystemZPtr;
1277 std::unique_ptr<SemaWasm> WasmPtr;
1278 std::unique_ptr<SemaX86> X86Ptr;
1279
1280 ///@}
1281
1282 //
1283 //
1284 // -------------------------------------------------------------------------
1285 //
1286 //
1287
1288 /// \name API Notes
1289 /// Implementations are in SemaAPINotes.cpp
1290 ///@{
1291
1292public:
1293 /// Map any API notes provided for this declaration to attributes on the
1294 /// declaration.
1295 ///
1296 /// Triggered by declaration-attribute processing.
1297 void ProcessAPINotes(Decl *D);
1298
1299 ///@}
1300
1301 //
1302 //
1303 // -------------------------------------------------------------------------
1304 //
1305 //
1306
1307 /// \name C++ Access Control
1308 /// Implementations are in SemaAccess.cpp
1309 ///@{
1310
1311public:
1318
1319 /// SetMemberAccessSpecifier - Set the access specifier of a member.
1320 /// Returns true on error (when the previous member decl access specifier
1321 /// is different from the new member decl access specifier).
1322 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1323 NamedDecl *PrevMemberDecl,
1324 AccessSpecifier LexicalAS);
1325
1326 /// Perform access-control checking on a previously-unresolved member
1327 /// access which has now been resolved to a member.
1329 DeclAccessPair FoundDecl);
1331 DeclAccessPair FoundDecl);
1332
1333 /// Checks access to an overloaded operator new or delete.
1335 SourceRange PlacementRange,
1336 CXXRecordDecl *NamingClass,
1337 DeclAccessPair FoundDecl,
1338 bool Diagnose = true);
1339
1340 /// Checks access to a constructor.
1342 DeclAccessPair FoundDecl,
1343 const InitializedEntity &Entity,
1344 bool IsCopyBindingRefToTemp = false);
1345
1346 /// Checks access to a constructor.
1348 DeclAccessPair FoundDecl,
1349 const InitializedEntity &Entity,
1350 const PartialDiagnostic &PDiag);
1352 CXXDestructorDecl *Dtor,
1353 const PartialDiagnostic &PDiag,
1354 QualType objectType = QualType());
1355
1356 /// Checks access to the target of a friend declaration.
1358
1359 /// Checks access to a member.
1361 CXXRecordDecl *NamingClass,
1363
1364 /// Checks implicit access to a member in a structured binding.
1367 CXXRecordDecl *DecomposedClass,
1368 DeclAccessPair Field);
1370 const SourceRange &,
1371 DeclAccessPair FoundDecl);
1372
1373 /// Checks access to an overloaded member operator, including
1374 /// conversion operators.
1376 Expr *ArgExpr,
1377 DeclAccessPair FoundDecl);
1379 ArrayRef<Expr *> ArgExprs,
1380 DeclAccessPair FoundDecl);
1382 DeclAccessPair FoundDecl);
1383
1384 /// Checks access for a hierarchy conversion.
1385 ///
1386 /// \param ForceCheck true if this check should be performed even if access
1387 /// control is disabled; some things rely on this for semantics
1388 /// \param ForceUnprivileged true if this check should proceed as if the
1389 /// context had no special privileges
1391 QualType Derived, const CXXBasePath &Path,
1392 unsigned DiagID, bool ForceCheck = false,
1393 bool ForceUnprivileged = false);
1394
1395 /// Checks access to all the declarations in the given result set.
1396 void CheckLookupAccess(const LookupResult &R);
1397
1398 /// Checks access to Target from the given class. The check will take access
1399 /// specifiers into account, but no member access expressions and such.
1400 ///
1401 /// \param Target the declaration to check if it can be accessed
1402 /// \param NamingClass the class in which the lookup was started.
1403 /// \param BaseType type of the left side of member access expression.
1404 /// \p BaseType and \p NamingClass are used for C++ access control.
1405 /// Depending on the lookup case, they should be set to the following:
1406 /// - lhs.target (member access without a qualifier):
1407 /// \p BaseType and \p NamingClass are both the type of 'lhs'.
1408 /// - lhs.X::target (member access with a qualifier):
1409 /// BaseType is the type of 'lhs', NamingClass is 'X'
1410 /// - X::target (qualified lookup without member access):
1411 /// BaseType is null, NamingClass is 'X'.
1412 /// - target (unqualified lookup).
1413 /// BaseType is null, NamingClass is the parent class of 'target'.
1414 /// \return true if the Target is accessible from the Class, false otherwise.
1415 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1416 QualType BaseType);
1417
1418 /// Is the given member accessible for the purposes of deciding whether to
1419 /// define a special member function as deleted?
1421 DeclAccessPair Found, QualType ObjectType,
1423 const PartialDiagnostic &Diag);
1426 QualType ObjectType) {
1427 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1428 SourceLocation(), PDiag());
1429 }
1430
1432 const DependentDiagnostic &DD,
1433 const MultiLevelTemplateArgumentList &TemplateArgs);
1435
1436 ///@}
1437
1438 //
1439 //
1440 // -------------------------------------------------------------------------
1441 //
1442 //
1443
1444 /// \name Attributes
1445 /// Implementations are in SemaAttr.cpp
1446 ///@{
1447
1448public:
1449 /// Controls member pointer representation format under the MS ABI.
1452
1453 bool MSStructPragmaOn; // True when \#pragma ms_struct on
1454
1455 /// Source location for newly created implicit MSInheritanceAttrs
1457
1458 /// pragma clang section kind
1465 PCSK_Relro = 5
1467
1469
1471 std::string SectionName;
1472 bool Valid = false;
1474 };
1475
1481
1483 PSK_Reset = 0x0, // #pragma ()
1484 PSK_Set = 0x1, // #pragma (value)
1485 PSK_Push = 0x2, // #pragma (push[, id])
1486 PSK_Pop = 0x4, // #pragma (pop[, id])
1487 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
1488 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1489 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
1490 };
1491
1494 StringRef SlotLabel;
1496 };
1497
1498 // #pragma pack and align.
1500 public:
1501 // `Native` represents default align mode, which may vary based on the
1502 // platform.
1503 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1504
1505 // #pragma pack info constructor
1506 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1507 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1508 assert(Num == PackNumber && "The pack number has been truncated.");
1509 }
1510
1511 // #pragma align info constructor
1513 : PackAttr(false), AlignMode(M),
1514 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1515
1516 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1517
1519
1520 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1521 // integer encoding for it. This should only be passed to
1522 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
1523 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
1524 std::uint32_t Encoding{};
1525 if (Info.IsXLStack())
1526 Encoding |= IsXLMask;
1527
1528 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1529
1530 if (Info.IsPackAttr())
1531 Encoding |= PackAttrMask;
1532
1533 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1534
1535 return Encoding;
1536 }
1537
1538 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1539 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1541 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1542 int PackNumber = (Encoding & PackNumMask) >> 4;
1543
1544 if (Encoding & PackAttrMask)
1545 return AlignPackInfo(M, PackNumber, IsXL);
1546
1547 return AlignPackInfo(M, IsXL);
1548 }
1549
1550 bool IsPackAttr() const { return PackAttr; }
1551
1552 bool IsAlignAttr() const { return !PackAttr; }
1553
1554 Mode getAlignMode() const { return AlignMode; }
1555
1556 unsigned getPackNumber() const { return PackNumber; }
1557
1558 bool IsPackSet() const {
1559 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1560 // attriute on a decl.
1561 return PackNumber != UninitPackVal && PackNumber != 0;
1562 }
1563
1564 bool IsXLStack() const { return XLStack; }
1565
1566 bool operator==(const AlignPackInfo &Info) const {
1567 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
1568 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
1569 Info.XLStack);
1570 }
1571
1572 bool operator!=(const AlignPackInfo &Info) const {
1573 return !(*this == Info);
1574 }
1575
1576 private:
1577 /// \brief True if this is a pragma pack attribute,
1578 /// not a pragma align attribute.
1579 bool PackAttr;
1580
1581 /// \brief The alignment mode that is in effect.
1582 Mode AlignMode;
1583
1584 /// \brief The pack number of the stack.
1585 unsigned char PackNumber;
1586
1587 /// \brief True if it is a XL #pragma align/pack stack.
1588 bool XLStack;
1589
1590 /// \brief Uninitialized pack value.
1591 static constexpr unsigned char UninitPackVal = -1;
1592
1593 // Masks to encode and decode an AlignPackInfo.
1594 static constexpr uint32_t IsXLMask{0x0000'0001};
1595 static constexpr uint32_t AlignModeMask{0x0000'0006};
1596 static constexpr uint32_t PackAttrMask{0x00000'0008};
1597 static constexpr uint32_t PackNumMask{0x0000'01F0};
1598 };
1599
1600 template <typename ValueType> struct PragmaStack {
1601 struct Slot {
1602 llvm::StringRef StackSlotLabel;
1603 ValueType Value;
1606 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
1611 };
1612
1613 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
1614 llvm::StringRef StackSlotLabel, ValueType Value) {
1615 if (Action == PSK_Reset) {
1617 CurrentPragmaLocation = PragmaLocation;
1618 return;
1619 }
1620 if (Action & PSK_Push)
1621 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
1622 PragmaLocation);
1623 else if (Action & PSK_Pop) {
1624 if (!StackSlotLabel.empty()) {
1625 // If we've got a label, try to find it and jump there.
1626 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
1627 return x.StackSlotLabel == StackSlotLabel;
1628 });
1629 // If we found the label so pop from there.
1630 if (I != Stack.rend()) {
1631 CurrentValue = I->Value;
1632 CurrentPragmaLocation = I->PragmaLocation;
1633 Stack.erase(std::prev(I.base()), Stack.end());
1634 }
1635 } else if (!Stack.empty()) {
1636 // We do not have a label, just pop the last entry.
1637 CurrentValue = Stack.back().Value;
1638 CurrentPragmaLocation = Stack.back().PragmaLocation;
1639 Stack.pop_back();
1640 }
1641 }
1642 if (Action & PSK_Set) {
1644 CurrentPragmaLocation = PragmaLocation;
1645 }
1646 }
1647
1648 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
1649 // method body to restore the stacks on exit, so it works like this:
1650 //
1651 // struct S {
1652 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
1653 // void Method {}
1654 // #pragma <name>(pop, InternalPragmaSlot)
1655 // };
1656 //
1657 // It works even with #pragma vtordisp, although MSVC doesn't support
1658 // #pragma vtordisp(push [, id], n)
1659 // syntax.
1660 //
1661 // Push / pop a named sentinel slot.
1662 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
1663 assert((Action == PSK_Push || Action == PSK_Pop) &&
1664 "Can only push / pop #pragma stack sentinels!");
1666 }
1667
1668 // Constructors.
1669 explicit PragmaStack(const ValueType &Default)
1671
1672 bool hasValue() const { return CurrentValue != DefaultValue; }
1673
1675 ValueType DefaultValue; // Value used for PSK_Reset action.
1676 ValueType CurrentValue;
1678 };
1679 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
1680 // we shouldn't do so if they're in a module).
1681
1682 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
1683 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
1684 ///
1685 /// 0: Suppress all vtordisps
1686 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
1687 /// structors
1688 /// 2: Always insert vtordisps to support RTTI on partially constructed
1689 /// objects
1692 // The current #pragma align/pack values and locations at each #include.
1697 };
1699 // Segment #pragmas.
1704
1705 // #pragma strict_gs_check.
1707
1708 // This stack tracks the current state of Sema.CurFPFeatures.
1711 FPOptionsOverride result;
1712 if (!FpPragmaStack.hasValue()) {
1713 result = FPOptionsOverride();
1714 } else {
1715 result = FpPragmaStack.CurrentValue;
1716 }
1717 return result;
1718 }
1719
1725 };
1726
1727 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
1728 // Actions should be performed only if we enter / exit a C++ method body.
1730 public:
1731 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
1733
1734 private:
1735 Sema &S;
1736 StringRef SlotLabel;
1737 bool ShouldAct;
1738 };
1739
1740 /// Last section used with #pragma init_seg.
1743
1744 /// Sections used with #pragma alloc_text.
1745 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
1746
1747 /// VisContext - Manages the stack for \#pragma GCC visibility.
1748 void *VisContext; // Really a "PragmaVisStack*"
1749
1750 /// This an attribute introduced by \#pragma clang attribute.
1756 };
1757
1758 /// A push'd group of PragmaAttributeEntries.
1760 /// The location of the push attribute.
1762 /// The namespace of this push group.
1765 };
1766
1768
1769 /// The declaration that is currently receiving an attribute from the
1770 /// #pragma attribute stack.
1772
1773 /// This represents the last location of a "#pragma clang optimize off"
1774 /// directive if such a directive has not been closed by an "on" yet. If
1775 /// optimizations are currently "on", this is set to an invalid location.
1777
1778 /// Get the location for the currently active "\#pragma clang optimize
1779 /// off". If this location is invalid, then the state of the pragma is "on".
1782 }
1783
1784 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
1785 /// whether the optimizations in the list passed to the pragma should be
1786 /// turned off or on. This boolean is true by default because command line
1787 /// options are honored when `#pragma optimize("", on)`.
1788 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
1790
1791 /// Set of no-builtin functions listed by \#pragma function.
1793
1794 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
1795 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
1797
1798 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
1800
1801 /// Add gsl::Pointer attribute to std::container::iterator
1802 /// \param ND The declaration that introduces the name
1803 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
1804 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
1805
1806 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
1808
1809 /// Add [[gsl::Pointer]] attributes for std:: types.
1811
1812 /// Add _Nullable attributes for std:: types.
1814
1816 POAK_Native, // #pragma options align=native
1817 POAK_Natural, // #pragma options align=natural
1818 POAK_Packed, // #pragma options align=packed
1819 POAK_Power, // #pragma options align=power
1820 POAK_Mac68k, // #pragma options align=mac68k
1821 POAK_Reset // #pragma options align=reset
1823
1824 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
1827 PragmaClangSectionKind SecKind,
1828 StringRef SecName);
1829
1830 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
1832 SourceLocation PragmaLoc);
1833
1834 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
1835 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
1836 StringRef SlotLabel, Expr *Alignment);
1837
1838 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
1839 /// (unless they are value dependent or type dependent). Returns false
1840 /// and emits a diagnostic if one or more of the arguments could not be
1841 /// folded into a constant.
1844
1848 };
1849
1851 SourceLocation IncludeLoc);
1853
1854 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
1856
1857 /// ActOnPragmaMSComment - Called on well formed
1858 /// \#pragma comment(kind, "arg").
1860 StringRef Arg);
1861
1862 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
1863 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
1864 StringRef Value);
1865
1866 /// Are precise floating point semantics currently enabled?
1868 return !CurFPFeatures.getAllowFPReassociate() &&
1869 !CurFPFeatures.getNoSignedZero() &&
1870 !CurFPFeatures.getAllowReciprocal() &&
1871 !CurFPFeatures.getAllowApproxFunc();
1872 }
1873
1876
1877 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
1880
1881 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
1882 /// pointers_to_members(representation method[, general purpose
1883 /// representation]).
1886 SourceLocation PragmaLoc);
1887
1888 /// Called on well formed \#pragma vtordisp().
1891
1892 bool UnifySection(StringRef SectionName, int SectionFlags,
1893 NamedDecl *TheDecl);
1894 bool UnifySection(StringRef SectionName, int SectionFlags,
1895 SourceLocation PragmaSectionLocation);
1896
1897 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
1898 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
1899 PragmaMsStackAction Action,
1900 llvm::StringRef StackSlotLabel,
1901 StringLiteral *SegmentName, llvm::StringRef PragmaName);
1902
1903 /// Called on well formed \#pragma section().
1904 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
1905 StringLiteral *SegmentName);
1906
1907 /// Called on well-formed \#pragma init_seg().
1908 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
1909 StringLiteral *SegmentName);
1910
1911 /// Called on well-formed \#pragma alloc_text().
1913 SourceLocation PragmaLocation, StringRef Section,
1914 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
1915 &Functions);
1916
1917 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
1918 /// strict_gs_check.
1920 PragmaMsStackAction Action,
1921 bool Value);
1922
1923 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
1924 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
1925 SourceLocation PragmaLoc);
1926
1928 SourceLocation PragmaLoc,
1931 const IdentifierInfo *Namespace);
1932
1933 /// Called on well-formed '\#pragma clang attribute pop'.
1935 const IdentifierInfo *Namespace);
1936
1937 /// Adds the attributes that have been specified using the
1938 /// '\#pragma clang attribute push' directives to the given declaration.
1939 void AddPragmaAttributes(Scope *S, Decl *D);
1940
1942
1944
1945 /// Called on well formed \#pragma clang optimize.
1946 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
1947
1948 /// #pragma optimize("[optimization-list]", on | off).
1949 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
1950
1951 /// Call on well formed \#pragma function.
1952 void
1954 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
1955
1956 /// Only called on function definitions; if there is a pragma in scope
1957 /// with the effect of a range-based optnone, consider marking the function
1958 /// with attribute optnone.
1960
1961 /// Only called on function definitions; if there is a `#pragma alloc_text`
1962 /// that decides which code section the function should be in, add
1963 /// attribute section to the function.
1965
1966 /// Adds the 'optnone' attribute to the function declaration if there
1967 /// are no conflicts; Loc represents the location causing the 'optnone'
1968 /// attribute to be added (usually because of a pragma).
1970
1971 /// Only called on function definitions; if there is a MSVC #pragma optimize
1972 /// in scope, consider changing the function's attributes based on the
1973 /// optimization list passed to the pragma.
1975
1976 /// Only called on function definitions; if there is a pragma in scope
1977 /// with the effect of a range-based no_builtin, consider marking the function
1978 /// with attribute no_builtin.
1980
1981 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
1982 /// add an appropriate visibility attribute.
1984
1985 /// FreeVisContext - Deallocate and null out VisContext.
1986 void FreeVisContext();
1987
1988 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
1989 void ActOnPragmaVisibility(const IdentifierInfo *VisType,
1990 SourceLocation PragmaLoc);
1991
1992 /// ActOnPragmaFPContract - Called on well formed
1993 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
1994 /// \#pragma clang fp contract
1996
1997 /// Called on well formed
1998 /// \#pragma clang fp reassociate
1999 /// or
2000 /// \#pragma clang fp reciprocal
2002 bool IsEnabled);
2003
2004 /// ActOnPragmaFenvAccess - Called on well formed
2005 /// \#pragma STDC FENV_ACCESS
2006 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
2007
2008 /// ActOnPragmaCXLimitedRange - Called on well formed
2009 /// \#pragma STDC CX_LIMITED_RANGE
2012
2013 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
2016
2017 /// Called to set constant rounding mode for floating point operations.
2018 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
2019
2020 /// Called to set exception behavior for floating point operations.
2022
2023 /// PushNamespaceVisibilityAttr - Note that we've entered a
2024 /// namespace with a visibility attribute.
2025 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
2027
2028 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
2029 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
2030 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
2031
2032 /// Handles semantic checking for features that are common to all attributes,
2033 /// such as checking whether a parameter was properly specified, or the
2034 /// correct number of arguments were passed, etc. Returns true if the
2035 /// attribute has been diagnosed.
2036 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
2037 bool SkipArgCountCheck = false);
2038 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
2039 bool SkipArgCountCheck = false);
2040
2041 ///@}
2042
2043 //
2044 //
2045 // -------------------------------------------------------------------------
2046 //
2047 //
2048
2049 /// \name Availability Attribute Handling
2050 /// Implementations are in SemaAvailability.cpp
2051 ///@{
2052
2053public:
2054 /// Issue any -Wunguarded-availability warnings in \c FD
2056
2058
2059 /// Retrieve the current function, if any, that should be analyzed for
2060 /// potential availability violations.
2062
2064 const ObjCInterfaceDecl *UnknownObjCClass,
2065 bool ObjCPropertyAccess,
2066 bool AvoidPartialAvailabilityChecks = false,
2067 ObjCInterfaceDecl *ClassReceiver = nullptr);
2068
2069 ///@}
2070
2071 //
2072 //
2073 // -------------------------------------------------------------------------
2074 //
2075 //
2076
2077 /// \name Bounds Safety
2078 /// Implementations are in SemaBoundsSafety.cpp
2079 ///@{
2080public:
2081 /// Check if applying the specified attribute variant from the "counted by"
2082 /// family of attributes to FieldDecl \p FD is semantically valid. If
2083 /// semantically invalid diagnostics will be emitted explaining the problems.
2084 ///
2085 /// \param FD The FieldDecl to apply the attribute to
2086 /// \param E The count expression on the attribute
2087 /// \param CountInBytes If true the attribute is from the "sized_by" family of
2088 /// attributes. If the false the attribute is from
2089 /// "counted_by" family of attributes.
2090 /// \param OrNull If true the attribute is from the "_or_null" suffixed family
2091 /// of attributes. If false the attribute does not have the
2092 /// suffix.
2093 ///
2094 /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g.
2095 /// \p CountInBytes and \p OrNull both being true indicates the
2096 /// `counted_by_or_null` attribute.
2097 ///
2098 /// \returns false iff semantically valid.
2099 bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
2100 bool OrNull);
2101
2102 ///@}
2103
2104 //
2105 //
2106 // -------------------------------------------------------------------------
2107 //
2108 //
2109
2110 /// \name Casts
2111 /// Implementations are in SemaCast.cpp
2112 ///@{
2113
2114public:
2116 return CCK == CheckedConversionKind::CStyleCast ||
2119 }
2120
2121 /// ActOnCXXNamedCast - Parse
2122 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
2124 SourceLocation LAngleBracketLoc, Declarator &D,
2125 SourceLocation RAngleBracketLoc,
2126 SourceLocation LParenLoc, Expr *E,
2127 SourceLocation RParenLoc);
2128
2130 TypeSourceInfo *Ty, Expr *E,
2131 SourceRange AngleBrackets, SourceRange Parens);
2132
2134 ExprResult Operand,
2135 SourceLocation RParenLoc);
2136
2138 Expr *Operand, SourceLocation RParenLoc);
2139
2140 // Checks that reinterpret casts don't have undefined behavior.
2141 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2142 bool IsDereference, SourceRange Range);
2143
2144 // Checks that the vector type should be initialized from a scalar
2145 // by splatting the value rather than populating a single element.
2146 // This is the case for AltiVecVector types as well as with
2147 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
2148 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
2149
2150 // Checks if the -faltivec-src-compat=gcc option is specified.
2151 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
2152 // treated the same way as they are when trying to initialize
2153 // these vectors on gcc (an error is emitted).
2155 QualType SrcTy);
2156
2158 SourceLocation RParenLoc, Expr *Op);
2159
2161 SourceLocation LParenLoc,
2162 Expr *CastExpr,
2163 SourceLocation RParenLoc);
2164
2165 ///@}
2166
2167 //
2168 //
2169 // -------------------------------------------------------------------------
2170 //
2171 //
2172
2173 /// \name Extra Semantic Checking
2174 /// Implementations are in SemaChecking.cpp
2175 ///@{
2176
2177public:
2178 /// Used to change context to isConstantEvaluated without pushing a heavy
2179 /// ExpressionEvaluationContextRecord object.
2181
2185 }
2186
2188 unsigned ByteNo) const;
2189
2191 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
2192 FAPK_Variadic, // values to format are passed as variadic arguments
2193 FAPK_VAList, // values to format are passed in a va_list
2194 };
2195
2196 // Used to grab the relevant information from a FormatAttr and a
2197 // FunctionDeclaration.
2199 unsigned FormatIdx;
2202 };
2203
2204 /// Given a FunctionDecl's FormatAttr, attempts to populate the
2205 /// FomatStringInfo parameter with the FormatAttr's correct format_idx and
2206 /// firstDataArg. Returns true when the format fits the function and the
2207 /// FormatStringInfo has been populated.
2208 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2209 bool IsVariadic, FormatStringInfo *FSI);
2210
2211 // Used by C++ template instantiation.
2213
2214 /// ConvertVectorExpr - Handle __builtin_convertvector
2216 SourceLocation BuiltinLoc,
2217 SourceLocation RParenLoc);
2218
2232 static FormatStringType GetFormatStringType(const FormatAttr *Format);
2233
2234 bool FormatStringHasSArg(const StringLiteral *FExpr);
2235
2236 /// Check for comparisons of floating-point values using == and !=. Issue a
2237 /// warning if the comparison is not likely to do what the programmer
2238 /// intended.
2240 BinaryOperatorKind Opcode);
2241
2242 /// Register a magic integral constant to be used as a type tag.
2243 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
2244 uint64_t MagicValue, QualType Type,
2245 bool LayoutCompatible, bool MustBeNull);
2246
2249
2253
2255
2256 /// If true, \c Type should be compared with other expression's types for
2257 /// layout-compatibility.
2258 LLVM_PREFERRED_TYPE(bool)
2260 LLVM_PREFERRED_TYPE(bool)
2261 unsigned MustBeNull : 1;
2262 };
2263
2264 /// A pair of ArgumentKind identifier and magic value. This uniquely
2265 /// identifies the magic value.
2266 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
2267
2268 /// Diagnoses the current set of gathered accesses. This typically
2269 /// happens at full expression level. The set is cleared after emitting the
2270 /// diagnostics.
2272
2273 /// This function checks if the expression is in the sef of potentially
2274 /// misaligned members and it is converted to some pointer type T with lower
2275 /// or equal alignment requirements. If so it removes it. This is used when
2276 /// we do not want to diagnose such misaligned access (e.g. in conversions to
2277 /// void*).
2279
2280 /// This function calls Action when it determines that E designates a
2281 /// misaligned member due to the packed attribute. This is used to emit
2282 /// local diagnostics like in reference binding.
2284 Expr *E,
2285 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
2286 Action);
2287
2288 enum class AtomicArgumentOrder { API, AST };
2290 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
2291 SourceLocation RParenLoc, MultiExprArg Args,
2294
2295 /// Check to see if a given expression could have '.c_str()' called on it.
2296 bool hasCStrMethod(const Expr *E);
2297
2298 /// Diagnose pointers that are always non-null.
2299 /// \param E the expression containing the pointer
2300 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
2301 /// compared to a null pointer
2302 /// \param IsEqual True when the comparison is equal to a null pointer
2303 /// \param Range Extra SourceRange to highlight in the diagnostic
2306 bool IsEqual, SourceRange Range);
2307
2308 /// CheckParmsForFunctionDef - Check that the parameters of the given
2309 /// function are appropriate for the definition of a function. This
2310 /// takes care of any checks that cannot be performed on the
2311 /// declaration itself, e.g., that the types of each of the function
2312 /// parameters are complete.
2314 bool CheckParameterNames);
2315
2316 /// CheckCastAlign - Implements -Wcast-align, which warns when a
2317 /// pointer cast increases the alignment requirements.
2318 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2319
2320 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
2321 /// to weak/__unsafe_unretained type.
2323
2324 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
2325 /// to weak/__unsafe_unretained expression.
2327
2328 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2329 /// statement as a \p Body, and it is located on the same line.
2330 ///
2331 /// This helps prevent bugs due to typos, such as:
2332 /// if (condition);
2333 /// do_stuff();
2334 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
2335 unsigned DiagID);
2336
2337 /// Warn if a for/while loop statement \p S, which is followed by
2338 /// \p PossibleBody, has a suspicious null statement as a body.
2339 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
2340
2341 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
2342 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2343 SourceLocation OpLoc);
2344
2345 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
2353
2354 bool IsLayoutCompatible(QualType T1, QualType T2) const;
2356 const TypeSourceInfo *Derived);
2357
2358 /// CheckFunctionCall - Check a direct function call for various correctness
2359 /// and safety properties not strictly enforced by the C type system.
2360 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2361 const FunctionProtoType *Proto);
2362
2363 bool BuiltinVectorMath(CallExpr *TheCall, QualType &Res);
2364 bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2365
2366 /// Handles the checks for format strings, non-POD arguments to vararg
2367 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
2368 /// attributes and AArch64 SME attributes.
2369 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2370 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2371 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2372 VariadicCallType CallType);
2373
2374 /// \brief Enforce the bounds of a TCB
2375 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
2376 /// directly calls other functions in the same TCB as marked by the
2377 /// enforce_tcb and enforce_tcb_leaf attributes.
2378 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2379 const NamedDecl *Callee);
2380
2381 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2382
2383 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2384 /// TheCall is a constant expression.
2385 bool BuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result);
2386
2387 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2388 /// TheCall is a constant expression in the range [Low, High].
2389 bool BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High,
2390 bool RangeIsError = true);
2391
2392 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
2393 /// TheCall is a constant expression is a multiple of Num..
2394 bool BuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
2395 unsigned Multiple);
2396
2397 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
2398 /// constant expression representing a power of 2.
2399 bool BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
2400
2401 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
2402 /// a constant expression representing an arbitrary byte value shifted left by
2403 /// a multiple of 8 bits.
2404 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
2405 unsigned ArgBits);
2406
2407 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
2408 /// TheCall is a constant expression representing either a shifted byte value,
2409 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
2410 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
2411 /// Arm MVE intrinsics.
2412 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
2413 unsigned ArgBits);
2414
2415 /// Checks that a call expression's argument count is at least the desired
2416 /// number. This is useful when doing custom type-checking on a variadic
2417 /// function. Returns true on error.
2418 bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount);
2419
2420 /// Checks that a call expression's argument count is at most the desired
2421 /// number. This is useful when doing custom type-checking on a variadic
2422 /// function. Returns true on error.
2423 bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount);
2424
2425 /// Checks that a call expression's argument count is in the desired range.
2426 /// This is useful when doing custom type-checking on a variadic function.
2427 /// Returns true on error.
2428 bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
2429 unsigned MaxArgCount);
2430
2431 /// Checks that a call expression's argument count is the desired number.
2432 /// This is useful when doing custom type-checking. Returns true on error.
2433 bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount);
2434
2435 /// Returns true if the argument consists of one contiguous run of 1s with any
2436 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
2437 /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
2438 /// since all 1s are not contiguous.
2439 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
2440
2442 bool *ICContext = nullptr,
2443 bool IsListInit = false);
2444
2446 bool CheckForFloatArgs = true);
2448
2449private:
2450 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
2451 const ArraySubscriptExpr *ASE = nullptr,
2452 bool AllowOnePastEnd = true, bool IndexNegated = false);
2453 void CheckArrayAccess(const Expr *E);
2454
2455 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2456 const FunctionProtoType *Proto);
2457
2458 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2459 /// such as function pointers returned from functions.
2460 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
2461
2462 /// CheckConstructorCall - Check a constructor call for correctness and safety
2463 /// properties not enforced by the C type system.
2464 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
2466 const FunctionProtoType *Proto, SourceLocation Loc);
2467
2468 /// Warn if a pointer or reference argument passed to a function points to an
2469 /// object that is less aligned than the parameter. This can happen when
2470 /// creating a typedef with a lower alignment than the original type and then
2471 /// calling functions defined in terms of the original type.
2472 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
2473 StringRef ParamName, QualType ArgTy, QualType ParamTy);
2474
2475 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
2476
2477 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2478 CallExpr *TheCall);
2479
2480 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2481 CallExpr *TheCall);
2482
2483 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
2484
2485 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2486 /// for validity. Emit an error and return true on failure; return false
2487 /// on success.
2488 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
2489 bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
2490
2491 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2492 /// friends. This is declared to take (...), so we have to check everything.
2493 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
2494
2495 /// BuiltinSemaBuiltinFPClassification - Handle functions like
2496 /// __builtin_isnan and friends. This is declared to take (...), so we have
2497 /// to check everything.
2498 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
2499 unsigned BuiltinID);
2500
2501 /// Perform semantic analysis for a call to __builtin_complex.
2502 bool BuiltinComplex(CallExpr *TheCall);
2503 bool BuiltinOSLogFormat(CallExpr *TheCall);
2504
2505 /// BuiltinPrefetch - Handle __builtin_prefetch.
2506 /// This is declared to take (const void*, ...) and can take two
2507 /// optional constant int args.
2508 bool BuiltinPrefetch(CallExpr *TheCall);
2509
2510 /// Handle __builtin_alloca_with_align. This is declared
2511 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
2512 /// than 8.
2513 bool BuiltinAllocaWithAlign(CallExpr *TheCall);
2514
2515 /// BuiltinArithmeticFence - Handle __arithmetic_fence.
2516 bool BuiltinArithmeticFence(CallExpr *TheCall);
2517
2518 /// BuiltinAssume - Handle __assume (MS Extension).
2519 /// __assume does not evaluate its arguments, and should warn if its argument
2520 /// has side effects.
2521 bool BuiltinAssume(CallExpr *TheCall);
2522
2523 /// Handle __builtin_assume_aligned. This is declared
2524 /// as (const void*, size_t, ...) and can take one optional constant int arg.
2525 bool BuiltinAssumeAligned(CallExpr *TheCall);
2526
2527 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
2528 /// This checks that the target supports __builtin_longjmp and
2529 /// that val is a constant 1.
2530 bool BuiltinLongjmp(CallExpr *TheCall);
2531
2532 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2533 /// This checks that the target supports __builtin_setjmp.
2534 bool BuiltinSetjmp(CallExpr *TheCall);
2535
2536 /// We have a call to a function like __sync_fetch_and_add, which is an
2537 /// overloaded function based on the pointer type of its first argument.
2538 /// The main BuildCallExpr routines have already promoted the types of
2539 /// arguments because all of these calls are prototyped as void(...).
2540 ///
2541 /// This function goes through and does final semantic checking for these
2542 /// builtins, as well as generating any warnings.
2543 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
2544
2545 /// BuiltinNontemporalOverloaded - We have a call to
2546 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2547 /// overloaded function based on the pointer type of its last argument.
2548 ///
2549 /// This function goes through and does final semantic checking for these
2550 /// builtins.
2551 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
2552 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
2554
2555 bool BuiltinElementwiseMath(CallExpr *TheCall);
2556 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
2557
2558 bool BuiltinNonDeterministicValue(CallExpr *TheCall);
2559
2560 // Matrix builtin handling.
2561 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
2562 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
2563 ExprResult CallResult);
2564 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
2565 ExprResult CallResult);
2566
2567 /// CheckFormatArguments - Check calls to printf and scanf (and similar
2568 /// functions) for correct use of format strings.
2569 /// Returns true if a format string has been fully checked.
2570 bool CheckFormatArguments(const FormatAttr *Format,
2571 ArrayRef<const Expr *> Args, bool IsCXXMember,
2574 llvm::SmallBitVector &CheckedVarArgs);
2575 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
2576 FormatArgumentPassingKind FAPK, unsigned format_idx,
2577 unsigned firstDataArg, FormatStringType Type,
2579 SourceRange range,
2580 llvm::SmallBitVector &CheckedVarArgs);
2581
2582 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
2583
2584 /// Warn when using the wrong abs() function.
2585 void CheckAbsoluteValueFunction(const CallExpr *Call,
2586 const FunctionDecl *FDecl);
2587
2588 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
2589
2590 /// Check for dangerous or invalid arguments to memset().
2591 ///
2592 /// This issues warnings on known problematic, dangerous or unspecified
2593 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2594 /// function calls.
2595 ///
2596 /// \param Call The call expression to diagnose.
2597 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
2598 IdentifierInfo *FnName);
2599
2600 // Warn if the user has made the 'size' argument to strlcpy or strlcat
2601 // be the size of the source, instead of the destination.
2602 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
2603
2604 // Warn on anti-patterns as the 'size' argument to strncat.
2605 // The correct size argument should look like following:
2606 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
2607 void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName);
2608
2609 /// Alerts the user that they are attempting to free a non-malloc'd object.
2610 void CheckFreeArguments(const CallExpr *E);
2611
2612 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
2613 SourceLocation ReturnLoc, bool isObjCMethod = false,
2614 const AttrVec *Attrs = nullptr,
2615 const FunctionDecl *FD = nullptr);
2616
2617 /// Diagnoses "dangerous" implicit conversions within the given
2618 /// expression (which is a full expression). Implements -Wconversion
2619 /// and -Wsign-compare.
2620 ///
2621 /// \param CC the "context" location of the implicit conversion, i.e.
2622 /// the most location of the syntactic entity requiring the implicit
2623 /// conversion
2624 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
2625
2626 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
2627 /// Input argument E is a logical expression.
2628 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
2629
2630 /// Diagnose when expression is an integer constant expression and its
2631 /// evaluation results in integer overflow
2632 void CheckForIntOverflow(const Expr *E);
2633 void CheckUnsequencedOperations(const Expr *E);
2634
2635 /// Perform semantic checks on a completed expression. This will either
2636 /// be a full-expression or a default argument expression.
2637 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
2638 bool IsConstexpr = false);
2639
2640 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
2641 Expr *Init);
2642
2643 /// A map from magic value to type information.
2644 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
2645 TypeTagForDatatypeMagicValues;
2646
2647 /// Peform checks on a call of a function with argument_with_type_tag
2648 /// or pointer_with_type_tag attributes.
2649 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
2650 const ArrayRef<const Expr *> ExprArgs,
2651 SourceLocation CallSiteLoc);
2652
2653 /// Check if we are taking the address of a packed field
2654 /// as this may be a problem if the pointer value is dereferenced.
2655 void CheckAddressOfPackedMember(Expr *rhs);
2656
2657 /// Helper class that collects misaligned member designations and
2658 /// their location info for delayed diagnostics.
2659 struct MisalignedMember {
2660 Expr *E;
2661 RecordDecl *RD;
2662 ValueDecl *MD;
2663 CharUnits Alignment;
2664
2665 MisalignedMember() : E(), RD(), MD() {}
2666 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
2667 CharUnits Alignment)
2668 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
2669 explicit MisalignedMember(Expr *E)
2670 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
2671
2672 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
2673 };
2674 /// Small set of gathered accesses to potentially misaligned members
2675 /// due to the packed attribute.
2676 SmallVector<MisalignedMember, 4> MisalignedMembers;
2677
2678 /// Adds an expression to the set of gathered misaligned members.
2679 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
2680 CharUnits Alignment);
2681 ///@}
2682
2683 //
2684 //
2685 // -------------------------------------------------------------------------
2686 //
2687 //
2688
2689 /// \name C++ Coroutines
2690 /// Implementations are in SemaCoroutine.cpp
2691 ///@{
2692
2693public:
2694 /// The C++ "std::coroutine_traits" template, which is defined in
2695 /// <coroutine_traits>
2697
2699 StringRef Keyword);
2703
2706 UnresolvedLookupExpr *Lookup);
2708 Expr *Awaiter, bool IsImplicit = false);
2710 UnresolvedLookupExpr *Lookup);
2713 bool IsImplicit = false);
2718
2719 // As a clang extension, enforces that a non-coroutine function must be marked
2720 // with [[clang::coro_wrapper]] if it returns a type marked with
2721 // [[clang::coro_return_type]].
2722 // Expects that FD is not a coroutine.
2724 /// Lookup 'coroutine_traits' in std namespace and std::experimental
2725 /// namespace. The namespace found is recorded in Namespace.
2727 SourceLocation FuncLoc);
2728 /// Check that the expression co_await promise.final_suspend() shall not be
2729 /// potentially-throwing.
2730 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
2731
2732 ///@}
2733
2734 //
2735 //
2736 // -------------------------------------------------------------------------
2737 //
2738 //
2739
2740 /// \name C++ Scope Specifiers
2741 /// Implementations are in SemaCXXScopeSpec.cpp
2742 ///@{
2743
2744public:
2745 // Marks SS invalid if it represents an incomplete type.
2747 // Complete an enum decl, maybe without a scope spec.
2749 CXXScopeSpec *SS = nullptr);
2750
2751 /// Compute the DeclContext that is associated with the given type.
2752 ///
2753 /// \param T the type for which we are attempting to find a DeclContext.
2754 ///
2755 /// \returns the declaration context represented by the type T,
2756 /// or NULL if the declaration context cannot be computed (e.g., because it is
2757 /// dependent and not the current instantiation).
2759
2760 /// Compute the DeclContext that is associated with the given
2761 /// scope specifier.
2762 ///
2763 /// \param SS the C++ scope specifier as it appears in the source
2764 ///
2765 /// \param EnteringContext when true, we will be entering the context of
2766 /// this scope specifier, so we can retrieve the declaration context of a
2767 /// class template or class template partial specialization even if it is
2768 /// not the current instantiation.
2769 ///
2770 /// \returns the declaration context represented by the scope specifier @p SS,
2771 /// or NULL if the declaration context cannot be computed (e.g., because it is
2772 /// dependent and not the current instantiation).
2774 bool EnteringContext = false);
2776
2777 /// If the given nested name specifier refers to the current
2778 /// instantiation, return the declaration that corresponds to that
2779 /// current instantiation (C++0x [temp.dep.type]p1).
2780 ///
2781 /// \param NNS a dependent nested name specifier.
2783
2784 /// The parser has parsed a global nested-name-specifier '::'.
2785 ///
2786 /// \param CCLoc The location of the '::'.
2787 ///
2788 /// \param SS The nested-name-specifier, which will be updated in-place
2789 /// to reflect the parsed nested-name-specifier.
2790 ///
2791 /// \returns true if an error occurred, false otherwise.
2793
2794 /// The parser has parsed a '__super' nested-name-specifier.
2795 ///
2796 /// \param SuperLoc The location of the '__super' keyword.
2797 ///
2798 /// \param ColonColonLoc The location of the '::'.
2799 ///
2800 /// \param SS The nested-name-specifier, which will be updated in-place
2801 /// to reflect the parsed nested-name-specifier.
2802 ///
2803 /// \returns true if an error occurred, false otherwise.
2805 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
2806
2807 /// Determines whether the given declaration is an valid acceptable
2808 /// result for name lookup of a nested-name-specifier.
2809 /// \param SD Declaration checked for nested-name-specifier.
2810 /// \param IsExtension If not null and the declaration is accepted as an
2811 /// extension, the pointed variable is assigned true.
2813 bool *CanCorrect = nullptr);
2814
2815 /// If the given nested-name-specifier begins with a bare identifier
2816 /// (e.g., Base::), perform name lookup for that identifier as a
2817 /// nested-name-specifier within the given scope, and return the result of
2818 /// that name lookup.
2820
2821 /// Keeps information about an identifier in a nested-name-spec.
2822 ///
2824 /// The type of the object, if we're parsing nested-name-specifier in
2825 /// a member access expression.
2827
2828 /// The identifier preceding the '::'.
2830
2831 /// The location of the identifier.
2833
2834 /// The location of the '::'.
2836
2837 /// Creates info object for the most typical case.
2839 SourceLocation ColonColonLoc,
2840 ParsedType ObjectType = ParsedType())
2841 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
2842 CCLoc(ColonColonLoc) {}
2843
2845 SourceLocation ColonColonLoc, QualType ObjectType)
2846 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
2847 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
2848 };
2849
2850 /// Build a new nested-name-specifier for "identifier::", as described
2851 /// by ActOnCXXNestedNameSpecifier.
2852 ///
2853 /// \param S Scope in which the nested-name-specifier occurs.
2854 /// \param IdInfo Parser information about an identifier in the
2855 /// nested-name-spec.
2856 /// \param EnteringContext If true, enter the context specified by the
2857 /// nested-name-specifier.
2858 /// \param SS Optional nested name specifier preceding the identifier.
2859 /// \param ScopeLookupResult Provides the result of name lookup within the
2860 /// scope of the nested-name-specifier that was computed at template
2861 /// definition time.
2862 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
2863 /// error recovery and what kind of recovery is performed.
2864 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
2865 /// are allowed. The bool value pointed by this parameter is set to
2866 /// 'true' if the identifier is treated as if it was followed by ':',
2867 /// not '::'.
2868 /// \param OnlyNamespace If true, only considers namespaces in lookup.
2869 ///
2870 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
2871 /// that it contains an extra parameter \p ScopeLookupResult, which provides
2872 /// the result of name lookup within the scope of the nested-name-specifier
2873 /// that was computed at template definition time.
2874 ///
2875 /// If ErrorRecoveryLookup is true, then this call is used to improve error
2876 /// recovery. This means that it should not emit diagnostics, it should
2877 /// just return true on failure. It also means it should only return a valid
2878 /// scope if it *knows* that the result is correct. It should not return in a
2879 /// dependent context, for example. Nor will it extend \p SS with the scope
2880 /// specifier.
2881 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
2882 bool EnteringContext, CXXScopeSpec &SS,
2883 NamedDecl *ScopeLookupResult,
2884 bool ErrorRecoveryLookup,
2885 bool *IsCorrectedToColon = nullptr,
2886 bool OnlyNamespace = false);
2887
2888 /// The parser has parsed a nested-name-specifier 'identifier::'.
2889 ///
2890 /// \param S The scope in which this nested-name-specifier occurs.
2891 ///
2892 /// \param IdInfo Parser information about an identifier in the
2893 /// nested-name-spec.
2894 ///
2895 /// \param EnteringContext Whether we're entering the context nominated by
2896 /// this nested-name-specifier.
2897 ///
2898 /// \param SS The nested-name-specifier, which is both an input
2899 /// parameter (the nested-name-specifier before this type) and an
2900 /// output parameter (containing the full nested-name-specifier,
2901 /// including this new type).
2902 ///
2903 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
2904 /// are allowed. The bool value pointed by this parameter is set to 'true'
2905 /// if the identifier is treated as if it was followed by ':', not '::'.
2906 ///
2907 /// \param OnlyNamespace If true, only considers namespaces in lookup.
2908 ///
2909 /// \returns true if an error occurred, false otherwise.
2910 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
2911 bool EnteringContext, CXXScopeSpec &SS,
2912 bool *IsCorrectedToColon = nullptr,
2913 bool OnlyNamespace = false);
2914
2915 /// The parser has parsed a nested-name-specifier
2916 /// 'template[opt] template-name < template-args >::'.
2917 ///
2918 /// \param S The scope in which this nested-name-specifier occurs.
2919 ///
2920 /// \param SS The nested-name-specifier, which is both an input
2921 /// parameter (the nested-name-specifier before this type) and an
2922 /// output parameter (containing the full nested-name-specifier,
2923 /// including this new type).
2924 ///
2925 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
2926 /// \param TemplateName the template name.
2927 /// \param TemplateNameLoc The location of the template name.
2928 /// \param LAngleLoc The location of the opening angle bracket ('<').
2929 /// \param TemplateArgs The template arguments.
2930 /// \param RAngleLoc The location of the closing angle bracket ('>').
2931 /// \param CCLoc The location of the '::'.
2932 ///
2933 /// \param EnteringContext Whether we're entering the context of the
2934 /// nested-name-specifier.
2935 ///
2936 ///
2937 /// \returns true if an error occurred, false otherwise.
2939 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2940 TemplateTy TemplateName, SourceLocation TemplateNameLoc,
2941 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
2942 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
2943
2945 SourceLocation ColonColonLoc);
2946
2948 const DeclSpec &DS,
2949 SourceLocation ColonColonLoc,
2950 QualType Type);
2951
2952 /// IsInvalidUnlessNestedName - This method is used for error recovery
2953 /// purposes to determine whether the specified identifier is only valid as
2954 /// a nested name specifier, for example a namespace name. It is
2955 /// conservatively correct to always return false from this method.
2956 ///
2957 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
2959 NestedNameSpecInfo &IdInfo,
2960 bool EnteringContext);
2961
2962 /// Given a C++ nested-name-specifier, produce an annotation value
2963 /// that the parser can use later to reconstruct the given
2964 /// nested-name-specifier.
2965 ///
2966 /// \param SS A nested-name-specifier.
2967 ///
2968 /// \returns A pointer containing all of the information in the
2969 /// nested-name-specifier \p SS.
2971
2972 /// Given an annotation pointer for a nested-name-specifier, restore
2973 /// the nested-name-specifier structure.
2974 ///
2975 /// \param Annotation The annotation pointer, produced by
2976 /// \c SaveNestedNameSpecifierAnnotation().
2977 ///
2978 /// \param AnnotationRange The source range corresponding to the annotation.
2979 ///
2980 /// \param SS The nested-name-specifier that will be updated with the contents
2981 /// of the annotation pointer.
2982 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
2983 SourceRange AnnotationRange,
2984 CXXScopeSpec &SS);
2985
2986 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
2987
2988 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
2989 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
2990 /// After this method is called, according to [C++ 3.4.3p3], names should be
2991 /// looked up in the declarator-id's scope, until the declarator is parsed and
2992 /// ActOnCXXExitDeclaratorScope is called.
2993 /// The 'SS' should be a non-empty valid CXXScopeSpec.
2995
2996 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
2997 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
2998 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
2999 /// Used to indicate that names should revert to being looked up in the
3000 /// defining scope.
3002
3003 ///@}
3004
3005 //
3006 //
3007 // -------------------------------------------------------------------------
3008 //
3009 //
3010
3011 /// \name Declarations
3012 /// Implementations are in SemaDecl.cpp
3013 ///@{
3014
3015public:
3017
3018 /// The index of the first InventedParameterInfo that refers to the current
3019 /// context.
3021
3022 /// A RAII object to temporarily push a declaration context.
3024 private:
3025 Sema &S;
3026 DeclContext *SavedContext;
3027 ProcessingContextState SavedContextState;
3028 QualType SavedCXXThisTypeOverride;
3029 unsigned SavedFunctionScopesStart;
3030 unsigned SavedInventedParameterInfosStart;
3031
3032 public:
3033 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
3034 : S(S), SavedContext(S.CurContext),
3035 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
3036 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
3037 SavedFunctionScopesStart(S.FunctionScopesStart),
3038 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
3039 assert(ContextToPush && "pushing null context");
3040 S.CurContext = ContextToPush;
3041 if (NewThisContext)
3042 S.CXXThisTypeOverride = QualType();
3043 // Any saved FunctionScopes do not refer to this context.
3044 S.FunctionScopesStart = S.FunctionScopes.size();
3045 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
3046 }
3047
3048 void pop() {
3049 if (!SavedContext)
3050 return;
3051 S.CurContext = SavedContext;
3052 S.DelayedDiagnostics.popUndelayed(SavedContextState);
3053 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
3054 S.FunctionScopesStart = SavedFunctionScopesStart;
3055 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
3056 SavedContext = nullptr;
3057 }
3058
3059 ~ContextRAII() { pop(); }
3060 };
3061
3062 void DiagnoseInvalidJumps(Stmt *Body);
3063
3064 /// The function definitions which were renamed as part of typo-correction
3065 /// to match their respective declarations. We want to keep track of them
3066 /// to ensure that we don't emit a "redefinition" error if we encounter a
3067 /// correctly named definition after the renamed definition.
3069
3070 /// A cache of the flags available in enumerations with the flag_bits
3071 /// attribute.
3072 mutable llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
3073
3074 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
3075 /// declared. Rare. May alias another identifier, declared or undeclared.
3076 ///
3077 /// For aliases, the target identifier is used as a key for eventual
3078 /// processing when the target is declared. For the single-identifier form,
3079 /// the sole identifier is used as the key. Each entry is a `SetVector`
3080 /// (ordered by parse order) of aliases (identified by the alias name) in case
3081 /// of multiple aliases to the same undeclared identifier.
3082 llvm::MapVector<
3084 llvm::SetVector<
3086 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
3088
3089 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
3090 /// \#pragma redefine_extname before declared. Used in Solaris system headers
3091 /// to define functions that occur in multiple standards to call the version
3092 /// in the currently selected standard.
3093 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *> ExtnameUndeclaredIdentifiers;
3094
3095 /// Set containing all typedefs that are likely unused.
3098
3102
3103 /// The set of file scoped decls seen so far that have not been used
3104 /// and must warn if not used. Only contains the first declaration.
3106
3110
3111 /// All the tentative definitions encountered in the TU.
3113
3114 /// All the external declarations encoutered and used in the TU.
3116
3117 /// Generally null except when we temporarily switch decl contexts,
3118 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
3120
3121 /// Is the module scope we are in a C++ Header Unit?
3123 return ModuleScopes.empty() ? false
3124 : ModuleScopes.back().Module->isHeaderUnit();
3125 }
3126
3127 /// Get the module owning an entity.
3128 Module *getOwningModule(const Decl *Entity) {
3129 return Entity->getOwningModule();
3130 }
3131
3132 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
3133
3134 /// If the identifier refers to a type name within this scope,
3135 /// return the declaration of that type.
3136 ///
3137 /// This routine performs ordinary name lookup of the identifier II
3138 /// within the given scope, with optional C++ scope specifier SS, to
3139 /// determine whether the name refers to a type. If so, returns an
3140 /// opaque pointer (actually a QualType) corresponding to that
3141 /// type. Otherwise, returns NULL.
3143 Scope *S, CXXScopeSpec *SS = nullptr,
3144 bool isClassName = false, bool HasTrailingDot = false,
3145 ParsedType ObjectType = nullptr,
3146 bool IsCtorOrDtorName = false,
3147 bool WantNontrivialTypeSourceInfo = false,
3148 bool IsClassTemplateDeductionContext = true,
3149 ImplicitTypenameContext AllowImplicitTypename =
3151 IdentifierInfo **CorrectedII = nullptr);
3152
3153 /// isTagName() - This method is called *for error recovery purposes only*
3154 /// to determine if the specified name is a valid tag name ("struct foo"). If
3155 /// so, this returns the TST for the tag corresponding to it (TST_enum,
3156 /// TST_union, TST_struct, TST_interface, TST_class). This is used to
3157 /// diagnose cases in C where the user forgot to specify the tag.
3159
3160 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
3161 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
3162 /// then downgrade the missing typename error to a warning.
3163 /// This is needed for MSVC compatibility; Example:
3164 /// @code
3165 /// template<class T> class A {
3166 /// public:
3167 /// typedef int TYPE;
3168 /// };
3169 /// template<class T> class B : public A<T> {
3170 /// public:
3171 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
3172 /// };
3173 /// @endcode
3174 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
3176 Scope *S, CXXScopeSpec *SS,
3177 ParsedType &SuggestedType,
3178 bool IsTemplateName = false);
3179
3180 /// Attempt to behave like MSVC in situations where lookup of an unqualified
3181 /// type name has failed in a dependent context. In these situations, we
3182 /// automatically form a DependentTypeName that will retry lookup in a related
3183 /// scope during instantiation.
3185 SourceLocation NameLoc,
3186 bool IsTemplateTypeArg);
3187
3188 /// Describes the result of the name lookup and resolution performed
3189 /// by \c ClassifyName().
3191 /// This name is not a type or template in this context, but might be
3192 /// something else.
3194 /// Classification failed; an error has been produced.
3196 /// The name has been typo-corrected to a keyword.
3198 /// The name was classified as a type.
3200 /// The name was classified as a specific non-type, non-template
3201 /// declaration. ActOnNameClassifiedAsNonType should be called to
3202 /// convert the declaration to an expression.
3204 /// The name was classified as an ADL-only function name.
3205 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
3206 /// result to an expression.
3208 /// The name denotes a member of a dependent type that could not be
3209 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
3210 /// convert the result to an expression.
3212 /// The name was classified as an overload set, and an expression
3213 /// representing that overload set has been formed.
3214 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
3215 /// expression referencing the overload set.
3217 /// The name was classified as a template whose specializations are types.
3219 /// The name was classified as a variable template name.
3221 /// The name was classified as a function template name.
3223 /// The name was classified as an ADL-only function template name.
3225 /// The name was classified as a concept name.
3227 };
3228
3231 union {
3236 };
3237
3239
3240 public:
3242
3243 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
3244
3245 static NameClassification Error() { return NameClassification(NC_Error); }
3246
3248 return NameClassification(NC_Unknown);
3249 }
3250
3252 NameClassification Result(NC_OverloadSet);
3253 Result.Expr = E;
3254 return Result;
3255 }
3256
3258 NameClassification Result(NC_NonType);
3259 Result.NonTypeDecl = D;
3260 return Result;
3261 }
3262
3264 return NameClassification(NC_UndeclaredNonType);
3265 }
3266
3268 return NameClassification(NC_DependentNonType);
3269 }
3270
3272 NameClassification Result(NC_TypeTemplate);
3273 Result.Template = Name;
3274 return Result;
3275 }
3276
3278 NameClassification Result(NC_VarTemplate);
3279 Result.Template = Name;
3280 return Result;
3281 }
3282
3284 NameClassification Result(NC_FunctionTemplate);
3285 Result.Template = Name;
3286 return Result;
3287 }
3288
3290 NameClassification Result(NC_Concept);
3291 Result.Template = Name;
3292 return Result;
3293 }
3294
3296 NameClassification Result(NC_UndeclaredTemplate);
3297 Result.Template = Name;
3298 return Result;
3299 }
3300
3302
3304 assert(Kind == NC_OverloadSet);
3305 return Expr;
3306 }
3307
3309 assert(Kind == NC_Type);
3310 return Type;
3311 }
3312
3314 assert(Kind == NC_NonType);
3315 return NonTypeDecl;
3316 }
3317
3319 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
3320 Kind == NC_VarTemplate || Kind == NC_Concept ||
3321 Kind == NC_UndeclaredTemplate);
3322 return Template;
3323 }
3324
3326 switch (Kind) {
3327 case NC_TypeTemplate:
3328 return TNK_Type_template;
3329 case NC_FunctionTemplate:
3330 return TNK_Function_template;
3331 case NC_VarTemplate:
3332 return TNK_Var_template;
3333 case NC_Concept:
3334 return TNK_Concept_template;
3335 case NC_UndeclaredTemplate:
3337 default:
3338 llvm_unreachable("unsupported name classification.");
3339 }
3340 }
3341 };
3342
3343 /// Perform name lookup on the given name, classifying it based on
3344 /// the results of name lookup and the following token.
3345 ///
3346 /// This routine is used by the parser to resolve identifiers and help direct
3347 /// parsing. When the identifier cannot be found, this routine will attempt
3348 /// to correct the typo and classify based on the resulting name.
3349 ///
3350 /// \param S The scope in which we're performing name lookup.
3351 ///
3352 /// \param SS The nested-name-specifier that precedes the name.
3353 ///
3354 /// \param Name The identifier. If typo correction finds an alternative name,
3355 /// this pointer parameter will be updated accordingly.
3356 ///
3357 /// \param NameLoc The location of the identifier.
3358 ///
3359 /// \param NextToken The token following the identifier. Used to help
3360 /// disambiguate the name.
3361 ///
3362 /// \param CCC The correction callback, if typo correction is desired.
3363 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
3364 IdentifierInfo *&Name, SourceLocation NameLoc,
3365 const Token &NextToken,
3366 CorrectionCandidateCallback *CCC = nullptr);
3367
3368 /// Act on the result of classifying a name as an undeclared (ADL-only)
3369 /// non-type declaration.
3371 SourceLocation NameLoc);
3372 /// Act on the result of classifying a name as an undeclared member of a
3373 /// dependent base class.
3375 IdentifierInfo *Name,
3376 SourceLocation NameLoc,
3377 bool IsAddressOfOperand);
3378 /// Act on the result of classifying a name as a specific non-type
3379 /// declaration.
3382 SourceLocation NameLoc,
3383 const Token &NextToken);
3384 /// Act on the result of classifying a name as an overload set.
3386
3387 /// Describes the detailed kind of a template name. Used in diagnostics.
3394 Concept,
3396 };
3399
3400 /// Determine whether it's plausible that E was intended to be a
3401 /// template-name.
3403 if (!getLangOpts().CPlusPlus || E.isInvalid())
3404 return false;
3405 Dependent = false;
3406 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
3407 return !DRE->hasExplicitTemplateArgs();
3408 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
3409 return !ME->hasExplicitTemplateArgs();
3410 Dependent = true;
3411 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
3412 return !DSDRE->hasExplicitTemplateArgs();
3413 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
3414 return !DSME->hasExplicitTemplateArgs();
3415 // Any additional cases recognized here should also be handled by
3416 // diagnoseExprIntendedAsTemplateName.
3417 return false;
3418 }
3419
3421
3423
3425 MultiTemplateParamsArg TemplateParameterLists);
3426
3427 /// Attempt to fold a variable-sized type to a constant-sized type, returning
3428 /// true if we were successful.
3431 unsigned FailedFoldDiagID);
3432
3433 /// Register the given locally-scoped extern "C" declaration so
3434 /// that it can be found later for redeclarations. We include any extern "C"
3435 /// declaration that is not visible in the translation unit here, not just
3436 /// function-scope declarations.
3438
3439 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3440 /// If T is the name of a class, then each of the following shall have a
3441 /// name different from T:
3442 /// - every static data member of class T;
3443 /// - every member function of class T
3444 /// - every member of class T that is itself a type;
3445 /// \returns true if the declaration name violates these rules.
3447
3448 /// Diagnose a declaration whose declarator-id has the given
3449 /// nested-name-specifier.
3450 ///
3451 /// \param SS The nested-name-specifier of the declarator-id.
3452 ///
3453 /// \param DC The declaration context to which the nested-name-specifier
3454 /// resolves.
3455 ///
3456 /// \param Name The name of the entity being declared.
3457 ///
3458 /// \param Loc The location of the name of the entity being declared.
3459 ///
3460 /// \param IsMemberSpecialization Whether we are declaring a member
3461 /// specialization.
3462 ///
3463 /// \param TemplateId The template-id, if any.
3464 ///
3465 /// \returns true if we cannot safely recover from this error, false
3466 /// otherwise.
3469 TemplateIdAnnotation *TemplateId,
3470 bool IsMemberSpecialization);
3471
3473
3474 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
3475
3476 /// Diagnose function specifiers on a declaration of an identifier that
3477 /// does not identify a function.
3478 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
3479
3480 /// Return the declaration shadowed by the given typedef \p D, or null
3481 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3483 const LookupResult &R);
3484
3485 /// Return the declaration shadowed by the given variable \p D, or null
3486 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3488
3489 /// Return the declaration shadowed by the given variable \p D, or null
3490 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3492 const LookupResult &R);
3493 /// Diagnose variable or built-in function shadowing. Implements
3494 /// -Wshadow.
3495 ///
3496 /// This method is called whenever a VarDecl is added to a "useful"
3497 /// scope.
3498 ///
3499 /// \param ShadowedDecl the declaration that is shadowed by the given variable
3500 /// \param R the lookup of the name
3501 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
3502 const LookupResult &R);
3503
3504 /// Check -Wshadow without the advantage of a previous lookup.
3505 void CheckShadow(Scope *S, VarDecl *D);
3506
3507 /// Warn if 'E', which is an expression that is about to be modified, refers
3508 /// to a shadowing declaration.
3510
3511 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
3512 /// when these variables are captured by the lambda.
3514
3515 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
3516 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3517 TypedefNameDecl *NewTD);
3520 TypeSourceInfo *TInfo,
3522
3523 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
3524 /// declares a typedef-name, either using the 'typedef' type specifier or via
3525 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
3527 LookupResult &Previous, bool &Redeclaration);
3529 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
3530 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
3531 bool &AddToScope, ArrayRef<BindingDecl *> Bindings = std::nullopt);
3532
3533 /// Perform semantic checking on a newly-created variable
3534 /// declaration.
3535 ///
3536 /// This routine performs all of the type-checking required for a
3537 /// variable declaration once it has been built. It is used both to
3538 /// check variables after they have been parsed and their declarators
3539 /// have been translated into a declaration, and to check variables
3540 /// that have been instantiated from a template.
3541 ///
3542 /// Sets NewVD->isInvalidDecl() if an error was encountered.
3543 ///
3544 /// Returns true if the variable declaration is a redeclaration.
3548
3550 TypeSourceInfo *TInfo,
3552 MultiTemplateParamsArg TemplateParamLists,
3553 bool &AddToScope);
3554
3555 /// AddOverriddenMethods - See if a method overrides any in the base classes,
3556 /// and if so, check that it's a valid override and remember it.
3558
3559 /// Perform semantic checking of a new function declaration.
3560 ///
3561 /// Performs semantic analysis of the new function declaration
3562 /// NewFD. This routine performs all semantic checking that does not
3563 /// require the actual declarator involved in the declaration, and is
3564 /// used both for the declaration of functions as they are parsed
3565 /// (called via ActOnDeclarator) and for the declaration of functions
3566 /// that have been instantiated via C++ template instantiation (called
3567 /// via InstantiateDecl).
3568 ///
3569 /// \param IsMemberSpecialization whether this new function declaration is
3570 /// a member specialization (that replaces any definition provided by the
3571 /// previous declaration).
3572 ///
3573 /// This sets NewFD->isInvalidDecl() to true if there was an error.
3574 ///
3575 /// \returns true if the function declaration is a redeclaration.
3578 bool IsMemberSpecialization, bool DeclIsDefn);
3579
3580 /// Checks if the new declaration declared in dependent context must be
3581 /// put in the same redeclaration chain as the specified declaration.
3582 ///
3583 /// \param D Declaration that is checked.
3584 /// \param PrevDecl Previous declaration found with proper lookup method for
3585 /// the same declaration name.
3586 /// \returns True if D must be added to the redeclaration chain which PrevDecl
3587 /// belongs to.
3589
3590 /// Determines if we can perform a correct type check for \p D as a
3591 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
3592 /// best-effort check.
3593 ///
3594 /// \param NewD The new declaration.
3595 /// \param OldD The old declaration.
3596 /// \param NewT The portion of the type of the new declaration to check.
3597 /// \param OldT The portion of the type of the old declaration to check.
3599 QualType NewT, QualType OldT);
3600 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
3602
3603 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
3604 /// containing class. Otherwise it will return implicit SectionAttr if the
3605 /// function is a definition and there is an active value on CodeSegStack
3606 /// (from the current #pragma code-seg value).
3607 ///
3608 /// \param FD Function being declared.
3609 /// \param IsDefinition Whether it is a definition or just a declaration.
3610 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
3611 /// nullptr if no attribute should be added.
3613 bool IsDefinition);
3614
3615 /// Common checks for a parameter-declaration that should apply to both
3616 /// function parameters and non-type template parameters.
3618
3619 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
3620 /// to introduce parameters into function prototype scope.
3622 SourceLocation ExplicitThisLoc = {});
3623
3624 /// Synthesizes a variable for a parameter arising from a
3625 /// typedef.
3626 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
3627 QualType T);
3628 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
3629 SourceLocation NameLoc,
3630 const IdentifierInfo *Name, QualType T,
3631 TypeSourceInfo *TSInfo, StorageClass SC);
3632
3633 // Contexts where using non-trivial C union types can be disallowed. This is
3634 // passed to err_non_trivial_c_union_in_invalid_context.
3636 // Function parameter.
3638 // Function return.
3640 // Default-initialized object.
3642 // Variable with automatic storage duration.
3644 // Initializer expression that might copy from another object.
3646 // Assignment.
3648 // Compound literal.
3650 // Block capture.
3652 // lvalue-to-rvalue conversion of volatile type.
3654 };
3655
3656 /// Emit diagnostics if the initializer or any of its explicit or
3657 /// implicitly-generated subexpressions require copying or
3658 /// default-initializing a type that is or contains a C union type that is
3659 /// non-trivial to copy or default-initialize.
3661
3662 // These flags are passed to checkNonTrivialCUnion.
3667 };
3668
3669 /// Emit diagnostics if a non-trivial C union type or a struct that contains
3670 /// a non-trivial C union is used in an invalid context.
3672 NonTrivialCUnionContext UseContext,
3673 unsigned NonTrivialKind);
3674
3675 /// AddInitializerToDecl - Adds the initializer Init to the
3676 /// declaration dcl. If DirectInit is true, this is C++ direct
3677 /// initialization rather than copy initialization.
3678 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
3679 void ActOnUninitializedDecl(Decl *dcl);
3680
3681 /// ActOnInitializerError - Given that there was an error parsing an
3682 /// initializer for the given declaration, try to at least re-establish
3683 /// invariants such as whether a variable's type is either dependent or
3684 /// complete.
3685 void ActOnInitializerError(Decl *Dcl);
3686
3689 IdentifierInfo *Ident,
3690 ParsedAttributes &Attrs);
3691
3692 /// Check if VD needs to be dllexport/dllimport due to being in a
3693 /// dllexport/import function.
3696
3697 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
3698 /// any semantic actions necessary after any initializer has been attached.
3699 void FinalizeDeclaration(Decl *D);
3701 ArrayRef<Decl *> Group);
3702
3703 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
3704 /// group, performing any necessary semantic checking.
3706
3707 /// Should be called on all declarations that might have attached
3708 /// documentation comments.
3711
3712 enum class FnBodyKind {
3713 /// C++26 [dcl.fct.def.general]p1
3714 /// function-body:
3715 /// ctor-initializer[opt] compound-statement
3716 /// function-try-block
3717 Other,
3718 /// = default ;
3719 Default,
3720 /// deleted-function-body
3721 ///
3722 /// deleted-function-body:
3723 /// = delete ;
3724 /// = delete ( unevaluated-string ) ;
3725 Delete
3726 };
3727
3729 SourceLocation LocAfterDecls);
3731 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
3732 SkipBodyInfo *SkipBody = nullptr);
3734 MultiTemplateParamsArg TemplateParamLists,
3735 SkipBodyInfo *SkipBody = nullptr,
3736 FnBodyKind BodyKind = FnBodyKind::Other);
3738 SkipBodyInfo *SkipBody = nullptr,
3739 FnBodyKind BodyKind = FnBodyKind::Other);
3741
3742 /// Determine whether we can delay parsing the body of a function or
3743 /// function template until it is used, assuming we don't care about emitting
3744 /// code for that function.
3745 ///
3746 /// This will be \c false if we may need the body of the function in the
3747 /// middle of parsing an expression (where it's impractical to switch to
3748 /// parsing a different function), for instance, if it's constexpr in C++11
3749 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
3750 bool canDelayFunctionBody(const Declarator &D);
3751
3752 /// Determine whether we can skip parsing the body of a function
3753 /// definition, assuming we don't care about analyzing its body or emitting
3754 /// code for that function.
3755 ///
3756 /// This will be \c false only if we may need the body of the function in
3757 /// order to parse the rest of the program (for instance, if it is
3758 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
3759 bool canSkipFunctionBody(Decl *D);
3760
3761 /// Given the set of return statements within a function body,
3762 /// compute the variables that are subject to the named return value
3763 /// optimization.
3764 ///
3765 /// Each of the variables that is subject to the named return value
3766 /// optimization will be marked as NRVO variables in the AST, and any
3767 /// return statement that has a marked NRVO variable as its NRVO candidate can
3768 /// use the named return value optimization.
3769 ///
3770 /// This function applies a very simplistic algorithm for NRVO: if every
3771 /// return statement in the scope of a variable has the same NRVO candidate,
3772 /// that candidate is an NRVO variable.
3775 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
3778
3779 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
3780 /// attribute for which parsing is delayed.
3782
3783 /// Diagnose any unused parameters in the given sequence of
3784 /// ParmVarDecl pointers.
3786
3787 /// Diagnose whether the size of parameters or return value of a
3788 /// function or obj-c method definition is pass-by-value and larger than a
3789 /// specified threshold.
3790 void
3792 QualType ReturnTy, NamedDecl *D);
3793
3795 SourceLocation RParenLoc);
3796
3799
3801
3802 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3803 /// no declarator (e.g. "struct foo;") is parsed.
3805 const ParsedAttributesView &DeclAttrs,
3806 RecordDecl *&AnonRecord);
3807
3808 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3809 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3810 /// parameters to cope with template friend declarations.
3812 const ParsedAttributesView &DeclAttrs,
3813 MultiTemplateParamsArg TemplateParams,
3814 bool IsExplicitInstantiation,
3815 RecordDecl *&AnonRecord,
3816 SourceLocation EllipsisLoc = {});
3817
3818 /// BuildAnonymousStructOrUnion - Handle the declaration of an
3819 /// anonymous structure or union. Anonymous unions are a C++ feature
3820 /// (C++ [class.union]) and a C11 feature; anonymous structures
3821 /// are a C11 feature and GNU C++ extension.
3822 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS,
3823 RecordDecl *Record,
3824 const PrintingPolicy &Policy);
3825
3826 /// Called once it is known whether
3827 /// a tag declaration is an anonymous union or struct.
3829
3830 /// Emit diagnostic warnings for placeholder members.
3831 /// We can only do that after the class is fully constructed,
3832 /// as anonymous union/structs can insert placeholders
3833 /// in their parent scope (which might be a Record).
3835
3836 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3837 /// Microsoft C anonymous structure.
3838 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3839 /// Example:
3840 ///
3841 /// struct A { int a; };
3842 /// struct B { struct A; int b; };
3843 ///
3844 /// void foo() {
3845 /// B var;
3846 /// var.a = 3;
3847 /// }
3848 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3849 RecordDecl *Record);
3850
3851 /// Common ways to introduce type names without a tag for use in diagnostics.
3852 /// Keep in sync with err_tag_reference_non_tag.
3863 };
3864
3865 /// Given a non-tag type declaration, returns an enum useful for indicating
3866 /// what kind of non-tag type this is.
3868
3869 /// Determine whether a tag with a given kind is acceptable
3870 /// as a redeclaration of the given tag declaration.
3871 ///
3872 /// \returns true if the new tag kind is acceptable, false otherwise.
3874 bool isDefinition, SourceLocation NewTagLoc,
3875 const IdentifierInfo *Name);
3876
3878 // Not parsing a type within __builtin_offsetof.
3880 // Parsing a type within __builtin_offsetof.
3882 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
3883 // To improve our diagnostic message.
3885 };
3886
3887 /// This is invoked when we see 'struct foo' or 'struct {'. In the
3888 /// former case, Name will be non-null. In the later case, Name will be null.
3889 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is
3890 /// a reference/declaration/definition of a tag.
3891 ///
3892 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
3893 /// trailing-type-specifier) other than one in an alias-declaration.
3894 ///
3895 /// \param SkipBody If non-null, will be set to indicate if the caller should
3896 /// skip the definition of this tag and treat it as if it were a declaration.
3897 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3898 SourceLocation KWLoc, CXXScopeSpec &SS,
3899 IdentifierInfo *Name, SourceLocation NameLoc,
3901 SourceLocation ModulePrivateLoc,
3902 MultiTemplateParamsArg TemplateParameterLists,
3903 bool &OwnedDecl, bool &IsDependent,
3904 SourceLocation ScopedEnumKWLoc,
3905 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3906 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3907 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
3908
3909 /// ActOnField - Each field of a C struct/union is passed into this in order
3910 /// to create a FieldDecl object for it.
3911 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3912 Declarator &D, Expr *BitfieldWidth);
3913
3914 /// HandleField - Analyze a field of a C struct or a C++ data member.
3915 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3916 Declarator &D, Expr *BitfieldWidth,
3917 InClassInitStyle InitStyle, AccessSpecifier AS);
3918
3919 /// Build a new FieldDecl and check its well-formedness.
3920 ///
3921 /// This routine builds a new FieldDecl given the fields name, type,
3922 /// record, etc. \p PrevDecl should refer to any previous declaration
3923 /// with the same name and in the same scope as the field to be
3924 /// created.
3925 ///
3926 /// \returns a new FieldDecl.
3927 ///
3928 /// \todo The Declarator argument is a hack. It will be removed once
3931 SourceLocation Loc, bool Mutable,
3932 Expr *BitfieldWidth, InClassInitStyle InitStyle,
3934 NamedDecl *PrevDecl, Declarator *D = nullptr);
3935
3937
3938 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
3939 /// class and class extensions. For every class \@interface and class
3940 /// extension \@interface, if the last ivar is a bitfield of any type,
3941 /// then add an implicit `char :0` ivar to the end of that interface.
3942 void ActOnLastBitfield(SourceLocation DeclStart,
3943 SmallVectorImpl<Decl *> &AllIvarDecls);
3944
3945 // This is used for both record definitions and ObjC interface declarations.
3946 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3947 ArrayRef<Decl *> Fields, SourceLocation LBrac,
3948 SourceLocation RBrac, const ParsedAttributesView &AttrList);
3949
3950 /// ActOnTagStartDefinition - Invoked when we have entered the
3951 /// scope of a tag's definition (e.g., for an enumeration, class,
3952 /// struct, or union).
3954
3955 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3956 /// Differently from C++, actually parse the body and reject / error out
3957 /// in case of a structural mismatch.
3958 bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3959
3961
3962 /// Invoked when we enter a tag definition that we're skipping.
3964
3965 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3966 /// C++ record definition's base-specifiers clause and are starting its
3967 /// member declarations.
3969 SourceLocation FinalLoc,
3970 bool IsFinalSpelledSealed,
3971 bool IsAbstract,
3972 SourceLocation LBraceLoc);
3973
3974 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3975 /// the definition of a tag (enumeration, class, struct, or union).
3977 SourceRange BraceRange);
3978
3980
3981 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3982 /// error parsing the definition of a tag.
3984
3986 EnumConstantDecl *LastEnumConst,
3988 Expr *val);
3989
3990 /// Check that this is a valid underlying type for an enum declaration.
3992
3993 /// Check whether this is a valid redeclaration of a previous enumeration.
3994 /// \return true if the redeclaration was invalid.
3995 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3996 QualType EnumUnderlyingTy, bool IsFixed,
3997 const EnumDecl *Prev);
3998
3999 /// Determine whether the body of an anonymous enumeration should be skipped.
4000 /// \param II The name of the first enumerator.
4002 SourceLocation IILoc);
4003
4004 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
4006 const ParsedAttributesView &Attrs,
4007 SourceLocation EqualLoc, Expr *Val);
4008 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
4009 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
4010 const ParsedAttributesView &Attr);
4011
4012 /// Set the current declaration context until it gets popped.
4013 void PushDeclContext(Scope *S, DeclContext *DC);
4014 void PopDeclContext();
4015
4016 /// EnterDeclaratorContext - Used when we must lookup names in the context
4017 /// of a declarator's nested name specifier.
4020
4021 /// Enter a template parameter scope, after it's been associated with a
4022 /// particular DeclContext. Causes lookup within the scope to chain through
4023 /// enclosing contexts in the correct order.
4025
4026 /// Push the parameters of D, which must be a function, into scope.
4029
4030 /// Add this decl to the scope shadowed decl chains.
4031 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
4032
4033 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
4034 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
4035 /// true if 'D' belongs to the given declaration context.
4036 ///
4037 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
4038 /// enclosing namespace set of the context, rather than contained
4039 /// directly within it.
4040 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
4041 bool AllowInlineNamespace = false) const;
4042
4043 /// Finds the scope corresponding to the given decl context, if it
4044 /// happens to be an enclosing scope. Otherwise return NULL.
4046
4047 /// Subroutines of ActOnDeclarator().
4049 TypeSourceInfo *TInfo);
4050 bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New);
4051
4052 /// Describes the kind of merge to perform for availability
4053 /// attributes (including "deprecated", "unavailable", and "availability").
4055 /// Don't merge availability attributes at all.
4057 /// Merge availability attributes for a redeclaration, which requires
4058 /// an exact match.
4060 /// Merge availability attributes for an override, which requires
4061 /// an exact match or a weakening of constraints.
4063 /// Merge availability attributes for an implementation of
4064 /// a protocol requirement.
4066 /// Merge availability attributes for an implementation of
4067 /// an optional protocol requirement.
4070
4071 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
4072 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
4074
4075 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
4076 /// same name and scope as a previous declaration 'Old'. Figure out
4077 /// how to resolve this situation, merging decls or emitting
4078 /// diagnostics as appropriate. If there was an error, set New to be invalid.
4080 LookupResult &OldDecls);
4081
4082 /// MergeFunctionDecl - We just parsed a function 'New' from
4083 /// declarator D which has the same name and scope as a previous
4084 /// declaration 'Old'. Figure out how to resolve this situation,
4085 /// merging decls or emitting diagnostics as appropriate.
4086 ///
4087 /// In C++, New and Old must be declarations that are not
4088 /// overloaded. Use IsOverload to determine whether New and Old are
4089 /// overloaded, and to select the Old declaration that New should be
4090 /// merged with.
4091 ///
4092 /// Returns true if there was an error, false otherwise.
4093 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
4094 bool MergeTypeWithOld, bool NewDeclIsDefn);
4095
4096 /// Completes the merge of two function declarations that are
4097 /// known to be compatible.
4098 ///
4099 /// This routine handles the merging of attributes and other
4100 /// properties of function declarations from the old declaration to
4101 /// the new declaration, once we know that New is in fact a
4102 /// redeclaration of Old.
4103 ///
4104 /// \returns false
4106 Scope *S, bool MergeTypeWithOld);
4108
4109 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4110 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4111 /// situation, merging decls or emitting diagnostics as appropriate.
4112 ///
4113 /// Tentative definition rules (C99 6.9.2p2) are checked by
4114 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4115 /// definitions here, since the initializer hasn't been attached.
4117
4118 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4119 /// scope as a previous declaration 'Old'. Figure out how to merge their
4120 /// types, emitting diagnostics as appropriate.
4121 ///
4122 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call
4123 /// back to here in AddInitializerToDecl. We can't check them before the
4124 /// initializer is attached.
4125 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
4126
4127 /// We've just determined that \p Old and \p New both appear to be definitions
4128 /// of the same variable. Either diagnose or fix the problem.
4129 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
4130 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
4131
4132 /// Filters out lookup results that don't fall within the given scope
4133 /// as determined by isDeclInScope.
4135 bool ConsiderLinkage, bool AllowInlineNamespace);
4136
4137 /// We've determined that \p New is a redeclaration of \p Old. Check that they
4138 /// have compatible owning modules.
4140
4141 /// [module.interface]p6:
4142 /// A redeclaration of an entity X is implicitly exported if X was introduced
4143 /// by an exported declaration; otherwise it shall not be exported.
4145
4146 /// A wrapper function for checking the semantic restrictions of
4147 /// a redeclaration within a module.
4149
4150 /// Check the redefinition in C++20 Modules.
4151 ///
4152 /// [basic.def.odr]p14:
4153 /// For any definable item D with definitions in multiple translation units,
4154 /// - if D is a non-inline non-templated function or variable, or
4155 /// - if the definitions in different translation units do not satisfy the
4156 /// following requirements,
4157 /// the program is ill-formed; a diagnostic is required only if the
4158 /// definable item is attached to a named module and a prior definition is
4159 /// reachable at the point where a later definition occurs.
4160 /// - Each such definition shall not be attached to a named module
4161 /// ([module.unit]).
4162 /// - Each such definition shall consist of the same sequence of tokens, ...
4163 /// ...
4164 ///
4165 /// Return true if the redefinition is not allowed. Return false otherwise.
4166 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
4167
4169
4170 /// If it's a file scoped decl that must warn if not used, keep track
4171 /// of it.
4173
4174 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
4176
4179 DiagReceiverTy DiagReceiver);
4180 void DiagnoseUnusedDecl(const NamedDecl *ND);
4181
4182 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
4183 /// unless they are marked attr(unused).
4184 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
4185
4186 /// If VD is set but not otherwise used, diagnose, for a parameter or a
4187 /// variable.
4188 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
4189
4190 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
4191 /// from S, where a non-field would be declared. This routine copes
4192 /// with the difference between C and C++ scoping rules in structs and
4193 /// unions. For example, the following code is well-formed in C but
4194 /// ill-formed in C++:
4195 /// @code
4196 /// struct S6 {
4197 /// enum { BAR } e;
4198 /// };
4199 ///
4200 /// void test_S6() {
4201 /// struct S6 a;
4202 /// a.e = BAR;
4203 /// }
4204 /// @endcode
4205 /// For the declaration of BAR, this routine will return a different
4206 /// scope. The scope S will be the scope of the unnamed enumeration
4207 /// within S6. In C++, this routine will return the scope associated
4208 /// with S6, because the enumeration's scope is a transparent
4209 /// context but structures can contain non-field names. In C, this
4210 /// routine will return the translation unit scope, since the
4211 /// enumeration's scope is a transparent context and structures cannot
4212 /// contain non-field names.
4214
4217
4218 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
4219 /// file scope. lazily create a decl for it. ForRedeclaration is true
4220 /// if we're creating this built-in in anticipation of redeclaring the
4221 /// built-in.
4223 bool ForRedeclaration, SourceLocation Loc);
4224
4225 /// Get the outermost AttributedType node that sets a calling convention.
4226 /// Valid types should not have multiple attributes with different CCs.
4228
4229 /// GetNameForDeclarator - Determine the full declaration name for the
4230 /// given Declarator.
4232
4233 /// Retrieves the declaration name from a parsed unqualified-id.
4235
4236 /// ParsingInitForAutoVars - a set of declarations with auto types for which
4237 /// we are currently parsing the initializer.
4239
4240 /// Look for a locally scoped extern "C" declaration by the given name.
4242
4244
4245 /// Adjust the \c DeclContext for a function or variable that might be a
4246 /// function-local external declaration.
4248
4250
4251 /// Checks if the variant/multiversion functions are compatible.
4253 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
4254 const PartialDiagnostic &NoProtoDiagID,
4255 const PartialDiagnosticAt &NoteCausedDiagIDAt,
4256 const PartialDiagnosticAt &NoSupportDiagIDAt,
4257 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
4258 bool ConstexprSupported, bool CLinkageMayDiffer);
4259
4260 /// type checking declaration initializers (C99 6.7.8)
4262 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
4263
4267 Expr *Init);
4268
4270 Expr *Init);
4271
4273
4274 // Heuristically tells if the function is `get_return_object` member of a
4275 // coroutine promise_type by matching the function name.
4276 static bool CanBeGetReturnObject(const FunctionDecl *FD);
4277 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
4278
4279 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4280 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4282 Scope *S);
4283
4284 /// If this function is a C++ replaceable global allocation function
4285 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
4286 /// adds any function attributes that we know a priori based on the standard.
4287 ///
4288 /// We need to check for duplicate attributes both here and where user-written
4289 /// attributes are applied to declarations.
4291 FunctionDecl *FD);
4292
4293 /// Adds any function attributes that we know a priori based on
4294 /// the declaration of this function.
4295 ///
4296 /// These attributes can apply both to implicitly-declared builtins
4297 /// (like __builtin___printf_chk) or to library-declared functions
4298 /// like NSLog or printf.
4299 ///
4300 /// We need to check for duplicate attributes both here and where user-written
4301 /// attributes are applied to declarations.
4303
4304 /// VerifyBitField - verifies that a bit field expression is an ICE and has
4305 /// the correct width, and that the field type is valid.
4306 /// Returns false on success.
4308 const IdentifierInfo *FieldName, QualType FieldTy,
4309 bool IsMsStruct, Expr *BitWidth);
4310
4311 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
4312 /// enum. If AllowMask is true, then we also allow the complement of a valid
4313 /// value, to be used as a mask.
4314 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
4315 bool AllowMask) const;
4316
4317 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
4318 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
4319 SourceLocation WeakNameLoc);
4320
4321 /// ActOnPragmaRedefineExtname - Called on well formed
4322 /// \#pragma redefine_extname oldname newname.
4324 IdentifierInfo *AliasName,
4325 SourceLocation PragmaLoc,
4326 SourceLocation WeakNameLoc,
4327 SourceLocation AliasNameLoc);
4328
4329 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
4330 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
4331 SourceLocation PragmaLoc,
4332 SourceLocation WeakNameLoc,
4333 SourceLocation AliasNameLoc);
4334
4335 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4337 Emitted,
4338 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4339 OMPDiscarded, // Discarded due to OpenMP hostness
4340 TemplateDiscarded, // Discarded due to uninstantiated templates
4341 Unknown,
4342 };
4343 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4344 bool Final = false);
4345
4346 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4348
4349private:
4350 /// Function or variable declarations to be checked for whether the deferred
4351 /// diagnostics should be emitted.
4352 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
4353
4354 /// Map of current shadowing declarations to shadowed declarations. Warn if
4355 /// it looks like the user is trying to modify the shadowing declaration.
4356 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
4357
4358 // We need this to handle
4359 //
4360 // typedef struct {
4361 // void *foo() { return 0; }
4362 // } A;
4363 //
4364 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
4365 // for example. If 'A', foo will have external linkage. If we have '*A',
4366 // foo will have no linkage. Since we can't know until we get to the end
4367 // of the typedef, this function finds out if D might have non-external
4368 // linkage. Callers should verify at the end of the TU if it D has external
4369 // linkage or not.
4370 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
4371
4372 ///@}
4373
4374 //
4375 //
4376 // -------------------------------------------------------------------------
4377 //
4378 //
4379
4380 /// \name Declaration Attribute Handling
4381 /// Implementations are in SemaDeclAttr.cpp
4382 ///@{
4383
4384public:
4385 /// Describes the kind of priority given to an availability attribute.
4386 ///
4387 /// The sum of priorities deteremines the final priority of the attribute.
4388 /// The final priority determines how the attribute will be merged.
4389 /// An attribute with a lower priority will always remove higher priority
4390 /// attributes for the specified platform when it is being applied. An
4391 /// attribute with a higher priority will not be applied if the declaration
4392 /// already has an availability attribute with a lower priority for the
4393 /// specified platform. The final prirority values are not expected to match
4394 /// the values in this enumeration, but instead should be treated as a plain
4395 /// integer value. This enumeration just names the priority weights that are
4396 /// used to calculate that final vaue.
4398 /// The availability attribute was specified explicitly next to the
4399 /// declaration.
4401
4402 /// The availability attribute was applied using '#pragma clang attribute'.
4404
4405 /// The availability attribute for a specific platform was inferred from
4406 /// an availability attribute for another platform.
4409
4410 /// Describes the reason a calling convention specification was ignored, used
4411 /// for diagnostics.
4413 ForThisTarget = 0,
4417 };
4418
4419 /// A helper function to provide Attribute Location for the Attr types
4420 /// AND the ParsedAttr.
4421 template <typename AttrInfo>
4422 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
4423 getAttrLoc(const AttrInfo &AL) {
4424 return AL.getLocation();
4425 }
4427
4428 /// If Expr is a valid integer constant, get the value of the integer
4429 /// expression and return success or failure. May output an error.
4430 ///
4431 /// Negative argument is implicitly converted to unsigned, unless
4432 /// \p StrictlyUnsigned is true.
4433 template <typename AttrInfo>
4434 bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val,
4435 unsigned Idx = UINT_MAX,
4436 bool StrictlyUnsigned = false) {
4437 std::optional<llvm::APSInt> I = llvm::APSInt(32);
4438 if (Expr->isTypeDependent() ||
4440 if (Idx != UINT_MAX)
4441 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
4442 << &AI << Idx << AANT_ArgumentIntegerConstant
4443 << Expr->getSourceRange();
4444 else
4445 Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
4447 return false;
4448 }
4449
4450 if (!I->isIntN(32)) {
4451 Diag(Expr->getExprLoc(), diag::err_ice_too_large)
4452 << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
4453 return false;
4454 }
4455
4456 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
4457 Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
4458 << &AI << /*non-negative*/ 1;
4459 return false;
4460 }
4461
4462 Val = (uint32_t)I->getZExtValue();
4463 return true;
4464 }
4465
4466 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
4467 /// \#pragma weak during processing of other Decls.
4468 /// I couldn't figure out a clean way to generate these in-line, so
4469 /// we store them here and handle separately -- which is a hack.
4470 /// It would be best to refactor this.
4472
4473 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
4475
4479
4480 /// ExtVectorDecls - This is a list all the extended vector types. This allows
4481 /// us to associate a raw vector type with one of the ext_vector type names.
4482 /// This is only necessary for issuing pretty diagnostics.
4484
4485 /// Check if the argument \p E is a ASCII string literal. If not emit an error
4486 /// and return false, otherwise set \p Str to the value of the string literal
4487 /// and return true.
4489 const Expr *E, StringRef &Str,
4490 SourceLocation *ArgLocation = nullptr);
4491
4492 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
4493 /// If not emit an error and return false. If the argument is an identifier it
4494 /// will emit an error with a fixit hint and treat it as if it was a string
4495 /// literal.
4496 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4497 StringRef &Str,
4498 SourceLocation *ArgLocation = nullptr);
4499
4500 /// Determine if type T is a valid subject for a nonnull and similar
4501 /// attributes. By default, we look through references (the behavior used by
4502 /// nonnull), but if the second parameter is true, then we treat a reference
4503 /// type as valid.
4504 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4505
4506 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
4507 /// declaration.
4509 Expr *OE);
4510
4511 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
4512 /// declaration.
4514 Expr *ParamExpr);
4515
4516 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4517 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4518
4519 AvailabilityAttr *mergeAvailabilityAttr(
4520 NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
4521 bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
4522 VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
4523 bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
4524 int Priority, IdentifierInfo *IIEnvironment);
4525
4526 TypeVisibilityAttr *
4528 TypeVisibilityAttr::VisibilityType Vis);
4529 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
4530 VisibilityAttr::VisibilityType Vis);
4531 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
4532 StringRef Name);
4533
4534 /// Used to implement to perform semantic checking on
4535 /// attribute((section("foo"))) specifiers.
4536 ///
4537 /// In this case, "foo" is passed in to be checked. If the section
4538 /// specifier is invalid, return an Error that indicates the problem.
4539 ///
4540 /// This is a simple quality of implementation feature to catch errors
4541 /// and give good diagnostics in cases when the assembler or code generator
4542 /// would otherwise reject the section specifier.
4543 llvm::Error isValidSectionSpecifier(StringRef Str);
4544 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4545 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
4546 StringRef Name);
4547
4548 // Check for things we'd like to warn about. Multiversioning issues are
4549 // handled later in the process, once we know how many exist.
4550 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4551
4552 /// Check Target Version attrs
4553 bool checkTargetVersionAttr(SourceLocation Loc, Decl *D, StringRef Str);
4555 SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal,
4556 Decl *D, bool &HasDefault, bool &HasCommas, bool &HasNotDefault,
4557 SmallVectorImpl<SmallString<64>> &StringsBuffer);
4558
4559 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
4560 StringRef NewUserDiagnostic);
4561 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
4562 IdentifierInfo *Format, int FormatIdx,
4563 int FirstArg);
4564
4565 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
4566 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4567 bool IsPackExpansion);
4569 bool IsPackExpansion);
4570
4571 /// AddAlignValueAttr - Adds an align_value attribute to a particular
4572 /// declaration.
4573 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
4574
4575 /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D.
4577 StringRef Annot, MutableArrayRef<Expr *> Args);
4578
4580 bool BestCase,
4581 MSInheritanceModel SemanticSpelling);
4582
4584
4585 /// AddModeAttr - Adds a mode attribute to a particular declaration.
4586 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
4587 bool InInstantiation = false);
4588 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
4589 const AttributeCommonInfo &CI,
4590 const IdentifierInfo *Ident);
4591 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
4592 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
4593 const AttributeCommonInfo &CI);
4594 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
4595 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
4596 const InternalLinkageAttr &AL);
4597
4598 /// Check validaty of calling convention attribute \p attr. If \p FD
4599 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
4600 /// target. Otherwise, it is specified by \p CFT.
4602 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
4604
4605 /// Checks a regparm attribute, returning true if it is ill-formed and
4606 /// otherwise setting numParams to the appropriate value.
4607 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4608
4609 /// Create an CUDALaunchBoundsAttr attribute.
4610 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
4611 Expr *MaxThreads,
4612 Expr *MinBlocks,
4613 Expr *MaxBlocks);
4614
4615 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
4616 /// declaration.
4618 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
4619