clang  17.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 
17 #include "clang/AST/ASTConcept.h"
18 #include "clang/AST/ASTFwd.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Availability.h"
22 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprConcepts.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
30 #include "clang/AST/LocInfoType.h"
32 #include "clang/AST/NSAPI.h"
34 #include "clang/AST/StmtCXX.h"
35 #include "clang/AST/StmtOpenMP.h"
36 #include "clang/AST/TypeLoc.h"
37 #include "clang/AST/TypeOrdering.h"
39 #include "clang/Basic/Builtins.h"
42 #include "clang/Basic/Module.h"
46 #include "clang/Basic/Specifiers.h"
48 #include "clang/Basic/TypeTraits.h"
50 #include "clang/Sema/CleanupInfo.h"
51 #include "clang/Sema/DeclSpec.h"
55 #include "clang/Sema/Ownership.h"
56 #include "clang/Sema/Scope.h"
57 #include "clang/Sema/SemaConcept.h"
59 #include "clang/Sema/Weak.h"
60 #include "llvm/ADT/ArrayRef.h"
61 #include "llvm/ADT/SetVector.h"
62 #include "llvm/ADT/SmallBitVector.h"
63 #include "llvm/ADT/SmallPtrSet.h"
64 #include "llvm/ADT/SmallSet.h"
65 #include "llvm/ADT/SmallVector.h"
66 #include "llvm/ADT/TinyPtrVector.h"
67 #include "llvm/Frontend/OpenMP/OMPConstants.h"
68 #include <deque>
69 #include <memory>
70 #include <optional>
71 #include <string>
72 #include <tuple>
73 #include <vector>
74 
75 namespace llvm {
76  class APSInt;
77  template <typename ValueT, typename ValueInfoT> class DenseSet;
78  class SmallBitVector;
79  struct InlineAsmIdentifierInfo;
80 }
81 
82 namespace clang {
83  class ADLResult;
84  class ASTConsumer;
85  class ASTContext;
86  class ASTMutationListener;
87  class ASTReader;
88  class ASTWriter;
89  class ArrayType;
90  class ParsedAttr;
91  class BindingDecl;
92  class BlockDecl;
93  class CapturedDecl;
94  class CXXBasePath;
95  class CXXBasePaths;
96  class CXXBindTemporaryExpr;
98  class CXXConstructorDecl;
99  class CXXConversionDecl;
100  class CXXDeleteExpr;
101  class CXXDestructorDecl;
102  class CXXFieldCollector;
103  class CXXMemberCallExpr;
104  class CXXMethodDecl;
105  class CXXScopeSpec;
106  class CXXTemporary;
107  class CXXTryStmt;
108  class CallExpr;
109  class ClassTemplateDecl;
110  class ClassTemplatePartialSpecializationDecl;
111  class ClassTemplateSpecializationDecl;
112  class VarTemplatePartialSpecializationDecl;
113  class CodeCompleteConsumer;
114  class CodeCompletionAllocator;
115  class CodeCompletionTUInfo;
116  class CodeCompletionResult;
117  class CoroutineBodyStmt;
118  class Decl;
119  class DeclAccessPair;
120  class DeclContext;
121  class DeclRefExpr;
122  class DeclaratorDecl;
123  class DeducedTemplateArgument;
124  class DependentDiagnostic;
125  class DesignatedInitExpr;
126  class Designation;
127  class EnableIfAttr;
128  class EnumConstantDecl;
129  class Expr;
130  class ExtVectorType;
131  class FormatAttr;
132  class FriendDecl;
133  class FunctionDecl;
134  class FunctionProtoType;
135  class FunctionTemplateDecl;
136  class ImplicitConversionSequence;
138  class InitListExpr;
139  class InitializationKind;
140  class InitializationSequence;
141  class InitializedEntity;
142  class IntegerLiteral;
143  class LabelStmt;
144  class LambdaExpr;
145  class LangOptions;
146  class LocalInstantiationScope;
147  class LookupResult;
148  class MacroInfo;
150  class ModuleLoader;
151  class MultiLevelTemplateArgumentList;
152  class NamedDecl;
153  class ObjCCategoryDecl;
154  class ObjCCategoryImplDecl;
155  class ObjCCompatibleAliasDecl;
156  class ObjCContainerDecl;
157  class ObjCImplDecl;
158  class ObjCImplementationDecl;
159  class ObjCInterfaceDecl;
160  class ObjCIvarDecl;
161  template <class T> class ObjCList;
162  class ObjCMessageExpr;
163  class ObjCMethodDecl;
164  class ObjCPropertyDecl;
165  class ObjCProtocolDecl;
166  class OMPThreadPrivateDecl;
167  class OMPRequiresDecl;
168  class OMPDeclareReductionDecl;
169  class OMPDeclareSimdDecl;
170  class OMPClause;
171  struct OMPVarListLocTy;
172  struct OverloadCandidate;
173  enum class OverloadCandidateParamOrder : char;
175  class OverloadCandidateSet;
176  class OverloadExpr;
177  class ParenListExpr;
178  class ParmVarDecl;
179  class Preprocessor;
180  class PseudoDestructorTypeStorage;
181  class PseudoObjectExpr;
182  class QualType;
183  class StandardConversionSequence;
184  class Stmt;
185  class StringLiteral;
186  class SwitchStmt;
187  class TemplateArgument;
188  class TemplateArgumentList;
189  class TemplateArgumentLoc;
190  class TemplateDecl;
191  class TemplateInstantiationCallback;
192  class TemplateParameterList;
193  class TemplatePartialOrderingContext;
194  class TemplateTemplateParmDecl;
195  class Token;
196  class TypeAliasDecl;
197  class TypedefDecl;
198  class TypedefNameDecl;
199  class TypeLoc;
200  class TypoCorrectionConsumer;
201  class UnqualifiedId;
202  class UnresolvedLookupExpr;
203  class UnresolvedMemberExpr;
204  class UnresolvedSetImpl;
205  class UnresolvedSetIterator;
206  class UsingDecl;
207  class UsingShadowDecl;
208  class ValueDecl;
209  class VarDecl;
210  class VarTemplateSpecializationDecl;
211  class VisibilityAttr;
212  class VisibleDeclConsumer;
213  class IndirectFieldDecl;
214  struct DeductionFailureInfo;
215  class TemplateSpecCandidateSet;
216 
217 namespace sema {
218  class AccessedEntity;
219  class BlockScopeInfo;
220  class Capture;
221  class CapturedRegionScopeInfo;
222  class CapturingScopeInfo;
223  class CompoundScopeInfo;
224  class DelayedDiagnostic;
225  class DelayedDiagnosticPool;
226  class FunctionScopeInfo;
227  class LambdaScopeInfo;
228  class PossiblyUnreachableDiag;
229  class RISCVIntrinsicManager;
230  class SemaPPCallbacks;
231  class TemplateDeductionInfo;
232 }
233 
234 namespace threadSafety {
235  class BeforeSet;
236  void threadSafetyCleanup(BeforeSet* Cache);
237 }
238 
239 // FIXME: No way to easily map from TemplateTypeParmTypes to
240 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
241 using UnexpandedParameterPack = std::pair<
242  llvm::PointerUnion<
243  const TemplateTypeParmType *, const SubstTemplateTypeParmPackType *,
244  const SubstNonTypeTemplateParmPackExpr *, const NamedDecl *>,
246 
247 /// Describes whether we've seen any nullability information for the given
248 /// file.
250  /// The first pointer declarator (of any pointer kind) in the file that does
251  /// not have a corresponding nullability annotation.
253 
254  /// The end location for the first pointer declarator in the file. Used for
255  /// placing fix-its.
257 
258  /// Which kind of pointer declarator we saw.
259  uint8_t PointerKind;
260 
261  /// Whether we saw any type nullability annotations in the given file.
262  bool SawTypeNullability = false;
263 };
264 
265 /// A mapping from file IDs to a record of whether we've seen nullability
266 /// information in that file.
268  /// A mapping from file IDs to the nullability information for each file ID.
269  llvm::DenseMap<FileID, FileNullability> Map;
270 
271  /// A single-element cache based on the file ID.
272  struct {
275  } Cache;
276 
277 public:
279  // Check the single-element cache.
280  if (file == Cache.File)
281  return Cache.Nullability;
282 
283  // It's not in the single-element cache; flush the cache if we have one.
284  if (!Cache.File.isInvalid()) {
285  Map[Cache.File] = Cache.Nullability;
286  }
287 
288  // Pull this entry into the cache.
289  Cache.File = file;
290  Cache.Nullability = Map[file];
291  return Cache.Nullability;
292  }
293 };
294 
295 /// Tracks expected type during expression parsing, for use in code completion.
296 /// The type is tied to a particular token, all functions that update or consume
297 /// the type take a start location of the token they are looking at as a
298 /// parameter. This avoids updating the type on hot paths in the parser.
300 public:
301  PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
302 
303  void enterCondition(Sema &S, SourceLocation Tok);
304  void enterReturn(Sema &S, SourceLocation Tok);
305  void enterVariableInit(SourceLocation Tok, Decl *D);
306  /// Handles e.g. BaseType{ .D = Tok...
308  const Designation &D);
309  /// Computing a type for the function argument may require running
310  /// overloading, so we postpone its computation until it is actually needed.
311  ///
312  /// Clients should be very careful when using this function, as it stores a
313  /// function_ref, clients should make sure all calls to get() with the same
314  /// location happen while function_ref is alive.
315  ///
316  /// The callback should also emit signature help as a side-effect, but only
317  /// if the completion point has been reached.
319  llvm::function_ref<QualType()> ComputeType);
320 
321  void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
322  void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
323  SourceLocation OpLoc);
324  void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
325  void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
326  void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
327  /// Handles all type casts, including C-style cast, C++ casts, etc.
329 
330  /// Get the expected type associated with this location, if any.
331  ///
332  /// If the location is a function argument, determining the expected type
333  /// involves considering all function overloads and the arguments so far.
334  /// In this case, signature help for these function overloads will be reported
335  /// as a side-effect (only if the completion point has been reached).
337  if (!Enabled || Tok != ExpectedLoc)
338  return QualType();
339  if (!Type.isNull())
340  return Type;
341  if (ComputeType)
342  return ComputeType();
343  return QualType();
344  }
345 
346 private:
347  bool Enabled;
348  /// Start position of a token for which we store expected type.
349  SourceLocation ExpectedLoc;
350  /// Expected type for a token starting at ExpectedLoc.
351  QualType Type;
352  /// A function to compute expected type at ExpectedLoc. It is only considered
353  /// if Type is null.
354  llvm::function_ref<QualType()> ComputeType;
355 };
356 
357 /// Sema - This implements semantic analysis and AST building for C.
358 class Sema final {
359  Sema(const Sema &) = delete;
360  void operator=(const Sema &) = delete;
361 
362  ///Source of additional semantic information.
364 
365  static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
366 
367  /// Determine whether two declarations should be linked together, given that
368  /// the old declaration might not be visible and the new declaration might
369  /// not have external linkage.
370  bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
371  const NamedDecl *New) {
372  if (isVisible(Old))
373  return true;
374  // See comment in below overload for why it's safe to compute the linkage
375  // of the new declaration here.
376  if (New->isExternallyDeclarable()) {
377  assert(Old->isExternallyDeclarable() &&
378  "should not have found a non-externally-declarable previous decl");
379  return true;
380  }
381  return false;
382  }
383  bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
384 
385  void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
386  QualType ResultTy,
387  ArrayRef<QualType> Args);
388 
389 public:
390  /// The maximum alignment, same as in llvm::Value. We duplicate them here
391  /// because that allows us not to duplicate the constants in clang code,
392  /// which we must to since we can't directly use the llvm constants.
393  /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
394  ///
395  /// This is the greatest alignment value supported by load, store, and alloca
396  /// instructions, and global values.
397  static const unsigned MaxAlignmentExponent = 32;
399 
403 
406 
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
452  PCSK_BSS = 1,
457  };
458 
460  PCSA_Set = 0,
462  };
463 
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 
486  // #pragma pack and align.
488  public:
489  // `Native` represents default align mode, which may vary based on the
490  // platform.
491  enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
492 
493  // #pragma pack info constructor
494  AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
495  : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
496  assert(Num == PackNumber && "The pack number has been truncated.");
497  }
498 
499  // #pragma align info constructor
501  : PackAttr(false), AlignMode(M),
502  PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
503 
504  explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
505 
507 
508  // When a AlignPackInfo itself cannot be used, this returns an 32-bit
509  // integer encoding for it. This should only be passed to
510  // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
511  static uint32_t getRawEncoding(const AlignPackInfo &Info) {
512  std::uint32_t Encoding{};
513  if (Info.IsXLStack())
514  Encoding |= IsXLMask;
515 
516  Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
517 
518  if (Info.IsPackAttr())
519  Encoding |= PackAttrMask;
520 
521  Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
522 
523  return Encoding;
524  }
525 
527  bool IsXL = static_cast<bool>(Encoding & IsXLMask);
529  static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
530  int PackNumber = (Encoding & PackNumMask) >> 4;
531 
532  if (Encoding & PackAttrMask)
533  return AlignPackInfo(M, PackNumber, IsXL);
534 
535  return AlignPackInfo(M, IsXL);
536  }
537 
538  bool IsPackAttr() const { return PackAttr; }
539 
540  bool IsAlignAttr() const { return !PackAttr; }
541 
542  Mode getAlignMode() const { return AlignMode; }
543 
544  unsigned getPackNumber() const { return PackNumber; }
545 
546  bool IsPackSet() const {
547  // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
548  // attriute on a decl.
549  return PackNumber != UninitPackVal && PackNumber != 0;
550  }
551 
552  bool IsXLStack() const { return XLStack; }
553 
554  bool operator==(const AlignPackInfo &Info) const {
555  return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
556  std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
557  Info.XLStack);
558  }
559 
560  bool operator!=(const AlignPackInfo &Info) const {
561  return !(*this == Info);
562  }
563 
564  private:
565  /// \brief True if this is a pragma pack attribute,
566  /// not a pragma align attribute.
567  bool PackAttr;
568 
569  /// \brief The alignment mode that is in effect.
570  Mode AlignMode;
571 
572  /// \brief The pack number of the stack.
573  unsigned char PackNumber;
574 
575  /// \brief True if it is a XL #pragma align/pack stack.
576  bool XLStack;
577 
578  /// \brief Uninitialized pack value.
579  static constexpr unsigned char UninitPackVal = -1;
580 
581  // Masks to encode and decode an AlignPackInfo.
582  static constexpr uint32_t IsXLMask{0x0000'0001};
583  static constexpr uint32_t AlignModeMask{0x0000'0006};
584  static constexpr uint32_t PackAttrMask{0x00000'0008};
585  static constexpr uint32_t PackNumMask{0x0000'01F0};
586  };
587 
588  template<typename ValueType>
589  struct PragmaStack {
590  struct Slot {
591  llvm::StringRef StackSlotLabel;
592  ValueType Value;
595  Slot(llvm::StringRef StackSlotLabel, ValueType Value,
600  };
601 
602  void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
603  llvm::StringRef StackSlotLabel, ValueType Value) {
604  if (Action == PSK_Reset) {
606  CurrentPragmaLocation = PragmaLocation;
607  return;
608  }
609  if (Action & PSK_Push)
610  Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
611  PragmaLocation);
612  else if (Action & PSK_Pop) {
613  if (!StackSlotLabel.empty()) {
614  // If we've got a label, try to find it and jump there.
615  auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
616  return x.StackSlotLabel == StackSlotLabel;
617  });
618  // If we found the label so pop from there.
619  if (I != Stack.rend()) {
620  CurrentValue = I->Value;
621  CurrentPragmaLocation = I->PragmaLocation;
622  Stack.erase(std::prev(I.base()), Stack.end());
623  }
624  } else if (!Stack.empty()) {
625  // We do not have a label, just pop the last entry.
626  CurrentValue = Stack.back().Value;
627  CurrentPragmaLocation = Stack.back().PragmaLocation;
628  Stack.pop_back();
629  }
630  }
631  if (Action & PSK_Set) {
633  CurrentPragmaLocation = PragmaLocation;
634  }
635  }
636 
637  // MSVC seems to add artificial slots to #pragma stacks on entering a C++
638  // method body to restore the stacks on exit, so it works like this:
639  //
640  // struct S {
641  // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
642  // void Method {}
643  // #pragma <name>(pop, InternalPragmaSlot)
644  // };
645  //
646  // It works even with #pragma vtordisp, although MSVC doesn't support
647  // #pragma vtordisp(push [, id], n)
648  // syntax.
649  //
650  // Push / pop a named sentinel slot.
651  void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
652  assert((Action == PSK_Push || Action == PSK_Pop) &&
653  "Can only push / pop #pragma stack sentinels!");
655  }
656 
657  // Constructors.
658  explicit PragmaStack(const ValueType &Default)
660 
661  bool hasValue() const { return CurrentValue != DefaultValue; }
662 
664  ValueType DefaultValue; // Value used for PSK_Reset action.
665  ValueType CurrentValue;
667  };
668  // FIXME: We should serialize / deserialize these if they occur in a PCH (but
669  // we shouldn't do so if they're in a module).
670 
671  /// Whether to insert vtordisps prior to virtual bases in the Microsoft
672  /// C++ ABI. Possible values are 0, 1, and 2, which mean:
673  ///
674  /// 0: Suppress all vtordisps
675  /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
676  /// structors
677  /// 2: Always insert vtordisps to support RTTI on partially constructed
678  /// objects
681  // The current #pragma align/pack values and locations at each #include.
686  };
688  // Segment #pragmas.
693 
694  // #pragma strict_gs_check.
696 
697  // This stack tracks the current state of Sema.CurFPFeatures.
700  FPOptionsOverride result;
701  if (!FpPragmaStack.hasValue()) {
702  result = FPOptionsOverride();
703  } else {
704  result = FpPragmaStack.CurrentValue;
705  }
706  return result;
707  }
708 
709  // RAII object to push / pop sentinel slots for all MS #pragma stacks.
710  // Actions should be performed only if we enter / exit a C++ method body.
712  public:
713  PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
715 
716  private:
717  Sema &S;
718  StringRef SlotLabel;
719  bool ShouldAct;
720  };
721 
722  /// A mapping that describes the nullability we've seen in each header file.
724 
725  /// Last section used with #pragma init_seg.
728 
729  /// Sections used with #pragma alloc_text.
730  llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
731 
732  /// VisContext - Manages the stack for \#pragma GCC visibility.
733  void *VisContext; // Really a "PragmaVisStack*"
734 
735  /// This an attribute introduced by \#pragma clang attribute.
740  bool IsUsed;
741  };
742 
743  /// A push'd group of PragmaAttributeEntries.
745  /// The location of the push attribute.
747  /// The namespace of this push group.
750  };
751 
753 
754  /// The declaration that is currently receiving an attribute from the
755  /// #pragma attribute stack.
757 
758  /// This represents the last location of a "#pragma clang optimize off"
759  /// directive if such a directive has not been closed by an "on" yet. If
760  /// optimizations are currently "on", this is set to an invalid location.
762 
763  /// The "on" or "off" argument passed by \#pragma optimize, that denotes
764  /// whether the optimizations in the list passed to the pragma should be
765  /// turned off or on. This boolean is true by default because command line
766  /// options are honored when `#pragma optimize("", on)`.
767  /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
768  bool MSPragmaOptimizeIsOn = true;
769 
770  /// Set of no-builtin functions listed by \#pragma function.
772 
773  /// Flag indicating if Sema is building a recovery call expression.
774  ///
775  /// This flag is used to avoid building recovery call expressions
776  /// if Sema is already doing so, which would cause infinite recursions.
778 
779  /// Used to control the generation of ExprWithCleanups.
781 
782  /// ExprCleanupObjects - This is the stack of objects requiring
783  /// cleanup that are created by the current full expression.
785 
786  /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
787  /// to a variable (constant) that may or may not be odr-used in this Expr, and
788  /// we won't know until all lvalue-to-rvalue and discarded value conversions
789  /// have been applied to all subexpressions of the enclosing full expression.
790  /// This is cleared at the end of each full expression.
791  using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
794 
795  std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
796 
797  /// Stack containing information about each of the nested
798  /// function, block, and method scopes that are currently active.
800 
801  /// The index of the first FunctionScope that corresponds to the current
802  /// context.
803  unsigned FunctionScopesStart = 0;
804 
807  FunctionScopes.end());
808  }
809 
810  /// Stack containing information needed when in C++2a an 'auto' is encountered
811  /// in a function declaration parameter type specifier in order to invent a
812  /// corresponding template parameter in the enclosing abbreviated function
813  /// template. This information is also present in LambdaScopeInfo, stored in
814  /// the FunctionScopes stack.
816 
817  /// The index of the first InventedParameterInfo that refers to the current
818  /// context.
820 
822  return llvm::ArrayRef(InventedParameterInfos.begin() +
824  InventedParameterInfos.end());
825  }
826 
830 
831  /// ExtVectorDecls - This is a list all the extended vector types. This allows
832  /// us to associate a raw vector type with one of the ext_vector type names.
833  /// This is only necessary for issuing pretty diagnostics.
835 
836  /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
837  std::unique_ptr<CXXFieldCollector> FieldCollector;
838 
840 
841  /// Set containing all declared private fields that are not used.
843 
844  /// Set containing all typedefs that are likely unused.
847 
848  /// Delete-expressions to be analyzed at the end of translation unit
849  ///
850  /// This list contains class members, and locations of delete-expressions
851  /// that could not be proven as to whether they mismatch with new-expression
852  /// used in initializer of the field.
853  typedef std::pair<SourceLocation, bool> DeleteExprLoc;
855  llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
856 
858 
859  /// PureVirtualClassDiagSet - a set of class declarations which we have
860  /// emitted a list of pure virtual functions. Used to prevent emitting the
861  /// same list more than once.
862  std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
863 
864  /// ParsingInitForAutoVars - a set of declarations with auto types for which
865  /// we are currently parsing the initializer.
867 
868  /// Look for a locally scoped extern "C" declaration by the given name.
870 
874 
875  /// All the tentative definitions encountered in the TU.
877 
878  /// All the external declarations encoutered and used in the TU.
880 
884 
885  /// The set of file scoped decls seen so far that have not been used
886  /// and must warn if not used. Only contains the first declaration.
888 
892 
893  /// All the delegating constructors seen so far in the file, used for
894  /// cycle detection at the end of the TU.
896 
897  /// All the overriding functions seen during a class definition
898  /// that had their exception spec checks delayed, plus the overridden
899  /// function.
902 
903  /// All the function redeclarations seen during a class definition that had
904  /// their exception spec checks delayed, plus the prior declaration they
905  /// should be checked against. Except during error recovery, the new decl
906  /// should always be a friend declaration, as that's the only valid way to
907  /// redeclare a special member before its class is complete.
910 
911  typedef llvm::MapVector<const FunctionDecl *,
912  std::unique_ptr<LateParsedTemplate>>
915 
916  /// Callback to the parser to parse templated functions when needed.
917  typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
918  typedef void LateTemplateParserCleanupCB(void *P);
922 
924  LateTemplateParserCleanupCB *LTPCleanup,
925  void *P) {
926  LateTemplateParser = LTP;
927  LateTemplateParserCleanup = LTPCleanup;
928  OpaqueParser = P;
929  }
930 
931  class DelayedDiagnostics;
932 
934  sema::DelayedDiagnosticPool *SavedPool;
936  };
939 
940  /// A class which encapsulates the logic for delaying diagnostics
941  /// during parsing and other processing.
943  /// The current pool of diagnostics into which delayed
944  /// diagnostics should go.
946 
947  public:
948  DelayedDiagnostics() : CurPool(nullptr) {}
949 
950  /// Adds a delayed diagnostic.
951  void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
952 
953  /// Determines whether diagnostics should be delayed.
954  bool shouldDelayDiagnostics() { return CurPool != nullptr; }
955 
956  /// Returns the current delayed-diagnostics pool.
958  return CurPool;
959  }
960 
961  /// Enter a new scope. Access and deprecation diagnostics will be
962  /// collected in this pool.
965  state.SavedPool = CurPool;
966  CurPool = &pool;
967  return state;
968  }
969 
970  /// Leave a delayed-diagnostic state that was previously pushed.
971  /// Do not emit any of the diagnostics. This is performed as part
972  /// of the bookkeeping of popping a pool "properly".
974  CurPool = state.SavedPool;
975  }
976 
977  /// Enter a new scope where access and deprecation diagnostics are
978  /// not delayed.
981  state.SavedPool = CurPool;
982  CurPool = nullptr;
983  return state;
984  }
985 
986  /// Undo a previous pushUndelayed().
988  assert(CurPool == nullptr);
989  CurPool = state.SavedPool;
990  }
992 
993  /// A RAII object to temporarily push a declaration context.
994  class ContextRAII {
995  private:
996  Sema &S;
997  DeclContext *SavedContext;
998  ProcessingContextState SavedContextState;
999  QualType SavedCXXThisTypeOverride;
1000  unsigned SavedFunctionScopesStart;
1001  unsigned SavedInventedParameterInfosStart;
1002 
1003  public:
1004  ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
1005  : S(S), SavedContext(S.CurContext),
1006  SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
1007  SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
1008  SavedFunctionScopesStart(S.FunctionScopesStart),
1009  SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
1010  {
1011  assert(ContextToPush && "pushing null context");
1012  S.CurContext = ContextToPush;
1013  if (NewThisContext)
1014  S.CXXThisTypeOverride = QualType();
1015  // Any saved FunctionScopes do not refer to this context.
1016  S.FunctionScopesStart = S.FunctionScopes.size();
1017  S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1018  }
1019 
1020  void pop() {
1021  if (!SavedContext) return;
1022  S.CurContext = SavedContext;
1023  S.DelayedDiagnostics.popUndelayed(SavedContextState);
1024  S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1025  S.FunctionScopesStart = SavedFunctionScopesStart;
1026  S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1027  SavedContext = nullptr;
1028  }
1029 
1031  pop();
1032  }
1033  };
1034 
1035  /// Whether the AST is currently being rebuilt to correct immediate
1036  /// invocations. Immediate invocation candidates and references to consteval
1037  /// functions aren't tracked when this is set.
1039 
1040  /// Used to change context to isConstantEvaluated without pushing a heavy
1041  /// ExpressionEvaluationContextRecord object.
1043 
1045  return ExprEvalContexts.back().isConstantEvaluated() ||
1047  }
1048 
1049  /// RAII object to handle the state changes required to synthesize
1050  /// a function body.
1052  Sema &S;
1053  Sema::ContextRAII SavedContext;
1054  bool PushedCodeSynthesisContext = false;
1055 
1056  public:
1058  : S(S), SavedContext(S, DC) {
1059  S.PushFunctionScope();
1060  S.PushExpressionEvaluationContext(
1062  if (auto *FD = dyn_cast<FunctionDecl>(DC))
1063  FD->setWillHaveBody(true);
1064  else
1065  assert(isa<ObjCMethodDecl>(DC));
1066  }
1067 
1069  assert(!PushedCodeSynthesisContext);
1070 
1073  Ctx.PointOfInstantiation = UseLoc;
1074  Ctx.Entity = cast<Decl>(S.CurContext);
1075  S.pushCodeSynthesisContext(Ctx);
1076 
1077  PushedCodeSynthesisContext = true;
1078  }
1079 
1081  if (PushedCodeSynthesisContext)
1082  S.popCodeSynthesisContext();
1083  if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1084  FD->setWillHaveBody(false);
1085  S.PopExpressionEvaluationContext();
1086  S.PopFunctionScopeInfo();
1087  }
1088  };
1089 
1090  /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
1091  /// declared. Rare. May alias another identifier, declared or undeclared.
1092  ///
1093  /// For aliases, the target identifier is used as a key for eventual
1094  /// processing when the target is declared. For the single-identifier form,
1095  /// the sole identifier is used as the key. Each entry is a `SetVector`
1096  /// (ordered by parse order) of aliases (identified by the alias name) in case
1097  /// of multiple aliases to the same undeclared identifier.
1098  llvm::MapVector<
1099  IdentifierInfo *,
1100  llvm::SetVector<
1102  llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
1104 
1105  /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1106  /// \#pragma redefine_extname before declared. Used in Solaris system headers
1107  /// to define functions that occur in multiple standards to call the version
1108  /// in the currently selected standard.
1109  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1110 
1111 
1112  /// Load weak undeclared identifiers from the external source.
1114 
1115  /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1116  /// \#pragma weak during processing of other Decls.
1117  /// I couldn't figure out a clean way to generate these in-line, so
1118  /// we store them here and handle separately -- which is a hack.
1119  /// It would be best to refactor this.
1121 
1123 
1124  /// Translation Unit Scope - useful to Objective-C actions that need
1125  /// to lookup file scope declarations in the "ordinary" C decl namespace.
1126  /// For example, user-defined classes, built-in "id" type, etc.
1128 
1129  /// The C++ "std" namespace, where the standard library resides.
1131 
1132  /// The C++ "std::bad_alloc" class, which is defined by the C++
1133  /// standard library.
1135 
1136  /// The C++ "std::align_val_t" enum class, which is defined by the C++
1137  /// standard library.
1139 
1140  /// The C++ "std::experimental" namespace, where the experimental parts
1141  /// of the standard library resides.
1143 
1144  /// The C++ "std::initializer_list" template, which is defined in
1145  /// <initializer_list>.
1147 
1148  /// The C++ "std::coroutine_traits" template, which is defined in
1149  /// <coroutine_traits>
1151  /// The namespace where coroutine components are defined. In standard,
1152  /// they are defined in std namespace. And in the previous implementation,
1153  /// they are defined in std::experimental namespace.
1155 
1156  /// The C++ "type_info" declaration, which is defined in <typeinfo>.
1158 
1159  /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1161 
1162  /// The C++ "std::source_location::__impl" struct, defined in
1163  /// <source_location>.
1165 
1166  /// Caches identifiers/selectors for NSFoundation APIs.
1167  std::unique_ptr<NSAPI> NSAPIObj;
1168 
1169  /// The declaration of the Objective-C NSNumber class.
1171 
1172  /// The declaration of the Objective-C NSValue class.
1174 
1175  /// Pointer to NSNumber type (NSNumber *).
1177 
1178  /// Pointer to NSValue type (NSValue *).
1180 
1181  /// The Objective-C NSNumber methods used to create NSNumber literals.
1183 
1184  /// The declaration of the Objective-C NSString class.
1186 
1187  /// Pointer to NSString type (NSString *).
1189 
1190  /// The declaration of the stringWithUTF8String: method.
1192 
1193  /// The declaration of the valueWithBytes:objCType: method.
1195 
1196  /// The declaration of the Objective-C NSArray class.
1198 
1199  /// The declaration of the arrayWithObjects:count: method.
1201 
1202  /// The declaration of the Objective-C NSDictionary class.
1204 
1205  /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1207 
1208  /// id<NSCopying> type.
1210 
1211  /// will hold 'respondsToSelector:'
1213 
1214  /// A flag to remember whether the implicit forms of operator new and delete
1215  /// have been declared.
1217 
1218  /// Describes how the expressions currently being parsed are
1219  /// evaluated at run-time, if at all.
1221  /// The current expression and its subexpressions occur within an
1222  /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1223  /// \c sizeof, where the type of the expression may be significant but
1224  /// no code will be generated to evaluate the value of the expression at
1225  /// run time.
1226  Unevaluated,
1227 
1228  /// The current expression occurs within a braced-init-list within
1229  /// an unevaluated operand. This is mostly like a regular unevaluated
1230  /// context, except that we still instantiate constexpr functions that are
1231  /// referenced here so that we can perform narrowing checks correctly.
1233 
1234  /// The current expression occurs within a discarded statement.
1235  /// This behaves largely similarly to an unevaluated operand in preventing
1236  /// definitions from being required, but not in other ways.
1238 
1239  /// The current expression occurs within an unevaluated
1240  /// operand that unconditionally permits abstract references to
1241  /// fields, such as a SIZE operator in MS-style inline assembly.
1243 
1244  /// The current context is "potentially evaluated" in C++11 terms,
1245  /// but the expression is evaluated at compile-time (like the values of
1246  /// cases in a switch statement).
1248 
1249  /// In addition of being constant evaluated, the current expression
1250  /// occurs in an immediate function context - either a consteval function
1251  /// or a consteval if function.
1253 
1254  /// The current expression is potentially evaluated at run time,
1255  /// which means that code may be generated to evaluate the value of the
1256  /// expression at run time.
1258 
1259  /// The current expression is potentially evaluated, but any
1260  /// declarations referenced inside that expression are only used if
1261  /// in fact the current expression is used.
1262  ///
1263  /// This value is used when parsing default function arguments, for which
1264  /// we would like to provide diagnostics (e.g., passing non-POD arguments
1265  /// through varargs) but do not want to mark declarations as "referenced"
1266  /// until the default argument is used.
1268  };
1269 
1270  using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1271 
1272  /// Data structure used to record current or nested
1273  /// expression evaluation contexts.
1275  /// The expression evaluation context.
1277 
1278  /// Whether the enclosing context needed a cleanup.
1280 
1281  /// The number of active cleanup objects when we entered
1282  /// this expression evaluation context.
1284 
1285  /// The number of typos encountered during this expression evaluation
1286  /// context (i.e. the number of TypoExprs created).
1287  unsigned NumTypos;
1288 
1290 
1291  /// The lambdas that are present within this context, if it
1292  /// is indeed an unevaluated context.
1294 
1295  /// The declaration that provides context for lambda expressions
1296  /// and block literals if the normal declaration context does not
1297  /// suffice, e.g., in a default function argument.
1299 
1300  /// If we are processing a decltype type, a set of call expressions
1301  /// for which we have deferred checking the completeness of the return type.
1303 
1304  /// If we are processing a decltype type, a set of temporary binding
1305  /// expressions for which we have deferred checking the destructor.
1307 
1309 
1310  /// Expressions appearing as the LHS of a volatile assignment in this
1311  /// context. We produce a warning for these when popping the context if
1312  /// they are not discarded-value expressions nor unevaluated operands.
1314 
1315  /// Set of candidates for starting an immediate invocation.
1317 
1318  /// Set of DeclRefExprs referencing a consteval function when used in a
1319  /// context not already known to be immediately invoked.
1321 
1322  /// \brief Describes whether we are in an expression constext which we have
1323  /// to handle differently.
1326  } ExprContext;
1327 
1328  // A context can be nested in both a discarded statement context and
1329  // an immediate function context, so they need to be tracked independently.
1332 
1334 
1335  // When evaluating immediate functions in the initializer of a default
1336  // argument or default member initializer, this is the declaration whose
1337  // default initializer is being evaluated and the location of the call
1338  // or constructor definition.
1342  : Loc(Loc), Decl(Decl), Context(Context) {
1343  assert(Decl && Context && "invalid initialization context");
1344  }
1345 
1347  ValueDecl *Decl = nullptr;
1348  DeclContext *Context = nullptr;
1349  };
1350  std::optional<InitializationContext> DelayedDefaultInitializationContext;
1351 
1353  unsigned NumCleanupObjects,
1361 
1362  bool isUnevaluated() const {
1366  }
1367 
1368  bool isConstantEvaluated() const {
1371  }
1372 
1377  // C++2b [expr.const]p14:
1378  // An expression or conversion is in an immediate function
1379  // context if it is potentially evaluated and either:
1380  // * its innermost enclosing non-block scope is a function
1381  // parameter scope of an immediate function, or
1382  // * its enclosing statement is enclosed by the compound-
1383  // statement of a consteval if statement.
1386  }
1387 
1390  (Context ==
1393  }
1394  };
1395 
1396  /// A stack of expression evaluation contexts.
1398 
1399  /// Emit a warning for all pending noderef expressions that we recorded.
1401 
1402  /// Compute the mangling number context for a lambda expression or
1403  /// block literal. Also return the extra mangling decl if any.
1404  ///
1405  /// \param DC - The DeclContext containing the lambda expression or
1406  /// block literal.
1407  std::tuple<MangleNumberingContext *, Decl *>
1409 
1410 
1411  /// SpecialMemberOverloadResult - The overloading result for a special member
1412  /// function.
1413  ///
1414  /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1415  /// integer are used to determine whether overload resolution succeeded.
1417  public:
1418  enum Kind {
1422  };
1423 
1424  private:
1425  llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
1426 
1427  public:
1430  : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1431 
1432  CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1433  void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1434 
1435  Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1436  void setKind(Kind K) { Pair.setInt(K); }
1437  };
1438 
1440  : public llvm::FastFoldingSetNode,
1442  public:
1443  SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1444  : FastFoldingSetNode(ID)
1445  {}
1446  };
1447 
1448  /// A cache of special member function overload resolution results
1449  /// for C++ records.
1450  llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1451 
1452  /// A cache of the flags available in enumerations with the flag_bits
1453  /// attribute.
1454  mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1455 
1456  /// The kind of translation unit we are processing.
1457  ///
1458  /// When we're processing a complete translation unit, Sema will perform
1459  /// end-of-translation-unit semantic tasks (such as creating
1460  /// initializers for tentative definitions in C) once parsing has
1461  /// completed. Modules and precompiled headers perform different kinds of
1462  /// checks.
1464 
1465  llvm::BumpPtrAllocator BumpAlloc;
1466 
1467  /// The number of SFINAE diagnostics that have been trapped.
1469 
1470  typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1472 
1473  /// A mapping from parameters with unparsed default arguments to the
1474  /// set of instantiations of each parameter.
1475  ///
1476  /// This mapping is a temporary data structure used when parsing
1477  /// nested class templates or nested classes of class templates,
1478  /// where we might end up instantiating an inner class before the
1479  /// default arguments of its methods have been parsed.
1481 
1482  // Contains the locations of the beginning of unparsed default
1483  // argument locations.
1484  llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1485 
1486  /// UndefinedInternals - all the used, undefined objects which require a
1487  /// definition in this translation unit.
1488  llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1489 
1490  /// Determine if VD, which must be a variable or function, is an external
1491  /// symbol that nonetheless can't be referenced from outside this translation
1492  /// unit because its type has no linkage and it's not extern "C".
1494 
1495  /// Obtain a sorted list of functions that are undefined but ODR-used.
1496  void getUndefinedButUsed(
1497  SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1498 
1499  /// Retrieves list of suspicious delete-expressions that will be checked at
1500  /// the end of translation unit.
1501  const llvm::MapVector<FieldDecl *, DeleteLocs> &
1503 
1505  public:
1506  using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1507  using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1508  iterator begin() { return Methods.begin(); }
1509  iterator end() { return Methods.end(); }
1510  iterator find(Selector Sel) { return Methods.find(Sel); }
1511  std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1512  return Methods.insert(Val);
1513  }
1514  int count(Selector Sel) const { return Methods.count(Sel); }
1515  bool empty() const { return Methods.empty(); }
1516 
1517  private:
1518  llvm::DenseMap<Selector, Lists> Methods;
1519  };
1520 
1521  /// Method Pool - allows efficient lookup when typechecking messages to "id".
1522  /// We need to maintain a list, since selectors can have differing signatures
1523  /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1524  /// of selectors are "overloaded").
1525  /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1526  /// methods inside categories with a particular selector.
1528 
1529  /// Method selectors used in a \@selector expression. Used for implementation
1530  /// of -Wselector.
1531  llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1532 
1533  /// List of SourceLocations where 'self' is implicitly retained inside a
1534  /// block.
1537 
1538  /// Kinds of C++ special members.
1547  };
1548 
1549  typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1551 
1552  /// The C++ special members which we are currently in the process of
1553  /// declaring. If this process recursively triggers the declaration of the
1554  /// same special member, we should act as if it is not yet declared.
1556 
1557  /// Kinds of defaulted comparison operator functions.
1558  enum class DefaultedComparisonKind : unsigned char {
1559  /// This is not a defaultable comparison operator.
1560  None,
1561  /// This is an operator== that should be implemented as a series of
1562  /// subobject comparisons.
1563  Equal,
1564  /// This is an operator<=> that should be implemented as a series of
1565  /// subobject comparisons.
1566  ThreeWay,
1567  /// This is an operator!= that should be implemented as a rewrite in terms
1568  /// of a == comparison.
1569  NotEqual,
1570  /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1571  /// terms of a <=> comparison.
1572  Relational,
1573  };
1574 
1575  /// The function definitions which were renamed as part of typo-correction
1576  /// to match their respective declarations. We want to keep track of them
1577  /// to ensure that we don't emit a "redefinition" error if we encounter a
1578  /// correctly named definition after the renamed definition.
1580 
1581  /// Stack of types that correspond to the parameter entities that are
1582  /// currently being copy-initialized. Can be empty.
1584 
1585  void ReadMethodPool(Selector Sel);
1587 
1588  /// Private Helper predicate to check for 'self'.
1589  bool isSelfExpr(Expr *RExpr);
1590  bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1591 
1592  /// Cause the active diagnostic on the DiagosticsEngine to be
1593  /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1594  /// should not be used elsewhere.
1595  void EmitCurrentDiagnostic(unsigned DiagID);
1596 
1597  /// Records and restores the CurFPFeatures state on entry/exit of compound
1598  /// statements.
1600  public:
1603  FPOptionsOverride getOverrides() { return OldOverrides; }
1604 
1605  private:
1606  Sema& S;
1607  FPOptions OldFPFeaturesState;
1608  FPOptionsOverride OldOverrides;
1609  LangOptions::FPEvalMethodKind OldEvalMethod;
1610  SourceLocation OldFPPragmaLocation;
1611  };
1612 
1613  void addImplicitTypedef(StringRef Name, QualType T);
1614 
1615  bool WarnedStackExhausted = false;
1616 
1617  /// Increment when we find a reference; decrement when we find an ignored
1618  /// assignment. Ultimately the value is 0 if every reference is an ignored
1619  /// assignment.
1620  llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1621 
1622  /// Indicate RISC-V vector builtin functions enabled or not.
1624 
1625 private:
1626  std::unique_ptr<sema::RISCVIntrinsicManager> RVIntrinsicManager;
1627 
1628  std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1629 
1630  bool WarnedDarwinSDKInfoMissing = false;
1631 
1632 public:
1633  Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1635  CodeCompleteConsumer *CompletionConsumer = nullptr);
1636  ~Sema();
1637 
1638  /// Perform initialization that occurs after the parser has been
1639  /// initialized but before it parses anything.
1640  void Initialize();
1641 
1642  /// This virtual key function only exists to limit the emission of debug info
1643  /// describing the Sema class. GCC and Clang only emit debug info for a class
1644  /// with a vtable when the vtable is emitted. Sema is final and not
1645  /// polymorphic, but the debug info size savings are so significant that it is
1646  /// worth adding a vtable just to take advantage of this optimization.
1647  virtual void anchor();
1648 
1649  const LangOptions &getLangOpts() const { return LangOpts; }
1652 
1655  Preprocessor &getPreprocessor() const { return PP; }
1656  ASTContext &getASTContext() const { return Context; }
1657  ASTConsumer &getASTConsumer() const { return Consumer; }
1659  ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
1660 
1662  StringRef Platform);
1664 
1665  ///Registers an external source. If an external source already exists,
1666  /// creates a multiplex external source and appends to it.
1667  ///
1668  ///\param[in] E - A non-null external sema source.
1669  ///
1671 
1672  void PrintStats() const;
1673 
1674  /// Warn that the stack is nearly exhausted.
1676 
1677  /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1678  /// guaranteed). Produces a warning if we're low on stack space and allocates
1679  /// more in that case. Use this in code that may recurse deeply (for example,
1680  /// in template instantiation) to avoid stack overflow.
1682  llvm::function_ref<void()> Fn);
1683 
1684  /// Helper class that creates diagnostics with optional
1685  /// template instantiation stacks.
1686  ///
1687  /// This class provides a wrapper around the basic DiagnosticBuilder
1688  /// class that emits diagnostics. ImmediateDiagBuilder is
1689  /// responsible for emitting the diagnostic (as DiagnosticBuilder
1690  /// does) and, if the diagnostic comes from inside a template
1691  /// instantiation, printing the template instantiation stack as
1692  /// well.
1694  Sema &SemaRef;
1695  unsigned DiagID;
1696 
1697  public:
1698  ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1699  : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1700  ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1701  : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1702 
1703  // This is a cunning lie. DiagnosticBuilder actually performs move
1704  // construction in its copy constructor (but due to varied uses, it's not
1705  // possible to conveniently express this as actual move construction). So
1706  // the default copy ctor here is fine, because the base class disables the
1707  // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1708  // in that case anwyay.
1709  ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1710 
1712  // If we aren't active, there is nothing to do.
1713  if (!isActive()) return;
1714 
1715  // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1716  // builder itself so it won't emit the diagnostic in its own destructor.
1717  //
1718  // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1719  // do its own needless checks to see if the diagnostic needs to be
1720  // emitted. However, because we take care to ensure that the builder
1721  // objects never escape, a sufficiently smart compiler will be able to
1722  // eliminate that code.
1723  Clear();
1724 
1725  // Dispatch to Sema to emit the diagnostic.
1726  SemaRef.EmitCurrentDiagnostic(DiagID);
1727  }
1728 
1729  /// Teach operator<< to produce an object of the correct type.
1730  template <typename T>
1731  friend const ImmediateDiagBuilder &
1733  const DiagnosticBuilder &BaseDiag = Diag;
1734  BaseDiag << Value;
1735  return Diag;
1736  }
1737 
1738  // It is necessary to limit this to rvalue reference to avoid calling this
1739  // function with a bitfield lvalue argument since non-const reference to
1740  // bitfield is not allowed.
1741  template <typename T,
1742  typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1743  const ImmediateDiagBuilder &operator<<(T &&V) const {
1744  const DiagnosticBuilder &BaseDiag = *this;
1745  BaseDiag << std::move(V);
1746  return *this;
1747  }
1748  };
1749 
1750  /// A generic diagnostic builder for errors which may or may not be deferred.
1751  ///
1752  /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1753  /// which are not allowed to appear inside __device__ functions and are
1754  /// allowed to appear in __host__ __device__ functions only if the host+device
1755  /// function is never codegen'ed.
1756  ///
1757  /// To handle this, we use the notion of "deferred diagnostics", where we
1758  /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1759  ///
1760  /// This class lets you emit either a regular diagnostic, a deferred
1761  /// diagnostic, or no diagnostic at all, according to an argument you pass to
1762  /// its constructor, thus simplifying the process of creating these "maybe
1763  /// deferred" diagnostics.
1765  public:
1766  enum Kind {
1767  /// Emit no diagnostics.
1769  /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1771  /// Emit the diagnostic immediately, and, if it's a warning or error, also
1772  /// emit a call stack showing how this function can be reached by an a
1773  /// priori known-emitted function.
1775  /// Create a deferred diagnostic, which is emitted only if the function
1776  /// it's attached to is codegen'ed. Also emit a call stack as with
1777  /// K_ImmediateWithCallStack.
1779  };
1780 
1781  SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1782  FunctionDecl *Fn, Sema &S);
1784  SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1786 
1787  bool isImmediate() const { return ImmediateDiag.has_value(); }
1788 
1789  /// Convertible to bool: True if we immediately emitted an error, false if
1790  /// we didn't emit an error or we created a deferred error.
1791  ///
1792  /// Example usage:
1793  ///
1794  /// if (SemaDiagnosticBuilder(...) << foo << bar)
1795  /// return ExprError();
1796  ///
1797  /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1798  /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1799  operator bool() const { return isImmediate(); }
1800 
1801  template <typename T>
1802  friend const SemaDiagnosticBuilder &
1804  if (Diag.ImmediateDiag)
1805  *Diag.ImmediateDiag << Value;
1806  else if (Diag.PartialDiagId)
1807  Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1808  << Value;
1809  return Diag;
1810  }
1811 
1812  // It is necessary to limit this to rvalue reference to avoid calling this
1813  // function with a bitfield lvalue argument since non-const reference to
1814  // bitfield is not allowed.
1815  template <typename T,
1816  typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1817  const SemaDiagnosticBuilder &operator<<(T &&V) const {
1818  if (ImmediateDiag)
1819  *ImmediateDiag << std::move(V);
1820  else if (PartialDiagId)
1821  S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1822  return *this;
1823  }
1824 
1825  friend const SemaDiagnosticBuilder &
1827  if (Diag.ImmediateDiag)
1828  PD.Emit(*Diag.ImmediateDiag);
1829  else if (Diag.PartialDiagId)
1830  Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1831  return Diag;
1832  }
1833 
1834  void AddFixItHint(const FixItHint &Hint) const {
1835  if (ImmediateDiag)
1836  ImmediateDiag->AddFixItHint(Hint);
1837  else if (PartialDiagId)
1838  S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1839  }
1840 
1842  return ExprError();
1843  }
1845  return StmtError();
1846  }
1847  operator ExprResult() const { return ExprError(); }
1848  operator StmtResult() const { return StmtError(); }
1849  operator TypeResult() const { return TypeError(); }
1850  operator DeclResult() const { return DeclResult(true); }
1851  operator MemInitResult() const { return MemInitResult(true); }
1852 
1853  private:
1854  Sema &S;
1855  SourceLocation Loc;
1856  unsigned DiagID;
1857  FunctionDecl *Fn;
1858  bool ShowCallStack;
1859 
1860  // Invariant: At most one of these Optionals has a value.
1861  // FIXME: Switch these to a Variant once that exists.
1862  std::optional<ImmediateDiagBuilder> ImmediateDiag;
1863  std::optional<unsigned> PartialDiagId;
1864  };
1865 
1866  /// Is the last error level diagnostic immediate. This is used to determined
1867  /// whether the next info diagnostic should be immediate.
1869 
1870  /// Emit a diagnostic.
1871  SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1872  bool DeferHint = false);
1873 
1874  /// Emit a partial diagnostic.
1876  bool DeferHint = false);
1877 
1878  /// Build a partial diagnostic.
1879  PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1880 
1881  /// Whether deferrable diagnostics should be deferred.
1882  bool DeferDiags = false;
1883 
1884  /// RAII class to control scope of DeferDiags.
1886  Sema &S;
1887  bool SavedDeferDiags = false;
1888 
1889  public:
1891  : S(S), SavedDeferDiags(S.DeferDiags) {
1892  S.DeferDiags = DeferDiags;
1893  }
1894  ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1895  };
1896 
1897  /// Whether uncompilable error has occurred. This includes error happens
1898  /// in deferred diagnostics.
1899  bool hasUncompilableErrorOccurred() const;
1900 
1901  bool findMacroSpelling(SourceLocation &loc, StringRef name);
1902 
1903  /// Get a string to suggest for zero-initialization of a type.
1904  std::string
1907 
1908  /// Calls \c Lexer::getLocForEndOfToken()
1910 
1911  /// Retrieve the module loader associated with the preprocessor.
1912  ModuleLoader &getModuleLoader() const;
1913 
1914  /// Invent a new identifier for parameters of abbreviated templates.
1915  IdentifierInfo *
1917  unsigned Index);
1918 
1920 
1921  private:
1922  /// Function or variable declarations to be checked for whether the deferred
1923  /// diagnostics should be emitted.
1924  llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1925 
1926  public:
1927  // Emit all deferred diagnostics.
1928  void emitDeferredDiags();
1929 
1931  /// The global module fragment, between 'module;' and a module-declaration.
1933  /// A normal translation unit fragment. For a non-module unit, this is the
1934  /// entire translation unit. Otherwise, it runs from the module-declaration
1935  /// to the private-module-fragment (if any) or the end of the TU (if not).
1937  /// The private module fragment, between 'module :private;' and the end of
1938  /// the translation unit.
1940  };
1941 
1945 
1947 
1949 
1950  void PushFunctionScope();
1951  void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1953 
1954  /// This is used to inform Sema what the current TemplateParameterDepth
1955  /// is during Parsing. Currently it is used to pass on the depth
1956  /// when parsing generic lambda 'auto' parameters.
1958 
1959  void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1961  unsigned OpenMPCaptureLevel = 0);
1962 
1963  /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1964  /// time after they've been popped.
1966  Sema *Self;
1967 
1968  public:
1969  explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1971  };
1972 
1973  using PoppedFunctionScopePtr =
1974  std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1975 
1978  const Decl *D = nullptr,
1979  QualType BlockType = QualType());
1980 
1982  return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1983  }
1984 
1986 
1990  void setFunctionHasMustTail();
1991 
1992  void PushCompoundScope(bool IsStmtExpr);
1993  void PopCompoundScope();
1994 
1996 
1998 
1999  /// Retrieve the current block, if any.
2001 
2002  /// Get the innermost lambda enclosing the current location, if any. This
2003  /// looks through intervening non-lambda scopes such as local functions and
2004  /// blocks.
2006 
2007  /// Retrieve the current lambda scope info, if any.
2008  /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
2009  /// lambda scope info ignoring all inner capturing scopes that are not
2010  /// lambda scopes.
2012  getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
2013 
2014  /// Retrieve the current generic lambda info, if any.
2016 
2017  /// Retrieve the current captured region, if any.
2019 
2020  /// Retrieve the current function, if any, that should be analyzed for
2021  /// potential availability violations.
2023 
2024  /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
2026 
2027  /// Called before parsing a function declarator belonging to a function
2028  /// declaration.
2030  unsigned TemplateParameterDepth);
2031 
2032  /// Called after parsing a function declarator belonging to a function
2033  /// declaration.
2035 
2036  void ActOnComment(SourceRange Comment);
2037 
2038  //===--------------------------------------------------------------------===//
2039  // Type Analysis / Processing: SemaType.cpp.
2040  //
2041 
2043  const DeclSpec *DS = nullptr);
2044  QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
2045  const DeclSpec *DS = nullptr);
2047  SourceLocation Loc, DeclarationName Entity);
2048  QualType BuildReferenceType(QualType T, bool LValueRef,
2049  SourceLocation Loc, DeclarationName Entity);
2051  Expr *ArraySize, unsigned Quals,
2052  SourceRange Brackets, DeclarationName Entity);
2053  QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
2054  QualType BuildExtVectorType(QualType T, Expr *ArraySize,
2055  SourceLocation AttrLoc);
2056  QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
2057  SourceLocation AttrLoc);
2058 
2059  QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
2060  SourceLocation AttrLoc);
2061 
2062  /// Same as above, but constructs the AddressSpace index if not provided.
2064  SourceLocation AttrLoc);
2065 
2067 
2069 
2070  /// Build a function type.
2071  ///
2072  /// This routine checks the function type according to C++ rules and
2073  /// under the assumption that the result type and parameter types have
2074  /// just been instantiated from a template. It therefore duplicates
2075  /// some of the behavior of GetTypeForDeclarator, but in a much
2076  /// simpler form that is only suitable for this narrow use case.
2077  ///
2078  /// \param T The return type of the function.
2079  ///
2080  /// \param ParamTypes The parameter types of the function. This array
2081  /// will be modified to account for adjustments to the types of the
2082  /// function parameters.
2083  ///
2084  /// \param Loc The location of the entity whose type involves this
2085  /// function type or, if there is no such entity, the location of the
2086  /// type that will have function type.
2087  ///
2088  /// \param Entity The name of the entity that involves the function
2089  /// type, if known.
2090  ///
2091  /// \param EPI Extra information about the function type. Usually this will
2092  /// be taken from an existing function with the same prototype.
2093  ///
2094  /// \returns A suitable function type, if there are no errors. The
2095  /// unqualified type will always be a FunctionProtoType.
2096  /// Otherwise, returns a NULL type.
2098  MutableArrayRef<QualType> ParamTypes,
2099  SourceLocation Loc, DeclarationName Entity,
2100  const FunctionProtoType::ExtProtoInfo &EPI);
2101 
2103  SourceLocation Loc,
2104  DeclarationName Entity);
2106  SourceLocation Loc, DeclarationName Entity);
2110  SourceLocation Loc);
2112  SourceLocation Loc);
2113  QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2114 
2117 
2118  /// Package the given type and TSI into a ParsedType.
2123  TypeSourceInfo **TInfo = nullptr);
2124  CanThrowResult canThrow(const Stmt *E);
2125  /// Determine whether the callee of a particular function call can throw.
2126  /// E, D and Loc are all optional.
2127  static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2128  SourceLocation Loc = SourceLocation());
2130  const FunctionProtoType *FPT);
2137  const FunctionProtoType *Old, SourceLocation OldLoc,
2138  const FunctionProtoType *New, SourceLocation NewLoc);
2140  const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2141  const FunctionProtoType *Old, SourceLocation OldLoc,
2142  const FunctionProtoType *New, SourceLocation NewLoc);
2143  bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2144  bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2145  const PartialDiagnostic &NestedDiagID,
2146  const PartialDiagnostic &NoteID,
2147  const PartialDiagnostic &NoThrowDiagID,
2148  const FunctionProtoType *Superset,
2149  SourceLocation SuperLoc,
2150  const FunctionProtoType *Subset,
2151  SourceLocation SubLoc);
2152  bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2153  const PartialDiagnostic &NoteID,
2154  const FunctionProtoType *Target,
2155  SourceLocation TargetLoc,
2156  const FunctionProtoType *Source,
2157  SourceLocation SourceLoc);
2158 
2160 
2161  /// The parser has parsed the context-sensitive type 'instancetype'
2162  /// in an Objective-C message declaration. Return the appropriate type.
2164 
2165  /// Abstract class used to diagnose incomplete types.
2166  struct TypeDiagnoser {
2168 
2169  virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2170  virtual ~TypeDiagnoser() {}
2171  };
2172 
2173  static int getPrintable(int I) { return I; }
2174  static unsigned getPrintable(unsigned I) { return I; }
2175  static bool getPrintable(bool B) { return B; }
2176  static const char * getPrintable(const char *S) { return S; }
2177  static StringRef getPrintable(StringRef S) { return S; }
2178  static const std::string &getPrintable(const std::string &S) { return S; }
2179  static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2180  return II;
2181  }
2183  static QualType getPrintable(QualType T) { return T; }
2184  static SourceRange getPrintable(SourceRange R) { return R; }
2185  static SourceRange getPrintable(SourceLocation L) { return L; }
2186  static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2187  static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2188 
2189  template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2190  protected:
2191  unsigned DiagID;
2192  std::tuple<const Ts &...> Args;
2193 
2194  template <std::size_t... Is>
2195  void emit(const SemaDiagnosticBuilder &DB,
2196  std::index_sequence<Is...>) const {
2197  // Apply all tuple elements to the builder in order.
2198  bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2199  (void)Dummy;
2200  }
2201 
2202  public:
2203  BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2204  : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2205  assert(DiagID != 0 && "no diagnostic for type diagnoser");
2206  }
2207 
2208  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2209  const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2210  emit(DB, std::index_sequence_for<Ts...>());
2211  DB << T;
2212  }
2213  };
2214 
2215  /// Do a check to make sure \p Name looks like a legal argument for the
2216  /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
2217  /// is invalid for the given declaration.
2218  ///
2219  /// \p AL is used to provide caret diagnostics in case of a malformed name.
2220  ///
2221  /// \returns true if the name is a valid swift name for \p D, false otherwise.
2222  bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2223  const ParsedAttr &AL, bool IsAsync);
2224 
2225  /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2226  /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2227  /// For example, a diagnostic with no other parameters would generally have
2228  /// the form "...%select{incomplete|sizeless}0 type %1...".
2229  template <typename... Ts>
2231  public:
2232  SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2233  : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2234 
2235  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2236  const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2237  this->emit(DB, std::index_sequence_for<Ts...>());
2238  DB << T->isSizelessType() << T;
2239  }
2240  };
2241 
2242  enum class CompleteTypeKind {
2243  /// Apply the normal rules for complete types. In particular,
2244  /// treat all sizeless types as incomplete.
2245  Normal,
2246 
2247  /// Relax the normal rules for complete types so that they include
2248  /// sizeless built-in types.
2250 
2251  // FIXME: Eventually we should flip the default to Normal and opt in
2252  // to AcceptSizeless rather than opt out of it.
2254  };
2255 
2257 
2258 private:
2259  /// Methods for marking which expressions involve dereferencing a pointer
2260  /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2261  /// they are parsed, meaning that a noderef pointer may not be accessed. For
2262  /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2263  /// `*p`, but need to check that `address of` is called on it. This requires
2264  /// keeping a container of all pending expressions and checking if the address
2265  /// of them are eventually taken.
2266  void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2267  void CheckAddressOfNoDeref(const Expr *E);
2268  void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2269 
2270  bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2271  CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2272 
2273  struct ModuleScope {
2274  SourceLocation BeginLoc;
2275  clang::Module *Module = nullptr;
2276  bool ModuleInterface = false;
2277  bool IsPartition = false;
2278  bool ImplicitGlobalModuleFragment = false;
2279  VisibleModuleSet OuterVisibleModules;
2280  };
2281  /// The modules we're currently parsing.
2283  /// The global module fragment of the current translation unit.
2284  clang::Module *GlobalModuleFragment = nullptr;
2285 
2286  /// The modules we imported directly.
2287  llvm::SmallPtrSet<clang::Module *, 8> DirectModuleImports;
2288 
2289  /// Namespace definitions that we will export when they finish.
2290  llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2291 
2292  /// In a C++ standard module, inline declarations require a definition to be
2293  /// present at the end of a definition domain. This set holds the decls to
2294  /// be checked at the end of the TU.
2295  llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
2296 
2297  /// Helper function to judge if we are in module purview.
2298  /// Return false if we are not in a module.
2299  bool isCurrentModulePurview() const {
2300  return getCurrentModule() ? getCurrentModule()->isModulePurview() : false;
2301  }
2302 
2303  /// Enter the scope of the global module.
2304  Module *PushGlobalModuleFragment(SourceLocation BeginLoc, bool IsImplicit);
2305  /// Leave the scope of the global module.
2306  void PopGlobalModuleFragment();
2307 
2308  VisibleModuleSet VisibleModules;
2309 
2310  /// Cache for module units which is usable for current module.
2311  llvm::DenseSet<const Module *> UsableModuleUnitsCache;
2312 
2313  bool isUsableModule(const Module *M);
2314 
2315  bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
2316 
2317 public:
2318  /// Get the module unit whose scope we are currently within.
2320  return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2321  }
2322 
2323  /// Is the module scope we are an interface?
2325  return ModuleScopes.empty() ? false : ModuleScopes.back().ModuleInterface;
2326  }
2327 
2328  /// Is the module scope we are in a C++ Header Unit?
2330  return ModuleScopes.empty() ? false
2331  : ModuleScopes.back().Module->isHeaderUnit();
2332  }
2333 
2334  /// Get the module owning an entity.
2335  Module *getOwningModule(const Decl *Entity) {
2336  return Entity->getOwningModule();
2337  }
2338 
2340  return DirectModuleImports.contains(M);
2341  }
2342 
2343  // Determine whether the module M belongs to the current TU.
2344  bool isModuleUnitOfCurrentTU(const Module *M) const;
2345 
2346  /// Make a merged definition of an existing hidden definition \p ND
2347  /// visible at the specified location.
2349 
2350  bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2351 
2352  // When loading a non-modular PCH files, this is used to restore module
2353  // visibility.
2354  void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2355  VisibleModules.setVisible(Mod, ImportLoc);
2356  }
2357 
2358  /// Determine whether a declaration is visible to name lookup.
2359  bool isVisible(const NamedDecl *D) {
2360  return D->isUnconditionallyVisible() ||
2361  isAcceptableSlow(D, AcceptableKind::Visible);
2362  }
2363 
2364  /// Determine whether a declaration is reachable.
2365  bool isReachable(const NamedDecl *D) {
2366  // All visible declarations are reachable.
2367  return D->isUnconditionallyVisible() ||
2368  isAcceptableSlow(D, AcceptableKind::Reachable);
2369  }
2370 
2371  /// Determine whether a declaration is acceptable (visible/reachable).
2373  return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
2374  }
2375 
2376  /// Determine whether any declaration of an entity is visible.
2377  bool
2379  llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2380  return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2381  }
2382 
2383  bool hasVisibleDeclarationSlow(const NamedDecl *D,
2385  /// Determine whether any declaration of an entity is reachable.
2386  bool
2388  llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2389  return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
2390  }
2392  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2393 
2396 
2397  /// Determine if \p D and \p Suggested have a structurally compatible
2398  /// layout as described in C11 6.2.7/1.
2399  bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2400 
2401  /// Determine if \p D has a visible definition. If not, suggest a declaration
2402  /// that should be made visible to expose the definition.
2403  bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2404  bool OnlyNeedComplete = false);
2406  NamedDecl *Hidden;
2407  return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2408  }
2409 
2410  /// Determine if \p D has a reachable definition. If not, suggest a
2411  /// declaration that should be made reachable to expose the definition.
2412  bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
2413  bool OnlyNeedComplete = false);
2415  NamedDecl *Hidden;
2416  return hasReachableDefinition(D, &Hidden);
2417  }
2418 
2419  bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
2421  bool OnlyNeedComplete = false);
2423  NamedDecl *Hidden;
2424  return hasAcceptableDefinition(D, &Hidden, Kind);
2425  }
2426 
2427  /// Determine if the template parameter \p D has a visible default argument.
2428  bool
2430  llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2431  /// Determine if the template parameter \p D has a reachable default argument.
2433  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2434  /// Determine if the template parameter \p D has a reachable default argument.
2438 
2439  /// Determine if there is a visible declaration of \p D that is an explicit
2440  /// specialization declaration for a specialization of a template. (For a
2441  /// member specialization, use hasVisibleMemberSpecialization.)
2443  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2444  /// Determine if there is a reachable declaration of \p D that is an explicit
2445  /// specialization declaration for a specialization of a template. (For a
2446  /// member specialization, use hasReachableMemberSpecialization.)
2448  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2449 
2450  /// Determine if there is a visible declaration of \p D that is a member
2451  /// specialization declaration (as opposed to an instantiated declaration).
2453  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2454  /// Determine if there is a reachable declaration of \p D that is a member
2455  /// specialization declaration (as opposed to an instantiated declaration).
2457  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2458 
2459  /// Determine if \p A and \p B are equivalent internal linkage declarations
2460  /// from different modules, and thus an ambiguity error can be downgraded to
2461  /// an extension warning.
2463  const NamedDecl *B);
2465  SourceLocation Loc, const NamedDecl *D,
2467 
2469 
2470  // Check whether the size of array element of type \p EltTy is a multiple of
2471  // its alignment and return false if it isn't.
2473 
2476  return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2477  }
2479  CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2481  CompleteTypeKind Kind, unsigned DiagID);
2482 
2484  TypeDiagnoser &Diagnoser) {
2485  return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2486  }
2487  bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2488  return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2489  }
2490 
2491  template <typename... Ts>
2492  bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2493  const Ts &...Args) {
2494  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2495  return RequireCompleteType(Loc, T, Diagnoser);
2496  }
2497 
2498  template <typename... Ts>
2499  bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2500  const Ts &... Args) {
2501  SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2502  return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2503  }
2504 
2505  /// Get the type of expression E, triggering instantiation to complete the
2506  /// type if necessary -- that is, if the expression refers to a templated
2507  /// static data member of incomplete array type.
2508  ///
2509  /// May still return an incomplete type if instantiation was not possible or
2510  /// if the type is incomplete for a different reason. Use
2511  /// RequireCompleteExprType instead if a diagnostic is expected for an
2512  /// incomplete expression type.
2514 
2515  void completeExprArrayBound(Expr *E);
2517  TypeDiagnoser &Diagnoser);
2518  bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2519 
2520  template <typename... Ts>
2521  bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2522  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2523  return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2524  }
2525 
2526  template <typename... Ts>
2527  bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2528  const Ts &... Args) {
2529  SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2530  return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2531  }
2532 
2534  TypeDiagnoser &Diagnoser);
2535  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2536 
2537  template <typename... Ts>
2538  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2539  const Ts &...Args) {
2540  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2541  return RequireLiteralType(Loc, T, Diagnoser);
2542  }
2543 
2545  const CXXScopeSpec &SS, QualType T,
2546  TagDecl *OwnedTagDecl = nullptr);
2547 
2548  // Returns the underlying type of a decltype with the given expression.
2550 
2552  /// If AsUnevaluated is false, E is treated as though it were an evaluated
2553  /// context, such as when building a type for decltype(auto).
2554  QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
2555 
2558  SourceLocation Loc);
2563  QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
2564  SourceLocation Loc);
2565  QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
2566  SourceLocation Loc);
2568  SourceLocation Loc);
2570  SourceLocation Loc);
2572  SourceLocation Loc);
2573 
2574  //===--------------------------------------------------------------------===//
2575  // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2576  //
2577 
2578  struct SkipBodyInfo {
2581  New(nullptr) {}
2586  };
2587 
2588  DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2589 
2591 
2593 
2595  Scope *S, CXXScopeSpec *SS = nullptr,
2596  bool isClassName = false, bool HasTrailingDot = false,
2597  ParsedType ObjectType = nullptr,
2598  bool IsCtorOrDtorName = false,
2599  bool WantNontrivialTypeSourceInfo = false,
2600  bool IsClassTemplateDeductionContext = true,
2601  ImplicitTypenameContext AllowImplicitTypename =
2603  IdentifierInfo **CorrectedII = nullptr);
2605  bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2607  SourceLocation IILoc,
2608  Scope *S,
2609  CXXScopeSpec *SS,
2610  ParsedType &SuggestedType,
2611  bool IsTemplateName = false);
2612 
2613  /// Attempt to behave like MSVC in situations where lookup of an unqualified
2614  /// type name has failed in a dependent context. In these situations, we
2615  /// automatically form a DependentTypeName that will retry lookup in a related
2616  /// scope during instantiation.
2618  SourceLocation NameLoc,
2619  bool IsTemplateTypeArg);
2620 
2621  /// Describes the result of the name lookup and resolution performed
2622  /// by \c ClassifyName().
2624  /// This name is not a type or template in this context, but might be
2625  /// something else.
2627  /// Classification failed; an error has been produced.
2629  /// The name has been typo-corrected to a keyword.
2631  /// The name was classified as a type.
2633  /// The name was classified as a specific non-type, non-template
2634  /// declaration. ActOnNameClassifiedAsNonType should be called to
2635  /// convert the declaration to an expression.
2637  /// The name was classified as an ADL-only function name.
2638  /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2639  /// result to an expression.
2641  /// The name denotes a member of a dependent type that could not be
2642  /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2643  /// convert the result to an expression.
2645  /// The name was classified as an overload set, and an expression
2646  /// representing that overload set has been formed.
2647  /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2648  /// expression referencing the overload set.
2650  /// The name was classified as a template whose specializations are types.
2652  /// The name was classified as a variable template name.
2654  /// The name was classified as a function template name.
2656  /// The name was classified as an ADL-only function template name.
2658  /// The name was classified as a concept name.
2660  };
2661 
2664  union {
2669  };
2670 
2671  explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2672 
2673  public:
2675 
2676  NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2677 
2679  return NameClassification(NC_Error);
2680  }
2681 
2684  }
2685 
2688  Result.Expr = E;
2689  return Result;
2690  }
2691 
2694  Result.NonTypeDecl = D;
2695  return Result;
2696  }
2697 
2700  }
2701 
2704  }
2705 
2708  Result.Template = Name;
2709  return Result;
2710  }
2711 
2714  Result.Template = Name;
2715  return Result;
2716  }
2717 
2720  Result.Template = Name;
2721  return Result;
2722  }
2723 
2726  Result.Template = Name;
2727  return Result;
2728  }
2729 
2732  Result.Template = Name;
2733  return Result;
2734  }
2735 
2736  NameClassificationKind getKind() const { return Kind; }
2737 
2739  assert(Kind == NC_OverloadSet);
2740  return Expr;
2741  }
2742 
2744  assert(Kind == NC_Type);
2745  return Type;
2746  }
2747 
2749  assert(Kind == NC_NonType);
2750  return NonTypeDecl;
2751  }
2752 
2754  assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2755  Kind == NC_VarTemplate || Kind == NC_Concept ||
2756  Kind == NC_UndeclaredTemplate);
2757  return Template;
2758  }
2759 
2761  switch (Kind) {
2762  case NC_TypeTemplate:
2763  return TNK_Type_template;
2764  case NC_FunctionTemplate:
2765  return TNK_Function_template;
2766  case NC_VarTemplate:
2767  return TNK_Var_template;
2768  case NC_Concept:
2769  return TNK_Concept_template;
2770  case NC_UndeclaredTemplate:
2771  return TNK_Undeclared_template;
2772  default:
2773  llvm_unreachable("unsupported name classification.");
2774  }
2775  }
2776  };
2777 
2778  /// Perform name lookup on the given name, classifying it based on
2779  /// the results of name lookup and the following token.
2780  ///
2781  /// This routine is used by the parser to resolve identifiers and help direct
2782  /// parsing. When the identifier cannot be found, this routine will attempt
2783  /// to correct the typo and classify based on the resulting name.
2784  ///
2785  /// \param S The scope in which we're performing name lookup.
2786  ///
2787  /// \param SS The nested-name-specifier that precedes the name.
2788  ///
2789  /// \param Name The identifier. If typo correction finds an alternative name,
2790  /// this pointer parameter will be updated accordingly.
2791  ///
2792  /// \param NameLoc The location of the identifier.
2793  ///
2794  /// \param NextToken The token following the identifier. Used to help
2795  /// disambiguate the name.
2796  ///
2797  /// \param CCC The correction callback, if typo correction is desired.
2798  NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2799  IdentifierInfo *&Name, SourceLocation NameLoc,
2800  const Token &NextToken,
2801  CorrectionCandidateCallback *CCC = nullptr);
2802 
2803  /// Act on the result of classifying a name as an undeclared (ADL-only)
2804  /// non-type declaration.
2806  SourceLocation NameLoc);
2807  /// Act on the result of classifying a name as an undeclared member of a
2808  /// dependent base class.
2810  IdentifierInfo *Name,
2811  SourceLocation NameLoc,
2812  bool IsAddressOfOperand);
2813  /// Act on the result of classifying a name as a specific non-type
2814  /// declaration.
2816  NamedDecl *Found,
2817  SourceLocation NameLoc,
2818  const Token &NextToken);
2819  /// Act on the result of classifying a name as an overload set.
2821 
2822  /// Describes the detailed kind of a template name. Used in diagnostics.
2824  ClassTemplate,
2826  VarTemplate,
2827  AliasTemplate,
2829  Concept,
2831  };
2834 
2835  /// Determine whether it's plausible that E was intended to be a
2836  /// template-name.
2837  bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2838  if (!getLangOpts().CPlusPlus || E.isInvalid())
2839  return false;
2840  Dependent = false;
2841  if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2842  return !DRE->hasExplicitTemplateArgs();
2843  if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2844  return !ME->hasExplicitTemplateArgs();
2845  Dependent = true;
2846  if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2847  return !DSDRE->hasExplicitTemplateArgs();
2848  if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2849  return !DSME->hasExplicitTemplateArgs();
2850  // Any additional cases recognized here should also be handled by
2851  // diagnoseExprIntendedAsTemplateName.
2852  return false;
2853  }
2855  SourceLocation Less,
2856  SourceLocation Greater);
2857 
2858  void warnOnReservedIdentifier(const NamedDecl *D);
2859 
2861 
2863  MultiTemplateParamsArg TemplateParameterLists);
2865  QualType &T, SourceLocation Loc,
2866  unsigned FailedFoldDiagID);
2870  DeclarationName Name, SourceLocation Loc,
2871  bool IsTemplateId);
2872  void
2873  diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2874  SourceLocation FallbackLoc,
2875  SourceLocation ConstQualLoc = SourceLocation(),
2876  SourceLocation VolatileQualLoc = SourceLocation(),
2877  SourceLocation RestrictQualLoc = SourceLocation(),
2878  SourceLocation AtomicQualLoc = SourceLocation(),
2879  SourceLocation UnalignedQualLoc = SourceLocation());
2880 
2881  static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2882  void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2884  const LookupResult &R);
2887  const LookupResult &R);
2888  void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2889  const LookupResult &R);
2890  void CheckShadow(Scope *S, VarDecl *D);
2891 
2892  /// Warn if 'E', which is an expression that is about to be modified, refers
2893  /// to a shadowing declaration.
2895 
2897 
2898 private:
2899  /// Map of current shadowing declarations to shadowed declarations. Warn if
2900  /// it looks like the user is trying to modify the shadowing declaration.
2901  llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2902 
2903 public:
2904  void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2905  void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2906  void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2907  TypedefNameDecl *NewTD);
2910  TypeSourceInfo *TInfo,
2913  LookupResult &Previous, bool &Redeclaration);
2915  Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
2916  LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
2917  bool &AddToScope, ArrayRef<BindingDecl *> Bindings = std::nullopt);
2918  NamedDecl *
2920  MultiTemplateParamsArg TemplateParamLists);
2921  // Returns true if the variable declaration is a redeclaration
2924  bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2925  Expr *Init);
2929 
2931  TypeSourceInfo *TInfo,
2933  MultiTemplateParamsArg TemplateParamLists,
2934  bool &AddToScope);
2936 
2937  enum class CheckConstexprKind {
2938  /// Diagnose issues that are non-constant or that are extensions.
2939  Diagnose,
2940  /// Identify whether this function satisfies the formal rules for constexpr
2941  /// functions in the current lanugage mode (with no extensions).
2942  CheckValid
2943  };
2944 
2947 
2950  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2952  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2953  // Returns true if the function declaration is a redeclaration
2956  bool IsMemberSpecialization, bool DeclIsDefn);
2957  bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2959  QualType NewT, QualType OldT);
2960  void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2964  bool IsDefinition);
2968  SourceLocation Loc,
2969  QualType T);
2971  SourceLocation NameLoc, IdentifierInfo *Name,
2972  QualType T, TypeSourceInfo *TSInfo,
2973  StorageClass SC);
2974  void ActOnParamDefaultArgument(Decl *param,
2975  SourceLocation EqualLoc,
2976  Expr *defarg);
2978  SourceLocation ArgLoc);
2979  void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2981  SourceLocation EqualLoc);
2982  void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2983  SourceLocation EqualLoc);
2984 
2985  // Contexts where using non-trivial C union types can be disallowed. This is
2986  // passed to err_non_trivial_c_union_in_invalid_context.
2988  // Function parameter.
2990  // Function return.
2992  // Default-initialized object.
2994  // Variable with automatic storage duration.
2996  // Initializer expression that might copy from another object.
2998  // Assignment.
3000  // Compound literal.
3002  // Block capture.
3004  // lvalue-to-rvalue conversion of volatile type.
3006  };
3007 
3008  /// Emit diagnostics if the initializer or any of its explicit or
3009  /// implicitly-generated subexpressions require copying or
3010  /// default-initializing a type that is or contains a C union type that is
3011  /// non-trivial to copy or default-initialize.
3013 
3014  // These flags are passed to checkNonTrivialCUnion.
3016  NTCUK_Init = 0x1,
3018  NTCUK_Copy = 0x4,
3019  };
3020 
3021  /// Emit diagnostics if a non-trivial C union type or a struct that contains
3022  /// a non-trivial C union is used in an invalid context.
3024  NonTrivialCUnionContext UseContext,
3025  unsigned NonTrivialKind);
3026 
3027  void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
3028  void ActOnUninitializedDecl(Decl *dcl);
3029  void ActOnInitializerError(Decl *Dcl);
3030 
3031  void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
3032  void ActOnCXXForRangeDecl(Decl *D);
3034  IdentifierInfo *Ident,
3035  ParsedAttributes &Attrs);
3036  void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
3037  void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
3040  void FinalizeDeclaration(Decl *D);
3044 
3045  /// Should be called on all declarations that might have attached
3046  /// documentation comments.
3047  void ActOnDocumentableDecl(Decl *D);
3049 
3050  enum class FnBodyKind {
3051  /// C++ [dcl.fct.def.general]p1
3052  /// function-body:
3053  /// ctor-initializer[opt] compound-statement
3054  /// function-try-block
3055  Other,
3056  /// = default ;
3057  Default,
3058  /// = delete ;
3059  Delete
3060  };
3061 
3063  SourceLocation LocAfterDecls);
3065  FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
3066  SkipBodyInfo *SkipBody = nullptr);
3068  MultiTemplateParamsArg TemplateParamLists,
3069  SkipBodyInfo *SkipBody = nullptr,
3070  FnBodyKind BodyKind = FnBodyKind::Other);
3072  SkipBodyInfo *SkipBody = nullptr,
3073  FnBodyKind BodyKind = FnBodyKind::Other);
3074  void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind);
3077  ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
3078  void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
3080  return D && isa<ObjCMethodDecl>(D);
3081  }
3082 
3083  /// Determine whether we can delay parsing the body of a function or
3084  /// function template until it is used, assuming we don't care about emitting
3085  /// code for that function.
3086  ///
3087  /// This will be \c false if we may need the body of the function in the
3088  /// middle of parsing an expression (where it's impractical to switch to
3089  /// parsing a different function), for instance, if it's constexpr in C++11
3090  /// or has an 'auto' return type in C++14. These cases are essentially bugs.
3091  bool canDelayFunctionBody(const Declarator &D);
3092 
3093  /// Determine whether we can skip parsing the body of a function
3094  /// definition, assuming we don't care about analyzing its body or emitting
3095  /// code for that function.
3096  ///
3097  /// This will be \c false only if we may need the body of the function in
3098  /// order to parse the rest of the program (for instance, if it is
3099  /// \c constexpr in C++11 or has an 'auto' return type in C++14).
3100  bool canSkipFunctionBody(Decl *D);
3101 
3102  /// Determine whether \param D is function like (function or function
3103  /// template) for parsing.
3105 
3108  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
3111 
3112  /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
3113  /// attribute for which parsing is delayed.
3115 
3116  /// Diagnose any unused parameters in the given sequence of
3117  /// ParmVarDecl pointers.
3119 
3120  /// Diagnose whether the size of parameters or return value of a
3121  /// function or obj-c method definition is pass-by-value and larger than a
3122  /// specified threshold.
3123  void
3125  QualType ReturnTy, NamedDecl *D);
3126 
3127  void DiagnoseInvalidJumps(Stmt *Body);
3129  SourceLocation AsmLoc,
3130  SourceLocation RParenLoc);
3131 
3132  Decl *ActOnTopLevelStmtDecl(Stmt *Statement);
3133 
3134  /// Handle a C++11 empty-declaration and attribute-declaration.
3136  SourceLocation SemiLoc);
3137 
3138  enum class ModuleDeclKind {
3139  Interface, ///< 'export module X;'
3140  Implementation, ///< 'module X;'
3141  PartitionInterface, ///< 'export module X:Y;'
3142  PartitionImplementation, ///< 'module X:Y;'
3143  };
3144 
3145  /// An enumeration to represent the transition of states in parsing module
3146  /// fragments and imports. If we are not parsing a C++20 TU, or we find
3147  /// an error in state transition, the state is set to NotACXX20Module.
3148  enum class ModuleImportState {
3149  FirstDecl, ///< Parsing the first decl in a TU.
3150  GlobalFragment, ///< after 'module;' but before 'module X;'
3151  ImportAllowed, ///< after 'module X;' but before any non-import decl.
3152  ImportFinished, ///< after any non-import decl.
3153  PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
3154  ///< non-import decl.
3155  PrivateFragmentImportFinished, ///< after 'module :private;' but a
3156  ///< non-import decl has already been seen.
3157  NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
3158  };
3159 
3160 private:
3161  /// The parser has begun a translation unit to be compiled as a C++20
3162  /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
3163  void HandleStartOfHeaderUnit();
3164 
3165 public:
3166  /// The parser has processed a module-declaration that begins the definition
3167  /// of a module interface or implementation.
3169  SourceLocation ModuleLoc, ModuleDeclKind MDK,
3170  ModuleIdPath Path, ModuleIdPath Partition,
3171  ModuleImportState &ImportState);
3172 
3173  /// The parser has processed a global-module-fragment declaration that begins
3174  /// the definition of the global module fragment of the current module unit.
3175  /// \param ModuleLoc The location of the 'module' keyword.
3177 
3178  /// The parser has processed a private-module-fragment declaration that begins
3179  /// the definition of the private module fragment of the current module unit.
3180  /// \param ModuleLoc The location of the 'module' keyword.
3181  /// \param PrivateLoc The location of the 'private' keyword.
3183  SourceLocation PrivateLoc);
3184 
3185  /// The parser has processed a module import declaration.
3186  ///
3187  /// \param StartLoc The location of the first token in the declaration. This
3188  /// could be the location of an '@', 'export', or 'import'.
3189  /// \param ExportLoc The location of the 'export' keyword, if any.
3190  /// \param ImportLoc The location of the 'import' keyword.
3191  /// \param Path The module toplevel name as an access path.
3192  /// \param IsPartition If the name is for a partition.
3194  SourceLocation ExportLoc,
3195  SourceLocation ImportLoc, ModuleIdPath Path,
3196  bool IsPartition = false);
3198  SourceLocation ExportLoc,
3199  SourceLocation ImportLoc, Module *M,
3200  ModuleIdPath Path = {});
3201 
3202  /// The parser has processed a module import translated from a
3203  /// #include or similar preprocessing directive.
3204  void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3205  void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3206 
3207  /// The parsed has entered a submodule.
3208  void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
3209  /// The parser has left a submodule.
3210  void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
3211 
3212  /// Create an implicit import of the given module at the given
3213  /// source location, for error recovery, if possible.
3214  ///
3215  /// This routine is typically used when an entity found by name lookup
3216  /// is actually hidden within a module that we know about but the user
3217  /// has forgotten to import.
3218  void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
3219  Module *Mod);
3220 
3221  /// Kinds of missing import. Note, the values of these enumerators correspond
3222  /// to %select values in diagnostics.
3223  enum class MissingImportKind {
3224  Declaration,
3225  Definition,
3229  };
3230 
3231  /// Diagnose that the specified declaration needs to be visible but
3232  /// isn't, and suggest a module import that would resolve the problem.
3234  MissingImportKind MIK, bool Recover = true);
3236  SourceLocation DeclLoc, ArrayRef<Module *> Modules,
3237  MissingImportKind MIK, bool Recover);
3238 
3240  SourceLocation LBraceLoc);
3242  SourceLocation RBraceLoc);
3243 
3244  /// We've found a use of a templated declaration that would trigger an
3245  /// implicit instantiation. Check that any relevant explicit specializations
3246  /// and partial specializations are visible/reachable, and diagnose if not.
3249 
3250  /// Retrieve a suitable printing policy for diagnostics.
3252  return getPrintingPolicy(Context, PP);
3253  }
3254 
3255  /// Retrieve a suitable printing policy for diagnostics.
3256  static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
3257  const Preprocessor &PP);
3258 
3259  /// Scope actions.
3260  void ActOnPopScope(SourceLocation Loc, Scope *S);
3262 
3264  const ParsedAttributesView &DeclAttrs,
3265  RecordDecl *&AnonRecord);
3267  const ParsedAttributesView &DeclAttrs,
3268  MultiTemplateParamsArg TemplateParams,
3269  bool IsExplicitInstantiation,
3270  RecordDecl *&AnonRecord);
3271 
3273  AccessSpecifier AS,
3274  RecordDecl *Record,
3275  const PrintingPolicy &Policy);
3276 
3278  RecordDecl *Record);
3279 
3280  /// Common ways to introduce type names without a tag for use in diagnostics.
3281  /// Keep in sync with err_tag_reference_non_tag.
3282  enum NonTagKind {
3292  };
3293 
3294  /// Given a non-tag type declaration, returns an enum useful for indicating
3295  /// what kind of non-tag type this is.
3297 
3299  TagTypeKind NewTag, bool isDefinition,
3300  SourceLocation NewTagLoc,
3301  const IdentifierInfo *Name);
3302 
3303  enum TagUseKind {
3304  TUK_Reference, // Reference to a tag: 'struct foo *X;'
3305  TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
3306  TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
3307  TUK_Friend // Friend declaration: 'friend struct foo;'
3308  };
3309 
3311  // Not parsing a type within __builtin_offsetof.
3313  // Parsing a type within __builtin_offsetof.
3315  // Parsing a type within macro "offsetof", defined in __buitin_offsetof
3316  // To improve our diagnostic message.
3318  };
3319 
3320  DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3321  SourceLocation KWLoc, CXXScopeSpec &SS,
3322  IdentifierInfo *Name, SourceLocation NameLoc,
3324  SourceLocation ModulePrivateLoc,
3325  MultiTemplateParamsArg TemplateParameterLists,
3326  bool &OwnedDecl, bool &IsDependent,
3327  SourceLocation ScopedEnumKWLoc,
3328  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3329  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3330  OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
3331 
3333  unsigned TagSpec, SourceLocation TagLoc,
3334  CXXScopeSpec &SS, IdentifierInfo *Name,
3335  SourceLocation NameLoc,
3336  const ParsedAttributesView &Attr,
3337  MultiTemplateParamsArg TempParamLists);
3338 
3340  unsigned TagSpec,
3341  TagUseKind TUK,
3342  const CXXScopeSpec &SS,
3343  IdentifierInfo *Name,
3344  SourceLocation TagLoc,
3345  SourceLocation NameLoc);
3346 
3347  void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3348  IdentifierInfo *ClassName,
3349  SmallVectorImpl<Decl *> &Decls);
3350  Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3351  Declarator &D, Expr *BitfieldWidth);
3352 
3353  FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3354  Declarator &D, Expr *BitfieldWidth,
3355  InClassInitStyle InitStyle,
3356  AccessSpecifier AS);
3358  SourceLocation DeclStart, Declarator &D,
3359  Expr *BitfieldWidth,
3360  InClassInitStyle InitStyle,
3361  AccessSpecifier AS,
3362  const ParsedAttr &MSPropertyAttr);
3363 
3365  TypeSourceInfo *TInfo,
3366  RecordDecl *Record, SourceLocation Loc,
3367  bool Mutable, Expr *BitfieldWidth,
3368  InClassInitStyle InitStyle,
3369  SourceLocation TSSL,
3370  AccessSpecifier AS, NamedDecl *PrevDecl,
3371  Declarator *D = nullptr);
3372 
3373  bool CheckNontrivialField(FieldDecl *FD);
3374  void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3375 
3377  /// The triviality of a method unaffected by "trivial_abi".
3379 
3380  /// The triviality of a method affected by "trivial_abi".
3382  };
3383 
3386  bool Diagnose = false);
3387 
3388  /// For a defaulted function, the kind of defaulted function that it is.
3390  CXXSpecialMember SpecialMember : 8;
3391  DefaultedComparisonKind Comparison : 8;
3392 
3393  public:
3395  : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3396  }
3398  : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3400  : SpecialMember(CXXInvalid), Comparison(Comp) {}
3401 
3402  bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3403  bool isComparison() const {
3404  return Comparison != DefaultedComparisonKind::None;
3405  }
3406 
3407  explicit operator bool() const {
3408  return isSpecialMember() || isComparison();
3409  }
3410 
3411  CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3412  DefaultedComparisonKind asComparison() const { return Comparison; }
3413 
3414  /// Get the index of this function kind for use in diagnostics.
3415  unsigned getDiagnosticIndex() const {
3416  static_assert(CXXInvalid > CXXDestructor,
3417  "invalid should have highest index");
3418  static_assert((unsigned)DefaultedComparisonKind::None == 0,
3419  "none should be equal to zero");
3420  return SpecialMember + (unsigned)Comparison;
3421  }
3422  };
3423 
3424  DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3425 
3428  }
3431  }
3432 
3433  void ActOnLastBitfield(SourceLocation DeclStart,
3434  SmallVectorImpl<Decl *> &AllIvarDecls);
3435  Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3436  Declarator &D, Expr *BitfieldWidth,
3437  tok::ObjCKeywordKind visibility);
3438 
3439  // This is used for both record definitions and ObjC interface declarations.
3440  void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3441  ArrayRef<Decl *> Fields, SourceLocation LBrac,
3442  SourceLocation RBrac, const ParsedAttributesView &AttrList);
3443 
3444  /// ActOnTagStartDefinition - Invoked when we have entered the
3445  /// scope of a tag's definition (e.g., for an enumeration, class,
3446  /// struct, or union).
3448 
3449  /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3450  /// Differently from C++, actually parse the body and reject / error out
3451  /// in case of a structural mismatch.
3452  bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3453 
3454  /// Check ODR hashes for C/ObjC when merging types from modules.
3455  /// Differently from C++, actually parse the body and reject in case
3456  /// of a mismatch.
3457  template <typename T,
3458  typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
3460  if (Duplicate->getODRHash() != Previous->getODRHash())
3461  return false;
3462 
3463  // Make the previous decl visible.
3465  return true;
3466  }
3467 
3469 
3470  /// Invoked when we enter a tag definition that we're skipping.
3472 
3474 
3475  /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3476  /// C++ record definition's base-specifiers clause and are starting its
3477  /// member declarations.
3479  SourceLocation FinalLoc,
3480  bool IsFinalSpelledSealed,
3481  bool IsAbstract,
3482  SourceLocation LBraceLoc);
3483 
3484  /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3485  /// the definition of a tag (enumeration, class, struct, or union).
3487  SourceRange BraceRange);
3488 
3490 
3492 
3493  /// Invoked when we must temporarily exit the objective-c container
3494  /// scope for parsing/looking-up C constructs.
3495  ///
3496  /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3499 
3500  /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3501  /// error parsing the definition of a tag.
3503 
3505  EnumConstantDecl *LastEnumConst,
3506  SourceLocation IdLoc,
3507  IdentifierInfo *Id,
3508  Expr *val);
3510  bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3511  QualType EnumUnderlyingTy, bool IsFixed,
3512  const EnumDecl *Prev);
3513 
3514  /// Determine whether the body of an anonymous enumeration should be skipped.
3515  /// \param II The name of the first enumerator.
3517  SourceLocation IILoc);
3518 
3519  Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3521  const ParsedAttributesView &Attrs,
3522  SourceLocation EqualLoc, Expr *Val);
3523  void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3524  Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3525  const ParsedAttributesView &Attr);
3526 
3527  /// Set the current declaration context until it gets popped.
3528  void PushDeclContext(Scope *S, DeclContext *DC);
3529  void PopDeclContext();
3530 
3531  /// EnterDeclaratorContext - Used when we must lookup names in the context
3532  /// of a declarator's nested name specifier.
3534  void ExitDeclaratorContext(Scope *S);
3535 
3536  /// Enter a template parameter scope, after it's been associated with a particular
3537  /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3538  /// in the correct order.
3539  void EnterTemplatedContext(Scope *S, DeclContext *DC);
3540 
3541  /// Push the parameters of D, which must be a function, into scope.
3542  void ActOnReenterFunctionContext(Scope* S, Decl* D);
3543  void ActOnExitFunctionContext();
3544 
3545  /// If \p AllowLambda is true, treat lambda as function.
3546  DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false);
3547 
3548  /// Returns a pointer to the innermost enclosing function, or nullptr if the
3549  /// current context is not inside a function. If \p AllowLambda is true,
3550  /// this can return the call operator of an enclosing lambda, otherwise
3551  /// lambdas are skipped when looking for an enclosing function.
3552  FunctionDecl *getCurFunctionDecl(bool AllowLambda = false);
3553 
3554  /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3555  /// the method decl for the method being parsed. If we're currently
3556  /// in a 'block', this returns the containing context.
3558 
3559  /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3560  /// or C function we're in, otherwise return null. If we're currently
3561  /// in a 'block', this returns the containing context.
3563 
3564  /// Add this decl to the scope shadowed decl chains.
3565  void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3566 
3567  /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3568  /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3569  /// true if 'D' belongs to the given declaration context.
3570  ///
3571  /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3572  /// enclosing namespace set of the context, rather than contained
3573  /// directly within it.
3574  bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3575  bool AllowInlineNamespace = false);
3576 
3577  /// Finds the scope corresponding to the given decl context, if it
3578  /// happens to be an enclosing scope. Otherwise return NULL.
3579  static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3580 
3581  /// Subroutines of ActOnDeclarator().
3583  TypeSourceInfo *TInfo);
3585 
3586  /// Describes the kind of merge to perform for availability
3587  /// attributes (including "deprecated", "unavailable", and "availability").
3589  /// Don't merge availability attributes at all.
3591  /// Merge availability attributes for a redeclaration, which requires
3592  /// an exact match.
3594  /// Merge availability attributes for an override, which requires
3595  /// an exact match or a weakening of constraints.
3597  /// Merge availability attributes for an implementation of
3598  /// a protocol requirement.
3600  /// Merge availability attributes for an implementation of
3601  /// an optional protocol requirement.
3603  };
3604 
3605  /// Describes the kind of priority given to an availability attribute.
3606  ///
3607  /// The sum of priorities deteremines the final priority of the attribute.
3608  /// The final priority determines how the attribute will be merged.
3609  /// An attribute with a lower priority will always remove higher priority
3610  /// attributes for the specified platform when it is being applied. An
3611  /// attribute with a higher priority will not be applied if the declaration
3612  /// already has an availability attribute with a lower priority for the
3613  /// specified platform. The final prirority values are not expected to match
3614  /// the values in this enumeration, but instead should be treated as a plain
3615  /// integer value. This enumeration just names the priority weights that are
3616  /// used to calculate that final vaue.
3618  /// The availability attribute was specified explicitly next to the
3619  /// declaration.
3621 
3622  /// The availability attribute was applied using '#pragma clang attribute'.
3624 
3625  /// The availability attribute for a specific platform was inferred from
3626  /// an availability attribute for another platform.
3628  };
3629 
3630  /// Attribute merging methods. Return true if a new attribute was added.
3631  AvailabilityAttr *
3633  IdentifierInfo *Platform, bool Implicit,
3634  VersionTuple Introduced, VersionTuple Deprecated,
3635  VersionTuple Obsoleted, bool IsUnavailable,
3636  StringRef Message, bool IsStrict, StringRef Replacement,
3637  AvailabilityMergeKind AMK, int Priority);
3638  TypeVisibilityAttr *
3640  TypeVisibilityAttr::VisibilityType Vis);
3641  VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3642  VisibilityAttr::VisibilityType Vis);
3643  UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3644  StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3645  DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3646  DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3647  MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3648  const AttributeCommonInfo &CI,
3649  bool BestCase,
3650  MSInheritanceModel Model);
3651  ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3652  StringRef NewUserDiagnostic);
3653  FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3654  IdentifierInfo *Format, int FormatIdx,
3655  int FirstArg);
3656  SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3657  StringRef Name);
3658  CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3659  StringRef Name);
3660  AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3661  const AttributeCommonInfo &CI,
3662  const IdentifierInfo *Ident);
3663  MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3664  SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3665  StringRef Name);
3666  OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3667  const AttributeCommonInfo &CI);
3668  InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3669  InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3670  const InternalLinkageAttr &AL);
3671  WebAssemblyImportNameAttr *mergeImportNameAttr(
3672  Decl *D, const WebAssemblyImportNameAttr &AL);
3673  WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3674  Decl *D, const WebAssemblyImportModuleAttr &AL);
3675  EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3676  EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3677  const EnforceTCBLeafAttr &AL);
3678  BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
3679  HLSLNumThreadsAttr *mergeHLSLNumThreadsAttr(Decl *D,
3680  const AttributeCommonInfo &AL,
3681  int X, int Y, int Z);
3682  HLSLShaderAttr *mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL,
3683  HLSLShaderAttr::ShaderType ShaderType);
3684 
3685  void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3688  LookupResult &OldDecls);
3689  bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3690  bool MergeTypeWithOld, bool NewDeclIsDefn);
3692  Scope *S, bool MergeTypeWithOld);
3695  void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3696  void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3697  bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3698  void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3699  bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3700 
3701  // AssignmentAction - This is used by all the assignment diagnostic functions
3702  // to represent what is actually causing the operation
3712  };
3713 
3714  /// C++ Overloading.
3716  /// This is a legitimate overload: the existing declarations are
3717  /// functions or function templates with different signatures.
3719 
3720  /// This is not an overload because the signature exactly matches
3721  /// an existing declaration.
3723 
3724  /// This is not an overload because the lookup results contain a
3725  /// non-function.
3727  };
3729  FunctionDecl *New,
3730  const LookupResult &OldDecls,
3731  NamedDecl *&OldDecl,
3732  bool UseMemberUsingDeclRules);
3733  bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
3734  bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true,
3735  bool ConsiderRequiresClauses = true);
3736 
3737  // Calculates whether the expression Constraint depends on an enclosing
3738  // template, for the purposes of [temp.friend] p9.
3739  // TemplateDepth is the 'depth' of the friend function, which is used to
3740  // compare whether a declaration reference is referring to a containing
3741  // template, or just the current friend function. A 'lower' TemplateDepth in
3742  // the AST refers to a 'containing' template. As the constraint is
3743  // uninstantiated, this is relative to the 'top' of the TU.
3744  bool
3746  unsigned TemplateDepth,
3747  const Expr *Constraint);
3748 
3749  // Calculates whether the friend function depends on an enclosing template for
3750  // the purposes of [temp.friend] p9.
3752 
3753  // Calculates whether two constraint expressions are equal irrespective of a
3754  // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
3755  // 'New', which are the "source" of the constraint, since this is necessary
3756  // for figuring out the relative 'depth' of the constraint. The depth of the
3757  // 'primary template' and the 'instantiated from' templates aren't necessarily
3758  // the same, such as a case when one is a 'friend' defined in a class.
3759  bool AreConstraintExpressionsEqual(const NamedDecl *Old,
3760  const Expr *OldConstr,
3761  const NamedDecl *New,
3762  const Expr *NewConstr);
3763 
3764  enum class AllowedExplicit {
3765  /// Allow no explicit functions to be used.
3766  None,
3767  /// Allow explicit conversion functions but not explicit constructors.
3768  Conversions,
3769  /// Allow both explicit conversion functions and explicit constructors.
3770  All
3771  };
3772 
3774  TryImplicitConversion(Expr *From, QualType ToType,
3775  bool SuppressUserConversions,
3776  AllowedExplicit AllowExplicit,
3777  bool InOverloadResolution,
3778  bool CStyle,
3779  bool AllowObjCWritebackConversion);
3780 
3781  bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3782  bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3783  bool IsComplexPromotion(QualType FromType, QualType ToType);
3784  bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3785  bool InOverloadResolution,
3786  QualType& ConvertedType, bool &IncompatibleObjC);
3787  bool isObjCPointerConversion(QualType FromType, QualType ToType,
3788  QualType& ConvertedType, bool &IncompatibleObjC);
3789  bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3790  QualType &ConvertedType);
3791  bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3792  QualType& ConvertedType);
3793  bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3794  const FunctionProtoType *NewType,
3795  unsigned *ArgPos = nullptr,
3796  bool Reversed = false);
3798  QualType FromType, QualType ToType);
3799 
3802  bool CheckPointerConversion(Expr *From, QualType ToType,
3803  CastKind &Kind,
3804  CXXCastPath& BasePath,
3805  bool IgnoreBaseAccess,
3806  bool Diagnose = true);
3807  bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3808  bool InOverloadResolution,
3809  QualType &ConvertedType);
3810  bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3811  CastKind &Kind,
3812  CXXCastPath &BasePath,
3813  bool IgnoreBaseAccess);
3814  bool IsQualificationConversion(QualType FromType, QualType ToType,
3815  bool CStyle, bool &ObjCLifetimeConversion);
3816  bool IsFunctionConversion(QualType FromType, QualType ToType,
3817  QualType &ResultTy);
3820 
3822  const InitializedEntity &Entity, InitListExpr *From);
3823 
3824  bool IsStringInit(Expr *Init, const ArrayType *AT);
3825 
3827  ExprResult Init);
3829  SourceLocation EqualLoc,
3830  ExprResult Init,
3831  bool TopLevelOfInitList = false,
3832  bool AllowExplicit = false);
3834  NestedNameSpecifier *Qualifier,
3835  NamedDecl *FoundDecl,
3836  CXXMethodDecl *Method);
3837 
3838  /// Check that the lifetime of the initializer (and its subobjects) is
3839  /// sufficient for initializing the entity, and perform lifetime extension
3840  /// (when permitted) if not.
3841  void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3842 
3845 
3846  /// Contexts in which a converted constant expression is required.
3847  enum CCEKind {
3848  CCEK_CaseValue, ///< Expression in a case label.
3849  CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
3850  CCEK_TemplateArg, ///< Value of a non-type template parameter.
3851  CCEK_ArrayBound, ///< Array bound in array declarator or new-expression.
3852  CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier.
3853  CCEK_Noexcept ///< Condition in a noexcept(bool) specifier.
3854  };
3856  llvm::APSInt &Value, CCEKind CCE);
3858  APValue &Value, CCEKind CCE,
3859  NamedDecl *Dest = nullptr);
3860 
3861  /// Abstract base class used to perform a contextual implicit
3862  /// conversion from an expression to any type passing a filter.
3864  public:
3865  bool Suppress;
3867 
3869  bool SuppressConversion = false)
3871 
3872  /// Determine whether the specified type is a valid destination type
3873  /// for this conversion.
3874  virtual bool match(QualType T) = 0;
3875 
3876  /// Emits a diagnostic complaining that the expression does not have
3877  /// integral or enumeration type.
3878  virtual SemaDiagnosticBuilder
3879  diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3880 
3881  /// Emits a diagnostic when the expression has incomplete class type.
3882  virtual SemaDiagnosticBuilder
3884 
3885  /// Emits a diagnostic when the only matching conversion function
3886  /// is explicit.
3888  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3889 
3890  /// Emits a note for the explicit conversion function.
3891  virtual SemaDiagnosticBuilder
3892  noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3893 
3894  /// Emits a diagnostic when there are multiple possible conversion
3895  /// functions.
3896  virtual SemaDiagnosticBuilder
3898 
3899  /// Emits a note for one of the candidate conversions.
3900  virtual SemaDiagnosticBuilder
3901  noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3902 
3903  /// Emits a diagnostic when we picked a conversion function
3904  /// (for cases when we are not allowed to pick a conversion function).
3906  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3907 
3909  };
3910 
3912  bool AllowScopedEnumerations;
3913 
3914  public:
3915  ICEConvertDiagnoser(bool AllowScopedEnumerations,
3916  bool Suppress, bool SuppressConversion)
3918  AllowScopedEnumerations(AllowScopedEnumerations) {}
3919 
3920  /// Match an integral or (possibly scoped) enumeration type.
3921  bool match(QualType T) override;
3922 
3925  return diagnoseNotInt(S, Loc, T);
3926  }
3927 
3928  /// Emits a diagnostic complaining that the expression does not have
3929  /// integral or enumeration type.
3930  virtual SemaDiagnosticBuilder
3931  diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3932  };
3933 
3934  /// Perform a contextual implicit conversion.
3936  SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3937 
3938 
3943  };
3945 
3946  // Note that LK_String is intentionally after the other literals, as
3947  // this is used for diagnostics logic.
3956  };
3958 
3960  NestedNameSpecifier *Qualifier,
3961  NamedDecl *FoundDecl,
3962  NamedDecl *Member);
3963 
3964  // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3965  // TODO: make this is a typesafe union.
3968 
3970 
3971  void AddOverloadCandidate(
3972  FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
3973  OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3974  bool PartialOverloading = false, bool AllowExplicit = true,
3975  bool AllowExplicitConversion = false,
3976  ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3977  ConversionSequenceList EarlyConversions = std::nullopt,
3978  OverloadCandidateParamOrder PO = {});
3979  void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3980  ArrayRef<Expr *> Args,
3981  OverloadCandidateSet &CandidateSet,
3982  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3983  bool SuppressUserConversions = false,
3984  bool PartialOverloading = false,
3985  bool FirstArgumentIsBase = false);
3986  void AddMethodCandidate(DeclAccessPair FoundDecl,
3987  QualType ObjectType,
3988  Expr::Classification ObjectClassification,
3989  ArrayRef<Expr *> Args,
3990  OverloadCandidateSet& CandidateSet,
3991  bool SuppressUserConversion = false,
3992  OverloadCandidateParamOrder PO = {});
3993  void
3994  AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
3995  CXXRecordDecl *ActingContext, QualType ObjectType,
3996  Expr::Classification ObjectClassification,
3997  ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3998  bool SuppressUserConversions = false,
3999  bool PartialOverloading = false,
4000  ConversionSequenceList EarlyConversions = std::nullopt,
4001  OverloadCandidateParamOrder PO = {});
4002  void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
4003  DeclAccessPair FoundDecl,
4004  CXXRecordDecl *ActingContext,
4005  TemplateArgumentListInfo *ExplicitTemplateArgs,
4006  QualType ObjectType,
4007  Expr::Classification ObjectClassification,
4008  ArrayRef<Expr *> Args,
4009  OverloadCandidateSet& CandidateSet,
4010  bool SuppressUserConversions = false,
4011  bool PartialOverloading = false,
4012  OverloadCandidateParamOrder PO = {});
4014  FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
4015  TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4016  OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
4017  bool PartialOverloading = false, bool AllowExplicit = true,
4018  ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
4019  OverloadCandidateParamOrder PO = {});
4021  FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
4022  ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
4023  ConversionSequenceList &Conversions, bool SuppressUserConversions,
4024  CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
4025  Expr::Classification ObjectClassification = {},
4026  OverloadCandidateParamOrder PO = {});
4028  CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
4029  CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
4030  OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
4031  bool AllowExplicit, bool AllowResultConversion = true);
4033  FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
4034  CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
4035  OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
4036  bool AllowExplicit, bool AllowResultConversion = true);
4037  void AddSurrogateCandidate(CXXConversionDecl *Conversion,
4038  DeclAccessPair FoundDecl,
4039  CXXRecordDecl *ActingContext,
4040  const FunctionProtoType *Proto,
4041  Expr *Object, ArrayRef<Expr *> Args,
4042  OverloadCandidateSet& CandidateSet);
4044  const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
4045  OverloadCandidateSet &CandidateSet,
4046  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4048  SourceLocation OpLoc, ArrayRef<Expr *> Args,
4049  OverloadCandidateSet &CandidateSet,
4050  OverloadCandidateParamOrder PO = {});
4051  void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
4052  OverloadCandidateSet& CandidateSet,
4053  bool IsAssignmentOperator = false,
4054  unsigned NumContextualBoolArguments = 0);
4056  SourceLocation OpLoc, ArrayRef<Expr *> Args,
4057  OverloadCandidateSet& CandidateSet);
4058  void AddArgumentDependentLookupCandidates(DeclarationName Name,
4059  SourceLocation Loc,
4060  ArrayRef<Expr *> Args,
4061  TemplateArgumentListInfo *ExplicitTemplateArgs,
4062  OverloadCandidateSet& CandidateSet,
4063  bool PartialOverloading = false);
4064 
4065  // Emit as a 'note' the specific overload candidate
4066  void NoteOverloadCandidate(
4067  NamedDecl *Found, FunctionDecl *Fn,
4069  QualType DestType = QualType(), bool TakingAddress = false);
4070 
4071  // Emit as a series of 'note's all template and non-templates identified by
4072  // the expression Expr
4073  void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
4074  bool TakingAddress = false);
4075 
4076  /// Check the enable_if expressions on the given function. Returns the first
4077  /// failing attribute, or NULL if they were all successful.
4078  EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
4079  ArrayRef<Expr *> Args,
4080  bool MissingImplicitThis = false);
4081 
4082  /// Find the failed Boolean condition within a given Boolean
4083  /// constant expression, and describe it with a string.
4084  std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
4085 
4086  /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
4087  /// non-ArgDependent DiagnoseIfAttrs.
4088  ///
4089  /// Argument-dependent diagnose_if attributes should be checked each time a
4090  /// function is used as a direct callee of a function call.
4091  ///
4092  /// Returns true if any errors were emitted.
4093  bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
4094  const Expr *ThisArg,
4095  ArrayRef<const Expr *> Args,
4096  SourceLocation Loc);
4097 
4098  /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
4099  /// ArgDependent DiagnoseIfAttrs.
4100  ///
4101  /// Argument-independent diagnose_if attributes should be checked on every use
4102  /// of a function.
4103  ///
4104  /// Returns true if any errors were emitted.
4105  bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
4106  SourceLocation Loc);
4107 
4108  /// Returns whether the given function's address can be taken or not,
4109  /// optionally emitting a diagnostic if the address can't be taken.
4110  ///
4111  /// Returns false if taking the address of the function is illegal.
4112  bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
4113  bool Complain = false,
4114  SourceLocation Loc = SourceLocation());
4115 
4116  // [PossiblyAFunctionType] --> [Return]
4117  // NonFunctionType --> NonFunctionType
4118  // R (A) --> R(A)
4119  // R (*)(A) --> R (A)
4120  // R (&)(A) --> R (A)
4121  // R (S::*)(A) --> R (A)
4122  QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
4123 
4124  FunctionDecl *
4125  ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
4126  QualType TargetType,
4127  bool Complain,
4128  DeclAccessPair &Found,
4129  bool *pHadMultipleCandidates = nullptr);
4130 
4131  FunctionDecl *
4132  resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
4133 
4135  ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
4136 
4137  FunctionDecl *
4139  bool Complain = false,
4140  DeclAccessPair *Found = nullptr);
4141 
4143  ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
4144  bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
4145  QualType DestTypeForComplaining = QualType(),
4146  unsigned DiagIDForComplaining = 0);
4147 
4148  Expr *FixOverloadedFunctionReference(Expr *E,
4149  DeclAccessPair FoundDecl,
4150  FunctionDecl *Fn);
4152  DeclAccessPair FoundDecl,
4153  FunctionDecl *Fn);
4154 
4155  void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
4156  ArrayRef<Expr *> Args,
4157  OverloadCandidateSet &CandidateSet,
4158  bool PartialOverloading = false);
4160  LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
4161  ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
4162 
4163  // An enum used to represent the different possible results of building a
4164  // range-based for loop.
4169  };
4170 
4172  SourceLocation RangeLoc,
4173  const DeclarationNameInfo &NameInfo,
4174  LookupResult &MemberLookup,
4175  OverloadCandidateSet *CandidateSet,
4176  Expr *Range, ExprResult *CallExpr);
4177 
4179  UnresolvedLookupExpr *ULE,
4180  SourceLocation LParenLoc,
4181  MultiExprArg Args,
4182  SourceLocation RParenLoc,
4183  Expr *ExecConfig,
4184  bool AllowTypoCorrection=true,
4185  bool CalleesAddressIsTaken=false);
4186 
4188  MultiExprArg Args, SourceLocation RParenLoc,
4189  OverloadCandidateSet *CandidateSet,
4190  ExprResult *Result);
4191 
4193  NestedNameSpecifierLoc NNSLoc,
4194  DeclarationNameInfo DNI,
4195  const UnresolvedSetImpl &Fns,
4196  bool PerformADL = true);
4197 
4199  UnaryOperatorKind Opc,
4200  const UnresolvedSetImpl &Fns,
4201  Expr *input, bool RequiresADL = true);
4202 
4203  void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
4205  const UnresolvedSetImpl &Fns,
4206  ArrayRef<Expr *> Args, bool RequiresADL = true);
4208  BinaryOperatorKind Opc,
4209  const UnresolvedSetImpl &Fns,
4210  Expr *LHS, Expr *RHS,
4211  bool RequiresADL = true,
4212  bool AllowRewrittenCandidates = true,
4213  FunctionDecl *DefaultedFn = nullptr);
4215  const UnresolvedSetImpl &Fns,
4216  Expr *LHS, Expr *RHS,
4217  FunctionDecl *DefaultedFn);
4218 
4220  SourceLocation RLoc, Expr *Base,
4221  MultiExprArg Args);
4222 
4224  SourceLocation LParenLoc,
4225  MultiExprArg Args,
4226  SourceLocation RParenLoc,
4227  Expr *ExecConfig = nullptr,
4228  bool IsExecConfig = false,
4229  bool AllowRecovery = false);
4230  ExprResult
4231  BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
4232  MultiExprArg Args,
4233  SourceLocation RParenLoc);
4234 
4236  SourceLocation OpLoc,
4237  bool *NoArrowOperatorFound = nullptr);
4238 
4239  /// CheckCallReturnType - Checks that a call expression's return type is
4240  /// complete. Returns true on failure. The location passed in is the location
4241  /// that best represents the call.
4242  bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
4243  CallExpr *CE, FunctionDecl *FD);
4244 
4245  /// Helpers for dealing with blocks and functions.
4247  bool CheckParameterNames);
4251 
4252  /// \name Name lookup
4253  ///
4254  /// These routines provide name lookup that is used during semantic
4255  /// analysis to resolve the various kinds of names (identifiers,
4256  /// overloaded operator names, constructor names, etc.) into zero or
4257  /// more declarations within a particular scope. The major entry
4258  /// points are LookupName, which performs unqualified name lookup,
4259  /// and LookupQualifiedName, which performs qualified name lookup.
4260  ///
4261  /// All name lookup is performed based on some specific criteria,
4262  /// which specify what names will be visible to name lookup and how
4263  /// far name lookup should work. These criteria are important both
4264  /// for capturing language semantics (certain lookups will ignore
4265  /// certain names, for example) and for performance, since name
4266  /// lookup is often a bottleneck in the compilation of C++. Name
4267  /// lookup criteria is specified via the LookupCriteria enumeration.
4268  ///
4269  /// The results of name lookup can vary based on the kind of name
4270  /// lookup performed, the current language, and the translation
4271  /// unit. In C, for example, name lookup will either return nothing
4272  /// (no entity found) or a single declaration. In C++, name lookup
4273  /// can additionally refer to a set of overloaded functions or
4274  /// result in an ambiguity. All of the possible results of name
4275  /// lookup are captured by the LookupResult class, which provides
4276  /// the ability to distinguish among them.
4277  //@{
4278 
4279  /// Describes the kind of name lookup to perform.
4281  /// Ordinary name lookup, which finds ordinary names (functions,
4282  /// variables, typedefs, etc.) in C and most kinds of names
4283  /// (functions, variables, members, types, etc.) in C++.
4285  /// Tag name lookup, which finds the names of enums, classes,
4286  /// structs, and unions.
4288  /// Label name lookup.
4290  /// Member name lookup, which finds the names of
4291  /// class/struct/union members.
4293  /// Look up of an operator name (e.g., operator+) for use with
4294  /// operator overloading. This lookup is similar to ordinary name
4295  /// lookup, but will ignore any declarations that are class members.
4297  /// Look up a name following ~ in a destructor name. This is an ordinary
4298  /// lookup, but prefers tags to typedefs.
4300  /// Look up of a name that precedes the '::' scope resolution
4301  /// operator in C++. This lookup completely ignores operator, object,
4302  /// function, and enumerator names (C++ [basic.lookup.qual]p1).
4304  /// Look up a namespace name within a C++ using directive or
4305  /// namespace alias definition, ignoring non-namespace names (C++
4306  /// [basic.lookup.udir]p1).
4308  /// Look up all declarations in a scope with the given name,
4309  /// including resolved using declarations. This is appropriate
4310  /// for checking redeclarations for a using declaration.
4312  /// Look up an ordinary name that is going to be redeclared as a
4313  /// name with linkage. This lookup ignores any declarations that
4314  /// are outside of the current scope unless they have linkage. See
4315  /// C99 6.2.2p4-5 and C++ [basic.link]p6.
4317  /// Look up a friend of a local class. This lookup does not look
4318  /// outside the innermost non-class scope. See C++11 [class.friend]p11.
4320  /// Look up the name of an Objective-C protocol.
4322  /// Look up implicit 'self' parameter of an objective-c method.
4324  /// Look up the name of an OpenMP user-defined reduction operation.
4326  /// Look up the name of an OpenMP user-defined mapper.
4328  /// Look up any declaration with any name.
4330  };
4331 
4332  /// Specifies whether (or how) name lookup is being performed for a
4333  /// redeclaration (vs. a reference).
4335  /// The lookup is a reference to this name that is not for the
4336  /// purpose of redeclaring the name.
4338  /// The lookup results will be used for redeclaration of a name,
4339  /// if an entity by that name already exists and is visible.
4341  /// The lookup results will be used for redeclaration of a name
4342  /// with external linkage; non-visible lookup results with external linkage
4343  /// may also be found.
4345  };
4346 
4348  // A declaration with an owning module for linkage can never link against
4349  // anything that is not visible. We don't need to check linkage here; if
4350  // the context has internal linkage, redeclaration lookup won't find things
4351  // from other TUs, and we can't safely compute linkage yet in general.
4352  if (cast<Decl>(CurContext)
4353  ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
4354  return ForVisibleRedeclaration;
4355  return ForExternalRedeclaration;
4356  }
4357 
4358  /// The possible outcomes of name lookup for a literal operator.
4360  /// The lookup resulted in an error.
4362  /// The lookup found no match but no diagnostic was issued.
4364  /// The lookup found a single 'cooked' literal operator, which
4365  /// expects a normal literal to be built and passed to it.
4367  /// The lookup found a single 'raw' literal operator, which expects
4368  /// a string literal containing the spelling of the literal token.
4370  /// The lookup found an overload set of literal operator templates,
4371  /// which expect the characters of the spelling of the literal token to be
4372  /// passed as a non-type template argument pack.
4374  /// The lookup found an overload set of literal operator templates,
4375  /// which expect the character type and characters of the spelling of the
4376  /// string literal token to be passed as template arguments.
4378  };
4379 
4380  SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
4382  bool ConstArg,
4383  bool VolatileArg,
4384  bool RValueThis,
4385  bool ConstThis,
4386  bool VolatileThis);
4387 
4388  typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
4389  typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
4391 
4392 private:
4393  bool CppLookupName(LookupResult &R, Scope *S);
4394 
4395  struct TypoExprState {
4396  std::unique_ptr<TypoCorrectionConsumer> Consumer;
4397  TypoDiagnosticGenerator DiagHandler;
4398  TypoRecoveryCallback RecoveryHandler;
4399  TypoExprState();
4400  TypoExprState(TypoExprState &&other) noexcept;
4401  TypoExprState &operator=(TypoExprState &&other) noexcept;
4402  };
4403 
4404  /// The set of unhandled TypoExprs and their associated state.
4405  llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
4406 
4407  /// Creates a new TypoExpr AST node.
4408  TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4410  TypoRecoveryCallback TRC, SourceLocation TypoLoc);
4411 
4412  // The set of known/encountered (unique, canonicalized) NamespaceDecls.
4413  //
4414  // The boolean value will be true to indicate that the namespace was loaded
4415  // from an AST/PCH file, or false otherwise.
4416  llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
4417 
4418  /// Whether we have already loaded known namespaces from an extenal
4419  /// source.
4420  bool LoadedExternalKnownNamespaces;
4421 
4422  /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
4423  /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
4424  /// should be skipped entirely.
4425  std::unique_ptr<TypoCorrectionConsumer>
4426  makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
4427  Sema::LookupNameKind LookupKind, Scope *S,
4428  CXXScopeSpec *SS,
4430  DeclContext *MemberContext, bool EnteringContext,
4431  const ObjCObjectPointerType *OPT,
4432  bool ErrorRecovery);
4433 
4434 public:
4435  const TypoExprState &getTypoExprState(TypoExpr *TE) const;
4436 
4437  /// Clears the state of the given TypoExpr.
4438  void clearDelayedTypo(TypoExpr *TE);
4439 
4440  /// Look up a name, looking for a single declaration. Return
4441  /// null if the results were absent, ambiguous, or overloaded.
4442  ///
4443  /// It is preferable to use the elaborated form and explicitly handle
4444  /// ambiguity and overloaded.
4446  SourceLocation Loc,
4447  LookupNameKind NameKind,
4448  RedeclarationKind Redecl
4450  bool LookupBuiltin(LookupResult &R);
4451  void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
4452  bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
4453  bool ForceNoCPlusPlus = false);
4454  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4455  bool InUnqualifiedLookup = false);
4456  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4457  CXXScopeSpec &SS);
4459  bool AllowBuiltinCreation = false,
4460  bool EnteringContext = false);
4462  RedeclarationKind Redecl
4464  bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
4465 
4467  UnresolvedSetImpl &Functions);
4468 
4470  SourceLocation GnuLabelLoc = SourceLocation());
4471 
4475  unsigned Quals);
4476  CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
4477  bool RValueThis, unsigned ThisQuals);
4479  unsigned Quals);
4480  CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
4481  bool RValueThis, unsigned ThisQuals);
4483 
4484  bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
4485  bool IsUDSuffix);
4488  bool AllowRaw, bool AllowTemplate,
4489  bool AllowStringTemplate, bool DiagnoseMissing,
4490  StringLiteral *StringLit = nullptr);
4491  bool isKnownName(StringRef name);
4492 
4493  /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4495  Emitted,
4496  CUDADiscarded, // Discarded due to CUDA/HIP hostness
4497  OMPDiscarded, // Discarded due to OpenMP hostness
4498  TemplateDiscarded, // Discarded due to uninstantiated templates
4499  Unknown,
4500  };
4502  bool Final = false);
4503 
4504  // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4506 
4508  ArrayRef<Expr *> Args, ADLResult &Functions);
4509 
4512  bool IncludeGlobalScope = true,
4513  bool LoadExternal = true);
4516  bool IncludeGlobalScope = true,
4517  bool IncludeDependentBases = false,
4518  bool LoadExternal = true);
4519 
4521  CTK_NonError, // CorrectTypo used in a non error recovery situation.
4522  CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
4523  };
4524 
4526  Sema::LookupNameKind LookupKind,
4527  Scope *S, CXXScopeSpec *SS,
4529  CorrectTypoKind Mode,
4530  DeclContext *MemberContext = nullptr,
4531  bool EnteringContext = false,
4532  const ObjCObjectPointerType *OPT = nullptr,
4533  bool RecordFailure = true);
4534 
4536  Sema::LookupNameKind LookupKind, Scope *S,
4537  CXXScopeSpec *SS,
4541  DeclContext *MemberContext = nullptr,
4542  bool EnteringContext = false,
4543  const ObjCObjectPointerType *OPT = nullptr);
4544 
4545  /// Process any TypoExprs in the given Expr and its children,
4546  /// generating diagnostics as appropriate and returning a new Expr if there
4547  /// were typos that were all successfully corrected and ExprError if one or
4548  /// more typos could not be corrected.
4549  ///
4550  /// \param E The Expr to check for TypoExprs.
4551  ///
4552  /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
4553  /// initializer.
4554  ///
4555  /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
4556  /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
4557  ///
4558  /// \param Filter A function applied to a newly rebuilt Expr to determine if
4559  /// it is an acceptable/usable result from a single combination of typo
4560  /// corrections. As long as the filter returns ExprError, different
4561  /// combinations of corrections will be tried until all are exhausted.
4563  Expr *E, VarDecl *InitDecl = nullptr,
4564  bool RecoverUncorrectedTypos = false,
4565  llvm::function_ref<ExprResult(Expr *)> Filter =
4566  [](Expr *E) -> ExprResult { return E; });
4567 
4569  ExprResult ER, VarDecl *InitDecl = nullptr,
4570  bool RecoverUncorrectedTypos = false,
4571  llvm::function_ref<ExprResult(Expr *)> Filter =
4572  [](Expr *E) -> ExprResult { return E; }) {
4573  return ER.isInvalid()
4574  ? ER
4575  : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
4576  RecoverUncorrectedTypos, Filter);
4577  }
4578 
4579  void diagnoseTypo(const TypoCorrection &Correction,
4580  const PartialDiagnostic &TypoDiag,
4581  bool ErrorRecovery = true);
4582 
4583  void diagnoseTypo(const TypoCorrection &Correction,
4584  const PartialDiagnostic &TypoDiag,
4585  const PartialDiagnostic &PrevNote,
4586  bool ErrorRecovery = true);
4587 
4588  void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4589 
4590  void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
4591  ArrayRef<Expr *> Args,
4592  AssociatedNamespaceSet &AssociatedNamespaces,
4593  AssociatedClassSet &AssociatedClasses);
4594 
4595  void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4596  bool ConsiderLinkage, bool AllowInlineNamespace);
4597 
4598  bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4599  bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4600  bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4601  bool IsRedefinitionInModule(const NamedDecl *New,
4602  const NamedDecl *Old) const;
4603 
4604  void DiagnoseAmbiguousLookup(LookupResult &Result);
4605  //@}
4606 
4607  /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
4608  ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
4609  ArrayRef<Expr *> SubExprs,
4610  QualType T = QualType());
4611 
4612  ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
4613  SourceLocation IdLoc,
4614  bool TypoCorrection = false);
4615  FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4616  SourceLocation Loc);
4617  NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,