clang  16.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/Optional.h"
62 #include "llvm/ADT/SetVector.h"
63 #include "llvm/ADT/SmallBitVector.h"
64 #include "llvm/ADT/SmallPtrSet.h"
65 #include "llvm/ADT/SmallSet.h"
66 #include "llvm/ADT/SmallVector.h"
67 #include "llvm/ADT/TinyPtrVector.h"
68 #include "llvm/Frontend/OpenMP/OMPConstants.h"
69 #include <deque>
70 #include <memory>
71 #include <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 
806  return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
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::makeArrayRef(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  unsigned NumCleanupObjects,
1342 
1343  bool isUnevaluated() const {
1347  }
1348 
1349  bool isConstantEvaluated() const {
1352  }
1353 
1358  // C++2b [expr.const]p14:
1359  // An expression or conversion is in an immediate function
1360  // context if it is potentially evaluated and either:
1361  // * its innermost enclosing non-block scope is a function
1362  // parameter scope of an immediate function, or
1363  // * its enclosing statement is enclosed by the compound-
1364  // statement of a consteval if statement.
1367  }
1368 
1371  (Context ==
1374  }
1375  };
1376 
1377  /// A stack of expression evaluation contexts.
1379 
1380  /// Emit a warning for all pending noderef expressions that we recorded.
1382 
1383  /// Compute the mangling number context for a lambda expression or
1384  /// block literal. Also return the extra mangling decl if any.
1385  ///
1386  /// \param DC - The DeclContext containing the lambda expression or
1387  /// block literal.
1388  std::tuple<MangleNumberingContext *, Decl *>
1390 
1391 
1392  /// SpecialMemberOverloadResult - The overloading result for a special member
1393  /// function.
1394  ///
1395  /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1396  /// integer are used to determine whether overload resolution succeeded.
1398  public:
1399  enum Kind {
1403  };
1404 
1405  private:
1406  llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
1407 
1408  public:
1411  : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1412 
1413  CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1414  void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1415 
1416  Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1417  void setKind(Kind K) { Pair.setInt(K); }
1418  };
1419 
1421  : public llvm::FastFoldingSetNode,
1423  public:
1424  SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1425  : FastFoldingSetNode(ID)
1426  {}
1427  };
1428 
1429  /// A cache of special member function overload resolution results
1430  /// for C++ records.
1431  llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1432 
1433  /// A cache of the flags available in enumerations with the flag_bits
1434  /// attribute.
1435  mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1436 
1437  /// The kind of translation unit we are processing.
1438  ///
1439  /// When we're processing a complete translation unit, Sema will perform
1440  /// end-of-translation-unit semantic tasks (such as creating
1441  /// initializers for tentative definitions in C) once parsing has
1442  /// completed. Modules and precompiled headers perform different kinds of
1443  /// checks.
1445 
1446  llvm::BumpPtrAllocator BumpAlloc;
1447 
1448  /// The number of SFINAE diagnostics that have been trapped.
1450 
1451  typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1453 
1454  /// A mapping from parameters with unparsed default arguments to the
1455  /// set of instantiations of each parameter.
1456  ///
1457  /// This mapping is a temporary data structure used when parsing
1458  /// nested class templates or nested classes of class templates,
1459  /// where we might end up instantiating an inner class before the
1460  /// default arguments of its methods have been parsed.
1462 
1463  // Contains the locations of the beginning of unparsed default
1464  // argument locations.
1465  llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1466 
1467  /// UndefinedInternals - all the used, undefined objects which require a
1468  /// definition in this translation unit.
1469  llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1470 
1471  /// Determine if VD, which must be a variable or function, is an external
1472  /// symbol that nonetheless can't be referenced from outside this translation
1473  /// unit because its type has no linkage and it's not extern "C".
1475 
1476  /// Obtain a sorted list of functions that are undefined but ODR-used.
1477  void getUndefinedButUsed(
1478  SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1479 
1480  /// Retrieves list of suspicious delete-expressions that will be checked at
1481  /// the end of translation unit.
1482  const llvm::MapVector<FieldDecl *, DeleteLocs> &
1484 
1486  public:
1487  using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1488  using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1489  iterator begin() { return Methods.begin(); }
1490  iterator end() { return Methods.end(); }
1491  iterator find(Selector Sel) { return Methods.find(Sel); }
1492  std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1493  return Methods.insert(Val);
1494  }
1495  int count(Selector Sel) const { return Methods.count(Sel); }
1496  bool empty() const { return Methods.empty(); }
1497 
1498  private:
1499  llvm::DenseMap<Selector, Lists> Methods;
1500  };
1501 
1502  /// Method Pool - allows efficient lookup when typechecking messages to "id".
1503  /// We need to maintain a list, since selectors can have differing signatures
1504  /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1505  /// of selectors are "overloaded").
1506  /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1507  /// methods inside categories with a particular selector.
1509 
1510  /// Method selectors used in a \@selector expression. Used for implementation
1511  /// of -Wselector.
1512  llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1513 
1514  /// List of SourceLocations where 'self' is implicitly retained inside a
1515  /// block.
1518 
1519  /// Kinds of C++ special members.
1528  };
1529 
1530  typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1532 
1533  /// The C++ special members which we are currently in the process of
1534  /// declaring. If this process recursively triggers the declaration of the
1535  /// same special member, we should act as if it is not yet declared.
1537 
1538  /// Kinds of defaulted comparison operator functions.
1539  enum class DefaultedComparisonKind : unsigned char {
1540  /// This is not a defaultable comparison operator.
1541  None,
1542  /// This is an operator== that should be implemented as a series of
1543  /// subobject comparisons.
1544  Equal,
1545  /// This is an operator<=> that should be implemented as a series of
1546  /// subobject comparisons.
1547  ThreeWay,
1548  /// This is an operator!= that should be implemented as a rewrite in terms
1549  /// of a == comparison.
1550  NotEqual,
1551  /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1552  /// terms of a <=> comparison.
1553  Relational,
1554  };
1555 
1556  /// The function definitions which were renamed as part of typo-correction
1557  /// to match their respective declarations. We want to keep track of them
1558  /// to ensure that we don't emit a "redefinition" error if we encounter a
1559  /// correctly named definition after the renamed definition.
1561 
1562  /// Stack of types that correspond to the parameter entities that are
1563  /// currently being copy-initialized. Can be empty.
1565 
1566  void ReadMethodPool(Selector Sel);
1568 
1569  /// Private Helper predicate to check for 'self'.
1570  bool isSelfExpr(Expr *RExpr);
1571  bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1572 
1573  /// Cause the active diagnostic on the DiagosticsEngine to be
1574  /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1575  /// should not be used elsewhere.
1576  void EmitCurrentDiagnostic(unsigned DiagID);
1577 
1578  /// Records and restores the CurFPFeatures state on entry/exit of compound
1579  /// statements.
1581  public:
1584  FPOptionsOverride getOverrides() { return OldOverrides; }
1585 
1586  private:
1587  Sema& S;
1588  FPOptions OldFPFeaturesState;
1589  FPOptionsOverride OldOverrides;
1590  LangOptions::FPEvalMethodKind OldEvalMethod;
1591  SourceLocation OldFPPragmaLocation;
1592  };
1593 
1594  void addImplicitTypedef(StringRef Name, QualType T);
1595 
1596  bool WarnedStackExhausted = false;
1597 
1598  /// Increment when we find a reference; decrement when we find an ignored
1599  /// assignment. Ultimately the value is 0 if every reference is an ignored
1600  /// assignment.
1601  llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1602 
1603  /// Indicate RISC-V vector builtin functions enabled or not.
1605 
1606 private:
1607  std::unique_ptr<sema::RISCVIntrinsicManager> RVIntrinsicManager;
1608 
1609  Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1610 
1611  bool WarnedDarwinSDKInfoMissing = false;
1612 
1613 public:
1614  Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1616  CodeCompleteConsumer *CompletionConsumer = nullptr);
1617  ~Sema();
1618 
1619  /// Perform initialization that occurs after the parser has been
1620  /// initialized but before it parses anything.
1621  void Initialize();
1622 
1623  /// This virtual key function only exists to limit the emission of debug info
1624  /// describing the Sema class. GCC and Clang only emit debug info for a class
1625  /// with a vtable when the vtable is emitted. Sema is final and not
1626  /// polymorphic, but the debug info size savings are so significant that it is
1627  /// worth adding a vtable just to take advantage of this optimization.
1628  virtual void anchor();
1629 
1630  const LangOptions &getLangOpts() const { return LangOpts; }
1633 
1636  Preprocessor &getPreprocessor() const { return PP; }
1637  ASTContext &getASTContext() const { return Context; }
1638  ASTConsumer &getASTConsumer() const { return Consumer; }
1640  ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
1641 
1643  StringRef Platform);
1645 
1646  ///Registers an external source. If an external source already exists,
1647  /// creates a multiplex external source and appends to it.
1648  ///
1649  ///\param[in] E - A non-null external sema source.
1650  ///
1652 
1653  void PrintStats() const;
1654 
1655  /// Warn that the stack is nearly exhausted.
1657 
1658  /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1659  /// guaranteed). Produces a warning if we're low on stack space and allocates
1660  /// more in that case. Use this in code that may recurse deeply (for example,
1661  /// in template instantiation) to avoid stack overflow.
1663  llvm::function_ref<void()> Fn);
1664 
1665  /// Helper class that creates diagnostics with optional
1666  /// template instantiation stacks.
1667  ///
1668  /// This class provides a wrapper around the basic DiagnosticBuilder
1669  /// class that emits diagnostics. ImmediateDiagBuilder is
1670  /// responsible for emitting the diagnostic (as DiagnosticBuilder
1671  /// does) and, if the diagnostic comes from inside a template
1672  /// instantiation, printing the template instantiation stack as
1673  /// well.
1675  Sema &SemaRef;
1676  unsigned DiagID;
1677 
1678  public:
1679  ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1680  : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1681  ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1682  : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1683 
1684  // This is a cunning lie. DiagnosticBuilder actually performs move
1685  // construction in its copy constructor (but due to varied uses, it's not
1686  // possible to conveniently express this as actual move construction). So
1687  // the default copy ctor here is fine, because the base class disables the
1688  // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1689  // in that case anwyay.
1690  ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1691 
1693  // If we aren't active, there is nothing to do.
1694  if (!isActive()) return;
1695 
1696  // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1697  // builder itself so it won't emit the diagnostic in its own destructor.
1698  //
1699  // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1700  // do its own needless checks to see if the diagnostic needs to be
1701  // emitted. However, because we take care to ensure that the builder
1702  // objects never escape, a sufficiently smart compiler will be able to
1703  // eliminate that code.
1704  Clear();
1705 
1706  // Dispatch to Sema to emit the diagnostic.
1707  SemaRef.EmitCurrentDiagnostic(DiagID);
1708  }
1709 
1710  /// Teach operator<< to produce an object of the correct type.
1711  template <typename T>
1712  friend const ImmediateDiagBuilder &
1714  const DiagnosticBuilder &BaseDiag = Diag;
1715  BaseDiag << Value;
1716  return Diag;
1717  }
1718 
1719  // It is necessary to limit this to rvalue reference to avoid calling this
1720  // function with a bitfield lvalue argument since non-const reference to
1721  // bitfield is not allowed.
1722  template <typename T,
1723  typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1724  const ImmediateDiagBuilder &operator<<(T &&V) const {
1725  const DiagnosticBuilder &BaseDiag = *this;
1726  BaseDiag << std::move(V);
1727  return *this;
1728  }
1729  };
1730 
1731  /// A generic diagnostic builder for errors which may or may not be deferred.
1732  ///
1733  /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1734  /// which are not allowed to appear inside __device__ functions and are
1735  /// allowed to appear in __host__ __device__ functions only if the host+device
1736  /// function is never codegen'ed.
1737  ///
1738  /// To handle this, we use the notion of "deferred diagnostics", where we
1739  /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1740  ///
1741  /// This class lets you emit either a regular diagnostic, a deferred
1742  /// diagnostic, or no diagnostic at all, according to an argument you pass to
1743  /// its constructor, thus simplifying the process of creating these "maybe
1744  /// deferred" diagnostics.
1746  public:
1747  enum Kind {
1748  /// Emit no diagnostics.
1750  /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1752  /// Emit the diagnostic immediately, and, if it's a warning or error, also
1753  /// emit a call stack showing how this function can be reached by an a
1754  /// priori known-emitted function.
1756  /// Create a deferred diagnostic, which is emitted only if the function
1757  /// it's attached to is codegen'ed. Also emit a call stack as with
1758  /// K_ImmediateWithCallStack.
1760  };
1761 
1762  SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1763  FunctionDecl *Fn, Sema &S);
1765  SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1767 
1768  bool isImmediate() const { return ImmediateDiag.has_value(); }
1769 
1770  /// Convertible to bool: True if we immediately emitted an error, false if
1771  /// we didn't emit an error or we created a deferred error.
1772  ///
1773  /// Example usage:
1774  ///
1775  /// if (SemaDiagnosticBuilder(...) << foo << bar)
1776  /// return ExprError();
1777  ///
1778  /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1779  /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1780  operator bool() const { return isImmediate(); }
1781 
1782  template <typename T>
1783  friend const SemaDiagnosticBuilder &
1785  if (Diag.ImmediateDiag)
1786  *Diag.ImmediateDiag << Value;
1787  else if (Diag.PartialDiagId)
1788  Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1789  << Value;
1790  return Diag;
1791  }
1792 
1793  // It is necessary to limit this to rvalue reference to avoid calling this
1794  // function with a bitfield lvalue argument since non-const reference to
1795  // bitfield is not allowed.
1796  template <typename T,
1797  typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1798  const SemaDiagnosticBuilder &operator<<(T &&V) const {
1799  if (ImmediateDiag)
1800  *ImmediateDiag << std::move(V);
1801  else if (PartialDiagId)
1802  S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1803  return *this;
1804  }
1805 
1806  friend const SemaDiagnosticBuilder &
1808  if (Diag.ImmediateDiag)
1809  PD.Emit(*Diag.ImmediateDiag);
1810  else if (Diag.PartialDiagId)
1811  Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1812  return Diag;
1813  }
1814 
1815  void AddFixItHint(const FixItHint &Hint) const {
1816  if (ImmediateDiag)
1817  ImmediateDiag->AddFixItHint(Hint);
1818  else if (PartialDiagId)
1819  S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1820  }
1821 
1823  return ExprError();
1824  }
1826  return StmtError();
1827  }
1828  operator ExprResult() const { return ExprError(); }
1829  operator StmtResult() const { return StmtError(); }
1830  operator TypeResult() const { return TypeError(); }
1831  operator DeclResult() const { return DeclResult(true); }
1832  operator MemInitResult() const { return MemInitResult(true); }
1833 
1834  private:
1835  Sema &S;
1836  SourceLocation Loc;
1837  unsigned DiagID;
1838  FunctionDecl *Fn;
1839  bool ShowCallStack;
1840 
1841  // Invariant: At most one of these Optionals has a value.
1842  // FIXME: Switch these to a Variant once that exists.
1844  llvm::Optional<unsigned> PartialDiagId;
1845  };
1846 
1847  /// Is the last error level diagnostic immediate. This is used to determined
1848  /// whether the next info diagnostic should be immediate.
1850 
1851  /// Emit a diagnostic.
1852  SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1853  bool DeferHint = false);
1854 
1855  /// Emit a partial diagnostic.
1857  bool DeferHint = false);
1858 
1859  /// Build a partial diagnostic.
1860  PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1861 
1862  /// Whether deferrable diagnostics should be deferred.
1863  bool DeferDiags = false;
1864 
1865  /// RAII class to control scope of DeferDiags.
1867  Sema &S;
1868  bool SavedDeferDiags = false;
1869 
1870  public:
1872  : S(S), SavedDeferDiags(S.DeferDiags) {
1873  S.DeferDiags = DeferDiags;
1874  }
1875  ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1876  };
1877 
1878  /// Whether uncompilable error has occurred. This includes error happens
1879  /// in deferred diagnostics.
1880  bool hasUncompilableErrorOccurred() const;
1881 
1882  bool findMacroSpelling(SourceLocation &loc, StringRef name);
1883 
1884  /// Get a string to suggest for zero-initialization of a type.
1885  std::string
1888 
1889  /// Calls \c Lexer::getLocForEndOfToken()
1891 
1892  /// Retrieve the module loader associated with the preprocessor.
1893  ModuleLoader &getModuleLoader() const;
1894 
1895  /// Invent a new identifier for parameters of abbreviated templates.
1896  IdentifierInfo *
1898  unsigned Index);
1899 
1901 
1902  private:
1903  /// Function or variable declarations to be checked for whether the deferred
1904  /// diagnostics should be emitted.
1905  llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1906 
1907  public:
1908  // Emit all deferred diagnostics.
1909  void emitDeferredDiags();
1910 
1912  /// The global module fragment, between 'module;' and a module-declaration.
1914  /// A normal translation unit fragment. For a non-module unit, this is the
1915  /// entire translation unit. Otherwise, it runs from the module-declaration
1916  /// to the private-module-fragment (if any) or the end of the TU (if not).
1918  /// The private module fragment, between 'module :private;' and the end of
1919  /// the translation unit.
1921  };
1922 
1926 
1928 
1930 
1931  void PushFunctionScope();
1932  void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1934 
1935  /// This is used to inform Sema what the current TemplateParameterDepth
1936  /// is during Parsing. Currently it is used to pass on the depth
1937  /// when parsing generic lambda 'auto' parameters.
1939 
1940  void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1942  unsigned OpenMPCaptureLevel = 0);
1943 
1944  /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1945  /// time after they've been popped.
1947  Sema *Self;
1948 
1949  public:
1950  explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1952  };
1953 
1954  using PoppedFunctionScopePtr =
1955  std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1956 
1959  const Decl *D = nullptr,
1960  QualType BlockType = QualType());
1961 
1963  return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1964  }
1965 
1967 
1971  void setFunctionHasMustTail();
1972 
1973  void PushCompoundScope(bool IsStmtExpr);
1974  void PopCompoundScope();
1975 
1977 
1979 
1980  /// Retrieve the current block, if any.
1982 
1983  /// Get the innermost lambda enclosing the current location, if any. This
1984  /// looks through intervening non-lambda scopes such as local functions and
1985  /// blocks.
1987 
1988  /// Retrieve the current lambda scope info, if any.
1989  /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1990  /// lambda scope info ignoring all inner capturing scopes that are not
1991  /// lambda scopes.
1993  getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1994 
1995  /// Retrieve the current generic lambda info, if any.
1997 
1998  /// Retrieve the current captured region, if any.
2000 
2001  /// Retrieve the current function, if any, that should be analyzed for
2002  /// potential availability violations.
2004 
2005  /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
2007 
2008  /// Called before parsing a function declarator belonging to a function
2009  /// declaration.
2011  unsigned TemplateParameterDepth);
2012 
2013  /// Called after parsing a function declarator belonging to a function
2014  /// declaration.
2016 
2017  void ActOnComment(SourceRange Comment);
2018 
2019  //===--------------------------------------------------------------------===//
2020  // Type Analysis / Processing: SemaType.cpp.
2021  //
2022 
2024  const DeclSpec *DS = nullptr);
2025  QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
2026  const DeclSpec *DS = nullptr);
2028  SourceLocation Loc, DeclarationName Entity);
2029  QualType BuildReferenceType(QualType T, bool LValueRef,
2030  SourceLocation Loc, DeclarationName Entity);
2032  Expr *ArraySize, unsigned Quals,
2033  SourceRange Brackets, DeclarationName Entity);
2034  QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
2035  QualType BuildExtVectorType(QualType T, Expr *ArraySize,
2036  SourceLocation AttrLoc);
2037  QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
2038  SourceLocation AttrLoc);
2039 
2040  QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
2041  SourceLocation AttrLoc);
2042 
2043  /// Same as above, but constructs the AddressSpace index if not provided.
2045  SourceLocation AttrLoc);
2046 
2048 
2050 
2051  /// Build a function type.
2052  ///
2053  /// This routine checks the function type according to C++ rules and
2054  /// under the assumption that the result type and parameter types have
2055  /// just been instantiated from a template. It therefore duplicates
2056  /// some of the behavior of GetTypeForDeclarator, but in a much
2057  /// simpler form that is only suitable for this narrow use case.
2058  ///
2059  /// \param T The return type of the function.
2060  ///
2061  /// \param ParamTypes The parameter types of the function. This array
2062  /// will be modified to account for adjustments to the types of the
2063  /// function parameters.
2064  ///
2065  /// \param Loc The location of the entity whose type involves this
2066  /// function type or, if there is no such entity, the location of the
2067  /// type that will have function type.
2068  ///
2069  /// \param Entity The name of the entity that involves the function
2070  /// type, if known.
2071  ///
2072  /// \param EPI Extra information about the function type. Usually this will
2073  /// be taken from an existing function with the same prototype.
2074  ///
2075  /// \returns A suitable function type, if there are no errors. The
2076  /// unqualified type will always be a FunctionProtoType.
2077  /// Otherwise, returns a NULL type.
2079  MutableArrayRef<QualType> ParamTypes,
2080  SourceLocation Loc, DeclarationName Entity,
2081  const FunctionProtoType::ExtProtoInfo &EPI);
2082 
2084  SourceLocation Loc,
2085  DeclarationName Entity);
2087  SourceLocation Loc, DeclarationName Entity);
2091  SourceLocation Loc);
2093  SourceLocation Loc);
2094  QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2095 
2098 
2099  /// Package the given type and TSI into a ParsedType.
2104  TypeSourceInfo **TInfo = nullptr);
2105  CanThrowResult canThrow(const Stmt *E);
2106  /// Determine whether the callee of a particular function call can throw.
2107  /// E, D and Loc are all optional.
2108  static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2109  SourceLocation Loc = SourceLocation());
2111  const FunctionProtoType *FPT);
2118  const FunctionProtoType *Old, SourceLocation OldLoc,
2119  const FunctionProtoType *New, SourceLocation NewLoc);
2121  const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2122  const FunctionProtoType *Old, SourceLocation OldLoc,
2123  const FunctionProtoType *New, SourceLocation NewLoc);
2124  bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2125  bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2126  const PartialDiagnostic &NestedDiagID,
2127  const PartialDiagnostic &NoteID,
2128  const PartialDiagnostic &NoThrowDiagID,
2129  const FunctionProtoType *Superset,
2130  SourceLocation SuperLoc,
2131  const FunctionProtoType *Subset,
2132  SourceLocation SubLoc);
2133  bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2134  const PartialDiagnostic &NoteID,
2135  const FunctionProtoType *Target,
2136  SourceLocation TargetLoc,
2137  const FunctionProtoType *Source,
2138  SourceLocation SourceLoc);
2139 
2141 
2142  /// The parser has parsed the context-sensitive type 'instancetype'
2143  /// in an Objective-C message declaration. Return the appropriate type.
2145 
2146  /// Abstract class used to diagnose incomplete types.
2147  struct TypeDiagnoser {
2149 
2150  virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2151  virtual ~TypeDiagnoser() {}
2152  };
2153 
2154  static int getPrintable(int I) { return I; }
2155  static unsigned getPrintable(unsigned I) { return I; }
2156  static bool getPrintable(bool B) { return B; }
2157  static const char * getPrintable(const char *S) { return S; }
2158  static StringRef getPrintable(StringRef S) { return S; }
2159  static const std::string &getPrintable(const std::string &S) { return S; }
2160  static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2161  return II;
2162  }
2164  static QualType getPrintable(QualType T) { return T; }
2165  static SourceRange getPrintable(SourceRange R) { return R; }
2166  static SourceRange getPrintable(SourceLocation L) { return L; }
2167  static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2168  static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2169 
2170  template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2171  protected:
2172  unsigned DiagID;
2173  std::tuple<const Ts &...> Args;
2174 
2175  template <std::size_t... Is>
2176  void emit(const SemaDiagnosticBuilder &DB,
2177  std::index_sequence<Is...>) const {
2178  // Apply all tuple elements to the builder in order.
2179  bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2180  (void)Dummy;
2181  }
2182 
2183  public:
2184  BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2185  : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2186  assert(DiagID != 0 && "no diagnostic for type diagnoser");
2187  }
2188 
2189  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2190  const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2191  emit(DB, std::index_sequence_for<Ts...>());
2192  DB << T;
2193  }
2194  };
2195 
2196  /// Do a check to make sure \p Name looks like a legal argument for the
2197  /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
2198  /// is invalid for the given declaration.
2199  ///
2200  /// \p AL is used to provide caret diagnostics in case of a malformed name.
2201  ///
2202  /// \returns true if the name is a valid swift name for \p D, false otherwise.
2203  bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2204  const ParsedAttr &AL, bool IsAsync);
2205 
2206  /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2207  /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2208  /// For example, a diagnostic with no other parameters would generally have
2209  /// the form "...%select{incomplete|sizeless}0 type %1...".
2210  template <typename... Ts>
2212  public:
2213  SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2214  : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2215 
2216  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2217  const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2218  this->emit(DB, std::index_sequence_for<Ts...>());
2219  DB << T->isSizelessType() << T;
2220  }
2221  };
2222 
2223  enum class CompleteTypeKind {
2224  /// Apply the normal rules for complete types. In particular,
2225  /// treat all sizeless types as incomplete.
2226  Normal,
2227 
2228  /// Relax the normal rules for complete types so that they include
2229  /// sizeless built-in types.
2231 
2232  // FIXME: Eventually we should flip the default to Normal and opt in
2233  // to AcceptSizeless rather than opt out of it.
2235  };
2236 
2238 
2239 private:
2240  /// Methods for marking which expressions involve dereferencing a pointer
2241  /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2242  /// they are parsed, meaning that a noderef pointer may not be accessed. For
2243  /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2244  /// `*p`, but need to check that `address of` is called on it. This requires
2245  /// keeping a container of all pending expressions and checking if the address
2246  /// of them are eventually taken.
2247  void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2248  void CheckAddressOfNoDeref(const Expr *E);
2249  void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2250 
2251  bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2252  CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2253 
2254  struct ModuleScope {
2255  SourceLocation BeginLoc;
2256  clang::Module *Module = nullptr;
2257  bool ModuleInterface = false;
2258  bool IsPartition = false;
2259  bool ImplicitGlobalModuleFragment = false;
2260  VisibleModuleSet OuterVisibleModules;
2261  };
2262  /// The modules we're currently parsing.
2264  /// The global module fragment of the current translation unit.
2265  clang::Module *GlobalModuleFragment = nullptr;
2266 
2267  /// The modules we imported directly.
2268  llvm::SmallPtrSet<clang::Module *, 8> DirectModuleImports;
2269 
2270  /// Namespace definitions that we will export when they finish.
2271  llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2272 
2273  /// In a C++ standard module, inline declarations require a definition to be
2274  /// present at the end of a definition domain. This set holds the decls to
2275  /// be checked at the end of the TU.
2276  llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
2277 
2278  /// Helper function to judge if we are in module purview.
2279  /// Return false if we are not in a module.
2280  bool isCurrentModulePurview() const {
2281  return getCurrentModule() ? getCurrentModule()->isModulePurview() : false;
2282  }
2283 
2284  /// Enter the scope of the global module.
2285  Module *PushGlobalModuleFragment(SourceLocation BeginLoc, bool IsImplicit);
2286  /// Leave the scope of the global module.
2287  void PopGlobalModuleFragment();
2288 
2289  VisibleModuleSet VisibleModules;
2290 
2291  /// Cache for module units which is usable for current module.
2292  llvm::DenseSet<const Module *> UsableModuleUnitsCache;
2293 
2294  bool isUsableModule(const Module *M);
2295 
2296  bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
2297 
2298 public:
2299  /// Get the module unit whose scope we are currently within.
2301  return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2302  }
2303 
2304  /// Is the module scope we are an interface?
2306  return ModuleScopes.empty() ? false : ModuleScopes.back().ModuleInterface;
2307  }
2308 
2309  /// Get the module owning an entity.
2310  Module *getOwningModule(const Decl *Entity) {
2311  return Entity->getOwningModule();
2312  }
2313 
2315  return DirectModuleImports.contains(M);
2316  }
2317 
2318  // Determine whether the module M belongs to the current TU.
2319  bool isModuleUnitOfCurrentTU(const Module *M) const;
2320 
2321  /// Make a merged definition of an existing hidden definition \p ND
2322  /// visible at the specified location.
2324 
2325  bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2326 
2327  // When loading a non-modular PCH files, this is used to restore module
2328  // visibility.
2329  void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2330  VisibleModules.setVisible(Mod, ImportLoc);
2331  }
2332 
2333  /// Determine whether a declaration is visible to name lookup.
2334  bool isVisible(const NamedDecl *D) {
2335  return D->isUnconditionallyVisible() ||
2336  isAcceptableSlow(D, AcceptableKind::Visible);
2337  }
2338 
2339  /// Determine whether a declaration is reachable.
2340  bool isReachable(const NamedDecl *D) {
2341  // All visible declarations are reachable.
2342  return D->isUnconditionallyVisible() ||
2343  isAcceptableSlow(D, AcceptableKind::Reachable);
2344  }
2345 
2346  /// Determine whether a declaration is acceptable (visible/reachable).
2348  return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
2349  }
2350 
2351  /// Determine whether any declaration of an entity is visible.
2352  bool
2354  llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2355  return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2356  }
2357 
2358  bool hasVisibleDeclarationSlow(const NamedDecl *D,
2360  /// Determine whether any declaration of an entity is reachable.
2361  bool
2363  llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2364  return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
2365  }
2367  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2368 
2371 
2372  /// Determine if \p D and \p Suggested have a structurally compatible
2373  /// layout as described in C11 6.2.7/1.
2374  bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2375 
2376  /// Determine if \p D has a visible definition. If not, suggest a declaration
2377  /// that should be made visible to expose the definition.
2378  bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2379  bool OnlyNeedComplete = false);
2381  NamedDecl *Hidden;
2382  return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2383  }
2384 
2385  /// Determine if \p D has a reachable definition. If not, suggest a
2386  /// declaration that should be made reachable to expose the definition.
2387  bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
2388  bool OnlyNeedComplete = false);
2390  NamedDecl *Hidden;
2391  return hasReachableDefinition(D, &Hidden);
2392  }
2393 
2394  bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
2396  bool OnlyNeedComplete = false);
2398  NamedDecl *Hidden;
2399  return hasAcceptableDefinition(D, &Hidden, Kind);
2400  }
2401 
2402  /// Determine if the template parameter \p D has a visible default argument.
2403  bool
2405  llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2406  /// Determine if the template parameter \p D has a reachable default argument.
2408  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2409  /// Determine if the template parameter \p D has a reachable default argument.
2413 
2414  /// Determine if there is a visible declaration of \p D that is an explicit
2415  /// specialization declaration for a specialization of a template. (For a
2416  /// member specialization, use hasVisibleMemberSpecialization.)
2418  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2419  /// Determine if there is a reachable declaration of \p D that is an explicit
2420  /// specialization declaration for a specialization of a template. (For a
2421  /// member specialization, use hasReachableMemberSpecialization.)
2423  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2424 
2425  /// Determine if there is a visible declaration of \p D that is a member
2426  /// specialization declaration (as opposed to an instantiated declaration).
2428  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2429  /// Determine if there is a reachable declaration of \p D that is a member
2430  /// specialization declaration (as opposed to an instantiated declaration).
2432  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2433 
2434  /// Determine if \p A and \p B are equivalent internal linkage declarations
2435  /// from different modules, and thus an ambiguity error can be downgraded to
2436  /// an extension warning.
2438  const NamedDecl *B);
2440  SourceLocation Loc, const NamedDecl *D,
2442 
2444 
2445  // Check whether the size of array element of type \p EltTy is a multiple of
2446  // its alignment and return false if it isn't.
2448 
2451  return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2452  }
2454  CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2456  CompleteTypeKind Kind, unsigned DiagID);
2457 
2459  TypeDiagnoser &Diagnoser) {
2460  return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2461  }
2462  bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2463  return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2464  }
2465 
2466  template <typename... Ts>
2467  bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2468  const Ts &...Args) {
2469  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2470  return RequireCompleteType(Loc, T, Diagnoser);
2471  }
2472 
2473  template <typename... Ts>
2474  bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2475  const Ts &... Args) {
2476  SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2477  return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2478  }
2479 
2480  /// Get the type of expression E, triggering instantiation to complete the
2481  /// type if necessary -- that is, if the expression refers to a templated
2482  /// static data member of incomplete array type.
2483  ///
2484  /// May still return an incomplete type if instantiation was not possible or
2485  /// if the type is incomplete for a different reason. Use
2486  /// RequireCompleteExprType instead if a diagnostic is expected for an
2487  /// incomplete expression type.
2489 
2490  void completeExprArrayBound(Expr *E);
2492  TypeDiagnoser &Diagnoser);
2493  bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2494 
2495  template <typename... Ts>
2496  bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2497  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2498  return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2499  }
2500 
2501  template <typename... Ts>
2502  bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2503  const Ts &... Args) {
2504  SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2505  return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2506  }
2507 
2509  TypeDiagnoser &Diagnoser);
2510  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2511 
2512  template <typename... Ts>
2513  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2514  const Ts &...Args) {
2515  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2516  return RequireLiteralType(Loc, T, Diagnoser);
2517  }
2518 
2520  const CXXScopeSpec &SS, QualType T,
2521  TagDecl *OwnedTagDecl = nullptr);
2522 
2523  // Returns the underlying type of a decltype with the given expression.
2525 
2527  /// If AsUnevaluated is false, E is treated as though it were an evaluated
2528  /// context, such as when building a type for decltype(auto).
2529  QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
2530 
2533  SourceLocation Loc);
2538  QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
2539  SourceLocation Loc);
2540  QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
2541  SourceLocation Loc);
2543  SourceLocation Loc);
2545  SourceLocation Loc);
2547  SourceLocation Loc);
2548 
2549  //===--------------------------------------------------------------------===//
2550  // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2551  //
2552 
2553  struct SkipBodyInfo {
2556  New(nullptr) {}
2561  };
2562 
2563  DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2564 
2566 
2568 
2570  Scope *S, CXXScopeSpec *SS = nullptr,
2571  bool isClassName = false, bool HasTrailingDot = false,
2572  ParsedType ObjectType = nullptr,
2573  bool IsCtorOrDtorName = false,
2574  bool WantNontrivialTypeSourceInfo = false,
2575  bool IsClassTemplateDeductionContext = true,
2576  ImplicitTypenameContext AllowImplicitTypename =
2578  IdentifierInfo **CorrectedII = nullptr);
2580  bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2582  SourceLocation IILoc,
2583  Scope *S,
2584  CXXScopeSpec *SS,
2585  ParsedType &SuggestedType,
2586  bool IsTemplateName = false);
2587 
2588  /// Attempt to behave like MSVC in situations where lookup of an unqualified
2589  /// type name has failed in a dependent context. In these situations, we
2590  /// automatically form a DependentTypeName that will retry lookup in a related
2591  /// scope during instantiation.
2593  SourceLocation NameLoc,
2594  bool IsTemplateTypeArg);
2595 
2596  /// Describes the result of the name lookup and resolution performed
2597  /// by \c ClassifyName().
2599  /// This name is not a type or template in this context, but might be
2600  /// something else.
2602  /// Classification failed; an error has been produced.
2604  /// The name has been typo-corrected to a keyword.
2606  /// The name was classified as a type.
2608  /// The name was classified as a specific non-type, non-template
2609  /// declaration. ActOnNameClassifiedAsNonType should be called to
2610  /// convert the declaration to an expression.
2612  /// The name was classified as an ADL-only function name.
2613  /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2614  /// result to an expression.
2616  /// The name denotes a member of a dependent type that could not be
2617  /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2618  /// convert the result to an expression.
2620  /// The name was classified as an overload set, and an expression
2621  /// representing that overload set has been formed.
2622  /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2623  /// expression referencing the overload set.
2625  /// The name was classified as a template whose specializations are types.
2627  /// The name was classified as a variable template name.
2629  /// The name was classified as a function template name.
2631  /// The name was classified as an ADL-only function template name.
2633  /// The name was classified as a concept name.
2635  };
2636 
2639  union {
2644  };
2645 
2646  explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2647 
2648  public:
2650 
2651  NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2652 
2654  return NameClassification(NC_Error);
2655  }
2656 
2659  }
2660 
2663  Result.Expr = E;
2664  return Result;
2665  }
2666 
2669  Result.NonTypeDecl = D;
2670  return Result;
2671  }
2672 
2675  }
2676 
2679  }
2680 
2683  Result.Template = Name;
2684  return Result;
2685  }
2686 
2689  Result.Template = Name;
2690  return Result;
2691  }
2692 
2695  Result.Template = Name;
2696  return Result;
2697  }
2698 
2701  Result.Template = Name;
2702  return Result;
2703  }
2704 
2707  Result.Template = Name;
2708  return Result;
2709  }
2710 
2711  NameClassificationKind getKind() const { return Kind; }
2712 
2714  assert(Kind == NC_OverloadSet);
2715  return Expr;
2716  }
2717 
2719  assert(Kind == NC_Type);
2720  return Type;
2721  }
2722 
2724  assert(Kind == NC_NonType);
2725  return NonTypeDecl;
2726  }
2727 
2729  assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2730  Kind == NC_VarTemplate || Kind == NC_Concept ||
2731  Kind == NC_UndeclaredTemplate);
2732  return Template;
2733  }
2734 
2736  switch (Kind) {
2737  case NC_TypeTemplate:
2738  return TNK_Type_template;
2739  case NC_FunctionTemplate:
2740  return TNK_Function_template;
2741  case NC_VarTemplate:
2742  return TNK_Var_template;
2743  case NC_Concept:
2744  return TNK_Concept_template;
2745  case NC_UndeclaredTemplate:
2746  return TNK_Undeclared_template;
2747  default:
2748  llvm_unreachable("unsupported name classification.");
2749  }
2750  }
2751  };
2752 
2753  /// Perform name lookup on the given name, classifying it based on
2754  /// the results of name lookup and the following token.
2755  ///
2756  /// This routine is used by the parser to resolve identifiers and help direct
2757  /// parsing. When the identifier cannot be found, this routine will attempt
2758  /// to correct the typo and classify based on the resulting name.
2759  ///
2760  /// \param S The scope in which we're performing name lookup.
2761  ///
2762  /// \param SS The nested-name-specifier that precedes the name.
2763  ///
2764  /// \param Name The identifier. If typo correction finds an alternative name,
2765  /// this pointer parameter will be updated accordingly.
2766  ///
2767  /// \param NameLoc The location of the identifier.
2768  ///
2769  /// \param NextToken The token following the identifier. Used to help
2770  /// disambiguate the name.
2771  ///
2772  /// \param CCC The correction callback, if typo correction is desired.
2773  NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2774  IdentifierInfo *&Name, SourceLocation NameLoc,
2775  const Token &NextToken,
2776  CorrectionCandidateCallback *CCC = nullptr);
2777 
2778  /// Act on the result of classifying a name as an undeclared (ADL-only)
2779  /// non-type declaration.
2781  SourceLocation NameLoc);
2782  /// Act on the result of classifying a name as an undeclared member of a
2783  /// dependent base class.
2785  IdentifierInfo *Name,
2786  SourceLocation NameLoc,
2787  bool IsAddressOfOperand);
2788  /// Act on the result of classifying a name as a specific non-type
2789  /// declaration.
2791  NamedDecl *Found,
2792  SourceLocation NameLoc,
2793  const Token &NextToken);
2794  /// Act on the result of classifying a name as an overload set.
2796 
2797  /// Describes the detailed kind of a template name. Used in diagnostics.
2799  ClassTemplate,
2801  VarTemplate,
2802  AliasTemplate,
2804  Concept,
2806  };
2809 
2810  /// Determine whether it's plausible that E was intended to be a
2811  /// template-name.
2812  bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2813  if (!getLangOpts().CPlusPlus || E.isInvalid())
2814  return false;
2815  Dependent = false;
2816  if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2817  return !DRE->hasExplicitTemplateArgs();
2818  if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2819  return !ME->hasExplicitTemplateArgs();
2820  Dependent = true;
2821  if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2822  return !DSDRE->hasExplicitTemplateArgs();
2823  if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2824  return !DSME->hasExplicitTemplateArgs();
2825  // Any additional cases recognized here should also be handled by
2826  // diagnoseExprIntendedAsTemplateName.
2827  return false;
2828  }
2830  SourceLocation Less,
2831  SourceLocation Greater);
2832 
2833  void warnOnReservedIdentifier(const NamedDecl *D);
2834 
2836 
2838  MultiTemplateParamsArg TemplateParameterLists);
2840  QualType &T, SourceLocation Loc,
2841  unsigned FailedFoldDiagID);
2845  DeclarationName Name, SourceLocation Loc,
2846  bool IsTemplateId);
2847  void
2848  diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2849  SourceLocation FallbackLoc,
2850  SourceLocation ConstQualLoc = SourceLocation(),
2851  SourceLocation VolatileQualLoc = SourceLocation(),
2852  SourceLocation RestrictQualLoc = SourceLocation(),
2853  SourceLocation AtomicQualLoc = SourceLocation(),
2854  SourceLocation UnalignedQualLoc = SourceLocation());
2855 
2856  static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2857  void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2859  const LookupResult &R);
2862  const LookupResult &R);
2863  void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2864  const LookupResult &R);
2865  void CheckShadow(Scope *S, VarDecl *D);
2866 
2867  /// Warn if 'E', which is an expression that is about to be modified, refers
2868  /// to a shadowing declaration.
2870 
2872 
2873 private:
2874  /// Map of current shadowing declarations to shadowed declarations. Warn if
2875  /// it looks like the user is trying to modify the shadowing declaration.
2876  llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2877 
2878 public:
2879  void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2880  void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2881  void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2882  TypedefNameDecl *NewTD);
2885  TypeSourceInfo *TInfo,
2888  LookupResult &Previous, bool &Redeclaration);
2890  TypeSourceInfo *TInfo,
2892  MultiTemplateParamsArg TemplateParamLists,
2893  bool &AddToScope,
2895  NamedDecl *
2897  MultiTemplateParamsArg TemplateParamLists);
2898  // Returns true if the variable declaration is a redeclaration
2901  bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2902  Expr *Init);
2906 
2908  TypeSourceInfo *TInfo,
2910  MultiTemplateParamsArg TemplateParamLists,
2911  bool &AddToScope);
2913 
2914  enum class CheckConstexprKind {
2915  /// Diagnose issues that are non-constant or that are extensions.
2916  Diagnose,
2917  /// Identify whether this function satisfies the formal rules for constexpr
2918  /// functions in the current lanugage mode (with no extensions).
2919  CheckValid
2920  };
2921 
2924 
2927  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2929  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2930  // Returns true if the function declaration is a redeclaration
2933  bool IsMemberSpecialization, bool DeclIsDefn);
2934  bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2936  QualType NewT, QualType OldT);
2937  void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2941  bool IsDefinition);
2945  SourceLocation Loc,
2946  QualType T);
2948  SourceLocation NameLoc, IdentifierInfo *Name,
2949  QualType T, TypeSourceInfo *TSInfo,
2950  StorageClass SC);
2951  void ActOnParamDefaultArgument(Decl *param,
2952  SourceLocation EqualLoc,
2953  Expr *defarg);
2955  SourceLocation ArgLoc);
2956  void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2958  SourceLocation EqualLoc);
2959  void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2960  SourceLocation EqualLoc);
2961 
2962  // Contexts where using non-trivial C union types can be disallowed. This is
2963  // passed to err_non_trivial_c_union_in_invalid_context.
2965  // Function parameter.
2967  // Function return.
2969  // Default-initialized object.
2971  // Variable with automatic storage duration.
2973  // Initializer expression that might copy from another object.
2975  // Assignment.
2977  // Compound literal.
2979  // Block capture.
2981  // lvalue-to-rvalue conversion of volatile type.
2983  };
2984 
2985  /// Emit diagnostics if the initializer or any of its explicit or
2986  /// implicitly-generated subexpressions require copying or
2987  /// default-initializing a type that is or contains a C union type that is
2988  /// non-trivial to copy or default-initialize.
2990 
2991  // These flags are passed to checkNonTrivialCUnion.
2993  NTCUK_Init = 0x1,
2995  NTCUK_Copy = 0x4,
2996  };
2997 
2998  /// Emit diagnostics if a non-trivial C union type or a struct that contains
2999  /// a non-trivial C union is used in an invalid context.
3001  NonTrivialCUnionContext UseContext,
3002  unsigned NonTrivialKind);
3003 
3004  void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
3005  void ActOnUninitializedDecl(Decl *dcl);
3006  void ActOnInitializerError(Decl *Dcl);
3007 
3008  void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
3009  void ActOnCXXForRangeDecl(Decl *D);
3011  IdentifierInfo *Ident,
3012  ParsedAttributes &Attrs);
3013  void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
3014  void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
3016  void FinalizeDeclaration(Decl *D);
3020 
3021  /// Should be called on all declarations that might have attached
3022  /// documentation comments.
3023  void ActOnDocumentableDecl(Decl *D);
3025 
3026  enum class FnBodyKind {
3027  /// C++ [dcl.fct.def.general]p1
3028  /// function-body:
3029  /// ctor-initializer[opt] compound-statement
3030  /// function-try-block
3031  Other,
3032  /// = default ;
3033  Default,
3034  /// = delete ;
3035  Delete
3036  };
3037 
3039  SourceLocation LocAfterDecls);
3041  FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
3042  SkipBodyInfo *SkipBody = nullptr);
3044  MultiTemplateParamsArg TemplateParamLists,
3045  SkipBodyInfo *SkipBody = nullptr,
3046  FnBodyKind BodyKind = FnBodyKind::Other);
3048  SkipBodyInfo *SkipBody = nullptr,
3049  FnBodyKind BodyKind = FnBodyKind::Other);
3050  void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind);
3053  ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
3054  void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
3056  return D && isa<ObjCMethodDecl>(D);
3057  }
3058 
3059  /// Determine whether we can delay parsing the body of a function or
3060  /// function template until it is used, assuming we don't care about emitting
3061  /// code for that function.
3062  ///
3063  /// This will be \c false if we may need the body of the function in the
3064  /// middle of parsing an expression (where it's impractical to switch to
3065  /// parsing a different function), for instance, if it's constexpr in C++11
3066  /// or has an 'auto' return type in C++14. These cases are essentially bugs.
3067  bool canDelayFunctionBody(const Declarator &D);
3068 
3069  /// Determine whether we can skip parsing the body of a function
3070  /// definition, assuming we don't care about analyzing its body or emitting
3071  /// code for that function.
3072  ///
3073  /// This will be \c false only if we may need the body of the function in
3074  /// order to parse the rest of the program (for instance, if it is
3075  /// \c constexpr in C++11 or has an 'auto' return type in C++14).
3076  bool canSkipFunctionBody(Decl *D);
3077 
3078  /// Determine whether \param D is function like (function or function
3079  /// template) for parsing.
3081 
3084  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
3087 
3088  /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
3089  /// attribute for which parsing is delayed.
3091 
3092  /// Diagnose any unused parameters in the given sequence of
3093  /// ParmVarDecl pointers.
3095 
3096  /// Diagnose whether the size of parameters or return value of a
3097  /// function or obj-c method definition is pass-by-value and larger than a
3098  /// specified threshold.
3099  void
3101  QualType ReturnTy, NamedDecl *D);
3102 
3103  void DiagnoseInvalidJumps(Stmt *Body);
3105  SourceLocation AsmLoc,
3106  SourceLocation RParenLoc);
3107 
3108  /// Handle a C++11 empty-declaration and attribute-declaration.
3110  SourceLocation SemiLoc);
3111 
3112  enum class ModuleDeclKind {
3113  Interface, ///< 'export module X;'
3114  Implementation, ///< 'module X;'
3115  PartitionInterface, ///< 'export module X:Y;'
3116  PartitionImplementation, ///< 'module X:Y;'
3117  };
3118 
3119  /// An enumeration to represent the transition of states in parsing module
3120  /// fragments and imports. If we are not parsing a C++20 TU, or we find
3121  /// an error in state transition, the state is set to NotACXX20Module.
3122  enum class ModuleImportState {
3123  FirstDecl, ///< Parsing the first decl in a TU.
3124  GlobalFragment, ///< after 'module;' but before 'module X;'
3125  ImportAllowed, ///< after 'module X;' but before any non-import decl.
3126  ImportFinished, ///< after any non-import decl.
3127  PrivateFragment, ///< after 'module :private;'.
3128  NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
3129  };
3130 
3131 private:
3132  /// The parser has begun a translation unit to be compiled as a C++20
3133  /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
3134  void HandleStartOfHeaderUnit();
3135 
3136 public:
3137  /// The parser has processed a module-declaration that begins the definition
3138  /// of a module interface or implementation.
3140  SourceLocation ModuleLoc, ModuleDeclKind MDK,
3141  ModuleIdPath Path, ModuleIdPath Partition,
3142  ModuleImportState &ImportState);
3143 
3144  /// The parser has processed a global-module-fragment declaration that begins
3145  /// the definition of the global module fragment of the current module unit.
3146  /// \param ModuleLoc The location of the 'module' keyword.
3148 
3149  /// The parser has processed a private-module-fragment declaration that begins
3150  /// the definition of the private module fragment of the current module unit.
3151  /// \param ModuleLoc The location of the 'module' keyword.
3152  /// \param PrivateLoc The location of the 'private' keyword.
3154  SourceLocation PrivateLoc);
3155 
3156  /// The parser has processed a module import declaration.
3157  ///
3158  /// \param StartLoc The location of the first token in the declaration. This
3159  /// could be the location of an '@', 'export', or 'import'.
3160  /// \param ExportLoc The location of the 'export' keyword, if any.
3161  /// \param ImportLoc The location of the 'import' keyword.
3162  /// \param Path The module toplevel name as an access path.
3163  /// \param IsPartition If the name is for a partition.
3165  SourceLocation ExportLoc,
3166  SourceLocation ImportLoc, ModuleIdPath Path,
3167  bool IsPartition = false);
3169  SourceLocation ExportLoc,
3170  SourceLocation ImportLoc, Module *M,
3171  ModuleIdPath Path = {});
3172 
3173  /// The parser has processed a module import translated from a
3174  /// #include or similar preprocessing directive.
3175  void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3176  void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3177 
3178  /// The parsed has entered a submodule.
3179  void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
3180  /// The parser has left a submodule.
3181  void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
3182 
3183  /// Create an implicit import of the given module at the given
3184  /// source location, for error recovery, if possible.
3185  ///
3186  /// This routine is typically used when an entity found by name lookup
3187  /// is actually hidden within a module that we know about but the user
3188  /// has forgotten to import.
3189  void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
3190  Module *Mod);
3191 
3192  /// Kinds of missing import. Note, the values of these enumerators correspond
3193  /// to %select values in diagnostics.
3194  enum class MissingImportKind {
3195  Declaration,
3196  Definition,
3200  };
3201 
3202  /// Diagnose that the specified declaration needs to be visible but
3203  /// isn't, and suggest a module import that would resolve the problem.
3205  MissingImportKind MIK, bool Recover = true);
3207  SourceLocation DeclLoc, ArrayRef<Module *> Modules,
3208  MissingImportKind MIK, bool Recover);
3209 
3211  SourceLocation LBraceLoc);
3213  SourceLocation RBraceLoc);
3214 
3215  /// We've found a use of a templated declaration that would trigger an
3216  /// implicit instantiation. Check that any relevant explicit specializations
3217  /// and partial specializations are visible/reachable, and diagnose if not.
3220 
3221  /// Retrieve a suitable printing policy for diagnostics.
3223  return getPrintingPolicy(Context, PP);
3224  }
3225 
3226  /// Retrieve a suitable printing policy for diagnostics.
3227  static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
3228  const Preprocessor &PP);
3229 
3230  /// Scope actions.
3231  void ActOnPopScope(SourceLocation Loc, Scope *S);
3233 
3235  const ParsedAttributesView &DeclAttrs,
3236  RecordDecl *&AnonRecord);
3238  const ParsedAttributesView &DeclAttrs,
3239  MultiTemplateParamsArg TemplateParams,
3240  bool IsExplicitInstantiation,
3241  RecordDecl *&AnonRecord);
3242 
3244  AccessSpecifier AS,
3245  RecordDecl *Record,
3246  const PrintingPolicy &Policy);
3247 
3249  RecordDecl *Record);
3250 
3251  /// Common ways to introduce type names without a tag for use in diagnostics.
3252  /// Keep in sync with err_tag_reference_non_tag.
3253  enum NonTagKind {
3263  };
3264 
3265  /// Given a non-tag type declaration, returns an enum useful for indicating
3266  /// what kind of non-tag type this is.
3268 
3270  TagTypeKind NewTag, bool isDefinition,
3271  SourceLocation NewTagLoc,
3272  const IdentifierInfo *Name);
3273 
3274  enum TagUseKind {
3275  TUK_Reference, // Reference to a tag: 'struct foo *X;'
3276  TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
3277  TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
3278  TUK_Friend // Friend declaration: 'friend struct foo;'
3279  };
3280 
3281  Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3282  SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
3283  SourceLocation NameLoc, const ParsedAttributesView &Attr,
3284  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
3285  MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
3286  bool &IsDependent, SourceLocation ScopedEnumKWLoc,
3287  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3288  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3289  SkipBodyInfo *SkipBody = nullptr);
3290 
3292  unsigned TagSpec, SourceLocation TagLoc,
3293  CXXScopeSpec &SS, IdentifierInfo *Name,
3294  SourceLocation NameLoc,
3295  const ParsedAttributesView &Attr,
3296  MultiTemplateParamsArg TempParamLists);
3297 
3299  unsigned TagSpec,
3300  TagUseKind TUK,
3301  const CXXScopeSpec &SS,
3302  IdentifierInfo *Name,
3303  SourceLocation TagLoc,
3304  SourceLocation NameLoc);
3305 
3306  void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3307  IdentifierInfo *ClassName,
3308  SmallVectorImpl<Decl *> &Decls);
3309  Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3310  Declarator &D, Expr *BitfieldWidth);
3311 
3312  FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3313  Declarator &D, Expr *BitfieldWidth,
3314  InClassInitStyle InitStyle,
3315  AccessSpecifier AS);
3317  SourceLocation DeclStart, Declarator &D,
3318  Expr *BitfieldWidth,
3319  InClassInitStyle InitStyle,
3320  AccessSpecifier AS,
3321  const ParsedAttr &MSPropertyAttr);
3322 
3324  TypeSourceInfo *TInfo,
3325  RecordDecl *Record, SourceLocation Loc,
3326  bool Mutable, Expr *BitfieldWidth,
3327  InClassInitStyle InitStyle,
3328  SourceLocation TSSL,
3329  AccessSpecifier AS, NamedDecl *PrevDecl,
3330  Declarator *D = nullptr);
3331 
3332  bool CheckNontrivialField(FieldDecl *FD);
3333  void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3334 
3336  /// The triviality of a method unaffected by "trivial_abi".
3338 
3339  /// The triviality of a method affected by "trivial_abi".
3341  };
3342 
3345  bool Diagnose = false);
3346 
3347  /// For a defaulted function, the kind of defaulted function that it is.
3349  CXXSpecialMember SpecialMember : 8;
3350  DefaultedComparisonKind Comparison : 8;
3351 
3352  public:
3354  : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3355  }
3357  : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3359  : SpecialMember(CXXInvalid), Comparison(Comp) {}
3360 
3361  bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3362  bool isComparison() const {
3363  return Comparison != DefaultedComparisonKind::None;
3364  }
3365 
3366  explicit operator bool() const {
3367  return isSpecialMember() || isComparison();
3368  }
3369 
3370  CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3371  DefaultedComparisonKind asComparison() const { return Comparison; }
3372 
3373  /// Get the index of this function kind for use in diagnostics.
3374  unsigned getDiagnosticIndex() const {
3375  static_assert(CXXInvalid > CXXDestructor,
3376  "invalid should have highest index");
3377  static_assert((unsigned)DefaultedComparisonKind::None == 0,
3378  "none should be equal to zero");
3379  return SpecialMember + (unsigned)Comparison;
3380  }
3381  };
3382 
3383  DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3384 
3387  }
3390  }
3391 
3392  void ActOnLastBitfield(SourceLocation DeclStart,
3393  SmallVectorImpl<Decl *> &AllIvarDecls);
3394  Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3395  Declarator &D, Expr *BitfieldWidth,
3396  tok::ObjCKeywordKind visibility);
3397 
3398  // This is used for both record definitions and ObjC interface declarations.
3399  void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3400  ArrayRef<Decl *> Fields, SourceLocation LBrac,
3401  SourceLocation RBrac, const ParsedAttributesView &AttrList);
3402 
3403  /// ActOnTagStartDefinition - Invoked when we have entered the
3404  /// scope of a tag's definition (e.g., for an enumeration, class,
3405  /// struct, or union).
3407 
3408  /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3409  /// Differently from C++, actually parse the body and reject / error out
3410  /// in case of a structural mismatch.
3411  bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3412 
3414 
3415  /// Invoked when we enter a tag definition that we're skipping.
3417 
3419 
3420  /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3421  /// C++ record definition's base-specifiers clause and are starting its
3422  /// member declarations.
3424  SourceLocation FinalLoc,
3425  bool IsFinalSpelledSealed,
3426  bool IsAbstract,
3427  SourceLocation LBraceLoc);
3428 
3429  /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3430  /// the definition of a tag (enumeration, class, struct, or union).
3432  SourceRange BraceRange);
3433 
3435 
3437 
3438  /// Invoked when we must temporarily exit the objective-c container
3439  /// scope for parsing/looking-up C constructs.
3440  ///
3441  /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3444 
3445  /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3446  /// error parsing the definition of a tag.
3448 
3450  EnumConstantDecl *LastEnumConst,
3451  SourceLocation IdLoc,
3452  IdentifierInfo *Id,
3453  Expr *val);
3455  bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3456  QualType EnumUnderlyingTy, bool IsFixed,
3457  const EnumDecl *Prev);
3458 
3459  /// Determine whether the body of an anonymous enumeration should be skipped.
3460  /// \param II The name of the first enumerator.
3462  SourceLocation IILoc);
3463 
3464  Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3466  const ParsedAttributesView &Attrs,
3467  SourceLocation EqualLoc, Expr *Val);
3468  void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3469  Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3470  const ParsedAttributesView &Attr);
3471 
3472  /// Set the current declaration context until it gets popped.
3473  void PushDeclContext(Scope *S, DeclContext *DC);
3474  void PopDeclContext();
3475 
3476  /// EnterDeclaratorContext - Used when we must lookup names in the context
3477  /// of a declarator's nested name specifier.
3479  void ExitDeclaratorContext(Scope *S);
3480 
3481  /// Enter a template parameter scope, after it's been associated with a particular
3482  /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3483  /// in the correct order.
3484  void EnterTemplatedContext(Scope *S, DeclContext *DC);
3485 
3486  /// Push the parameters of D, which must be a function, into scope.
3487  void ActOnReenterFunctionContext(Scope* S, Decl* D);
3488  void ActOnExitFunctionContext();
3489 
3490  /// If \p AllowLambda is true, treat lambda as function.
3491  DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false);
3492 
3493  /// Returns a pointer to the innermost enclosing function, or nullptr if the
3494  /// current context is not inside a function. If \p AllowLambda is true,
3495  /// this can return the call operator of an enclosing lambda, otherwise
3496  /// lambdas are skipped when looking for an enclosing function.
3497  FunctionDecl *getCurFunctionDecl(bool AllowLambda = false);
3498 
3499  /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3500  /// the method decl for the method being parsed. If we're currently
3501  /// in a 'block', this returns the containing context.
3503 
3504  /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3505  /// or C function we're in, otherwise return null. If we're currently
3506  /// in a 'block', this returns the containing context.
3508 
3509  /// Add this decl to the scope shadowed decl chains.
3510  void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3511 
3512  /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3513  /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3514  /// true if 'D' belongs to the given declaration context.
3515  ///
3516  /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3517  /// enclosing namespace set of the context, rather than contained
3518  /// directly within it.
3519  bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3520  bool AllowInlineNamespace = false);
3521 
3522  /// Finds the scope corresponding to the given decl context, if it
3523  /// happens to be an enclosing scope. Otherwise return NULL.
3524  static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3525 
3526  /// Subroutines of ActOnDeclarator().
3528  TypeSourceInfo *TInfo);
3530 
3531  /// Describes the kind of merge to perform for availability
3532  /// attributes (including "deprecated", "unavailable", and "availability").
3534  /// Don't merge availability attributes at all.
3536  /// Merge availability attributes for a redeclaration, which requires
3537  /// an exact match.
3539  /// Merge availability attributes for an override, which requires
3540  /// an exact match or a weakening of constraints.
3542  /// Merge availability attributes for an implementation of
3543  /// a protocol requirement.
3545  /// Merge availability attributes for an implementation of
3546  /// an optional protocol requirement.
3548  };
3549 
3550  /// Describes the kind of priority given to an availability attribute.
3551  ///
3552  /// The sum of priorities deteremines the final priority of the attribute.
3553  /// The final priority determines how the attribute will be merged.
3554  /// An attribute with a lower priority will always remove higher priority
3555  /// attributes for the specified platform when it is being applied. An
3556  /// attribute with a higher priority will not be applied if the declaration
3557  /// already has an availability attribute with a lower priority for the
3558  /// specified platform. The final prirority values are not expected to match
3559  /// the values in this enumeration, but instead should be treated as a plain
3560  /// integer value. This enumeration just names the priority weights that are
3561  /// used to calculate that final vaue.
3563  /// The availability attribute was specified explicitly next to the
3564  /// declaration.
3566 
3567  /// The availability attribute was applied using '#pragma clang attribute'.
3569 
3570  /// The availability attribute for a specific platform was inferred from
3571  /// an availability attribute for another platform.
3573  };
3574 
3575  /// Attribute merging methods. Return true if a new attribute was added.
3576  AvailabilityAttr *
3578  IdentifierInfo *Platform, bool Implicit,
3579  VersionTuple Introduced, VersionTuple Deprecated,
3580  VersionTuple Obsoleted, bool IsUnavailable,
3581  StringRef Message, bool IsStrict, StringRef Replacement,
3582  AvailabilityMergeKind AMK, int Priority);
3583  TypeVisibilityAttr *
3585  TypeVisibilityAttr::VisibilityType Vis);
3586  VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3587  VisibilityAttr::VisibilityType Vis);
3588  UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3589  StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3590  DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3591  DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3592  MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3593  const AttributeCommonInfo &CI,
3594  bool BestCase,
3595  MSInheritanceModel Model);
3596  ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3597  StringRef NewUserDiagnostic);
3598  FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3599  IdentifierInfo *Format, int FormatIdx,
3600  int FirstArg);
3601  SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3602  StringRef Name);
3603  CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3604  StringRef Name);
3605  AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3606  const AttributeCommonInfo &CI,
3607  const IdentifierInfo *Ident);
3608  MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3609  SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3610  StringRef Name);
3611  OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3612  const AttributeCommonInfo &CI);
3613  InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3614  InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3615  const InternalLinkageAttr &AL);
3616  WebAssemblyImportNameAttr *mergeImportNameAttr(
3617  Decl *D, const WebAssemblyImportNameAttr &AL);
3618  WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3619  Decl *D, const WebAssemblyImportModuleAttr &AL);
3620  EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3621  EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3622  const EnforceTCBLeafAttr &AL);
3623  BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
3624  HLSLNumThreadsAttr *mergeHLSLNumThreadsAttr(Decl *D,
3625  const AttributeCommonInfo &AL,
3626  int X, int Y, int Z);
3627  HLSLShaderAttr *mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL,
3628  HLSLShaderAttr::ShaderType ShaderType);
3629 
3630  void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3633  LookupResult &OldDecls);
3634  bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3635  bool MergeTypeWithOld, bool NewDeclIsDefn);
3637  Scope *S, bool MergeTypeWithOld);
3640  void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3641  void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3642  bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3643  void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3644  bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3645 
3646  // AssignmentAction - This is used by all the assignment diagnostic functions
3647  // to represent what is actually causing the operation
3657  };
3658 
3659  /// C++ Overloading.
3661  /// This is a legitimate overload: the existing declarations are
3662  /// functions or function templates with different signatures.
3664 
3665  /// This is not an overload because the signature exactly matches
3666  /// an existing declaration.
3668 
3669  /// This is not an overload because the lookup results contain a
3670  /// non-function.
3672  };
3674  FunctionDecl *New,
3675  const LookupResult &OldDecls,
3676  NamedDecl *&OldDecl,
3677  bool IsForUsingDecl);
3678  bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
3679  bool ConsiderCudaAttrs = true,
3680  bool ConsiderRequiresClauses = true);
3681 
3682  // Calculates whether the expression Constraint depends on an enclosing
3683  // template, for the purposes of [temp.friend] p9.
3684  // TemplateDepth is the 'depth' of the friend function, which is used to
3685  // compare whether a declaration reference is referring to a containing
3686  // template, or just the current friend function. A 'lower' TemplateDepth in
3687  // the AST refers to a 'containing' template. As the constraint is
3688  // uninstantiated, this is relative to the 'top' of the TU.
3689  bool ConstraintExpressionDependsOnEnclosingTemplate(unsigned TemplateDepth,
3690  const Expr *Constraint);
3691 
3692  // Calculates whether the friend function depends on an enclosing template for
3693  // the purposes of [temp.friend] p9.
3695 
3696  // Calculates whether two constraint expressions are equal irrespective of a
3697  // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
3698  // 'New', which are the "source" of the constraint, since this is necessary
3699  // for figuring out the relative 'depth' of the constraint. The depth of the
3700  // 'primary template' and the 'instantiated from' templates aren't necessarily
3701  // the same, such as a case when one is a 'friend' defined in a class.
3702  bool AreConstraintExpressionsEqual(const NamedDecl *Old,
3703  const Expr *OldConstr,
3704  const NamedDecl *New,
3705  const Expr *NewConstr);
3706 
3707  enum class AllowedExplicit {
3708  /// Allow no explicit functions to be used.
3709  None,
3710  /// Allow explicit conversion functions but not explicit constructors.
3711  Conversions,
3712  /// Allow both explicit conversion functions and explicit constructors.
3713  All
3714  };
3715 
3717  TryImplicitConversion(Expr *From, QualType ToType,
3718  bool SuppressUserConversions,
3719  AllowedExplicit AllowExplicit,
3720  bool InOverloadResolution,
3721  bool CStyle,
3722  bool AllowObjCWritebackConversion);
3723 
3724  bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3725  bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3726  bool IsComplexPromotion(QualType FromType, QualType ToType);
3727  bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3728  bool InOverloadResolution,
3729  QualType& ConvertedType, bool &IncompatibleObjC);
3730  bool isObjCPointerConversion(QualType FromType, QualType ToType,
3731  QualType& ConvertedType, bool &IncompatibleObjC);
3732  bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3733  QualType &ConvertedType);
3734  bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3735  QualType& ConvertedType);
3736  bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3737  const FunctionProtoType *NewType,
3738  unsigned *ArgPos = nullptr,
3739  bool Reversed = false);
3741  QualType FromType, QualType ToType);
3742 
3745  bool CheckPointerConversion(Expr *From, QualType ToType,
3746  CastKind &Kind,
3747  CXXCastPath& BasePath,
3748  bool IgnoreBaseAccess,
3749  bool Diagnose = true);
3750  bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3751  bool InOverloadResolution,
3752  QualType &ConvertedType);
3753  bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3754  CastKind &Kind,
3755  CXXCastPath &BasePath,
3756  bool IgnoreBaseAccess);
3757  bool IsQualificationConversion(QualType FromType, QualType ToType,
3758  bool CStyle, bool &ObjCLifetimeConversion);
3759  bool IsFunctionConversion(QualType FromType, QualType ToType,
3760  QualType &ResultTy);
3763 
3765  const InitializedEntity &Entity, InitListExpr *From);
3766 
3767  bool IsStringInit(Expr *Init, const ArrayType *AT);
3768 
3770  ExprResult Init);
3772  SourceLocation EqualLoc,
3773  ExprResult Init,
3774  bool TopLevelOfInitList = false,
3775  bool AllowExplicit = false);
3777  NestedNameSpecifier *Qualifier,
3778  NamedDecl *FoundDecl,
3779  CXXMethodDecl *Method);
3780 
3781  /// Check that the lifetime of the initializer (and its subobjects) is
3782  /// sufficient for initializing the entity, and perform lifetime extension
3783  /// (when permitted) if not.
3784  void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3785 
3788 
3789  /// Contexts in which a converted constant expression is required.
3790  enum CCEKind {
3791  CCEK_CaseValue, ///< Expression in a case label.
3792  CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
3793  CCEK_TemplateArg, ///< Value of a non-type template parameter.
3794  CCEK_ArrayBound, ///< Array bound in array declarator or new-expression.
3795  CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier.
3796  CCEK_Noexcept ///< Condition in a noexcept(bool) specifier.
3797  };
3799  llvm::APSInt &Value, CCEKind CCE);
3801  APValue &Value, CCEKind CCE,
3802  NamedDecl *Dest = nullptr);
3803 
3804  /// Abstract base class used to perform a contextual implicit
3805  /// conversion from an expression to any type passing a filter.
3807  public:
3808  bool Suppress;
3810 
3812  bool SuppressConversion = false)
3814 
3815  /// Determine whether the specified type is a valid destination type
3816  /// for this conversion.
3817  virtual bool match(QualType T) = 0;
3818 
3819  /// Emits a diagnostic complaining that the expression does not have
3820  /// integral or enumeration type.
3821  virtual SemaDiagnosticBuilder
3822  diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3823 
3824  /// Emits a diagnostic when the expression has incomplete class type.
3825  virtual SemaDiagnosticBuilder
3827 
3828  /// Emits a diagnostic when the only matching conversion function
3829  /// is explicit.
3831  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3832 
3833  /// Emits a note for the explicit conversion function.
3834  virtual SemaDiagnosticBuilder
3835  noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3836 
3837  /// Emits a diagnostic when there are multiple possible conversion
3838  /// functions.
3839  virtual SemaDiagnosticBuilder
3841 
3842  /// Emits a note for one of the candidate conversions.
3843  virtual SemaDiagnosticBuilder
3844  noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3845 
3846  /// Emits a diagnostic when we picked a conversion function
3847  /// (for cases when we are not allowed to pick a conversion function).
3849  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3850 
3852  };
3853 
3855  bool AllowScopedEnumerations;
3856 
3857  public:
3858  ICEConvertDiagnoser(bool AllowScopedEnumerations,
3859  bool Suppress, bool SuppressConversion)
3861  AllowScopedEnumerations(AllowScopedEnumerations) {}
3862 
3863  /// Match an integral or (possibly scoped) enumeration type.
3864  bool match(QualType T) override;
3865 
3868  return diagnoseNotInt(S, Loc, T);
3869  }
3870 
3871  /// Emits a diagnostic complaining that the expression does not have
3872  /// integral or enumeration type.
3873  virtual SemaDiagnosticBuilder
3874  diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3875  };
3876 
3877  /// Perform a contextual implicit conversion.
3879  SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3880 
3881 
3886  };
3888 
3889  // Note that LK_String is intentionally after the other literals, as
3890  // this is used for diagnostics logic.
3899  };
3901 
3903  NestedNameSpecifier *Qualifier,
3904  NamedDecl *FoundDecl,
3905  NamedDecl *Member);
3906 
3907  // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3908  // TODO: make this is a typesafe union.
3911 
3913 
3914  void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3915  ArrayRef<Expr *> Args,
3916  OverloadCandidateSet &CandidateSet,
3917  bool SuppressUserConversions = false,
3918  bool PartialOverloading = false,
3919  bool AllowExplicit = true,
3920  bool AllowExplicitConversion = false,
3921  ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3922  ConversionSequenceList EarlyConversions = None,
3923  OverloadCandidateParamOrder PO = {});
3924  void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3925  ArrayRef<Expr *> Args,
3926  OverloadCandidateSet &CandidateSet,
3927  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3928  bool SuppressUserConversions = false,
3929  bool PartialOverloading = false,
3930  bool FirstArgumentIsBase = false);
3931  void AddMethodCandidate(DeclAccessPair FoundDecl,
3932  QualType ObjectType,
3933  Expr::Classification ObjectClassification,
3934  ArrayRef<Expr *> Args,
3935  OverloadCandidateSet& CandidateSet,
3936  bool SuppressUserConversion = false,
3937  OverloadCandidateParamOrder PO = {});
3938  void AddMethodCandidate(CXXMethodDecl *Method,
3939  DeclAccessPair FoundDecl,
3940  CXXRecordDecl *ActingContext, QualType ObjectType,
3941  Expr::Classification ObjectClassification,
3942  ArrayRef<Expr *> Args,
3943  OverloadCandidateSet& CandidateSet,
3944  bool SuppressUserConversions = false,
3945  bool PartialOverloading = false,
3946  ConversionSequenceList EarlyConversions = None,
3947  OverloadCandidateParamOrder PO = {});
3948  void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3949  DeclAccessPair FoundDecl,
3950  CXXRecordDecl *ActingContext,
3951  TemplateArgumentListInfo *ExplicitTemplateArgs,
3952  QualType ObjectType,
3953  Expr::Classification ObjectClassification,
3954  ArrayRef<Expr *> Args,
3955  OverloadCandidateSet& CandidateSet,
3956  bool SuppressUserConversions = false,
3957  bool PartialOverloading = false,
3958  OverloadCandidateParamOrder PO = {});
3960  FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3961  TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3962  OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3963  bool PartialOverloading = false, bool AllowExplicit = true,
3964  ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3965  OverloadCandidateParamOrder PO = {});
3967  FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3968  ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3969  ConversionSequenceList &Conversions, bool SuppressUserConversions,
3970  CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3971  Expr::Classification ObjectClassification = {},
3972  OverloadCandidateParamOrder PO = {});
3974  CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3975  CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3976  OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3977  bool AllowExplicit, bool AllowResultConversion = true);
3979  FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3980  CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3981  OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3982  bool AllowExplicit, bool AllowResultConversion = true);
3983  void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3984  DeclAccessPair FoundDecl,
3985  CXXRecordDecl *ActingContext,
3986  const FunctionProtoType *Proto,
3987  Expr *Object, ArrayRef<Expr *> Args,
3988  OverloadCandidateSet& CandidateSet);
3990  const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3991  OverloadCandidateSet &CandidateSet,
3992  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3994  SourceLocation OpLoc, ArrayRef<Expr *> Args,
3995  OverloadCandidateSet &CandidateSet,
3996  OverloadCandidateParamOrder PO = {});
3997  void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3998  OverloadCandidateSet& CandidateSet,
3999  bool IsAssignmentOperator = false,
4000  unsigned NumContextualBoolArguments = 0);
4002  SourceLocation OpLoc, ArrayRef<Expr *> Args,
4003  OverloadCandidateSet& CandidateSet);
4004  void AddArgumentDependentLookupCandidates(DeclarationName Name,
4005  SourceLocation Loc,
4006  ArrayRef<Expr *> Args,
4007  TemplateArgumentListInfo *ExplicitTemplateArgs,
4008  OverloadCandidateSet& CandidateSet,
4009  bool PartialOverloading = false);
4010 
4011  // Emit as a 'note' the specific overload candidate
4012  void NoteOverloadCandidate(
4013  NamedDecl *Found, FunctionDecl *Fn,
4015  QualType DestType = QualType(), bool TakingAddress = false);
4016 
4017  // Emit as a series of 'note's all template and non-templates identified by
4018  // the expression Expr
4019  void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
4020  bool TakingAddress = false);
4021 
4022  /// Check the enable_if expressions on the given function. Returns the first
4023  /// failing attribute, or NULL if they were all successful.
4024  EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
4025  ArrayRef<Expr *> Args,
4026  bool MissingImplicitThis = false);
4027 
4028  /// Find the failed Boolean condition within a given Boolean
4029  /// constant expression, and describe it with a string.
4030  std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
4031 
4032  /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
4033  /// non-ArgDependent DiagnoseIfAttrs.
4034  ///
4035  /// Argument-dependent diagnose_if attributes should be checked each time a
4036  /// function is used as a direct callee of a function call.
4037  ///
4038  /// Returns true if any errors were emitted.
4039  bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
4040  const Expr *ThisArg,
4041  ArrayRef<const Expr *> Args,
4042  SourceLocation Loc);
4043 
4044  /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
4045  /// ArgDependent DiagnoseIfAttrs.
4046  ///
4047  /// Argument-independent diagnose_if attributes should be checked on every use
4048  /// of a function.
4049  ///
4050  /// Returns true if any errors were emitted.
4051  bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
4052  SourceLocation Loc);
4053 
4054  /// Returns whether the given function's address can be taken or not,
4055  /// optionally emitting a diagnostic if the address can't be taken.
4056  ///
4057  /// Returns false if taking the address of the function is illegal.
4058  bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
4059  bool Complain = false,
4060  SourceLocation Loc = SourceLocation());
4061 
4062  // [PossiblyAFunctionType] --> [Return]
4063  // NonFunctionType --> NonFunctionType
4064  // R (A) --> R(A)
4065  // R (*)(A) --> R (A)
4066  // R (&)(A) --> R (A)
4067  // R (S::*)(A) --> R (A)
4068  QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
4069 
4070  FunctionDecl *
4071  ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
4072  QualType TargetType,
4073  bool Complain,
4074  DeclAccessPair &Found,
4075  bool *pHadMultipleCandidates = nullptr);
4076 
4077  FunctionDecl *
4078  resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
4079 
4081  ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
4082 
4083  FunctionDecl *
4085  bool Complain = false,
4086  DeclAccessPair *Found = nullptr);
4087 
4089  ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
4090  bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
4091  QualType DestTypeForComplaining = QualType(),
4092  unsigned DiagIDForComplaining = 0);
4093 
4094  Expr *FixOverloadedFunctionReference(Expr *E,
4095  DeclAccessPair FoundDecl,
4096  FunctionDecl *Fn);
4098  DeclAccessPair FoundDecl,
4099  FunctionDecl *Fn);
4100 
4101  void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
4102  ArrayRef<Expr *> Args,
4103  OverloadCandidateSet &CandidateSet,
4104  bool PartialOverloading = false);
4106  LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
4107  ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
4108 
4109  // An enum used to represent the different possible results of building a
4110  // range-based for loop.
4115  };
4116 
4118  SourceLocation RangeLoc,
4119  const DeclarationNameInfo &NameInfo,
4120  LookupResult &MemberLookup,
4121  OverloadCandidateSet *CandidateSet,
4122  Expr *Range, ExprResult *CallExpr);
4123 
4125  UnresolvedLookupExpr *ULE,
4126  SourceLocation LParenLoc,
4127  MultiExprArg Args,
4128  SourceLocation RParenLoc,
4129  Expr *ExecConfig,
4130  bool AllowTypoCorrection=true,
4131  bool CalleesAddressIsTaken=false);
4132 
4134  MultiExprArg Args, SourceLocation RParenLoc,
4135  OverloadCandidateSet *CandidateSet,
4136  ExprResult *Result);
4137 
4139  NestedNameSpecifierLoc NNSLoc,
4140  DeclarationNameInfo DNI,
4141  const UnresolvedSetImpl &Fns,
4142  bool PerformADL = true);
4143 
4145  UnaryOperatorKind Opc,
4146  const UnresolvedSetImpl &Fns,
4147  Expr *input, bool RequiresADL = true);
4148 
4149  void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
4151  const UnresolvedSetImpl &Fns,
4152  ArrayRef<Expr *> Args, bool RequiresADL = true);
4154  BinaryOperatorKind Opc,
4155  const UnresolvedSetImpl &Fns,
4156  Expr *LHS, Expr *RHS,
4157  bool RequiresADL = true,
4158  bool AllowRewrittenCandidates = true,
4159  FunctionDecl *DefaultedFn = nullptr);
4161  const UnresolvedSetImpl &Fns,
4162  Expr *LHS, Expr *RHS,
4163  FunctionDecl *DefaultedFn);
4164 
4166  SourceLocation RLoc, Expr *Base,
4167  MultiExprArg Args);
4168 
4170  SourceLocation LParenLoc,
4171  MultiExprArg Args,
4172  SourceLocation RParenLoc,
4173  Expr *ExecConfig = nullptr,
4174  bool IsExecConfig = false,
4175  bool AllowRecovery = false);
4176  ExprResult
4177  BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
4178  MultiExprArg Args,
4179  SourceLocation RParenLoc);
4180 
4182  SourceLocation OpLoc,
4183  bool *NoArrowOperatorFound = nullptr);
4184 
4185  /// CheckCallReturnType - Checks that a call expression's return type is
4186  /// complete. Returns true on failure. The location passed in is the location
4187  /// that best represents the call.
4188  bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
4189  CallExpr *CE, FunctionDecl *FD);
4190 
4191  /// Helpers for dealing with blocks and functions.
4193  bool CheckParameterNames);
4197 
4198  /// \name Name lookup
4199  ///
4200  /// These routines provide name lookup that is used during semantic
4201  /// analysis to resolve the various kinds of names (identifiers,
4202  /// overloaded operator names, constructor names, etc.) into zero or
4203  /// more declarations within a particular scope. The major entry
4204  /// points are LookupName, which performs unqualified name lookup,
4205  /// and LookupQualifiedName, which performs qualified name lookup.
4206  ///
4207  /// All name lookup is performed based on some specific criteria,
4208  /// which specify what names will be visible to name lookup and how
4209  /// far name lookup should work. These criteria are important both
4210  /// for capturing language semantics (certain lookups will ignore
4211  /// certain names, for example) and for performance, since name
4212  /// lookup is often a bottleneck in the compilation of C++. Name
4213  /// lookup criteria is specified via the LookupCriteria enumeration.
4214  ///
4215  /// The results of name lookup can vary based on the kind of name
4216  /// lookup performed, the current language, and the translation
4217  /// unit. In C, for example, name lookup will either return nothing
4218  /// (no entity found) or a single declaration. In C++, name lookup
4219  /// can additionally refer to a set of overloaded functions or
4220  /// result in an ambiguity. All of the possible results of name
4221  /// lookup are captured by the LookupResult class, which provides
4222  /// the ability to distinguish among them.
4223  //@{
4224 
4225  /// Describes the kind of name lookup to perform.
4227  /// Ordinary name lookup, which finds ordinary names (functions,
4228  /// variables, typedefs, etc.) in C and most kinds of names
4229  /// (functions, variables, members, types, etc.) in C++.
4231  /// Tag name lookup, which finds the names of enums, classes,
4232  /// structs, and unions.
4234  /// Label name lookup.
4236  /// Member name lookup, which finds the names of
4237  /// class/struct/union members.
4239  /// Look up of an operator name (e.g., operator+) for use with
4240  /// operator overloading. This lookup is similar to ordinary name
4241  /// lookup, but will ignore any declarations that are class members.
4243  /// Look up a name following ~ in a destructor name. This is an ordinary
4244  /// lookup, but prefers tags to typedefs.
4246  /// Look up of a name that precedes the '::' scope resolution
4247  /// operator in C++. This lookup completely ignores operator, object,
4248  /// function, and enumerator names (C++ [basic.lookup.qual]p1).
4250  /// Look up a namespace name within a C++ using directive or
4251  /// namespace alias definition, ignoring non-namespace names (C++
4252  /// [basic.lookup.udir]p1).
4254  /// Look up all declarations in a scope with the given name,
4255  /// including resolved using declarations. This is appropriate
4256  /// for checking redeclarations for a using declaration.
4258  /// Look up an ordinary name that is going to be redeclared as a
4259  /// name with linkage. This lookup ignores any declarations that
4260  /// are outside of the current scope unless they have linkage. See
4261  /// C99 6.2.2p4-5 and C++ [basic.link]p6.
4263  /// Look up a friend of a local class. This lookup does not look
4264  /// outside the innermost non-class scope. See C++11 [class.friend]p11.
4266  /// Look up the name of an Objective-C protocol.
4268  /// Look up implicit 'self' parameter of an objective-c method.
4270  /// Look up the name of an OpenMP user-defined reduction operation.
4272  /// Look up the name of an OpenMP user-defined mapper.
4274  /// Look up any declaration with any name.
4276  };
4277 
4278  /// Specifies whether (or how) name lookup is being performed for a
4279  /// redeclaration (vs. a reference).
4281  /// The lookup is a reference to this name that is not for the
4282  /// purpose of redeclaring the name.
4284  /// The lookup results will be used for redeclaration of a name,
4285  /// if an entity by that name already exists and is visible.
4287  /// The lookup results will be used for redeclaration of a name
4288  /// with external linkage; non-visible lookup results with external linkage
4289  /// may also be found.
4291  };
4292 
4294  // A declaration with an owning module for linkage can never link against
4295  // anything that is not visible. We don't need to check linkage here; if
4296  // the context has internal linkage, redeclaration lookup won't find things
4297  // from other TUs, and we can't safely compute linkage yet in general.
4298  if (cast<Decl>(CurContext)
4299  ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
4300  return ForVisibleRedeclaration;
4301  return ForExternalRedeclaration;
4302  }
4303 
4304  /// The possible outcomes of name lookup for a literal operator.
4306  /// The lookup resulted in an error.
4308  /// The lookup found no match but no diagnostic was issued.
4310  /// The lookup found a single 'cooked' literal operator, which
4311  /// expects a normal literal to be built and passed to it.
4313  /// The lookup found a single 'raw' literal operator, which expects
4314  /// a string literal containing the spelling of the literal token.
4316  /// The lookup found an overload set of literal operator templates,
4317  /// which expect the characters of the spelling of the literal token to be
4318  /// passed as a non-type template argument pack.
4320  /// The lookup found an overload set of literal operator templates,
4321  /// which expect the character type and characters of the spelling of the
4322  /// string literal token to be passed as template arguments.
4324  };
4325 
4326  SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
4328  bool ConstArg,
4329  bool VolatileArg,
4330  bool RValueThis,
4331  bool ConstThis,
4332  bool VolatileThis);
4333 
4334  typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
4335  typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
4337 
4338 private:
4339  bool CppLookupName(LookupResult &R, Scope *S);
4340 
4341  struct TypoExprState {
4342  std::unique_ptr<TypoCorrectionConsumer> Consumer;
4343  TypoDiagnosticGenerator DiagHandler;
4344  TypoRecoveryCallback RecoveryHandler;
4345  TypoExprState();
4346  TypoExprState(TypoExprState &&other) noexcept;
4347  TypoExprState &operator=(TypoExprState &&other) noexcept;
4348  };
4349 
4350  /// The set of unhandled TypoExprs and their associated state.
4351  llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
4352 
4353  /// Creates a new TypoExpr AST node.
4354  TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4356  TypoRecoveryCallback TRC, SourceLocation TypoLoc);
4357 
4358  // The set of known/encountered (unique, canonicalized) NamespaceDecls.
4359  //
4360  // The boolean value will be true to indicate that the namespace was loaded
4361  // from an AST/PCH file, or false otherwise.
4362  llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
4363 
4364  /// Whether we have already loaded known namespaces from an extenal
4365  /// source.
4366  bool LoadedExternalKnownNamespaces;
4367 
4368  /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
4369  /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
4370  /// should be skipped entirely.
4371  std::unique_ptr<TypoCorrectionConsumer>
4372  makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
4373  Sema::LookupNameKind LookupKind, Scope *S,
4374  CXXScopeSpec *SS,
4376  DeclContext *MemberContext, bool EnteringContext,
4377  const ObjCObjectPointerType *OPT,
4378  bool ErrorRecovery);
4379 
4380 public:
4381  const TypoExprState &getTypoExprState(TypoExpr *TE) const;
4382 
4383  /// Clears the state of the given TypoExpr.
4384  void clearDelayedTypo(TypoExpr *TE);
4385 
4386  /// Look up a name, looking for a single declaration. Return
4387  /// null if the results were absent, ambiguous, or overloaded.
4388  ///
4389  /// It is preferable to use the elaborated form and explicitly handle
4390  /// ambiguity and overloaded.
4392  SourceLocation Loc,
4393  LookupNameKind NameKind,
4394  RedeclarationKind Redecl
4396  bool LookupBuiltin(LookupResult &R);
4397  void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
4398  bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
4399  bool ForceNoCPlusPlus = false);
4400  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4401  bool InUnqualifiedLookup = false);
4402  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4403  CXXScopeSpec &SS);
4405  bool AllowBuiltinCreation = false,
4406  bool EnteringContext = false);
4408  RedeclarationKind Redecl
4410  bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
4411 
4413  UnresolvedSetImpl &Functions);
4414 
4416  SourceLocation GnuLabelLoc = SourceLocation());
4417 
4421  unsigned Quals);
4422  CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
4423  bool RValueThis, unsigned ThisQuals);
4425  unsigned Quals);
4426  CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
4427  bool RValueThis, unsigned ThisQuals);
4429 
4430  bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
4431  bool IsUDSuffix);
4434  bool AllowRaw, bool AllowTemplate,
4435  bool AllowStringTemplate, bool DiagnoseMissing,
4436  StringLiteral *StringLit = nullptr);
4437  bool isKnownName(StringRef name);
4438 
4439  /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4441  Emitted,
4442  CUDADiscarded, // Discarded due to CUDA/HIP hostness
4443  OMPDiscarded, // Discarded due to OpenMP hostness
4444  TemplateDiscarded, // Discarded due to uninstantiated templates
4445  Unknown,
4446  };
4448  bool Final = false);
4449 
4450  // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4452 
4454  ArrayRef<Expr *> Args, ADLResult &Functions);
4455 
4458  bool IncludeGlobalScope = true,
4459  bool LoadExternal = true);
4462  bool IncludeGlobalScope = true,
4463  bool IncludeDependentBases = false,
4464  bool LoadExternal = true);
4465 
4467  CTK_NonError, // CorrectTypo used in a non error recovery situation.
4468  CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
4469  };
4470 
4472  Sema::LookupNameKind LookupKind,
4473  Scope *S, CXXScopeSpec *SS,
4475  CorrectTypoKind Mode,
4476  DeclContext *MemberContext = nullptr,
4477  bool EnteringContext = false,
4478  const ObjCObjectPointerType *OPT = nullptr,
4479  bool RecordFailure = true);
4480 
4482  Sema::LookupNameKind LookupKind, Scope *S,
4483  CXXScopeSpec *SS,
4487  DeclContext *MemberContext = nullptr,
4488  bool EnteringContext = false,
4489  const ObjCObjectPointerType *OPT = nullptr);
4490 
4491  /// Process any TypoExprs in the given Expr and its children,
4492  /// generating diagnostics as appropriate and returning a new Expr if there
4493  /// were typos that were all successfully corrected and ExprError if one or
4494  /// more typos could not be corrected.
4495  ///
4496  /// \param E The Expr to check for TypoExprs.
4497  ///
4498  /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
4499  /// initializer.
4500  ///
4501  /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
4502  /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
4503  ///
4504  /// \param Filter A function applied to a newly rebuilt Expr to determine if
4505  /// it is an acceptable/usable result from a single combination of typo
4506  /// corrections. As long as the filter returns ExprError, different
4507  /// combinations of corrections will be tried until all are exhausted.
4509  Expr *E, VarDecl *InitDecl = nullptr,
4510  bool RecoverUncorrectedTypos = false,
4511  llvm::function_ref<ExprResult(Expr *)> Filter =
4512  [](Expr *E) -> ExprResult { return E; });
4513 
4515  ExprResult ER, VarDecl *InitDecl = nullptr,
4516  bool RecoverUncorrectedTypos = false,
4517  llvm::function_ref<ExprResult(Expr *)> Filter =
4518  [](Expr *E) -> ExprResult { return E; }) {
4519  return ER.isInvalid()
4520  ? ER
4521  : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
4522  RecoverUncorrectedTypos, Filter);
4523  }
4524 
4525  void diagnoseTypo(const TypoCorrection &Correction,
4526  const PartialDiagnostic &TypoDiag,
4527  bool ErrorRecovery = true);
4528 
4529  void diagnoseTypo(const TypoCorrection &Correction,
4530  const PartialDiagnostic &TypoDiag,
4531  const PartialDiagnostic &PrevNote,
4532  bool ErrorRecovery = true);
4533 
4534  void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4535 
4536  void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
4537  ArrayRef<Expr *> Args,
4538  AssociatedNamespaceSet &AssociatedNamespaces,
4539  AssociatedClassSet &AssociatedClasses);
4540 
4541  void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4542  bool ConsiderLinkage, bool AllowInlineNamespace);
4543 
4544  bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4545  bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4546  bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4547  bool IsRedefinitionInModule(const NamedDecl *New,
4548  const NamedDecl *Old) const;
4549 
4550  void DiagnoseAmbiguousLookup(LookupResult &Result);
4551  //@}
4552 
4553  /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
4554  ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
4555  ArrayRef<Expr *> SubExprs,
4556  QualType T = QualType());
4557 
4558  ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
4559  SourceLocation IdLoc,
4560  bool TypoCorrection = false);
4561  FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4562  SourceLocation Loc);
4563  NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
4564  Scope *S, bool ForRedeclaration,
4565  SourceLocation Loc);
4566  NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4567  Scope *S);
4569  FunctionDecl *FD);
4570  void AddKnownFunctionAttributes(FunctionDecl *FD);
4571 
4572  // More parsing and symbol table subroutines.
4573 
4574  void ProcessPragmaWeak(Scope *S, Decl *D);
4575  // Decl attributes - this routine is the top level dispatcher.
4576  void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
4577  // Helper for delayed processing of attributes.
4578  void ProcessDeclAttributeDelayed(Decl *D,
4579  const ParsedAttributesView &AttrList);
4580 
4581  // Options for ProcessDeclAttributeList().
4585 
4587  ProcessDeclAttributeOptions Result = *this;
4588  Result.IncludeCXX11Attributes = Val;
4589  return Result;
4590  }
4591 
4593  ProcessDeclAttributeOptions Result = *this;
4594  Result.IgnoreTypeAttributes = Val;
4595  return Result;
4596  }
4597 
4598  // Should C++11 attributes be processed?
4600 
4601  // Should any type attributes encountered be ignored?
4602  // If this option is false, a diagnostic will be emitted for any type
4603  // attributes of a kind that does not "slide" from the declaration to
4604  // the decl-specifier-seq.
4606  };
4607 
4608  void ProcessDeclAttributeList(Scope *S, Decl *D,
4609  const ParsedAttributesView &AttrList,
4610  const ProcessDeclAttributeOptions &Options =
4613  const ParsedAttributesView &AttrList);
4614 
4616 
4617  /// Handles semantic checking for features that are common to all attributes,
4618  /// such as checking whether a parameter was properly specified, or the
4619  /// correct number of arguments were passed, etc. Returns true if the
4620  /// attribute has been diagnosed.
4621  bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
4622  bool SkipArgCountCheck = false);
4623  bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
4624  bool SkipArgCountCheck = false);
4625 
4626  /// Determine if type T is a valid subject for a nonnull and similar
4627  /// attributes. By default, we look through references (the