clang 18.0.0git
Sema.h
Go to the documentation of this file.
1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
19#include "clang/AST/ASTFwd.h"
20#include "clang/AST/Attr.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
28#include "clang/AST/ExprObjC.h"
33#include "clang/AST/NSAPI.h"
35#include "clang/AST/StmtCXX.h"
37#include "clang/AST/TypeLoc.h"
43#include "clang/Basic/Module.h"
52#include "clang/Sema/DeclSpec.h"
57#include "clang/Sema/Scope.h"
60#include "clang/Sema/Weak.h"
61#include "llvm/ADT/ArrayRef.h"
62#include "llvm/ADT/SetVector.h"
63#include "llvm/ADT/SmallBitVector.h"
64#include "llvm/ADT/SmallPtrSet.h"
65#include "llvm/ADT/SmallSet.h"
66#include "llvm/ADT/SmallVector.h"
67#include "llvm/ADT/TinyPtrVector.h"
68#include "llvm/Frontend/OpenMP/OMPConstants.h"
69#include <deque>
70#include <memory>
71#include <optional>
72#include <string>
73#include <tuple>
74#include <vector>
75
76namespace llvm {
77 class APSInt;
78 template <typename ValueT, typename ValueInfoT> class DenseSet;
79 class SmallBitVector;
80 struct InlineAsmIdentifierInfo;
81}
82
83namespace clang {
84 class ADLResult;
85 class ASTConsumer;
86 class ASTContext;
87 class ASTMutationListener;
88 class ASTReader;
89 class ASTWriter;
90 class ArrayType;
91 class ParsedAttr;
92 class BindingDecl;
93 class BlockDecl;
94 class CapturedDecl;
95 class CXXBasePath;
96 class CXXBasePaths;
97 class CXXBindTemporaryExpr;
99 class CXXConstructorDecl;
100 class CXXConversionDecl;
101 class CXXDeleteExpr;
102 class CXXDestructorDecl;
103 class CXXFieldCollector;
104 class CXXMemberCallExpr;
105 class CXXMethodDecl;
106 class CXXScopeSpec;
107 class CXXTemporary;
108 class CXXTryStmt;
109 class CallExpr;
110 class ClassTemplateDecl;
111 class ClassTemplatePartialSpecializationDecl;
112 class ClassTemplateSpecializationDecl;
113 class VarTemplatePartialSpecializationDecl;
114 class CodeCompleteConsumer;
115 class CodeCompletionAllocator;
116 class CodeCompletionTUInfo;
117 class CodeCompletionResult;
118 class CoroutineBodyStmt;
119 class Decl;
120 class DeclAccessPair;
121 class DeclContext;
122 class DeclRefExpr;
123 class DeclaratorDecl;
124 class DeducedTemplateArgument;
125 class DependentDiagnostic;
126 class DesignatedInitExpr;
127 class Designation;
128 class EnableIfAttr;
129 class EnumConstantDecl;
130 class Expr;
131 class ExtVectorType;
132 class FormatAttr;
133 class FriendDecl;
134 class FunctionDecl;
135 class FunctionProtoType;
136 class FunctionTemplateDecl;
137 class ImplicitConversionSequence;
139 class InitListExpr;
140 class InitializationKind;
141 class InitializationSequence;
142 class InitializedEntity;
143 class IntegerLiteral;
144 class LabelStmt;
145 class LambdaExpr;
146 class LangOptions;
147 class LocalInstantiationScope;
148 class LookupResult;
149 class MacroInfo;
151 class ModuleLoader;
152 class MultiLevelTemplateArgumentList;
153 class NamedDecl;
154 class ObjCCategoryDecl;
155 class ObjCCategoryImplDecl;
156 class ObjCCompatibleAliasDecl;
157 class ObjCContainerDecl;
158 class ObjCImplDecl;
159 class ObjCImplementationDecl;
160 class ObjCInterfaceDecl;
161 class ObjCIvarDecl;
162 template <class T> class ObjCList;
163 class ObjCMessageExpr;
164 class ObjCMethodDecl;
165 class ObjCPropertyDecl;
166 class ObjCProtocolDecl;
167 class OMPThreadPrivateDecl;
168 class OMPRequiresDecl;
169 class OMPDeclareReductionDecl;
170 class OMPDeclareSimdDecl;
171 class OMPClause;
172 struct OMPVarListLocTy;
173 struct OverloadCandidate;
174 enum class OverloadCandidateParamOrder : char;
176 class OverloadCandidateSet;
177 class OverloadExpr;
178 class ParenListExpr;
179 class ParmVarDecl;
180 class Preprocessor;
181 class PseudoDestructorTypeStorage;
182 class PseudoObjectExpr;
183 class QualType;
184 class StandardConversionSequence;
185 class Stmt;
186 class StringLiteral;
187 class SwitchStmt;
188 class TemplateArgument;
189 class TemplateArgumentList;
190 class TemplateArgumentLoc;
191 class TemplateDecl;
192 class TemplateInstantiationCallback;
193 class TemplateParameterList;
194 class TemplatePartialOrderingContext;
195 class TemplateTemplateParmDecl;
196 class Token;
197 class TypeAliasDecl;
198 class TypedefDecl;
199 class TypedefNameDecl;
200 class TypeLoc;
201 class TypoCorrectionConsumer;
202 class UnqualifiedId;
203 class UnresolvedLookupExpr;
204 class UnresolvedMemberExpr;
205 class UnresolvedSetImpl;
206 class UnresolvedSetIterator;
207 class UsingDecl;
208 class UsingShadowDecl;
209 class ValueDecl;
210 class VarDecl;
211 class VarTemplateSpecializationDecl;
212 class VisibilityAttr;
213 class VisibleDeclConsumer;
214 class IndirectFieldDecl;
215 struct DeductionFailureInfo;
216 class TemplateSpecCandidateSet;
217
218namespace sema {
219 class AccessedEntity;
220 class BlockScopeInfo;
221 class Capture;
222 class CapturedRegionScopeInfo;
223 class CapturingScopeInfo;
224 class CompoundScopeInfo;
225 class DelayedDiagnostic;
226 class DelayedDiagnosticPool;
227 class FunctionScopeInfo;
228 class LambdaScopeInfo;
229 class PossiblyUnreachableDiag;
230 class RISCVIntrinsicManager;
231 class SemaPPCallbacks;
232 class TemplateDeductionInfo;
233}
234
235namespace threadSafety {
236 class BeforeSet;
237 void threadSafetyCleanup(BeforeSet* Cache);
238}
239
240// FIXME: No way to easily map from TemplateTypeParmTypes to
241// TemplateTypeParmDecls, so we have this horrible PointerUnion.
242typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *>,
243 SourceLocation>
245
246/// Describes whether we've seen any nullability information for the given
247/// file.
249 /// The first pointer declarator (of any pointer kind) in the file that does
250 /// not have a corresponding nullability annotation.
252
253 /// The end location for the first pointer declarator in the file. Used for
254 /// placing fix-its.
256
257 /// Which kind of pointer declarator we saw.
258 uint8_t PointerKind;
259
260 /// Whether we saw any type nullability annotations in the given file.
261 bool SawTypeNullability = false;
262};
263
264/// A mapping from file IDs to a record of whether we've seen nullability
265/// information in that file.
267 /// A mapping from file IDs to the nullability information for each file ID.
268 llvm::DenseMap<FileID, FileNullability> Map;
269
270 /// A single-element cache based on the file ID.
271 struct {
274 } Cache;
275
276public:
278 // Check the single-element cache.
279 if (file == Cache.File)
280 return Cache.Nullability;
281
282 // It's not in the single-element cache; flush the cache if we have one.
283 if (!Cache.File.isInvalid()) {
284 Map[Cache.File] = Cache.Nullability;
285 }
286
287 // Pull this entry into the cache.
288 Cache.File = file;
289 Cache.Nullability = Map[file];
290 return Cache.Nullability;
291 }
292};
293
294/// Tracks expected type during expression parsing, for use in code completion.
295/// The type is tied to a particular token, all functions that update or consume
296/// the type take a start location of the token they are looking at as a
297/// parameter. This avoids updating the type on hot paths in the parser.
299public:
300 PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
301
302 void enterCondition(Sema &S, SourceLocation Tok);
303 void enterReturn(Sema &S, SourceLocation Tok);
305 /// Handles e.g. BaseType{ .D = Tok...
307 const Designation &D);
308 /// Computing a type for the function argument may require running
309 /// overloading, so we postpone its computation until it is actually needed.
310 ///
311 /// Clients should be very careful when using this function, as it stores a
312 /// function_ref, clients should make sure all calls to get() with the same
313 /// location happen while function_ref is alive.
314 ///
315 /// The callback should also emit signature help as a side-effect, but only
316 /// if the completion point has been reached.
318 llvm::function_ref<QualType()> ComputeType);
319
321 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
322 SourceLocation OpLoc);
323 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
325 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
326 /// Handles all type casts, including C-style cast, C++ casts, etc.
328
329 /// Get the expected type associated with this location, if any.
330 ///
331 /// If the location is a function argument, determining the expected type
332 /// involves considering all function overloads and the arguments so far.
333 /// In this case, signature help for these function overloads will be reported
334 /// as a side-effect (only if the completion point has been reached).
336 if (!Enabled || Tok != ExpectedLoc)
337 return QualType();
338 if (!Type.isNull())
339 return Type;
340 if (ComputeType)
341 return ComputeType();
342 return QualType();
343 }
344
345private:
346 bool Enabled;
347 /// Start position of a token for which we store expected type.
348 SourceLocation ExpectedLoc;
349 /// Expected type for a token starting at ExpectedLoc.
351 /// A function to compute expected type at ExpectedLoc. It is only considered
352 /// if Type is null.
353 llvm::function_ref<QualType()> ComputeType;
354};
355
356/// Sema - This implements semantic analysis and AST building for C.
357class Sema final {
358 Sema(const Sema &) = delete;
359 void operator=(const Sema &) = delete;
360
361 ///Source of additional semantic information.
363
364 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
365
366 /// Determine whether two declarations should be linked together, given that
367 /// the old declaration might not be visible and the new declaration might
368 /// not have external linkage.
369 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
370 const NamedDecl *New) {
371 if (isVisible(Old))
372 return true;
373 // See comment in below overload for why it's safe to compute the linkage
374 // of the new declaration here.
375 if (New->isExternallyDeclarable()) {
376 assert(Old->isExternallyDeclarable() &&
377 "should not have found a non-externally-declarable previous decl");
378 return true;
379 }
380 return false;
381 }
382 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
383
384 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
385 QualType ResultTy,
386 ArrayRef<QualType> Args);
387
388public:
389 /// The maximum alignment, same as in llvm::Value. We duplicate them here
390 /// because that allows us not to duplicate the constants in clang code,
391 /// which we must to since we can't directly use the llvm constants.
392 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
393 ///
394 /// This is the greatest alignment value supported by load, store, and alloca
395 /// instructions, and global values.
396 static const unsigned MaxAlignmentExponent = 32;
397 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
398
402
405
413
414 /// Flag indicating whether or not to collect detailed statistics.
416
417 /// Code-completion consumer.
419
420 /// CurContext - This is the current declaration context of parsing.
422
423 /// Generally null except when we temporarily switch decl contexts,
424 /// like in \see ActOnObjCTemporaryExitContainerContext.
426
427 /// VAListTagName - The declaration name corresponding to __va_list_tag.
428 /// This is used as part of a hack to omit that class from ADL results.
430
431 bool MSStructPragmaOn; // True when \#pragma ms_struct on
432
433 /// Controls member pointer representation format under the MS ABI.
436
437 /// Stack of active SEH __finally scopes. Can be empty.
439
440 /// Source location for newly created implicit MSInheritanceAttrs
442
443 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
444 /// `TransformTypos` in order to keep track of any TypoExprs that are created
445 /// recursively during typo correction and wipe them away if the correction
446 /// fails.
448
449 /// pragma clang section kind
456 PCSK_Relro = 5
457 };
458
461 PCSA_Clear = 1
462 };
463
465 std::string SectionName;
466 bool Valid = false;
468 };
469
475
477 PSK_Reset = 0x0, // #pragma ()
478 PSK_Set = 0x1, // #pragma (value)
479 PSK_Push = 0x2, // #pragma (push[, id])
480 PSK_Pop = 0x4, // #pragma (pop[, id])
481 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
482 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
483 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
484 };
485
488 StringRef SlotLabel;
490 };
491
492 // #pragma pack and align.
494 public:
495 // `Native` represents default align mode, which may vary based on the
496 // platform.
497 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
498
499 // #pragma pack info constructor
500 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
501 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
502 assert(Num == PackNumber && "The pack number has been truncated.");
503 }
504
505 // #pragma align info constructor
507 : PackAttr(false), AlignMode(M),
508 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
509
510 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
511
513
514 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
515 // integer encoding for it. This should only be passed to
516 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
517 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
518 std::uint32_t Encoding{};
519 if (Info.IsXLStack())
520 Encoding |= IsXLMask;
521
522 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
523
524 if (Info.IsPackAttr())
525 Encoding |= PackAttrMask;
526
527 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
528
529 return Encoding;
530 }
531
532 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
533 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
535 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
536 int PackNumber = (Encoding & PackNumMask) >> 4;
537
538 if (Encoding & PackAttrMask)
539 return AlignPackInfo(M, PackNumber, IsXL);
540
541 return AlignPackInfo(M, IsXL);
542 }
543
544 bool IsPackAttr() const { return PackAttr; }
545
546 bool IsAlignAttr() const { return !PackAttr; }
547
548 Mode getAlignMode() const { return AlignMode; }
549
550 unsigned getPackNumber() const { return PackNumber; }
551
552 bool IsPackSet() const {
553 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
554 // attriute on a decl.
555 return PackNumber != UninitPackVal && PackNumber != 0;
556 }
557
558 bool IsXLStack() const { return XLStack; }
559
560 bool operator==(const AlignPackInfo &Info) const {
561 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
562 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
563 Info.XLStack);
564 }
565
566 bool operator!=(const AlignPackInfo &Info) const {
567 return !(*this == Info);
568 }
569
570 private:
571 /// \brief True if this is a pragma pack attribute,
572 /// not a pragma align attribute.
573 bool PackAttr;
574
575 /// \brief The alignment mode that is in effect.
576 Mode AlignMode;
577
578 /// \brief The pack number of the stack.
579 unsigned char PackNumber;
580
581 /// \brief True if it is a XL #pragma align/pack stack.
582 bool XLStack;
583
584 /// \brief Uninitialized pack value.
585 static constexpr unsigned char UninitPackVal = -1;
586
587 // Masks to encode and decode an AlignPackInfo.
588 static constexpr uint32_t IsXLMask{0x0000'0001};
589 static constexpr uint32_t AlignModeMask{0x0000'0006};
590 static constexpr uint32_t PackAttrMask{0x00000'0008};
591 static constexpr uint32_t PackNumMask{0x0000'01F0};
592 };
593
594 template<typename ValueType>
595 struct PragmaStack {
596 struct Slot {
597 llvm::StringRef StackSlotLabel;
598 ValueType Value;
601 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
606 };
607
608 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
609 llvm::StringRef StackSlotLabel, ValueType Value) {
610 if (Action == PSK_Reset) {
612 CurrentPragmaLocation = PragmaLocation;
613 return;
614 }
615 if (Action & PSK_Push)
616 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
617 PragmaLocation);
618 else if (Action & PSK_Pop) {
619 if (!StackSlotLabel.empty()) {
620 // If we've got a label, try to find it and jump there.
621 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
622 return x.StackSlotLabel == StackSlotLabel;
623 });
624 // If we found the label so pop from there.
625 if (I != Stack.rend()) {
626 CurrentValue = I->Value;
627 CurrentPragmaLocation = I->PragmaLocation;
628 Stack.erase(std::prev(I.base()), Stack.end());
629 }
630 } else if (!Stack.empty()) {
631 // We do not have a label, just pop the last entry.
632 CurrentValue = Stack.back().Value;
633 CurrentPragmaLocation = Stack.back().PragmaLocation;
634 Stack.pop_back();
635 }
636 }
637 if (Action & PSK_Set) {
639 CurrentPragmaLocation = PragmaLocation;
640 }
641 }
642
643 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
644 // method body to restore the stacks on exit, so it works like this:
645 //
646 // struct S {
647 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
648 // void Method {}
649 // #pragma <name>(pop, InternalPragmaSlot)
650 // };
651 //
652 // It works even with #pragma vtordisp, although MSVC doesn't support
653 // #pragma vtordisp(push [, id], n)
654 // syntax.
655 //
656 // Push / pop a named sentinel slot.
657 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
658 assert((Action == PSK_Push || Action == PSK_Pop) &&
659 "Can only push / pop #pragma stack sentinels!");
661 }
662
663 // Constructors.
664 explicit PragmaStack(const ValueType &Default)
666
667 bool hasValue() const { return CurrentValue != DefaultValue; }
668
670 ValueType DefaultValue; // Value used for PSK_Reset action.
671 ValueType CurrentValue;
673 };
674 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
675 // we shouldn't do so if they're in a module).
676
677 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
678 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
679 ///
680 /// 0: Suppress all vtordisps
681 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
682 /// structors
683 /// 2: Always insert vtordisps to support RTTI on partially constructed
684 /// objects
687 // The current #pragma align/pack values and locations at each #include.
692 };
694 // Segment #pragmas.
699
700 // #pragma strict_gs_check.
702
703 // This stack tracks the current state of Sema.CurFPFeatures.
706 FPOptionsOverride result;
707 if (!FpPragmaStack.hasValue()) {
708 result = FPOptionsOverride();
709 } else {
710 result = FpPragmaStack.CurrentValue;
711 }
712 return result;
713 }
714
715 // Saves the current floating-point pragma stack and clear it in this Sema.
717 public:
719 : S(S), SavedStack(std::move(S.FpPragmaStack)) {
720 S.FpPragmaStack.Stack.clear();
721 }
722 ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); }
723
724 private:
725 Sema &S;
727 };
728
730 CurFPFeatures = FPO;
731 FpPragmaStack.CurrentValue = FPO.getChangesFrom(FPOptions(LangOpts));
732 }
733
734 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
735 // Actions should be performed only if we enter / exit a C++ method body.
737 public:
738 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
740
741 private:
742 Sema &S;
743 StringRef SlotLabel;
744 bool ShouldAct;
745 };
746
747 /// A mapping that describes the nullability we've seen in each header file.
749
750 /// Last section used with #pragma init_seg.
753
754 /// Sections used with #pragma alloc_text.
755 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
756
757 /// VisContext - Manages the stack for \#pragma GCC visibility.
758 void *VisContext; // Really a "PragmaVisStack*"
759
760 /// This an attribute introduced by \#pragma clang attribute.
765 bool IsUsed;
766 };
767
768 /// A push'd group of PragmaAttributeEntries.
770 /// The location of the push attribute.
772 /// The namespace of this push group.
775 };
776
778
779 /// The declaration that is currently receiving an attribute from the
780 /// #pragma attribute stack.
782
783 /// This represents the last location of a "#pragma clang optimize off"
784 /// directive if such a directive has not been closed by an "on" yet. If
785 /// optimizations are currently "on", this is set to an invalid location.
787
788 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
789 /// whether the optimizations in the list passed to the pragma should be
790 /// turned off or on. This boolean is true by default because command line
791 /// options are honored when `#pragma optimize("", on)`.
792 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
794
795 /// Set of no-builtin functions listed by \#pragma function.
797
798 /// Flag indicating if Sema is building a recovery call expression.
799 ///
800 /// This flag is used to avoid building recovery call expressions
801 /// if Sema is already doing so, which would cause infinite recursions.
803
804 /// Used to control the generation of ExprWithCleanups.
806
807 /// ExprCleanupObjects - This is the stack of objects requiring
808 /// cleanup that are created by the current full expression.
810
811 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
812 /// to a variable (constant) that may or may not be odr-used in this Expr, and
813 /// we won't know until all lvalue-to-rvalue and discarded value conversions
814 /// have been applied to all subexpressions of the enclosing full expression.
815 /// This is cleared at the end of each full expression.
818
819 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
820
821 /// Stack containing information about each of the nested
822 /// function, block, and method scopes that are currently active.
824
825 /// The index of the first FunctionScope that corresponds to the current
826 /// context.
828
829 /// Track the number of currently active capturing scopes.
831
834 FunctionScopes.end());
835 }
836
837 /// Stack containing information needed when in C++2a an 'auto' is encountered
838 /// in a function declaration parameter type specifier in order to invent a
839 /// corresponding template parameter in the enclosing abbreviated function
840 /// template. This information is also present in LambdaScopeInfo, stored in
841 /// the FunctionScopes stack.
843
844 /// The index of the first InventedParameterInfo that refers to the current
845 /// context.
847
852 }
853
857
858 /// ExtVectorDecls - This is a list all the extended vector types. This allows
859 /// us to associate a raw vector type with one of the ext_vector type names.
860 /// This is only necessary for issuing pretty diagnostics.
862
863 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
864 std::unique_ptr<CXXFieldCollector> FieldCollector;
865
867
868 /// Set containing all declared private fields that are not used.
870
871 /// Set containing all typedefs that are likely unused.
874
875 /// Delete-expressions to be analyzed at the end of translation unit
876 ///
877 /// This list contains class members, and locations of delete-expressions
878 /// that could not be proven as to whether they mismatch with new-expression
879 /// used in initializer of the field.
880 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
882 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
883
885
886 /// PureVirtualClassDiagSet - a set of class declarations which we have
887 /// emitted a list of pure virtual functions. Used to prevent emitting the
888 /// same list more than once.
889 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
890
891 /// ParsingInitForAutoVars - a set of declarations with auto types for which
892 /// we are currently parsing the initializer.
894
895 /// Look for a locally scoped extern "C" declaration by the given name.
897
901
902 /// All the tentative definitions encountered in the TU.
904
905 /// All the external declarations encoutered and used in the TU.
907
911
912 /// The set of file scoped decls seen so far that have not been used
913 /// and must warn if not used. Only contains the first declaration.
915
919
920 /// All the delegating constructors seen so far in the file, used for
921 /// cycle detection at the end of the TU.
923
924 /// All the overriding functions seen during a class definition
925 /// that had their exception spec checks delayed, plus the overridden
926 /// function.
929
930 /// All the function redeclarations seen during a class definition that had
931 /// their exception spec checks delayed, plus the prior declaration they
932 /// should be checked against. Except during error recovery, the new decl
933 /// should always be a friend declaration, as that's the only valid way to
934 /// redeclare a special member before its class is complete.
937
938 typedef llvm::MapVector<const FunctionDecl *,
939 std::unique_ptr<LateParsedTemplate>>
942
943 /// Callback to the parser to parse templated functions when needed.
944 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
945 typedef void LateTemplateParserCleanupCB(void *P);
949
951 LateTemplateParserCleanupCB *LTPCleanup,
952 void *P) {
953 LateTemplateParser = LTP;
954 LateTemplateParserCleanup = LTPCleanup;
955 OpaqueParser = P;
956 }
957
958 class DelayedDiagnostics;
959
961 sema::DelayedDiagnosticPool *SavedPool = nullptr;
963 };
966
967 /// A class which encapsulates the logic for delaying diagnostics
968 /// during parsing and other processing.
970 /// The current pool of diagnostics into which delayed
971 /// diagnostics should go.
972 sema::DelayedDiagnosticPool *CurPool = nullptr;
973
974 public:
976
977 /// Adds a delayed diagnostic.
978 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
979
980 /// Determines whether diagnostics should be delayed.
981 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
982
983 /// Returns the current delayed-diagnostics pool.
985 return CurPool;
986 }
987
988 /// Enter a new scope. Access and deprecation diagnostics will be
989 /// collected in this pool.
992 state.SavedPool = CurPool;
993 CurPool = &pool;
994 return state;
995 }
996
997 /// Leave a delayed-diagnostic state that was previously pushed.
998 /// Do not emit any of the diagnostics. This is performed as part
999 /// of the bookkeeping of popping a pool "properly".
1001 CurPool = state.SavedPool;
1002 }
1003
1004 /// Enter a new scope where access and deprecation diagnostics are
1005 /// not delayed.
1008 state.SavedPool = CurPool;
1009 CurPool = nullptr;
1010 return state;
1011 }
1012
1013 /// Undo a previous pushUndelayed().
1015 assert(CurPool == nullptr);
1016 CurPool = state.SavedPool;
1017 }
1018 } DelayedDiagnostics;
1019
1027
1028 /// A RAII object to temporarily push a declaration context.
1030 private:
1031 Sema &S;
1032 DeclContext *SavedContext;
1033 ProcessingContextState SavedContextState;
1034 QualType SavedCXXThisTypeOverride;
1035 unsigned SavedFunctionScopesStart;
1036 unsigned SavedInventedParameterInfosStart;
1037
1038 public:
1039 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
1040 : S(S), SavedContext(S.CurContext),
1041 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
1042 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
1043 SavedFunctionScopesStart(S.FunctionScopesStart),
1044 SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
1045 {
1046 assert(ContextToPush && "pushing null context");
1047 S.CurContext = ContextToPush;
1048 if (NewThisContext)
1049 S.CXXThisTypeOverride = QualType();
1050 // Any saved FunctionScopes do not refer to this context.
1051 S.FunctionScopesStart = S.FunctionScopes.size();
1052 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1053 }
1054
1055 void pop() {
1056 if (!SavedContext) return;
1057 S.CurContext = SavedContext;
1058 S.DelayedDiagnostics.popUndelayed(SavedContextState);
1059 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1060 S.FunctionScopesStart = SavedFunctionScopesStart;
1061 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1062 SavedContext = nullptr;
1063 }
1064
1066 pop();
1067 }
1068 };
1069
1070 /// RAII object to handle the state changes required to synthesize
1071 /// a function body.
1073 Sema &S;
1074 Sema::ContextRAII SavedContext;
1075 bool PushedCodeSynthesisContext = false;
1076
1077 public:
1079 : S(S), SavedContext(S, DC) {
1080 auto *FD = dyn_cast<FunctionDecl>(DC);
1081 S.PushFunctionScope();
1082 S.PushExpressionEvaluationContext(
1083 (FD && FD->isConsteval())
1086 if (FD) {
1087 FD->setWillHaveBody(true);
1088 S.ExprEvalContexts.back().InImmediateFunctionContext =
1089 FD->isImmediateFunction();
1090 S.ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
1091 S.getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
1092 } else
1093 assert(isa<ObjCMethodDecl>(DC));
1094 }
1095
1097 assert(!PushedCodeSynthesisContext);
1098
1101 Ctx.PointOfInstantiation = UseLoc;
1102 Ctx.Entity = cast<Decl>(S.CurContext);
1103 S.pushCodeSynthesisContext(Ctx);
1104
1105 PushedCodeSynthesisContext = true;
1106 }
1107
1109 if (PushedCodeSynthesisContext)
1110 S.popCodeSynthesisContext();
1111 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
1112 FD->setWillHaveBody(false);
1113 S.CheckImmediateEscalatingFunctionDefinition(FD, S.getCurFunction());
1114 }
1115 S.PopExpressionEvaluationContext();
1116 S.PopFunctionScopeInfo();
1117 }
1118 };
1119
1120 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
1121 /// declared. Rare. May alias another identifier, declared or undeclared.
1122 ///
1123 /// For aliases, the target identifier is used as a key for eventual
1124 /// processing when the target is declared. For the single-identifier form,
1125 /// the sole identifier is used as the key. Each entry is a `SetVector`
1126 /// (ordered by parse order) of aliases (identified by the alias name) in case
1127 /// of multiple aliases to the same undeclared identifier.
1128 llvm::MapVector<
1130 llvm::SetVector<
1132 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
1134
1135 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1136 /// \#pragma redefine_extname before declared. Used in Solaris system headers
1137 /// to define functions that occur in multiple standards to call the version
1138 /// in the currently selected standard.
1139 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1140
1141
1142 /// Load weak undeclared identifiers from the external source.
1144
1145 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1146 /// \#pragma weak during processing of other Decls.
1147 /// I couldn't figure out a clean way to generate these in-line, so
1148 /// we store them here and handle separately -- which is a hack.
1149 /// It would be best to refactor this.
1151
1153
1154 /// Translation Unit Scope - useful to Objective-C actions that need
1155 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1156 /// For example, user-defined classes, built-in "id" type, etc.
1158
1159 /// The C++ "std" namespace, where the standard library resides.
1161
1162 /// The C++ "std::bad_alloc" class, which is defined by the C++
1163 /// standard library.
1165
1166 /// The C++ "std::align_val_t" enum class, which is defined by the C++
1167 /// standard library.
1169
1170 /// The C++ "std::initializer_list" template, which is defined in
1171 /// <initializer_list>.
1173
1174 /// The C++ "std::coroutine_traits" template, which is defined in
1175 /// <coroutine_traits>
1177
1178 /// The C++ "type_info" declaration, which is defined in <typeinfo>.
1180
1181 /// The C++ "std::source_location::__impl" struct, defined in
1182 /// <source_location>.
1184
1185 /// Caches identifiers/selectors for NSFoundation APIs.
1186 std::unique_ptr<NSAPI> NSAPIObj;
1187
1188 /// The declaration of the Objective-C NSNumber class.
1190
1191 /// The declaration of the Objective-C NSValue class.
1193
1194 /// Pointer to NSNumber type (NSNumber *).
1196
1197 /// Pointer to NSValue type (NSValue *).
1199
1200 /// The Objective-C NSNumber methods used to create NSNumber literals.
1202
1203 /// The declaration of the Objective-C NSString class.
1205
1206 /// Pointer to NSString type (NSString *).
1208
1209 /// The declaration of the stringWithUTF8String: method.
1211
1212 /// The declaration of the valueWithBytes:objCType: method.
1214
1215 /// The declaration of the Objective-C NSArray class.
1217
1218 /// The declaration of the arrayWithObjects:count: method.
1220
1221 /// The declaration of the Objective-C NSDictionary class.
1223
1224 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1226
1227 /// id<NSCopying> type.
1229
1230 /// will hold 'respondsToSelector:'
1232
1233 /// A flag to remember whether the implicit forms of operator new and delete
1234 /// have been declared.
1236
1237 /// Describes how the expressions currently being parsed are
1238 /// evaluated at run-time, if at all.
1240 /// The current expression and its subexpressions occur within an
1241 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1242 /// \c sizeof, where the type of the expression may be significant but
1243 /// no code will be generated to evaluate the value of the expression at
1244 /// run time.
1246
1247 /// The current expression occurs within a braced-init-list within
1248 /// an unevaluated operand. This is mostly like a regular unevaluated
1249 /// context, except that we still instantiate constexpr functions that are
1250 /// referenced here so that we can perform narrowing checks correctly.
1252
1253 /// The current expression occurs within a discarded statement.
1254 /// This behaves largely similarly to an unevaluated operand in preventing
1255 /// definitions from being required, but not in other ways.
1257
1258 /// The current expression occurs within an unevaluated
1259 /// operand that unconditionally permits abstract references to
1260 /// fields, such as a SIZE operator in MS-style inline assembly.
1262
1263 /// The current context is "potentially evaluated" in C++11 terms,
1264 /// but the expression is evaluated at compile-time (like the values of
1265 /// cases in a switch statement).
1267
1268 /// In addition of being constant evaluated, the current expression
1269 /// occurs in an immediate function context - either a consteval function
1270 /// or a consteval if statement.
1272
1273 /// The current expression is potentially evaluated at run time,
1274 /// which means that code may be generated to evaluate the value of the
1275 /// expression at run time.
1277
1278 /// The current expression is potentially evaluated, but any
1279 /// declarations referenced inside that expression are only used if
1280 /// in fact the current expression is used.
1281 ///
1282 /// This value is used when parsing default function arguments, for which
1283 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1284 /// through varargs) but do not want to mark declarations as "referenced"
1285 /// until the default argument is used.
1287 };
1288
1289 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1290
1291 /// Data structure used to record current or nested
1292 /// expression evaluation contexts.
1294 /// The expression evaluation context.
1296
1297 /// Whether the enclosing context needed a cleanup.
1299
1300 /// The number of active cleanup objects when we entered
1301 /// this expression evaluation context.
1303
1304 /// The number of typos encountered during this expression evaluation
1305 /// context (i.e. the number of TypoExprs created).
1306 unsigned NumTypos;
1307
1309
1310 /// The lambdas that are present within this context, if it
1311 /// is indeed an unevaluated context.
1313
1314 /// The declaration that provides context for lambda expressions
1315 /// and block literals if the normal declaration context does not
1316 /// suffice, e.g., in a default function argument.
1318
1319 /// If we are processing a decltype type, a set of call expressions
1320 /// for which we have deferred checking the completeness of the return type.
1322
1323 /// If we are processing a decltype type, a set of temporary binding
1324 /// expressions for which we have deferred checking the destructor.
1326
1328
1329 /// Expressions appearing as the LHS of a volatile assignment in this
1330 /// context. We produce a warning for these when popping the context if
1331 /// they are not discarded-value expressions nor unevaluated operands.
1333
1334 /// Set of candidates for starting an immediate invocation.
1336
1337 /// Set of DeclRefExprs referencing a consteval function when used in a
1338 /// context not already known to be immediately invoked.
1340
1341 /// \brief Describes whether we are in an expression constext which we have
1342 /// to handle differently.
1346
1347 // A context can be nested in both a discarded statement context and
1348 // an immediate function context, so they need to be tracked independently.
1352
1354
1355 // We are in a constant context, but we also allow
1356 // non constant expressions, for example for array bounds (which may be
1357 // VLAs).
1359
1360 // When evaluating immediate functions in the initializer of a default
1361 // argument or default member initializer, this is the declaration whose
1362 // default initializer is being evaluated and the location of the call
1363 // or constructor definition.
1367 : Loc(Loc), Decl(Decl), Context(Context) {
1368 assert(Decl && Context && "invalid initialization context");
1369 }
1370
1372 ValueDecl *Decl = nullptr;
1374 };
1375 std::optional<InitializationContext> DelayedDefaultInitializationContext;
1376
1378 unsigned NumCleanupObjects,
1387
1388 bool isUnevaluated() const {
1392 }
1393
1394 bool isConstantEvaluated() const {
1397 }
1398
1403 // C++23 [expr.const]p14:
1404 // An expression or conversion is in an immediate function
1405 // context if it is potentially evaluated and either:
1406 // * its innermost enclosing non-block scope is a function
1407 // parameter scope of an immediate function, or
1408 // * its enclosing statement is enclosed by the compound-
1409 // statement of a consteval if statement.
1412 }
1413
1416 (Context ==
1419 }
1420 };
1421
1422 /// A stack of expression evaluation contexts.
1424
1425 // Set of failed immediate invocations to avoid double diagnosing.
1427
1428 /// Emit a warning for all pending noderef expressions that we recorded.
1430
1431 /// Compute the mangling number context for a lambda expression or
1432 /// block literal. Also return the extra mangling decl if any.
1433 ///
1434 /// \param DC - The DeclContext containing the lambda expression or
1435 /// block literal.
1436 std::tuple<MangleNumberingContext *, Decl *>
1438
1439
1440 /// SpecialMemberOverloadResult - The overloading result for a special member
1441 /// function.
1442 ///
1443 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1444 /// integer are used to determine whether overload resolution succeeded.
1446 public:
1447 enum Kind {
1450 Success
1452
1453 private:
1454 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
1455
1456 public:
1459 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1460
1461 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1462 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1463
1464 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1465 void setKind(Kind K) { Pair.setInt(K); }
1466 };
1467
1469 : public llvm::FastFoldingSetNode,
1471 public:
1472 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1473 : FastFoldingSetNode(ID)
1474 {}
1475 };
1476
1477 /// A cache of special member function overload resolution results
1478 /// for C++ records.
1479 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1480
1481 /// A cache of the flags available in enumerations with the flag_bits
1482 /// attribute.
1483 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1484
1485 /// The kind of translation unit we are processing.
1486 ///
1487 /// When we're processing a complete translation unit, Sema will perform
1488 /// end-of-translation-unit semantic tasks (such as creating
1489 /// initializers for tentative definitions in C) once parsing has
1490 /// completed. Modules and precompiled headers perform different kinds of
1491 /// checks.
1493
1494 llvm::BumpPtrAllocator BumpAlloc;
1495
1496 /// The number of SFINAE diagnostics that have been trapped.
1498
1499 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1501
1502 /// A mapping from parameters with unparsed default arguments to the
1503 /// set of instantiations of each parameter.
1504 ///
1505 /// This mapping is a temporary data structure used when parsing
1506 /// nested class templates or nested classes of class templates,
1507 /// where we might end up instantiating an inner class before the
1508 /// default arguments of its methods have been parsed.
1510
1511 // Contains the locations of the beginning of unparsed default
1512 // argument locations.
1513 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1514
1515 /// UndefinedInternals - all the used, undefined objects which require a
1516 /// definition in this translation unit.
1517 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1518
1519 /// Determine if VD, which must be a variable or function, is an external
1520 /// symbol that nonetheless can't be referenced from outside this translation
1521 /// unit because its type has no linkage and it's not extern "C".
1522 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
1523
1524 /// Obtain a sorted list of functions that are undefined but ODR-used.
1526 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1527
1528 /// Retrieves list of suspicious delete-expressions that will be checked at
1529 /// the end of translation unit.
1530 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1532
1534 public:
1535 using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1536 using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1537 iterator begin() { return Methods.begin(); }
1538 iterator end() { return Methods.end(); }
1539 iterator find(Selector Sel) { return Methods.find(Sel); }
1540 std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1541 return Methods.insert(Val);
1542 }
1543 int count(Selector Sel) const { return Methods.count(Sel); }
1544 bool empty() const { return Methods.empty(); }
1545
1546 private:
1547 llvm::DenseMap<Selector, Lists> Methods;
1548 };
1549
1550 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1551 /// We need to maintain a list, since selectors can have differing signatures
1552 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1553 /// of selectors are "overloaded").
1554 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1555 /// methods inside categories with a particular selector.
1557
1558 /// Method selectors used in a \@selector expression. Used for implementation
1559 /// of -Wselector.
1560 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1561
1562 /// List of SourceLocations where 'self' is implicitly retained inside a
1563 /// block.
1566
1567 /// Kinds of C++ special members.
1577
1578 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1580
1581 /// The C++ special members which we are currently in the process of
1582 /// declaring. If this process recursively triggers the declaration of the
1583 /// same special member, we should act as if it is not yet declared.
1585
1586 /// Kinds of defaulted comparison operator functions.
1587 enum class DefaultedComparisonKind : unsigned char {
1588 /// This is not a defaultable comparison operator.
1589 None,
1590 /// This is an operator== that should be implemented as a series of
1591 /// subobject comparisons.
1592 Equal,
1593 /// This is an operator<=> that should be implemented as a series of
1594 /// subobject comparisons.
1595 ThreeWay,
1596 /// This is an operator!= that should be implemented as a rewrite in terms
1597 /// of a == comparison.
1598 NotEqual,
1599 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1600 /// terms of a <=> comparison.
1601 Relational,
1602 };
1603
1604 /// The function definitions which were renamed as part of typo-correction
1605 /// to match their respective declarations. We want to keep track of them
1606 /// to ensure that we don't emit a "redefinition" error if we encounter a
1607 /// correctly named definition after the renamed definition.
1609
1610 /// Stack of types that correspond to the parameter entities that are
1611 /// currently being copy-initialized. Can be empty.
1613
1614 void ReadMethodPool(Selector Sel);
1616
1617 /// Private Helper predicate to check for 'self'.
1618 bool isSelfExpr(Expr *RExpr);
1619 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1620
1621 /// Cause the active diagnostic on the DiagosticsEngine to be
1622 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1623 /// should not be used elsewhere.
1624 void EmitCurrentDiagnostic(unsigned DiagID);
1625
1626 /// Records and restores the CurFPFeatures state on entry/exit of compound
1627 /// statements.
1629 public:
1632 FPOptionsOverride getOverrides() { return OldOverrides; }
1633
1634 private:
1635 Sema& S;
1636 FPOptions OldFPFeaturesState;
1637 FPOptionsOverride OldOverrides;
1638 LangOptions::FPEvalMethodKind OldEvalMethod;
1639 SourceLocation OldFPPragmaLocation;
1640 };
1641
1642 void addImplicitTypedef(StringRef Name, QualType T);
1643
1645
1646 /// Increment when we find a reference; decrement when we find an ignored
1647 /// assignment. Ultimately the value is 0 if every reference is an ignored
1648 /// assignment.
1649 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1650
1651 /// Indicate RISC-V vector builtin functions enabled or not.
1653
1654 /// Indicate RISC-V SiFive vector builtin functions enabled or not.
1656
1657private:
1658 std::unique_ptr<sema::RISCVIntrinsicManager> RVIntrinsicManager;
1659
1660 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1661
1662 bool WarnedDarwinSDKInfoMissing = false;
1663
1664public:
1665 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1667 CodeCompleteConsumer *CompletionConsumer = nullptr);
1668 ~Sema();
1669
1670 /// Perform initialization that occurs after the parser has been
1671 /// initialized but before it parses anything.
1672 void Initialize();
1673
1674 /// This virtual key function only exists to limit the emission of debug info
1675 /// describing the Sema class. GCC and Clang only emit debug info for a class
1676 /// with a vtable when the vtable is emitted. Sema is final and not
1677 /// polymorphic, but the debug info size savings are so significant that it is
1678 /// worth adding a vtable just to take advantage of this optimization.
1679 virtual void anchor();
1680
1681 const LangOptions &getLangOpts() const { return LangOpts; }
1684
1687 Preprocessor &getPreprocessor() const { return PP; }
1688 ASTContext &getASTContext() const { return Context; }
1692
1694 StringRef Platform);
1696
1697 ///Registers an external source. If an external source already exists,
1698 /// creates a multiplex external source and appends to it.
1699 ///
1700 ///\param[in] E - A non-null external sema source.
1701 ///
1703
1704 void PrintStats() const;
1705
1706 /// Warn that the stack is nearly exhausted.
1708
1709 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1710 /// guaranteed). Produces a warning if we're low on stack space and allocates
1711 /// more in that case. Use this in code that may recurse deeply (for example,
1712 /// in template instantiation) to avoid stack overflow.
1714 llvm::function_ref<void()> Fn);
1715
1716 /// Helper class that creates diagnostics with optional
1717 /// template instantiation stacks.
1718 ///
1719 /// This class provides a wrapper around the basic DiagnosticBuilder
1720 /// class that emits diagnostics. ImmediateDiagBuilder is
1721 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1722 /// does) and, if the diagnostic comes from inside a template
1723 /// instantiation, printing the template instantiation stack as
1724 /// well.
1726 Sema &SemaRef;
1727 unsigned DiagID;
1728
1729 public:
1730 ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1731 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1732 ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1733 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1734
1735 // This is a cunning lie. DiagnosticBuilder actually performs move
1736 // construction in its copy constructor (but due to varied uses, it's not
1737 // possible to conveniently express this as actual move construction). So
1738 // the default copy ctor here is fine, because the base class disables the
1739 // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1740 // in that case anwyay.
1742
1744 // If we aren't active, there is nothing to do.
1745 if (!isActive()) return;
1746
1747 // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1748 // builder itself so it won't emit the diagnostic in its own destructor.
1749 //
1750 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1751 // do its own needless checks to see if the diagnostic needs to be
1752 // emitted. However, because we take care to ensure that the builder
1753 // objects never escape, a sufficiently smart compiler will be able to
1754 // eliminate that code.
1755 Clear();
1756
1757 // Dispatch to Sema to emit the diagnostic.
1758 SemaRef.EmitCurrentDiagnostic(DiagID);
1759 }
1760
1761 /// Teach operator<< to produce an object of the correct type.
1762 template <typename T>
1764 operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1765 const DiagnosticBuilder &BaseDiag = Diag;
1766 BaseDiag << Value;
1767 return Diag;
1768 }
1769
1770 // It is necessary to limit this to rvalue reference to avoid calling this
1771 // function with a bitfield lvalue argument since non-const reference to
1772 // bitfield is not allowed.
1773 template <typename T,
1774 typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1776 const DiagnosticBuilder &BaseDiag = *this;
1777 BaseDiag << std::move(V);
1778 return *this;
1779 }
1780 };
1781
1782 /// A generic diagnostic builder for errors which may or may not be deferred.
1783 ///
1784 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1785 /// which are not allowed to appear inside __device__ functions and are
1786 /// allowed to appear in __host__ __device__ functions only if the host+device
1787 /// function is never codegen'ed.
1788 ///
1789 /// To handle this, we use the notion of "deferred diagnostics", where we
1790 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1791 ///
1792 /// This class lets you emit either a regular diagnostic, a deferred
1793 /// diagnostic, or no diagnostic at all, according to an argument you pass to
1794 /// its constructor, thus simplifying the process of creating these "maybe
1795 /// deferred" diagnostics.
1797 public:
1798 enum Kind {
1799 /// Emit no diagnostics.
1801 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1803 /// Emit the diagnostic immediately, and, if it's a warning or error, also
1804 /// emit a call stack showing how this function can be reached by an a
1805 /// priori known-emitted function.
1807 /// Create a deferred diagnostic, which is emitted only if the function
1808 /// it's attached to is codegen'ed. Also emit a call stack as with
1809 /// K_ImmediateWithCallStack.
1812
1813 SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1814 const FunctionDecl *Fn, Sema &S);
1817
1818 // The copy and move assignment operator is defined as deleted pending
1819 // further motivation.
1822
1824
1825 bool isImmediate() const { return ImmediateDiag.has_value(); }
1826
1827 /// Convertible to bool: True if we immediately emitted an error, false if
1828 /// we didn't emit an error or we created a deferred error.
1829 ///
1830 /// Example usage:
1831 ///
1832 /// if (SemaDiagnosticBuilder(...) << foo << bar)
1833 /// return ExprError();
1834 ///
1835 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1836 /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1837 operator bool() const { return isImmediate(); }
1838
1839 template <typename T>
1841 operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1842 if (Diag.ImmediateDiag)
1843 *Diag.ImmediateDiag << Value;
1844 else if (Diag.PartialDiagId)
1845 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1846 << Value;
1847 return Diag;
1848 }
1849
1850 // It is necessary to limit this to rvalue reference to avoid calling this
1851 // function with a bitfield lvalue argument since non-const reference to
1852 // bitfield is not allowed.
1853 template <typename T,
1854 typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1856 if (ImmediateDiag)
1857 *ImmediateDiag << std::move(V);
1858 else if (PartialDiagId)
1859 S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1860 return *this;
1861 }
1862
1865 if (Diag.ImmediateDiag)
1866 PD.Emit(*Diag.ImmediateDiag);
1867 else if (Diag.PartialDiagId)
1868 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1869 return Diag;
1870 }
1871
1872 void AddFixItHint(const FixItHint &Hint) const {
1873 if (ImmediateDiag)
1874 ImmediateDiag->AddFixItHint(Hint);
1875 else if (PartialDiagId)
1876 S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1877 }
1878
1880 return ExprError();
1881 }
1883 return StmtError();
1884 }
1885 operator ExprResult() const { return ExprError(); }
1886 operator StmtResult() const { return StmtError(); }
1887 operator TypeResult() const { return TypeError(); }
1888 operator DeclResult() const { return DeclResult(true); }
1889 operator MemInitResult() const { return MemInitResult(true); }
1890
1891 private:
1892 Sema &S;
1893 SourceLocation Loc;
1894 unsigned DiagID;
1895 const FunctionDecl *Fn;
1896 bool ShowCallStack;
1897
1898 // Invariant: At most one of these Optionals has a value.
1899 // FIXME: Switch these to a Variant once that exists.
1900 std::optional<ImmediateDiagBuilder> ImmediateDiag;
1901 std::optional<unsigned> PartialDiagId;
1902 };
1903
1904 /// Is the last error level diagnostic immediate. This is used to determined
1905 /// whether the next info diagnostic should be immediate.
1907
1908 /// Emit a diagnostic.
1909 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1910 bool DeferHint = false);
1911
1912 /// Emit a partial diagnostic.
1914 bool DeferHint = false);
1915
1916 /// Build a partial diagnostic.
1917 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1918
1919 /// Whether deferrable diagnostics should be deferred.
1920 bool DeferDiags = false;
1921
1922 /// RAII class to control scope of DeferDiags.
1924 Sema &S;
1925 bool SavedDeferDiags = false;
1926
1927 public:
1929 : S(S), SavedDeferDiags(S.DeferDiags) {
1930 S.DeferDiags = DeferDiags;
1931 }
1932 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1933 };
1934
1935 /// Whether uncompilable error has occurred. This includes error happens
1936 /// in deferred diagnostics.
1937 bool hasUncompilableErrorOccurred() const;
1938
1939 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1940
1941 /// Get a string to suggest for zero-initialization of a type.
1942 std::string
1944 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1945
1946 /// Calls \c Lexer::getLocForEndOfToken()
1947 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1948
1949 /// Retrieve the module loader associated with the preprocessor.
1951
1952 /// Invent a new identifier for parameters of abbreviated templates.
1955 unsigned Index);
1956
1958
1959 private:
1960 /// Function or variable declarations to be checked for whether the deferred
1961 /// diagnostics should be emitted.
1962 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1963
1964 public:
1965 // Emit all deferred diagnostics.
1966 void emitDeferredDiags();
1967
1969 /// The global module fragment, between 'module;' and a module-declaration.
1971 /// A normal translation unit fragment. For a non-module unit, this is the
1972 /// entire translation unit. Otherwise, it runs from the module-declaration
1973 /// to the private-module-fragment (if any) or the end of the TU (if not).
1975 /// The private module fragment, between 'module :private;' and the end of
1976 /// the translation unit.
1977 Private
1979
1983
1985
1987
1988 void PushFunctionScope();
1989 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1991
1992 /// This is used to inform Sema what the current TemplateParameterDepth
1993 /// is during Parsing. Currently it is used to pass on the depth
1994 /// when parsing generic lambda 'auto' parameters.
1995 void RecordParsingTemplateParameterDepth(unsigned Depth);
1996
1997 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1999 unsigned OpenMPCaptureLevel = 0);
2000
2001 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
2002 /// time after they've been popped.
2004 Sema *Self;
2005
2006 public:
2007 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
2009 };
2010
2012 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
2013
2016 const Decl *D = nullptr,
2017 QualType BlockType = QualType());
2018
2020 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
2021 }
2022
2024
2029
2030 void PushCompoundScope(bool IsStmtExpr);
2031 void PopCompoundScope();
2032
2034
2036
2037 /// Retrieve the current block, if any.
2039
2040 /// Get the innermost lambda enclosing the current location, if any. This
2041 /// looks through intervening non-lambda scopes such as local functions and
2042 /// blocks.
2044
2045 /// Retrieve the current lambda scope info, if any.
2046 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
2047 /// lambda scope info ignoring all inner capturing scopes that are not
2048 /// lambda scopes.
2050 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
2051
2052 /// Retrieve the current generic lambda info, if any.
2054
2055 /// Retrieve the current captured region, if any.
2057
2058 /// Retrieve the current function, if any, that should be analyzed for
2059 /// potential availability violations.
2061
2062 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
2064
2065 /// Called before parsing a function declarator belonging to a function
2066 /// declaration.
2068 unsigned TemplateParameterDepth);
2069
2070 /// Called after parsing a function declarator belonging to a function
2071 /// declaration.
2073
2074 void ActOnComment(SourceRange Comment);
2075
2076 //===--------------------------------------------------------------------===//
2077 // Type Analysis / Processing: SemaType.cpp.
2078 //
2079
2081 const DeclSpec *DS = nullptr);
2082 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
2083 const DeclSpec *DS = nullptr);
2085 SourceLocation Loc, DeclarationName Entity);
2086 QualType BuildReferenceType(QualType T, bool LValueRef,
2087 SourceLocation Loc, DeclarationName Entity);
2089 unsigned Quals, SourceRange Brackets,
2090 DeclarationName Entity);
2091 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
2093 SourceLocation AttrLoc);
2094 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
2095 SourceLocation AttrLoc);
2096
2097 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
2098 SourceLocation AttrLoc);
2099
2100 /// Same as above, but constructs the AddressSpace index if not provided.
2102 SourceLocation AttrLoc);
2103
2104 CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E);
2106
2108
2110
2111 /// Build a function type.
2112 ///
2113 /// This routine checks the function type according to C++ rules and
2114 /// under the assumption that the result type and parameter types have
2115 /// just been instantiated from a template. It therefore duplicates
2116 /// some of the behavior of GetTypeForDeclarator, but in a much
2117 /// simpler form that is only suitable for this narrow use case.
2118 ///
2119 /// \param T The return type of the function.
2120 ///
2121 /// \param ParamTypes The parameter types of the function. This array
2122 /// will be modified to account for adjustments to the types of the
2123 /// function parameters.
2124 ///
2125 /// \param Loc The location of the entity whose type involves this
2126 /// function type or, if there is no such entity, the location of the
2127 /// type that will have function type.
2128 ///
2129 /// \param Entity The name of the entity that involves the function
2130 /// type, if known.
2131 ///
2132 /// \param EPI Extra information about the function type. Usually this will
2133 /// be taken from an existing function with the same prototype.
2134 ///
2135 /// \returns A suitable function type, if there are no errors. The
2136 /// unqualified type will always be a FunctionProtoType.
2137 /// Otherwise, returns a NULL type.
2139 MutableArrayRef<QualType> ParamTypes,
2140 SourceLocation Loc, DeclarationName Entity,
2142
2144 SourceLocation Loc,
2145 DeclarationName Entity);
2147 SourceLocation Loc, DeclarationName Entity);
2151 SourceLocation Loc);
2153 SourceLocation Loc);
2154 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2155
2158
2159 /// Package the given type and TSI into a ParsedType.
2164 TypeSourceInfo **TInfo = nullptr);
2165 CanThrowResult canThrow(const Stmt *E);
2166 /// Determine whether the callee of a particular function call can throw.
2167 /// E, D and Loc are all optional.
2168 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2171 const FunctionProtoType *FPT);
2178 const FunctionProtoType *Old, SourceLocation OldLoc,
2179 const FunctionProtoType *New, SourceLocation NewLoc);
2181 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2182 const FunctionProtoType *Old, SourceLocation OldLoc,
2183 const FunctionProtoType *New, SourceLocation NewLoc);
2184 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2186 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
2187 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
2188 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
2189 SourceLocation SuperLoc, const FunctionProtoType *Subset,
2190 bool SkipSubsetFirstParameter, SourceLocation SubLoc);
2192 const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID,
2193 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
2194 SourceLocation TargetLoc, const FunctionProtoType *Source,
2195 bool SkipSourceFirstParameter, SourceLocation SourceLoc);
2196
2198
2199 /// The parser has parsed the context-sensitive type 'instancetype'
2200 /// in an Objective-C message declaration. Return the appropriate type.
2202
2203 /// Abstract class used to diagnose incomplete types.
2206
2207 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2208 virtual ~TypeDiagnoser() {}
2209 };
2210
2211 static int getPrintable(int I) { return I; }
2212 static unsigned getPrintable(unsigned I) { return I; }
2213 static bool getPrintable(bool B) { return B; }
2214 static const char * getPrintable(const char *S) { return S; }
2215 static StringRef getPrintable(StringRef S) { return S; }
2216 static const std::string &getPrintable(const std::string &S) { return S; }
2217 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2218 return II;
2219 }
2221 static QualType getPrintable(QualType T) { return T; }
2222 static SourceRange getPrintable(SourceRange R) { return R; }
2224 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2226
2227 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2228 protected:
2229 unsigned DiagID;
2230 std::tuple<const Ts &...> Args;
2231
2232 template <std::size_t... Is>
2234 std::index_sequence<Is...>) const {
2235 // Apply all tuple elements to the builder in order.
2236 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2237 (void)Dummy;
2238 }
2239
2240 public:
2241 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2242 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2243 assert(DiagID != 0 && "no diagnostic for type diagnoser");
2244 }
2245
2246 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2247 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2248 emit(DB, std::index_sequence_for<Ts...>());
2249 DB << T;
2250 }
2251 };
2252
2253 /// Do a check to make sure \p Name looks like a legal argument for the
2254 /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
2255 /// is invalid for the given declaration.
2256 ///
2257 /// \p AL is used to provide caret diagnostics in case of a malformed name.
2258 ///
2259 /// \returns true if the name is a valid swift name for \p D, false otherwise.
2260 bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2261 const ParsedAttr &AL, bool IsAsync);
2262
2263 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2264 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2265 /// For example, a diagnostic with no other parameters would generally have
2266 /// the form "...%select{incomplete|sizeless}0 type %1...".
2267 template <typename... Ts>
2269 public:
2270 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2271 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2272
2273 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2274 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2275 this->emit(DB, std::index_sequence_for<Ts...>());
2276 DB << T->isSizelessType() << T;
2277 }
2278 };
2279
2280 enum class CompleteTypeKind {
2281 /// Apply the normal rules for complete types. In particular,
2282 /// treat all sizeless types as incomplete.
2283 Normal,
2284
2285 /// Relax the normal rules for complete types so that they include
2286 /// sizeless built-in types.
2288
2289 // FIXME: Eventually we should flip the default to Normal and opt in
2290 // to AcceptSizeless rather than opt out of it.
2292 };
2293
2295
2296private:
2297 /// Methods for marking which expressions involve dereferencing a pointer
2298 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2299 /// they are parsed, meaning that a noderef pointer may not be accessed. For
2300 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2301 /// `*p`, but need to check that `address of` is called on it. This requires
2302 /// keeping a container of all pending expressions and checking if the address
2303 /// of them are eventually taken.
2304 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2305 void CheckAddressOfNoDeref(const Expr *E);
2306 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2307
2308 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2309 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2310
2311 struct ModuleScope {
2312 SourceLocation BeginLoc;
2313 clang::Module *Module = nullptr;
2314 VisibleModuleSet OuterVisibleModules;
2315 };
2316 /// The modules we're currently parsing.
2318
2319 /// For an interface unit, this is the implicitly imported interface unit.
2320 clang::Module *ThePrimaryInterface = nullptr;
2321
2322 /// The explicit global module fragment of the current translation unit.
2323 /// The explicit Global Module Fragment, as specified in C++
2324 /// [module.global.frag].
2325 clang::Module *TheGlobalModuleFragment = nullptr;
2326
2327 /// The implicit global module fragments of the current translation unit.
2328 ///
2329 /// The contents in the implicit global module fragment can't be discarded.
2330 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
2331
2332 /// Namespace definitions that we will export when they finish.
2333 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2334
2335 /// In a C++ standard module, inline declarations require a definition to be
2336 /// present at the end of a definition domain. This set holds the decls to
2337 /// be checked at the end of the TU.
2338 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
2339
2340 /// Helper function to judge if we are in module purview.
2341 /// Return false if we are not in a module.
2342 bool isCurrentModulePurview() const;
2343
2344 /// Enter the scope of the explicit global module fragment.
2345 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
2346 /// Leave the scope of the explicit global module fragment.
2347 void PopGlobalModuleFragment();
2348
2349 /// Enter the scope of an implicit global module fragment.
2350 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
2351 /// Leave the scope of an implicit global module fragment.
2352 void PopImplicitGlobalModuleFragment();
2353
2354 VisibleModuleSet VisibleModules;
2355
2356 /// Cache for module units which is usable for current module.
2357 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
2358
2359 bool isUsableModule(const Module *M);
2360
2361 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
2362
2363public:
2364 /// Get the module unit whose scope we are currently within.
2366 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2367 }
2368
2369 /// Is the module scope we are an implementation unit?
2371 return ModuleScopes.empty()
2372 ? false
2373 : ModuleScopes.back().Module->isModuleImplementation();
2374 }
2375
2376 /// Is the module scope we are in a C++ Header Unit?
2378 return ModuleScopes.empty() ? false
2379 : ModuleScopes.back().Module->isHeaderUnit();
2380 }
2381
2382 /// Get the module owning an entity.
2383 Module *getOwningModule(const Decl *Entity) {
2384 return Entity->getOwningModule();
2385 }
2386
2387 /// Make a merged definition of an existing hidden definition \p ND
2388 /// visible at the specified location.
2390
2391 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2392
2393 // When loading a non-modular PCH files, this is used to restore module
2394 // visibility.
2396 VisibleModules.setVisible(Mod, ImportLoc);
2397 }
2398
2399 /// Determine whether a declaration is visible to name lookup.
2400 bool isVisible(const NamedDecl *D) {
2401 return D->isUnconditionallyVisible() ||
2402 isAcceptableSlow(D, AcceptableKind::Visible);
2403 }
2404
2405 /// Determine whether a declaration is reachable.
2406 bool isReachable(const NamedDecl *D) {
2407 // All visible declarations are reachable.
2408 return D->isUnconditionallyVisible() ||
2409 isAcceptableSlow(D, AcceptableKind::Reachable);
2410 }
2411
2412 /// Determine whether a declaration is acceptable (visible/reachable).
2414 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
2415 }
2416
2417 /// Determine whether any declaration of an entity is visible.
2418 bool
2420 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2421 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2422 }
2423
2426 /// Determine whether any declaration of an entity is reachable.
2427 bool
2429 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2430 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
2431 }
2433 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2434
2435 bool hasVisibleMergedDefinition(const NamedDecl *Def);
2437
2438 /// Determine if \p D and \p Suggested have a structurally compatible
2439 /// layout as described in C11 6.2.7/1.
2440 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2441
2442 /// Determine if \p D has a visible definition. If not, suggest a declaration
2443 /// that should be made visible to expose the definition.
2444 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2445 bool OnlyNeedComplete = false);
2447 NamedDecl *Hidden;
2448 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2449 }
2450
2451 /// Determine if \p D has a reachable definition. If not, suggest a
2452 /// declaration that should be made reachable to expose the definition.
2453 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
2454 bool OnlyNeedComplete = false);
2456 NamedDecl *Hidden;
2457 return hasReachableDefinition(D, &Hidden);
2458 }
2459
2460 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
2461 AcceptableKind Kind,
2462 bool OnlyNeedComplete = false);
2464 NamedDecl *Hidden;
2465 return hasAcceptableDefinition(D, &Hidden, Kind);
2466 }
2467
2468 /// Determine if the template parameter \p D has a visible default argument.
2469 bool
2471 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2472 /// Determine if the template parameter \p D has a reachable default argument.
2474 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2475 /// Determine if the template parameter \p D has a reachable default argument.
2479
2480 /// Determine if there is a visible declaration of \p D that is an explicit
2481 /// specialization declaration for a specialization of a template. (For a
2482 /// member specialization, use hasVisibleMemberSpecialization.)
2484 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2485 /// Determine if there is a reachable declaration of \p D that is an explicit
2486 /// specialization declaration for a specialization of a template. (For a
2487 /// member specialization, use hasReachableMemberSpecialization.)
2489 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2490
2491 /// Determine if there is a visible declaration of \p D that is a member
2492 /// specialization declaration (as opposed to an instantiated declaration).
2494 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2495 /// Determine if there is a reachable declaration of \p D that is a member
2496 /// specialization declaration (as opposed to an instantiated declaration).
2498 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2499
2500 /// Determine if \p A and \p B are equivalent internal linkage declarations
2501 /// from different modules, and thus an ambiguity error can be downgraded to
2502 /// an extension warning.
2504 const NamedDecl *B);
2506 SourceLocation Loc, const NamedDecl *D,
2508
2510
2511 // Check whether the size of array element of type \p EltTy is a multiple of
2512 // its alignment and return false if it isn't.
2514
2517 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2518 }
2520 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2522 CompleteTypeKind Kind, unsigned DiagID);
2523
2525 TypeDiagnoser &Diagnoser) {
2526 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2527 }
2528 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2529 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2530 }
2531
2532 template <typename... Ts>
2533 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2534 const Ts &...Args) {
2535 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2536 return RequireCompleteType(Loc, T, Diagnoser);
2537 }
2538
2539 template <typename... Ts>
2541 const Ts &... Args) {
2542 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2543 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2544 }
2545
2546 /// Get the type of expression E, triggering instantiation to complete the
2547 /// type if necessary -- that is, if the expression refers to a templated
2548 /// static data member of incomplete array type.
2549 ///
2550 /// May still return an incomplete type if instantiation was not possible or
2551 /// if the type is incomplete for a different reason. Use
2552 /// RequireCompleteExprType instead if a diagnostic is expected for an
2553 /// incomplete expression type.
2555
2558 TypeDiagnoser &Diagnoser);
2559 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2560
2561 template <typename... Ts>
2562 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2563 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2565 }
2566
2567 template <typename... Ts>
2568 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2569 const Ts &... Args) {
2570 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2572 }
2573
2575 TypeDiagnoser &Diagnoser);
2576 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2577
2578 template <typename... Ts>
2579 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2580 const Ts &...Args) {
2581 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2582 return RequireLiteralType(Loc, T, Diagnoser);
2583 }
2584
2586 const CXXScopeSpec &SS, QualType T,
2587 TagDecl *OwnedTagDecl = nullptr);
2588
2589 // Returns the underlying type of a decltype with the given expression.
2591
2593 /// If AsUnevaluated is false, E is treated as though it were an evaluated
2594 /// context, such as when building a type for decltype(auto).
2595 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
2596
2599 SourceLocation Loc);
2605 SourceLocation Loc);
2607 SourceLocation Loc);
2609 SourceLocation Loc);
2611 SourceLocation Loc);
2613 SourceLocation Loc);
2614
2615 //===--------------------------------------------------------------------===//
2616 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2617 //
2618
2620 SkipBodyInfo() = default;
2621 bool ShouldSkip = false;
2624 NamedDecl *New = nullptr;
2625 };
2626
2627 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2628
2630
2631 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2632
2634 Scope *S, CXXScopeSpec *SS = nullptr,
2635 bool isClassName = false, bool HasTrailingDot = false,
2636 ParsedType ObjectType = nullptr,
2637 bool IsCtorOrDtorName = false,
2638 bool WantNontrivialTypeSourceInfo = false,
2639 bool IsClassTemplateDeductionContext = true,
2640 ImplicitTypenameContext AllowImplicitTypename =
2642 IdentifierInfo **CorrectedII = nullptr);
2644 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2646 SourceLocation IILoc,
2647 Scope *S,
2648 CXXScopeSpec *SS,
2649 ParsedType &SuggestedType,
2650 bool IsTemplateName = false);
2651
2652 /// Attempt to behave like MSVC in situations where lookup of an unqualified
2653 /// type name has failed in a dependent context. In these situations, we
2654 /// automatically form a DependentTypeName that will retry lookup in a related
2655 /// scope during instantiation.
2657 SourceLocation NameLoc,
2658 bool IsTemplateTypeArg);
2659
2660 /// Describes the result of the name lookup and resolution performed
2661 /// by \c ClassifyName().
2663 /// This name is not a type or template in this context, but might be
2664 /// something else.
2666 /// Classification failed; an error has been produced.
2668 /// The name has been typo-corrected to a keyword.
2670 /// The name was classified as a type.
2672 /// The name was classified as a specific non-type, non-template
2673 /// declaration. ActOnNameClassifiedAsNonType should be called to
2674 /// convert the declaration to an expression.
2676 /// The name was classified as an ADL-only function name.
2677 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2678 /// result to an expression.
2680 /// The name denotes a member of a dependent type that could not be
2681 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2682 /// convert the result to an expression.
2684 /// The name was classified as an overload set, and an expression
2685 /// representing that overload set has been formed.
2686 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2687 /// expression referencing the overload set.
2689 /// The name was classified as a template whose specializations are types.
2691 /// The name was classified as a variable template name.
2693 /// The name was classified as a function template name.
2695 /// The name was classified as an ADL-only function template name.
2697 /// The name was classified as a concept name.
2699 };
2700
2703 union {
2708 };
2709
2710 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2711
2712 public:
2714
2716
2719 }
2720
2723 }
2724
2727 Result.Expr = E;
2728 return Result;
2729 }
2730
2733 Result.NonTypeDecl = D;
2734 return Result;
2735 }
2736
2739 }
2740
2743 }
2744
2747 Result.Template = Name;
2748 return Result;
2749 }
2750
2753 Result.Template = Name;
2754 return Result;
2755 }
2756
2759 Result.Template = Name;
2760 return Result;
2761 }
2762
2765 Result.Template = Name;
2766 return Result;
2767 }
2768
2771 Result.Template = Name;
2772 return Result;
2773 }
2774
2775 NameClassificationKind getKind() const { return Kind; }
2776
2778 assert(Kind == NC_OverloadSet);
2779 return Expr;
2780 }
2781
2783 assert(Kind == NC_Type);
2784 return Type;
2785 }
2786
2788 assert(Kind == NC_NonType);
2789 return NonTypeDecl;
2790 }
2791
2793 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2794 Kind == NC_VarTemplate || Kind == NC_Concept ||
2795 Kind == NC_UndeclaredTemplate);
2796 return Template;
2797 }
2798
2800 switch (Kind) {
2801 case NC_TypeTemplate:
2802 return TNK_Type_template;
2804 return TNK_Function_template;
2805 case NC_VarTemplate:
2806 return TNK_Var_template;
2807 case NC_Concept:
2808 return TNK_Concept_template;
2811 default:
2812 llvm_unreachable("unsupported name classification.");
2813 }
2814 }
2815 };
2816
2817 /// Perform name lookup on the given name, classifying it based on
2818 /// the results of name lookup and the following token.
2819 ///
2820 /// This routine is used by the parser to resolve identifiers and help direct
2821 /// parsing. When the identifier cannot be found, this routine will attempt
2822 /// to correct the typo and classify based on the resulting name.
2823 ///
2824 /// \param S The scope in which we're performing name lookup.
2825 ///
2826 /// \param SS The nested-name-specifier that precedes the name.
2827 ///
2828 /// \param Name The identifier. If typo correction finds an alternative name,
2829 /// this pointer parameter will be updated accordingly.
2830 ///
2831 /// \param NameLoc The location of the identifier.
2832 ///
2833 /// \param NextToken The token following the identifier. Used to help
2834 /// disambiguate the name.
2835 ///
2836 /// \param CCC The correction callback, if typo correction is desired.
2837 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2838 IdentifierInfo *&Name, SourceLocation NameLoc,
2839 const Token &NextToken,
2840 CorrectionCandidateCallback *CCC = nullptr);
2841
2842 /// Act on the result of classifying a name as an undeclared (ADL-only)
2843 /// non-type declaration.
2845 SourceLocation NameLoc);
2846 /// Act on the result of classifying a name as an undeclared member of a
2847 /// dependent base class.
2849 IdentifierInfo *Name,
2850 SourceLocation NameLoc,
2851 bool IsAddressOfOperand);
2852 /// Act on the result of classifying a name as a specific non-type
2853 /// declaration.
2855 NamedDecl *Found,
2856 SourceLocation NameLoc,
2857 const Token &NextToken);
2858 /// Act on the result of classifying a name as an overload set.
2860
2861 /// Describes the detailed kind of a template name. Used in diagnostics.
2868 Concept,
2870 };
2873
2874 /// Determine whether it's plausible that E was intended to be a
2875 /// template-name.
2877 if (!getLangOpts().CPlusPlus || E.isInvalid())
2878 return false;
2879 Dependent = false;
2880 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2881 return !DRE->hasExplicitTemplateArgs();
2882 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2883 return !ME->hasExplicitTemplateArgs();
2884 Dependent = true;
2885 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2886 return !DSDRE->hasExplicitTemplateArgs();
2887 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2888 return !DSME->hasExplicitTemplateArgs();
2889 // Any additional cases recognized here should also be handled by
2890 // diagnoseExprIntendedAsTemplateName.
2891 return false;
2892 }
2896
2897 void warnOnReservedIdentifier(const NamedDecl *D);
2898
2900
2902 MultiTemplateParamsArg TemplateParameterLists);
2904 QualType &T, SourceLocation Loc,
2905 unsigned FailedFoldDiagID);
2910 bool IsTemplateId);
2911 void
2912 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2913 SourceLocation FallbackLoc,
2914 SourceLocation ConstQualLoc = SourceLocation(),
2915 SourceLocation VolatileQualLoc = SourceLocation(),
2916 SourceLocation RestrictQualLoc = SourceLocation(),
2917 SourceLocation AtomicQualLoc = SourceLocation(),
2918 SourceLocation UnalignedQualLoc = SourceLocation());
2919
2921 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2923 const LookupResult &R);
2926 const LookupResult &R);
2927 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2928 const LookupResult &R);
2929 void CheckShadow(Scope *S, VarDecl *D);
2930
2931 /// Warn if 'E', which is an expression that is about to be modified, refers
2932 /// to a shadowing declaration.
2934
2936
2937private:
2938 /// Map of current shadowing declarations to shadowed declarations. Warn if
2939 /// it looks like the user is trying to modify the shadowing declaration.
2940 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2941
2942public:
2943 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2944 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2945 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2946 TypedefNameDecl *NewTD);
2949 TypeSourceInfo *TInfo,
2952 LookupResult &Previous, bool &Redeclaration);
2954 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
2955 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
2956 bool &AddToScope, ArrayRef<BindingDecl *> Bindings = std::nullopt);
2957 NamedDecl *
2959 MultiTemplateParamsArg TemplateParamLists);
2962 RecordDecl *ClassDecl,
2963 const IdentifierInfo *Name);
2964 // Returns true if the variable declaration is a redeclaration
2968 Expr *Init);
2972
2974 TypeSourceInfo *TInfo,
2976 MultiTemplateParamsArg TemplateParamLists,
2977 bool &AddToScope);
2979
2981 /// Diagnose issues that are non-constant or that are extensions.
2982 Diagnose,
2983 /// Identify whether this function satisfies the formal rules for constexpr
2984 /// functions in the current lanugage mode (with no extensions).
2986 };
2987
2989 CheckConstexprKind Kind);
2990
2993 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2995 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2996 // Returns true if the function declaration is a redeclaration
2999 bool IsMemberSpecialization, bool DeclIsDefn);
3002 QualType NewT, QualType OldT);
3003 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
3007 void CheckHLSLSemanticAnnotation(FunctionDecl *EntryPoint, const Decl *Param,
3008 const HLSLAnnotationAttr *AnnotationAttr);
3010 const Attr *A, HLSLShaderAttr::ShaderType Stage,
3011 std::initializer_list<HLSLShaderAttr::ShaderType> AllowedStages);
3013 bool IsDefinition);
3016 SourceLocation ExplicitThisLoc = {});
3017 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
3018 SourceLocation Loc,
3019 QualType T);
3020 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
3021 SourceLocation NameLoc, IdentifierInfo *Name,
3022 QualType T, TypeSourceInfo *TSInfo,
3023 StorageClass SC);
3024 void ActOnParamDefaultArgument(Decl *param,
3025 SourceLocation EqualLoc,
3026 Expr *defarg);
3027 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
3028 SourceLocation ArgLoc);
3029 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
3030 Expr* DefaultArg);
3031 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
3032 SourceLocation EqualLoc);
3033 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
3034 SourceLocation EqualLoc);
3035
3036 // Contexts where using non-trivial C union types can be disallowed. This is
3037 // passed to err_non_trivial_c_union_in_invalid_context.
3039 // Function parameter.
3041 // Function return.
3043 // Default-initialized object.
3045 // Variable with automatic storage duration.
3047 // Initializer expression that might copy from another object.
3049 // Assignment.
3051 // Compound literal.
3053 // Block capture.
3055 // lvalue-to-rvalue conversion of volatile type.
3057 };
3058
3059 /// Emit diagnostics if the initializer or any of its explicit or
3060 /// implicitly-generated subexpressions require copying or
3061 /// default-initializing a type that is or contains a C union type that is
3062 /// non-trivial to copy or default-initialize.
3064
3065 // These flags are passed to checkNonTrivialCUnion.
3070 };
3071
3072 /// Emit diagnostics if a non-trivial C union type or a struct that contains
3073 /// a non-trivial C union is used in an invalid context.
3075 NonTrivialCUnionContext UseContext,
3076 unsigned NonTrivialKind);
3077
3078 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
3079 void ActOnUninitializedDecl(Decl *dcl);
3080 void ActOnInitializerError(Decl *Dcl);
3081
3082 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
3083 void ActOnCXXForRangeDecl(Decl *D);
3085 IdentifierInfo *Ident,
3086 ParsedAttributes &Attrs);
3087 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
3088 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
3091 void FinalizeDeclaration(Decl *D);
3093 ArrayRef<Decl *> Group);
3095
3096 /// Should be called on all declarations that might have attached
3097 /// documentation comments.
3098 void ActOnDocumentableDecl(Decl *D);
3100
3101 enum class FnBodyKind {
3102 /// C++ [dcl.fct.def.general]p1
3103 /// function-body:
3104 /// ctor-initializer[opt] compound-statement
3105 /// function-try-block
3106 Other,
3107 /// = default ;
3108 Default,
3109 /// = delete ;
3110 Delete
3111 };
3112
3114 SourceLocation LocAfterDecls);
3116 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
3117 SkipBodyInfo *SkipBody = nullptr);
3119 MultiTemplateParamsArg TemplateParamLists,
3120 SkipBodyInfo *SkipBody = nullptr,
3121 FnBodyKind BodyKind = FnBodyKind::Other);
3123 SkipBodyInfo *SkipBody = nullptr,
3124 FnBodyKind BodyKind = FnBodyKind::Other);
3125 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind);
3131 return D && isa<ObjCMethodDecl>(D);
3132 }
3133
3134 /// Determine whether we can delay parsing the body of a function or
3135 /// function template until it is used, assuming we don't care about emitting
3136 /// code for that function.
3137 ///
3138 /// This will be \c false if we may need the body of the function in the
3139 /// middle of parsing an expression (where it's impractical to switch to
3140 /// parsing a different function), for instance, if it's constexpr in C++11
3141 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
3142 bool canDelayFunctionBody(const Declarator &D);
3143
3144 /// Determine whether we can skip parsing the body of a function
3145 /// definition, assuming we don't care about analyzing its body or emitting
3146 /// code for that function.
3147 ///
3148 /// This will be \c false only if we may need the body of the function in
3149 /// order to parse the rest of the program (for instance, if it is
3150 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
3151 bool canSkipFunctionBody(Decl *D);
3152
3153 /// Determine whether \param D is function like (function or function
3154 /// template) for parsing.
3156
3159 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
3162
3163 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
3164 /// attribute for which parsing is delayed.
3166
3167 /// Diagnose any unused parameters in the given sequence of
3168 /// ParmVarDecl pointers.
3170
3171 /// Diagnose whether the size of parameters or return value of a
3172 /// function or obj-c method definition is pass-by-value and larger than a
3173 /// specified threshold.
3174 void
3176 QualType ReturnTy, NamedDecl *D);
3177
3178 void DiagnoseInvalidJumps(Stmt *Body);
3180 SourceLocation AsmLoc,
3181 SourceLocation RParenLoc);
3182
3183 Decl *ActOnTopLevelStmtDecl(Stmt *Statement);
3184
3185 /// Handle a C++11 empty-declaration and attribute-declaration.
3187 SourceLocation SemiLoc);
3188
3189 enum class ModuleDeclKind {
3190 Interface, ///< 'export module X;'
3191 Implementation, ///< 'module X;'
3192 PartitionInterface, ///< 'export module X:Y;'
3193 PartitionImplementation, ///< 'module X:Y;'
3194 };
3195
3196 /// An enumeration to represent the transition of states in parsing module
3197 /// fragments and imports. If we are not parsing a C++20 TU, or we find
3198 /// an error in state transition, the state is set to NotACXX20Module.
3200 FirstDecl, ///< Parsing the first decl in a TU.
3201 GlobalFragment, ///< after 'module;' but before 'module X;'
3202 ImportAllowed, ///< after 'module X;' but before any non-import decl.
3203 ImportFinished, ///< after any non-import decl.
3204 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
3205 ///< non-import decl.
3206 PrivateFragmentImportFinished, ///< after 'module :private;' but a
3207 ///< non-import decl has already been seen.
3208 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
3209 };
3210
3211private:
3212 /// The parser has begun a translation unit to be compiled as a C++20
3213 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
3214 void HandleStartOfHeaderUnit();
3215
3216public:
3217 /// The parser has processed a module-declaration that begins the definition
3218 /// of a module interface or implementation.
3220 SourceLocation ModuleLoc, ModuleDeclKind MDK,
3221 ModuleIdPath Path, ModuleIdPath Partition,
3222 ModuleImportState &ImportState);
3223
3224 /// The parser has processed a global-module-fragment declaration that begins
3225 /// the definition of the global module fragment of the current module unit.
3226 /// \param ModuleLoc The location of the 'module' keyword.
3228
3229 /// The parser has processed a private-module-fragment declaration that begins
3230 /// the definition of the private module fragment of the current module unit.
3231 /// \param ModuleLoc The location of the 'module' keyword.
3232 /// \param PrivateLoc The location of the 'private' keyword.
3234 SourceLocation PrivateLoc);
3235
3236 /// The parser has processed a module import declaration.
3237 ///
3238 /// \param StartLoc The location of the first token in the declaration. This
3239 /// could be the location of an '@', 'export', or 'import'.
3240 /// \param ExportLoc The location of the 'export' keyword, if any.
3241 /// \param ImportLoc The location of the 'import' keyword.
3242 /// \param Path The module toplevel name as an access path.
3243 /// \param IsPartition If the name is for a partition.
3245 SourceLocation ExportLoc,
3246 SourceLocation ImportLoc, ModuleIdPath Path,
3247 bool IsPartition = false);
3249 SourceLocation ExportLoc,
3250 SourceLocation ImportLoc, Module *M,
3251 ModuleIdPath Path = {});
3252
3253 /// The parser has processed a module import translated from a
3254 /// #include or similar preprocessing directive.
3255 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3256 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3257
3258 /// The parsed has entered a submodule.
3259 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
3260 /// The parser has left a submodule.
3261 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
3262
3263 /// Create an implicit import of the given module at the given
3264 /// source location, for error recovery, if possible.
3265 ///
3266 /// This routine is typically used when an entity found by name lookup
3267 /// is actually hidden within a module that we know about but the user
3268 /// has forgotten to import.
3269 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
3270 Module *Mod);
3271
3272 /// Kinds of missing import. Note, the values of these enumerators correspond
3273 /// to %select values in diagnostics.
3276 Definition,
3280 };
3281
3282 /// Diagnose that the specified declaration needs to be visible but
3283 /// isn't, and suggest a module import that would resolve the problem.
3285 MissingImportKind MIK, bool Recover = true);
3287 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
3288 MissingImportKind MIK, bool Recover);
3289
3291 SourceLocation LBraceLoc);
3293 SourceLocation RBraceLoc);
3294
3295 /// We've found a use of a templated declaration that would trigger an
3296 /// implicit instantiation. Check that any relevant explicit specializations
3297 /// and partial specializations are visible/reachable, and diagnose if not.
3300
3301 /// Retrieve a suitable printing policy for diagnostics.
3303 return getPrintingPolicy(Context, PP);
3304 }
3305
3306 /// Retrieve a suitable printing policy for diagnostics.
3308 const Preprocessor &PP);
3309
3310 /// Scope actions.
3311 void ActOnPopScope(SourceLocation Loc, Scope *S);
3313
3315 const ParsedAttributesView &DeclAttrs,
3316 RecordDecl *&AnonRecord);
3318 const ParsedAttributesView &DeclAttrs,
3319 MultiTemplateParamsArg TemplateParams,
3320 bool IsExplicitInstantiation,
3321 RecordDecl *&AnonRecord);
3322
3324 AccessSpecifier AS,
3325 RecordDecl *Record,
3326 const PrintingPolicy &Policy);
3327
3328 /// Called once it is known whether
3329 /// a tag declaration is an anonymous union or struct.
3331
3333
3335 RecordDecl *Record);
3336
3337 /// Common ways to introduce type names without a tag for use in diagnostics.
3338 /// Keep in sync with err_tag_reference_non_tag.
3349 };
3350
3351 /// Given a non-tag type declaration, returns an enum useful for indicating
3352 /// what kind of non-tag type this is.
3354
3356 TagTypeKind NewTag, bool isDefinition,
3357 SourceLocation NewTagLoc,
3358 const IdentifierInfo *Name);
3359
3361 TUK_Reference, // Reference to a tag: 'struct foo *X;'
3362 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
3363 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
3364 TUK_Friend // Friend declaration: 'friend struct foo;'
3366
3368 // Not parsing a type within __builtin_offsetof.
3370 // Parsing a type within __builtin_offsetof.
3372 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
3373 // To improve our diagnostic message.
3375 };
3376
3377 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3378 SourceLocation KWLoc, CXXScopeSpec &SS,
3379 IdentifierInfo *Name, SourceLocation NameLoc,
3381 SourceLocation ModulePrivateLoc,
3382 MultiTemplateParamsArg TemplateParameterLists,
3383 bool &OwnedDecl, bool &IsDependent,
3384 SourceLocation ScopedEnumKWLoc,
3385 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3386 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3387 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
3388
3390 unsigned TagSpec, SourceLocation TagLoc,
3391 CXXScopeSpec &SS, IdentifierInfo *Name,
3392 SourceLocation NameLoc,
3394 MultiTemplateParamsArg TempParamLists);
3395
3397 unsigned TagSpec,
3398 TagUseKind TUK,
3399 const CXXScopeSpec &SS,
3400 IdentifierInfo *Name,
3401 SourceLocation TagLoc,
3402 SourceLocation NameLoc);
3403
3404 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3405 IdentifierInfo *ClassName,
3407 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3408 Declarator &D, Expr *BitfieldWidth);
3409
3410 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3411 Declarator &D, Expr *BitfieldWidth,
3412 InClassInitStyle InitStyle,
3413 AccessSpecifier AS);
3415 SourceLocation DeclStart, Declarator &D,
3416 Expr *BitfieldWidth,
3417 InClassInitStyle InitStyle,
3418 AccessSpecifier AS,
3419 const ParsedAttr &MSPropertyAttr);
3420
3422 TypeSourceInfo *TInfo,
3423 RecordDecl *Record, SourceLocation Loc,
3424 bool Mutable, Expr *BitfieldWidth,
3425 InClassInitStyle InitStyle,
3426 SourceLocation TSSL,
3427 AccessSpecifier AS, NamedDecl *PrevDecl,
3428 Declarator *D = nullptr);
3429
3431 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3432
3434 /// The triviality of a method unaffected by "trivial_abi".
3436
3437 /// The triviality of a method affected by "trivial_abi".
3440
3443 bool Diagnose = false);
3444
3445 /// For a defaulted function, the kind of defaulted function that it is.
3447 CXXSpecialMember SpecialMember : 8;
3448 DefaultedComparisonKind Comparison : 8;
3449
3450 public:
3452 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3453 }
3455 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3457 : SpecialMember(CXXInvalid), Comparison(Comp) {}
3458
3459 bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3460 bool isComparison() const {
3461 return Comparison != DefaultedComparisonKind::None;
3462 }
3463
3464 explicit operator bool() const {
3465 return isSpecialMember() || isComparison();
3466 }
3467
3468 CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3469 DefaultedComparisonKind asComparison() const { return Comparison; }
3470
3471 /// Get the index of this function kind for use in diagnostics.
3472 unsigned getDiagnosticIndex() const {
3473 static_assert(CXXInvalid > CXXDestructor,
3474 "invalid should have highest index");
3475 static_assert((unsigned)DefaultedComparisonKind::None == 0,
3476 "none should be equal to zero");
3477 return SpecialMember + (unsigned)Comparison;
3478 }
3479 };
3480
3481 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3482
3485 }
3488 }
3489
3490 void ActOnLastBitfield(SourceLocation DeclStart,
3491 SmallVectorImpl<Decl *> &AllIvarDecls);
3492 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D,
3493 Expr *BitWidth, tok::ObjCKeywordKind visibility);
3494
3495 // This is used for both record definitions and ObjC interface declarations.
3496 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3497 ArrayRef<Decl *> Fields, SourceLocation LBrac,
3498 SourceLocation RBrac, const ParsedAttributesView &AttrList);
3499
3500 /// ActOnTagStartDefinition - Invoked when we have entered the
3501 /// scope of a tag's definition (e.g., for an enumeration, class,
3502 /// struct, or union).
3504
3505 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3506 /// Differently from C++, actually parse the body and reject / error out
3507 /// in case of a structural mismatch.
3508 bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3509
3510 /// Check ODR hashes for C/ObjC when merging types from modules.
3511 /// Differently from C++, actually parse the body and reject in case
3512 /// of a mismatch.
3513 template <typename T,
3514 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
3516 if (Duplicate->getODRHash() != Previous->getODRHash())
3517 return false;
3518
3519 // Make the previous decl visible.
3521 return true;
3522 }
3523
3525
3526 /// Invoked when we enter a tag definition that we're skipping.
3528
3530
3531 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3532 /// C++ record definition's base-specifiers clause and are starting its
3533 /// member declarations.
3535 SourceLocation FinalLoc,
3536 bool IsFinalSpelledSealed,
3537 bool IsAbstract,
3538 SourceLocation LBraceLoc);
3539
3540 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3541 /// the definition of a tag (enumeration, class, struct, or union).
3543 SourceRange BraceRange);
3544
3546
3548
3549 /// Invoked when we must temporarily exit the objective-c container
3550 /// scope for parsing/looking-up C constructs.
3551 ///
3552 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3555
3556 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3557 /// error parsing the definition of a tag.
3559
3561 EnumConstantDecl *LastEnumConst,
3562 SourceLocation IdLoc,
3564 Expr *val);
3566 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3567 QualType EnumUnderlyingTy, bool IsFixed,
3568 const EnumDecl *Prev);
3569
3570 /// Determine whether the body of an anonymous enumeration should be skipped.
3571 /// \param II The name of the first enumerator.
3573 SourceLocation IILoc);
3574
3575 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3577 const ParsedAttributesView &Attrs,
3578 SourceLocation EqualLoc, Expr *Val);
3579 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3580 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3581 const ParsedAttributesView &Attr);
3582
3583 /// Set the current declaration context until it gets popped.
3584 void PushDeclContext(Scope *S, DeclContext *DC);
3585 void PopDeclContext();
3586
3587 /// EnterDeclaratorContext - Used when we must lookup names in the context
3588 /// of a declarator's nested name specifier.
3591
3592 /// Enter a template parameter scope, after it's been associated with a particular
3593 /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3594 /// in the correct order.
3596
3597 /// Push the parameters of D, which must be a function, into scope.
3600
3601 /// If \p AllowLambda is true, treat lambda as function.
3602 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
3603
3604 /// Returns a pointer to the innermost enclosing function, or nullptr if the
3605 /// current context is not inside a function. If \p AllowLambda is true,
3606 /// this can return the call operator of an enclosing lambda, otherwise
3607 /// lambdas are skipped when looking for an enclosing function.
3608 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
3609
3610 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3611 /// the method decl for the method being parsed. If we're currently
3612 /// in a 'block', this returns the containing context.
3614
3615 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3616 /// or C function we're in, otherwise return null. If we're currently
3617 /// in a 'block', this returns the containing context.
3619
3620 /// Add this decl to the scope shadowed decl chains.
3621 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3622
3623 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3624 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3625 /// true if 'D' belongs to the given declaration context.
3626 ///
3627 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3628 /// enclosing namespace set of the context, rather than contained
3629 /// directly within it.
3630 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3631 bool AllowInlineNamespace = false) const;
3632
3633 /// Finds the scope corresponding to the given decl context, if it
3634 /// happens to be an enclosing scope. Otherwise return NULL.
3636
3637 /// Subroutines of ActOnDeclarator().
3639 TypeSourceInfo *TInfo);
3641
3642 /// Describes the kind of merge to perform for availability
3643 /// attributes (including "deprecated", "unavailable", and "availability").
3645 /// Don't merge availability attributes at all.
3647 /// Merge availability attributes for a redeclaration, which requires
3648 /// an exact match.
3650 /// Merge availability attributes for an override, which requires
3651 /// an exact match or a weakening of constraints.
3653 /// Merge availability attributes for an implementation of
3654 /// a protocol requirement.
3656 /// Merge availability attributes for an implementation of
3657 /// an optional protocol requirement.
3660
3661 /// Describes the kind of priority given to an availability attribute.
3662 ///
3663 /// The sum of priorities deteremines the final priority of the attribute.
3664 /// The final priority determines how the attribute will be merged.
3665 /// An attribute with a lower priority will always remove higher priority
3666 /// attributes for the specified platform when it is being applied. An
3667 /// attribute with a higher priority will not be applied if the declaration
3668 /// already has an availability attribute with a lower priority for the
3669 /// specified platform. The final prirority values are not expected to match
3670 /// the values in this enumeration, but instead should be treated as a plain
3671 /// integer value. This enumeration just names the priority weights that are
3672 /// used to calculate that final vaue.
3674 /// The availability attribute was specified explicitly next to the
3675 /// declaration.
3677
3678 /// The availability attribute was applied using '#pragma clang attribute'.
3680
3681 /// The availability attribute for a specific platform was inferred from
3682 /// an availability attribute for another platform.
3685
3686 /// Attribute merging methods. Return true if a new attribute was added.
3687 AvailabilityAttr *
3689 IdentifierInfo *Platform, bool Implicit,
3690 VersionTuple Introduced, VersionTuple Deprecated,
3691 VersionTuple Obsoleted, bool IsUnavailable,
3692 StringRef Message, bool IsStrict, StringRef Replacement,
3694 TypeVisibilityAttr *
3696 TypeVisibilityAttr::VisibilityType Vis);
3697 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3698 VisibilityAttr::VisibilityType Vis);
3699 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3700 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3701 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3702 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3703 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3704 const AttributeCommonInfo &CI,
3705 bool BestCase,
3706 MSInheritanceModel Model);
3707 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3708 StringRef NewUserDiagnostic);
3709 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3710 IdentifierInfo *Format, int FormatIdx,
3711 int FirstArg);
3712 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3713 StringRef Name);
3714 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3715 StringRef Name);
3716 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3717 const AttributeCommonInfo &CI,
3718 const IdentifierInfo *Ident);
3719 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3720 SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3721 StringRef Name);
3722 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3723 const AttributeCommonInfo &CI);
3724 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3725 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3726 const InternalLinkageAttr &AL);
3727 WebAssemblyImportNameAttr *mergeImportNameAttr(
3728 Decl *D, const WebAssemblyImportNameAttr &AL);
3729 WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3730 Decl *D, const WebAssemblyImportModuleAttr &AL);
3731 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3732 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3733 const EnforceTCBLeafAttr &AL);
3734 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
3735 HLSLNumThreadsAttr *mergeHLSLNumThreadsAttr(Decl *D,
3736 const AttributeCommonInfo &AL,
3737 int X, int Y, int Z);
3738 HLSLShaderAttr *mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL,
3739 HLSLShaderAttr::ShaderType ShaderType);
3740 HLSLParamModifierAttr *
3742 HLSLParamModifierAttr::Spelling Spelling);
3743
3744 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3747 LookupResult &OldDecls);
3748 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3749 bool MergeTypeWithOld, bool NewDeclIsDefn);
3751 Scope *S, bool MergeTypeWithOld);
3754 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3756 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3757 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3759
3760 // AssignmentAction - This is used by all the assignment diagnostic functions
3761 // to represent what is actually causing the operation
3772
3773 /// C++ Overloading.
3775 /// This is a legitimate overload: the existing declarations are
3776 /// functions or function templates with different signatures.
3778
3779 /// This is not an overload because the signature exactly matches
3780 /// an existing declaration.
3782
3783 /// This is not an overload because the lookup results contain a
3784 /// non-function.
3788 FunctionDecl *New,
3789 const LookupResult &OldDecls,
3790 NamedDecl *&OldDecl,
3791 bool UseMemberUsingDeclRules);
3792 bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
3793 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
3794
3795 // Checks whether MD constitutes an override the base class method BaseMD.
3796 // When checking for overrides, the object object members are ignored.
3797 bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
3798 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
3799
3800 // Calculates whether the expression Constraint depends on an enclosing
3801 // template, for the purposes of [temp.friend] p9.
3802 // TemplateDepth is the 'depth' of the friend function, which is used to
3803 // compare whether a declaration reference is referring to a containing
3804 // template, or just the current friend function. A 'lower' TemplateDepth in
3805 // the AST refers to a 'containing' template. As the constraint is
3806 // uninstantiated, this is relative to the 'top' of the TU.
3807 bool
3809 unsigned TemplateDepth,
3810 const Expr *Constraint);
3811
3812 // Calculates whether the friend function depends on an enclosing template for
3813 // the purposes of [temp.friend] p9.
3815
3816 enum class AllowedExplicit {
3817 /// Allow no explicit functions to be used.
3818 None,
3819 /// Allow explicit conversion functions but not explicit constructors.
3821 /// Allow both explicit conversion functions and explicit constructors.
3822 All
3823 };
3824
3826 TryImplicitConversion(Expr *From, QualType ToType,
3827 bool SuppressUserConversions,
3828 AllowedExplicit AllowExplicit,
3829 bool InOverloadResolution,
3830 bool CStyle,
3831 bool AllowObjCWritebackConversion);
3832
3833 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3834 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3835 bool IsComplexPromotion(QualType FromType, QualType ToType);
3836 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3837 bool InOverloadResolution,
3838 QualType& ConvertedType, bool &IncompatibleObjC);
3839 bool isObjCPointerConversion(QualType FromType, QualType ToType,
3840 QualType& ConvertedType, bool &IncompatibleObjC);
3841 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3842 QualType &ConvertedType);
3843 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3844 QualType& ConvertedType);
3845
3848 unsigned *ArgPos = nullptr,
3849 bool Reversed = false);
3850
3852 const FunctionProtoType *NewType,
3853 unsigned *ArgPos = nullptr,
3854 bool Reversed = false);
3855
3856 bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3857 const FunctionDecl *NewFunction,
3858 unsigned *ArgPos = nullptr,
3859 bool Reversed = false);
3860
3862 QualType FromType, QualType ToType);
3863
3866 bool CheckPointerConversion(Expr *From, QualType ToType,
3867 CastKind &Kind,
3868 CXXCastPath& BasePath,
3869 bool IgnoreBaseAccess,
3870 bool Diagnose = true);
3871 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3872 bool InOverloadResolution,
3873 QualType &ConvertedType);
3874 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3875 CastKind &Kind,
3876 CXXCastPath &BasePath,
3877 bool IgnoreBaseAccess);
3878 bool IsQualificationConversion(QualType FromType, QualType ToType,
3879 bool CStyle, bool &ObjCLifetimeConversion);
3880 bool IsFunctionConversion(QualType FromType, QualType ToType,
3881 QualType &ResultTy);
3884
3886 const InitializedEntity &Entity, InitListExpr *From);
3887
3888 bool IsStringInit(Expr *Init, const ArrayType *AT);
3889
3893 SourceLocation EqualLoc,
3895 bool TopLevelOfInitList = false,
3896 bool AllowExplicit = false);
3898 FunctionDecl *Fun);
3900 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
3901 CXXMethodDecl *Method);
3902
3903 /// Check that the lifetime of the initializer (and its subobjects) is
3904 /// sufficient for initializing the entity, and perform lifetime extension
3905 /// (when permitted) if not.
3907
3910
3911 /// Contexts in which a converted constant expression is required.
3912 enum CCEKind {
3913 CCEK_CaseValue, ///< Expression in a case label.
3914 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
3915 CCEK_TemplateArg, ///< Value of a non-type template parameter.
3916 CCEK_ArrayBound, ///< Array bound in array declarator or new-expression.
3917 CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier.
3918 CCEK_Noexcept, ///< Condition in a noexcept(bool) specifier.
3919 CCEK_StaticAssertMessageSize, ///< Call to size() in a static assert
3920 ///< message.
3921 CCEK_StaticAssertMessageData, ///< Call to data() in a static assert
3922 ///< message.
3923 };
3924
3926 CCEKind CCE,
3927 NamedDecl *Dest = nullptr);
3928
3930 llvm::APSInt &Value, CCEKind CCE);
3932 APValue &Value, CCEKind CCE,
3933 NamedDecl *Dest = nullptr);
3934
3937 CCEKind CCE, bool RequireInt,
3938 const APValue &PreNarrowingValue);
3939
3940 /// Abstract base class used to perform a contextual implicit
3941 /// conversion from an expression to any type passing a filter.
3943 public:
3946
3948 bool SuppressConversion = false)
3950
3951 /// Determine whether the specified type is a valid destination type
3952 /// for this conversion.
3953 virtual bool match(QualType T) = 0;
3954
3955 /// Emits a diagnostic complaining that the expression does not have
3956 /// integral or enumeration type.
3957 virtual SemaDiagnosticBuilder
3959
3960 /// Emits a diagnostic when the expression has incomplete class type.
3961 virtual SemaDiagnosticBuilder
3963
3964 /// Emits a diagnostic when the only matching conversion function
3965 /// is explicit.
3967 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3968
3969 /// Emits a note for the explicit conversion function.
3970 virtual SemaDiagnosticBuilder
3972
3973 /// Emits a diagnostic when there are multiple possible conversion
3974 /// functions.
3975 virtual SemaDiagnosticBuilder
3977
3978 /// Emits a note for one of the candidate conversions.
3979 virtual SemaDiagnosticBuilder
3981
3982 /// Emits a diagnostic when we picked a conversion function
3983 /// (for cases when we are not allowed to pick a conversion function).
3985 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3986
3988 };
3989
3991 bool AllowScopedEnumerations;
3992
3993 public:
3994 ICEConvertDiagnoser(bool AllowScopedEnumerations,
3995 bool Suppress, bool SuppressConversion)
3997 AllowScopedEnumerations(AllowScopedEnumerations) {}
3998
3999 /// Match an integral or (possibly scoped) enumeration type.
4000 bool match(QualType T) override;
4001
4004 return diagnoseNotInt(S, Loc, T);
4005 }
4006
4007 /// Emits a diagnostic complaining that the expression does not have
4008 /// integral or enumeration type.
4009 virtual SemaDiagnosticBuilder
4011 };
4012
4013 /// Perform a contextual implicit conversion.
4015 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
4016
4017
4021 OS_Error
4024
4025 // Note that LK_String is intentionally after the other literals, as
4026 // this is used for diagnostics logic.
4034 LK_None
4037
4039 NestedNameSpecifier *Qualifier,
4040 NamedDecl *FoundDecl,
4041 NamedDecl *Member);
4042
4043 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
4044 // TODO: make this is a typesafe union.
4047
4049
4052 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
4053 bool PartialOverloading = false, bool AllowExplicit = true,
4054 bool AllowExplicitConversion = false,
4055 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
4056 ConversionSequenceList EarlyConversions = std::nullopt,
4058 bool AggregateCandidateDeduction = false);
4059 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
4060 ArrayRef<Expr *> Args,
4061 OverloadCandidateSet &CandidateSet,
4062 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4063 bool SuppressUserConversions = false,
4064 bool PartialOverloading = false,
4065 bool FirstArgumentIsBase = false);
4066 void AddMethodCandidate(DeclAccessPair FoundDecl,
4067 QualType ObjectType,
4068 Expr::Classification ObjectClassification,
4069 ArrayRef<Expr *> Args,
4070 OverloadCandidateSet& CandidateSet,
4071 bool SuppressUserConversion = false,
4073 void
4074 AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
4075 CXXRecordDecl *ActingContext, QualType ObjectType,
4076 Expr::Classification ObjectClassification,
4077 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
4078 bool SuppressUserConversions = false,
4079 bool PartialOverloading = false,
4080 ConversionSequenceList EarlyConversions = std::nullopt,
4082 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
4083 DeclAccessPair FoundDecl,
4084 CXXRecordDecl *ActingContext,
4085 TemplateArgumentListInfo *ExplicitTemplateArgs,
4086 QualType ObjectType,
4087 Expr::Classification ObjectClassification,
4088 ArrayRef<Expr *> Args,
4089 OverloadCandidateSet& CandidateSet,
4090 bool SuppressUserConversions = false,
4091 bool PartialOverloading = false,
4094 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
4095 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4096 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
4097 bool PartialOverloading = false, bool AllowExplicit = true,
4098 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
4100 bool AggregateCandidateDeduction = false);
4102 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
4103 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
4104 ConversionSequenceList &Conversions, bool SuppressUserConversions,
4105 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
4106 Expr::Classification ObjectClassification = {},
4109 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
4110 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
4111 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
4112 bool AllowExplicit, bool AllowResultConversion = true);
4114 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
4115 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
4116 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
4117 bool AllowExplicit, bool AllowResultConversion = true);
4118 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
4119 DeclAccessPair FoundDecl,
4120 CXXRecordDecl *ActingContext,
4121 const FunctionProtoType *Proto,
4122 Expr *Object, ArrayRef<Expr *> Args,
4123 OverloadCandidateSet& CandidateSet);
4125 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
4126 OverloadCandidateSet &CandidateSet,
4127 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4129 SourceLocation OpLoc, ArrayRef<Expr *> Args,
4130 OverloadCandidateSet &CandidateSet,
4132 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
4133 OverloadCandidateSet& CandidateSet,
4134 bool IsAssignmentOperator = false,
4135 unsigned NumContextualBoolArguments = 0);
4137 SourceLocation OpLoc, ArrayRef<Expr *> Args,
4138 OverloadCandidateSet& CandidateSet);
4139 void AddArgumentDependentLookupCandidates(DeclarationName Name,
4140 SourceLocation Loc,
4141 ArrayRef<Expr *> Args,
4142 TemplateArgumentListInfo *ExplicitTemplateArgs,
4143 OverloadCandidateSet& CandidateSet,
4144 bool PartialOverloading = false);
4145
4146 // Emit as a 'note' the specific overload candidate
4148 const NamedDecl *Found, const FunctionDecl *Fn,
4150 QualType DestType = QualType(), bool TakingAddress = false);
4151
4152 // Emit as a series of 'note's all template and non-templates identified by
4153 // the expression Expr
4154 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
4155 bool TakingAddress = false);
4156
4157 /// Check the enable_if expressions on the given function. Returns the first
4158 /// failing attribute, or NULL if they were all successful.
4159 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
4160 ArrayRef<Expr *> Args,
4161 bool MissingImplicitThis = false);
4162
4163 /// Find the failed Boolean condition within a given Boolean
4164 /// constant expression, and describe it with a string.
4165 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
4166
4167 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
4168 /// non-ArgDependent DiagnoseIfAttrs.
4169 ///
4170 /// Argument-dependent diagnose_if attributes should be checked each time a
4171 /// function is used as a direct callee of a function call.
4172 ///
4173 /// Returns true if any errors were emitted.
4174 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
4175 const Expr *ThisArg,
4176 ArrayRef<const Expr *> Args,
4177 SourceLocation Loc);
4178
4179 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
4180 /// ArgDependent DiagnoseIfAttrs.
4181 ///
4182 /// Argument-independent diagnose_if attributes should be checked on every use
4183 /// of a function.
4184 ///
4185 /// Returns true if any errors were emitted.
4186 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
4187 SourceLocation Loc);
4188
4189 /// Returns whether the given function's address can be taken or not,
4190 /// optionally emitting a diagnostic if the address can't be taken.
4191 ///
4192 /// Returns false if taking the address of the function is illegal.
4193 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
4194 bool Complain = false,
4195 SourceLocation Loc = SourceLocation());
4196
4197 // [PossiblyAFunctionType] --> [Return]
4198 // NonFunctionType --> NonFunctionType
4199 // R (A) --> R(A)
4200 // R (*)(A) --> R (A)
4201 // R (&)(A) --> R (A)
4202 // R (S::*)(A) --> R (A)
4203 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
4204
4205 FunctionDecl *
4206 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
4207 QualType TargetType,
4208 bool Complain,
4209 DeclAccessPair &Found,
4210 bool *pHadMultipleCandidates = nullptr);
4211
4212 FunctionDecl *
4213 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
4214
4216 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
4217
4219 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
4220 TemplateSpecCandidateSet *FailedTSC = nullptr);
4221
4223 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
4224 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
4225 QualType DestTypeForComplaining = QualType(),
4226 unsigned DiagIDForComplaining = 0);
4227
4228 ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl,
4229 FunctionDecl *Fn);
4231 DeclAccessPair FoundDecl,
4232 FunctionDecl *Fn);
4233
4234 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
4235 ArrayRef<Expr *> Args,
4236 OverloadCandidateSet &CandidateSet,
4237 bool PartialOverloading = false);
4239 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
4240 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
4241
4242 // An enum used to represent the different possible results of building a
4243 // range-based for loop.
4249
4251 SourceLocation RangeLoc,
4252 const DeclarationNameInfo &NameInfo,
4253 LookupResult &MemberLookup,
4254 OverloadCandidateSet *CandidateSet,
4255 Expr *Range, ExprResult *CallExpr);
4256
4259 SourceLocation LParenLoc,
4260 MultiExprArg Args,
4261 SourceLocation RParenLoc,
4262 Expr *ExecConfig,
4263 bool AllowTypoCorrection=true,
4264 bool CalleesAddressIsTaken=false);
4265
4267 MultiExprArg Args, SourceLocation RParenLoc,
4268 OverloadCandidateSet *CandidateSet,
4270
4274 const UnresolvedSetImpl &Fns,
4275 bool PerformADL = true);
4276
4279 const UnresolvedSetImpl &Fns,
4280 Expr *input, bool RequiresADL = true);
4281
4284 const UnresolvedSetImpl &Fns,
4285 ArrayRef<Expr *> Args, bool RequiresADL = true);
4288 const UnresolvedSetImpl &Fns,
4289 Expr *LHS, Expr *RHS,
4290 bool RequiresADL = true,
4291 bool AllowRewrittenCandidates = true,
4292 FunctionDecl *DefaultedFn = nullptr);
4294 const UnresolvedSetImpl &Fns,
4295 Expr *LHS, Expr *RHS,
4296 FunctionDecl *DefaultedFn);
4297
4299 SourceLocation RLoc, Expr *Base,
4300 MultiExprArg Args);
4301
4303 SourceLocation LParenLoc,
4304 MultiExprArg Args,
4305 SourceLocation RParenLoc,
4306 Expr *ExecConfig = nullptr,
4307 bool IsExecConfig = false,
4308 bool AllowRecovery = false);
4311 MultiExprArg Args,
4312 SourceLocation RParenLoc);
4313
4315 SourceLocation OpLoc,
4316 bool *NoArrowOperatorFound = nullptr);
4317
4318 /// CheckCallReturnType - Checks that a call expression's return type is
4319 /// complete. Returns true on failure. The location passed in is the location
4320 /// that best represents the call.
4321 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
4322 CallExpr *CE, FunctionDecl *FD);
4323
4324 /// Helpers for dealing with blocks and functions.
4326 bool CheckParameterNames);
4330
4331 /// \name Name lookup
4332 ///