clang  14.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 SemaPPCallbacks;
230  class TemplateDeductionInfo;
231 }
232 
233 namespace threadSafety {
234  class BeforeSet;
235  void threadSafetyCleanup(BeforeSet* Cache);
236 }
237 
238 // FIXME: No way to easily map from TemplateTypeParmTypes to
239 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
240 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
242 
243 /// Describes whether we've seen any nullability information for the given
244 /// file.
246  /// The first pointer declarator (of any pointer kind) in the file that does
247  /// not have a corresponding nullability annotation.
249 
250  /// The end location for the first pointer declarator in the file. Used for
251  /// placing fix-its.
253 
254  /// Which kind of pointer declarator we saw.
255  uint8_t PointerKind;
256 
257  /// Whether we saw any type nullability annotations in the given file.
258  bool SawTypeNullability = false;
259 };
260 
261 /// A mapping from file IDs to a record of whether we've seen nullability
262 /// information in that file.
264  /// A mapping from file IDs to the nullability information for each file ID.
265  llvm::DenseMap<FileID, FileNullability> Map;
266 
267  /// A single-element cache based on the file ID.
268  struct {
271  } Cache;
272 
273 public:
275  // Check the single-element cache.
276  if (file == Cache.File)
277  return Cache.Nullability;
278 
279  // It's not in the single-element cache; flush the cache if we have one.
280  if (!Cache.File.isInvalid()) {
281  Map[Cache.File] = Cache.Nullability;
282  }
283 
284  // Pull this entry into the cache.
285  Cache.File = file;
286  Cache.Nullability = Map[file];
287  return Cache.Nullability;
288  }
289 };
290 
291 /// Tracks expected type during expression parsing, for use in code completion.
292 /// The type is tied to a particular token, all functions that update or consume
293 /// the type take a start location of the token they are looking at as a
294 /// parameter. This avoids updating the type on hot paths in the parser.
296 public:
297  PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
298 
299  void enterCondition(Sema &S, SourceLocation Tok);
300  void enterReturn(Sema &S, SourceLocation Tok);
301  void enterVariableInit(SourceLocation Tok, Decl *D);
302  /// Handles e.g. BaseType{ .D = Tok...
304  const Designation &D);
305  /// Computing a type for the function argument may require running
306  /// overloading, so we postpone its computation until it is actually needed.
307  ///
308  /// Clients should be very careful when using this funciton, as it stores a
309  /// function_ref, clients should make sure all calls to get() with the same
310  /// location happen while function_ref is alive.
311  ///
312  /// The callback should also emit signature help as a side-effect, but only
313  /// if the completion point has been reached.
315  llvm::function_ref<QualType()> ComputeType);
316 
317  void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
318  void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
319  SourceLocation OpLoc);
320  void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
321  void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
322  void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
323  /// Handles all type casts, including C-style cast, C++ casts, etc.
325 
326  /// Get the expected type associated with this location, if any.
327  ///
328  /// If the location is a function argument, determining the expected type
329  /// involves considering all function overloads and the arguments so far.
330  /// In this case, signature help for these function overloads will be reported
331  /// as a side-effect (only if the completion point has been reached).
333  if (!Enabled || Tok != ExpectedLoc)
334  return QualType();
335  if (!Type.isNull())
336  return Type;
337  if (ComputeType)
338  return ComputeType();
339  return QualType();
340  }
341 
342 private:
343  bool Enabled;
344  /// Start position of a token for which we store expected type.
345  SourceLocation ExpectedLoc;
346  /// Expected type for a token starting at ExpectedLoc.
347  QualType Type;
348  /// A function to compute expected type at ExpectedLoc. It is only considered
349  /// if Type is null.
350  llvm::function_ref<QualType()> ComputeType;
351 };
352 
353 /// Sema - This implements semantic analysis and AST building for C.
354 class Sema final {
355  Sema(const Sema &) = delete;
356  void operator=(const Sema &) = delete;
357 
358  ///Source of additional semantic information.
359  ExternalSemaSource *ExternalSource;
360 
361  ///Whether Sema has generated a multiplexer and has to delete it.
362  bool isMultiplexExternalSource;
363 
364  static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
365 
366  bool isVisibleSlow(const NamedDecl *D);
367 
368  /// Determine whether two declarations should be linked together, given that
369  /// the old declaration might not be visible and the new declaration might
370  /// not have external linkage.
371  bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
372  const NamedDecl *New) {
373  if (isVisible(Old))
374  return true;
375  // See comment in below overload for why it's safe to compute the linkage
376  // of the new declaration here.
377  if (New->isExternallyDeclarable()) {
378  assert(Old->isExternallyDeclarable() &&
379  "should not have found a non-externally-declarable previous decl");
380  return true;
381  }
382  return false;
383  }
384  bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
385 
386  void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
387  QualType ResultTy,
388  ArrayRef<QualType> Args);
389 
390 public:
391  /// The maximum alignment, same as in llvm::Value. We duplicate them here
392  /// because that allows us not to duplicate the constants in clang code,
393  /// which we must to since we can't directly use the llvm constants.
394  /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
395  ///
396  /// This is the greatest alignment value supported by load, store, and alloca
397  /// instructions, and global values.
398  static const unsigned MaxAlignmentExponent = 32;
399  static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
400 
404 
407 
414 
415  /// Flag indicating whether or not to collect detailed statistics.
417 
418  /// Code-completion consumer.
420 
421  /// CurContext - This is the current declaration context of parsing.
423 
424  /// Generally null except when we temporarily switch decl contexts,
425  /// like in \see ActOnObjCTemporaryExitContainerContext.
427 
428  /// VAListTagName - The declaration name corresponding to __va_list_tag.
429  /// This is used as part of a hack to omit that class from ADL results.
431 
432  bool MSStructPragmaOn; // True when \#pragma ms_struct on
433 
434  /// Controls member pointer representation format under the MS ABI.
437 
438  /// Stack of active SEH __finally scopes. Can be empty.
440 
441  /// Source location for newly created implicit MSInheritanceAttrs
443 
444  /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
445  /// `TransformTypos` in order to keep track of any TypoExprs that are created
446  /// recursively during typo correction and wipe them away if the correction
447  /// fails.
449 
450  /// pragma clang section kind
453  PCSK_BSS = 1,
458  };
459 
461  PCSA_Set = 0,
463  };
464 
467  bool Valid = false;
469  };
470 
476 
478  PSK_Reset = 0x0, // #pragma ()
479  PSK_Set = 0x1, // #pragma (value)
480  PSK_Push = 0x2, // #pragma (push[, id])
481  PSK_Pop = 0x4, // #pragma (pop[, id])
482  PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
483  PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
484  PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
485  };
486 
487  // #pragma pack and align.
489  public:
490  // `Native` represents default align mode, which may vary based on the
491  // platform.
492  enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
493 
494  // #pragma pack info constructor
495  AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
496  : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
497  assert(Num == PackNumber && "The pack number has been truncated.");
498  }
499 
500  // #pragma align info constructor
502  : PackAttr(false), AlignMode(M),
503  PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
504 
505  explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
506 
508 
509  // When a AlignPackInfo itself cannot be used, this returns an 32-bit
510  // integer encoding for it. This should only be passed to
511  // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
512  static uint32_t getRawEncoding(const AlignPackInfo &Info) {
513  std::uint32_t Encoding{};
514  if (Info.IsXLStack())
515  Encoding |= IsXLMask;
516 
517  Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
518 
519  if (Info.IsPackAttr())
520  Encoding |= PackAttrMask;
521 
522  Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
523 
524  return Encoding;
525  }
526 
528  bool IsXL = static_cast<bool>(Encoding & IsXLMask);
530  static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
531  int PackNumber = (Encoding & PackNumMask) >> 4;
532 
533  if (Encoding & PackAttrMask)
534  return AlignPackInfo(M, PackNumber, IsXL);
535 
536  return AlignPackInfo(M, IsXL);
537  }
538 
539  bool IsPackAttr() const { return PackAttr; }
540 
541  bool IsAlignAttr() const { return !PackAttr; }
542 
543  Mode getAlignMode() const { return AlignMode; }
544 
545  unsigned getPackNumber() const { return PackNumber; }
546 
547  bool IsPackSet() const {
548  // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
549  // attriute on a decl.
550  return PackNumber != UninitPackVal && PackNumber != 0;
551  }
552 
553  bool IsXLStack() const { return XLStack; }
554 
555  bool operator==(const AlignPackInfo &Info) const {
556  return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
557  std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
558  Info.XLStack);
559  }
560 
561  bool operator!=(const AlignPackInfo &Info) const {
562  return !(*this == Info);
563  }
564 
565  private:
566  /// \brief True if this is a pragma pack attribute,
567  /// not a pragma align attribute.
568  bool PackAttr;
569 
570  /// \brief The alignment mode that is in effect.
571  Mode AlignMode;
572 
573  /// \brief The pack number of the stack.
574  unsigned char PackNumber;
575 
576  /// \brief True if it is a XL #pragma align/pack stack.
577  bool XLStack;
578 
579  /// \brief Uninitialized pack value.
580  static constexpr unsigned char UninitPackVal = -1;
581 
582  // Masks to encode and decode an AlignPackInfo.
583  static constexpr uint32_t IsXLMask{0x0000'0001};
584  static constexpr uint32_t AlignModeMask{0x0000'0006};
585  static constexpr uint32_t PackAttrMask{0x00000'0008};
586  static constexpr uint32_t PackNumMask{0x0000'01F0};
587  };
588 
589  template<typename ValueType>
590  struct PragmaStack {
591  struct Slot {
592  llvm::StringRef StackSlotLabel;
593  ValueType Value;
596  Slot(llvm::StringRef StackSlotLabel, ValueType Value,
601  };
602 
603  void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
604  llvm::StringRef StackSlotLabel, ValueType Value) {
605  if (Action == PSK_Reset) {
607  CurrentPragmaLocation = PragmaLocation;
608  return;
609  }
610  if (Action & PSK_Push)
611  Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
612  PragmaLocation);
613  else if (Action & PSK_Pop) {
614  if (!StackSlotLabel.empty()) {
615  // If we've got a label, try to find it and jump there.
616  auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
617  return x.StackSlotLabel == StackSlotLabel;
618  });
619  // If we found the label so pop from there.
620  if (I != Stack.rend()) {
621  CurrentValue = I->Value;
622  CurrentPragmaLocation = I->PragmaLocation;
623  Stack.erase(std::prev(I.base()), Stack.end());
624  }
625  } else if (!Stack.empty()) {
626  // We do not have a label, just pop the last entry.
627  CurrentValue = Stack.back().Value;
628  CurrentPragmaLocation = Stack.back().PragmaLocation;
629  Stack.pop_back();
630  }
631  }
632  if (Action & PSK_Set) {
634  CurrentPragmaLocation = PragmaLocation;
635  }
636  }
637 
638  // MSVC seems to add artificial slots to #pragma stacks on entering a C++
639  // method body to restore the stacks on exit, so it works like this:
640  //
641  // struct S {
642  // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
643  // void Method {}
644  // #pragma <name>(pop, InternalPragmaSlot)
645  // };
646  //
647  // It works even with #pragma vtordisp, although MSVC doesn't support
648  // #pragma vtordisp(push [, id], n)
649  // syntax.
650  //
651  // Push / pop a named sentinel slot.
652  void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
653  assert((Action == PSK_Push || Action == PSK_Pop) &&
654  "Can only push / pop #pragma stack sentinels!");
656  }
657 
658  // Constructors.
659  explicit PragmaStack(const ValueType &Default)
661 
662  bool hasValue() const { return CurrentValue != DefaultValue; }
663 
665  ValueType DefaultValue; // Value used for PSK_Reset action.
666  ValueType CurrentValue;
668  };
669  // FIXME: We should serialize / deserialize these if they occur in a PCH (but
670  // we shouldn't do so if they're in a module).
671 
672  /// Whether to insert vtordisps prior to virtual bases in the Microsoft
673  /// C++ ABI. Possible values are 0, 1, and 2, which mean:
674  ///
675  /// 0: Suppress all vtordisps
676  /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
677  /// structors
678  /// 2: Always insert vtordisps to support RTTI on partially constructed
679  /// objects
682  // The current #pragma align/pack values and locations at each #include.
687  };
689  // Segment #pragmas.
694 
695  // This stack tracks the current state of Sema.CurFPFeatures.
698  FPOptionsOverride result;
699  if (!FpPragmaStack.hasValue()) {
700  result = FPOptionsOverride();
701  } else {
702  result = FpPragmaStack.CurrentValue;
703  }
704  return result;
705  }
706 
707  // RAII object to push / pop sentinel slots for all MS #pragma stacks.
708  // Actions should be performed only if we enter / exit a C++ method body.
710  public:
711  PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
713 
714  private:
715  Sema &S;
716  StringRef SlotLabel;
717  bool ShouldAct;
718  };
719 
720  /// A mapping that describes the nullability we've seen in each header file.
722 
723  /// Last section used with #pragma init_seg.
726 
727  /// VisContext - Manages the stack for \#pragma GCC visibility.
728  void *VisContext; // Really a "PragmaVisStack*"
729 
730  /// This an attribute introduced by \#pragma clang attribute.
735  bool IsUsed;
736  };
737 
738  /// A push'd group of PragmaAttributeEntries.
740  /// The location of the push attribute.
742  /// The namespace of this push group.
745  };
746 
748 
749  /// The declaration that is currently receiving an attribute from the
750  /// #pragma attribute stack.
752 
753  /// This represents the last location of a "#pragma clang optimize off"
754  /// directive if such a directive has not been closed by an "on" yet. If
755  /// optimizations are currently "on", this is set to an invalid location.
757 
758  /// Flag indicating if Sema is building a recovery call expression.
759  ///
760  /// This flag is used to avoid building recovery call expressions
761  /// if Sema is already doing so, which would cause infinite recursions.
763 
764  /// Used to control the generation of ExprWithCleanups.
766 
767  /// ExprCleanupObjects - This is the stack of objects requiring
768  /// cleanup that are created by the current full expression.
770 
771  /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
772  /// to a variable (constant) that may or may not be odr-used in this Expr, and
773  /// we won't know until all lvalue-to-rvalue and discarded value conversions
774  /// have been applied to all subexpressions of the enclosing full expression.
775  /// This is cleared at the end of each full expression.
776  using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
779 
780  std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
781 
782  /// Stack containing information about each of the nested
783  /// function, block, and method scopes that are currently active.
785 
786  /// The index of the first FunctionScope that corresponds to the current
787  /// context.
788  unsigned FunctionScopesStart = 0;
789 
791  return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
792  FunctionScopes.end());
793  }
794 
795  /// Stack containing information needed when in C++2a an 'auto' is encountered
796  /// in a function declaration parameter type specifier in order to invent a
797  /// corresponding template parameter in the enclosing abbreviated function
798  /// template. This information is also present in LambdaScopeInfo, stored in
799  /// the FunctionScopes stack.
801 
802  /// The index of the first InventedParameterInfo that refers to the current
803  /// context.
805 
807  return llvm::makeArrayRef(InventedParameterInfos.begin() +
809  InventedParameterInfos.end());
810  }
811 
815 
816  /// ExtVectorDecls - This is a list all the extended vector types. This allows
817  /// us to associate a raw vector type with one of the ext_vector type names.
818  /// This is only necessary for issuing pretty diagnostics.
820 
821  /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
822  std::unique_ptr<CXXFieldCollector> FieldCollector;
823 
825 
826  /// Set containing all declared private fields that are not used.
828 
829  /// Set containing all typedefs that are likely unused.
832 
833  /// Delete-expressions to be analyzed at the end of translation unit
834  ///
835  /// This list contains class members, and locations of delete-expressions
836  /// that could not be proven as to whether they mismatch with new-expression
837  /// used in initializer of the field.
838  typedef std::pair<SourceLocation, bool> DeleteExprLoc;
840  llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
841 
843 
844  /// PureVirtualClassDiagSet - a set of class declarations which we have
845  /// emitted a list of pure virtual functions. Used to prevent emitting the
846  /// same list more than once.
847  std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
848 
849  /// ParsingInitForAutoVars - a set of declarations with auto types for which
850  /// we are currently parsing the initializer.
852 
853  /// Look for a locally scoped extern "C" declaration by the given name.
855 
859 
860  /// All the tentative definitions encountered in the TU.
862 
863  /// All the external declarations encoutered and used in the TU.
865 
869 
870  /// The set of file scoped decls seen so far that have not been used
871  /// and must warn if not used. Only contains the first declaration.
873 
877 
878  /// All the delegating constructors seen so far in the file, used for
879  /// cycle detection at the end of the TU.
881 
882  /// All the overriding functions seen during a class definition
883  /// that had their exception spec checks delayed, plus the overridden
884  /// function.
887 
888  /// All the function redeclarations seen during a class definition that had
889  /// their exception spec checks delayed, plus the prior declaration they
890  /// should be checked against. Except during error recovery, the new decl
891  /// should always be a friend declaration, as that's the only valid way to
892  /// redeclare a special member before its class is complete.
895 
896  typedef llvm::MapVector<const FunctionDecl *,
897  std::unique_ptr<LateParsedTemplate>>
900 
901  /// Callback to the parser to parse templated functions when needed.
902  typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
903  typedef void LateTemplateParserCleanupCB(void *P);
907 
909  LateTemplateParserCleanupCB *LTPCleanup,
910  void *P) {
911  LateTemplateParser = LTP;
912  LateTemplateParserCleanup = LTPCleanup;
913  OpaqueParser = P;
914  }
915 
916  class DelayedDiagnostics;
917 
919  sema::DelayedDiagnosticPool *SavedPool;
921  };
924 
925  /// A class which encapsulates the logic for delaying diagnostics
926  /// during parsing and other processing.
928  /// The current pool of diagnostics into which delayed
929  /// diagnostics should go.
931 
932  public:
933  DelayedDiagnostics() : CurPool(nullptr) {}
934 
935  /// Adds a delayed diagnostic.
936  void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
937 
938  /// Determines whether diagnostics should be delayed.
939  bool shouldDelayDiagnostics() { return CurPool != nullptr; }
940 
941  /// Returns the current delayed-diagnostics pool.
943  return CurPool;
944  }
945 
946  /// Enter a new scope. Access and deprecation diagnostics will be
947  /// collected in this pool.
950  state.SavedPool = CurPool;
951  CurPool = &pool;
952  return state;
953  }
954 
955  /// Leave a delayed-diagnostic state that was previously pushed.
956  /// Do not emit any of the diagnostics. This is performed as part
957  /// of the bookkeeping of popping a pool "properly".
959  CurPool = state.SavedPool;
960  }
961 
962  /// Enter a new scope where access and deprecation diagnostics are
963  /// not delayed.
966  state.SavedPool = CurPool;
967  CurPool = nullptr;
968  return state;
969  }
970 
971  /// Undo a previous pushUndelayed().
973  assert(CurPool == nullptr);
974  CurPool = state.SavedPool;
975  }
977 
978  /// A RAII object to temporarily push a declaration context.
979  class ContextRAII {
980  private:
981  Sema &S;
982  DeclContext *SavedContext;
983  ProcessingContextState SavedContextState;
984  QualType SavedCXXThisTypeOverride;
985  unsigned SavedFunctionScopesStart;
986  unsigned SavedInventedParameterInfosStart;
987 
988  public:
989  ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
990  : S(S), SavedContext(S.CurContext),
991  SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
992  SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
993  SavedFunctionScopesStart(S.FunctionScopesStart),
994  SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
995  {
996  assert(ContextToPush && "pushing null context");
997  S.CurContext = ContextToPush;
998  if (NewThisContext)
999  S.CXXThisTypeOverride = QualType();
1000  // Any saved FunctionScopes do not refer to this context.
1001  S.FunctionScopesStart = S.FunctionScopes.size();
1002  S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1003  }
1004 
1005  void pop() {
1006  if (!SavedContext) return;
1007  S.CurContext = SavedContext;
1008  S.DelayedDiagnostics.popUndelayed(SavedContextState);
1009  S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1010  S.FunctionScopesStart = SavedFunctionScopesStart;
1011  S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1012  SavedContext = nullptr;
1013  }
1014 
1016  pop();
1017  }
1018  };
1019 
1020  /// Whether the AST is currently being rebuilt to correct immediate
1021  /// invocations. Immediate invocation candidates and references to consteval
1022  /// functions aren't tracked when this is set.
1024 
1025  /// Used to change context to isConstantEvaluated without pushing a heavy
1026  /// ExpressionEvaluationContextRecord object.
1028 
1030  return ExprEvalContexts.back().isConstantEvaluated() ||
1032  }
1033 
1034  /// RAII object to handle the state changes required to synthesize
1035  /// a function body.
1037  Sema &S;
1038  Sema::ContextRAII SavedContext;
1039  bool PushedCodeSynthesisContext = false;
1040 
1041  public:
1043  : S(S), SavedContext(S, DC) {
1044  S.PushFunctionScope();
1045  S.PushExpressionEvaluationContext(
1047  if (auto *FD = dyn_cast<FunctionDecl>(DC))
1048  FD->setWillHaveBody(true);
1049  else
1050  assert(isa<ObjCMethodDecl>(DC));
1051  }
1052 
1054  assert(!PushedCodeSynthesisContext);
1055 
1058  Ctx.PointOfInstantiation = UseLoc;
1059  Ctx.Entity = cast<Decl>(S.CurContext);
1060  S.pushCodeSynthesisContext(Ctx);
1061 
1062  PushedCodeSynthesisContext = true;
1063  }
1064 
1066  if (PushedCodeSynthesisContext)
1067  S.popCodeSynthesisContext();
1068  if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1069  FD->setWillHaveBody(false);
1070  S.PopExpressionEvaluationContext();
1071  S.PopFunctionScopeInfo();
1072  }
1073  };
1074 
1075  /// WeakUndeclaredIdentifiers - Identifiers contained in
1076  /// \#pragma weak before declared. rare. may alias another
1077  /// identifier, declared or undeclared
1078  llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
1079 
1080  /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1081  /// \#pragma redefine_extname before declared. Used in Solaris system headers
1082  /// to define functions that occur in multiple standards to call the version
1083  /// in the currently selected standard.
1084  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1085 
1086 
1087  /// Load weak undeclared identifiers from the external source.
1089 
1090  /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1091  /// \#pragma weak during processing of other Decls.
1092  /// I couldn't figure out a clean way to generate these in-line, so
1093  /// we store them here and handle separately -- which is a hack.
1094  /// It would be best to refactor this.
1096 
1098 
1099  /// Translation Unit Scope - useful to Objective-C actions that need
1100  /// to lookup file scope declarations in the "ordinary" C decl namespace.
1101  /// For example, user-defined classes, built-in "id" type, etc.
1103 
1104  /// The C++ "std" namespace, where the standard library resides.
1106 
1107  /// The C++ "std::bad_alloc" class, which is defined by the C++
1108  /// standard library.
1110 
1111  /// The C++ "std::align_val_t" enum class, which is defined by the C++
1112  /// standard library.
1114 
1115  /// The C++ "std::experimental" namespace, where the experimental parts
1116  /// of the standard library resides.
1118 
1119  /// The C++ "std::initializer_list" template, which is defined in
1120  /// <initializer_list>.
1122 
1123  /// The C++ "std::coroutine_traits" template, which is defined in
1124  /// <coroutine_traits>
1126  /// The namespace where coroutine components are defined. In standard,
1127  /// they are defined in std namespace. And in the previous implementation,
1128  /// they are defined in std::experimental namespace.
1130 
1131  /// The C++ "type_info" declaration, which is defined in <typeinfo>.
1133 
1134  /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1136 
1137  /// Caches identifiers/selectors for NSFoundation APIs.
1138  std::unique_ptr<NSAPI> NSAPIObj;
1139 
1140  /// The declaration of the Objective-C NSNumber class.
1142 
1143  /// The declaration of the Objective-C NSValue class.
1145 
1146  /// Pointer to NSNumber type (NSNumber *).
1148 
1149  /// Pointer to NSValue type (NSValue *).
1151 
1152  /// The Objective-C NSNumber methods used to create NSNumber literals.
1154 
1155  /// The declaration of the Objective-C NSString class.
1157 
1158  /// Pointer to NSString type (NSString *).
1160 
1161  /// The declaration of the stringWithUTF8String: method.
1163 
1164  /// The declaration of the valueWithBytes:objCType: method.
1166 
1167  /// The declaration of the Objective-C NSArray class.
1169 
1170  /// The declaration of the arrayWithObjects:count: method.
1172 
1173  /// The declaration of the Objective-C NSDictionary class.
1175 
1176  /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1178 
1179  /// id<NSCopying> type.
1181 
1182  /// will hold 'respondsToSelector:'
1184 
1185  /// A flag to remember whether the implicit forms of operator new and delete
1186  /// have been declared.
1188 
1189  /// Describes how the expressions currently being parsed are
1190  /// evaluated at run-time, if at all.
1192  /// The current expression and its subexpressions occur within an
1193  /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1194  /// \c sizeof, where the type of the expression may be significant but
1195  /// no code will be generated to evaluate the value of the expression at
1196  /// run time.
1197  Unevaluated,
1198 
1199  /// The current expression occurs within a braced-init-list within
1200  /// an unevaluated operand. This is mostly like a regular unevaluated
1201  /// context, except that we still instantiate constexpr functions that are
1202  /// referenced here so that we can perform narrowing checks correctly.
1204 
1205  /// The current expression occurs within a discarded statement.
1206  /// This behaves largely similarly to an unevaluated operand in preventing
1207  /// definitions from being required, but not in other ways.
1209 
1210  /// The current expression occurs within an unevaluated
1211  /// operand that unconditionally permits abstract references to
1212  /// fields, such as a SIZE operator in MS-style inline assembly.
1214 
1215  /// The current context is "potentially evaluated" in C++11 terms,
1216  /// but the expression is evaluated at compile-time (like the values of
1217  /// cases in a switch statement).
1219 
1220  /// In addition of being constant evaluated, the current expression
1221  /// occurs in an immediate function context - either a consteval function
1222  /// or a consteval if function.
1224 
1225  /// The current expression is potentially evaluated at run time,
1226  /// which means that code may be generated to evaluate the value of the
1227  /// expression at run time.
1229 
1230  /// The current expression is potentially evaluated, but any
1231  /// declarations referenced inside that expression are only used if
1232  /// in fact the current expression is used.
1233  ///
1234  /// This value is used when parsing default function arguments, for which
1235  /// we would like to provide diagnostics (e.g., passing non-POD arguments
1236  /// through varargs) but do not want to mark declarations as "referenced"
1237  /// until the default argument is used.
1239  };
1240 
1241  using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1242 
1243  /// Data structure used to record current or nested
1244  /// expression evaluation contexts.
1246  /// The expression evaluation context.
1248 
1249  /// Whether the enclosing context needed a cleanup.
1251 
1252  /// The number of active cleanup objects when we entered
1253  /// this expression evaluation context.
1255 
1256  /// The number of typos encountered during this expression evaluation
1257  /// context (i.e. the number of TypoExprs created).
1258  unsigned NumTypos;
1259 
1261 
1262  /// The lambdas that are present within this context, if it
1263  /// is indeed an unevaluated context.
1265 
1266  /// The declaration that provides context for lambda expressions
1267  /// and block literals if the normal declaration context does not
1268  /// suffice, e.g., in a default function argument.
1270 
1271  /// If we are processing a decltype type, a set of call expressions
1272  /// for which we have deferred checking the completeness of the return type.
1274 
1275  /// If we are processing a decltype type, a set of temporary binding
1276  /// expressions for which we have deferred checking the destructor.
1278 
1280 
1281  /// Expressions appearing as the LHS of a volatile assignment in this
1282  /// context. We produce a warning for these when popping the context if
1283  /// they are not discarded-value expressions nor unevaluated operands.
1285 
1286  /// Set of candidates for starting an immediate invocation.
1288 
1289  /// Set of DeclRefExprs referencing a consteval function when used in a
1290  /// context not already known to be immediately invoked.
1292 
1293  /// \brief Describes whether we are in an expression constext which we have
1294  /// to handle differently.
1297  } ExprContext;
1298 
1299  // A context can be nested in both a discarded statement context and
1300  // an immediate function context, so they need to be tracked independently.
1303 
1305  unsigned NumCleanupObjects,
1313 
1314  bool isUnevaluated() const {
1318  }
1319 
1320  bool isConstantEvaluated() const {
1323  }
1324 
1329  }
1330 
1333  (Context ==
1336  }
1337  };
1338 
1339  /// A stack of expression evaluation contexts.
1341 
1342  /// Emit a warning for all pending noderef expressions that we recorded.
1344 
1345  /// Compute the mangling number context for a lambda expression or
1346  /// block literal. Also return the extra mangling decl if any.
1347  ///
1348  /// \param DC - The DeclContext containing the lambda expression or
1349  /// block literal.
1350  std::tuple<MangleNumberingContext *, Decl *>
1352 
1353 
1354  /// SpecialMemberOverloadResult - The overloading result for a special member
1355  /// function.
1356  ///
1357  /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1358  /// integer are used to determine whether overload resolution succeeded.
1360  public:
1361  enum Kind {
1365  };
1366 
1367  private:
1368  llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
1369 
1370  public:
1373  : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1374 
1375  CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1376  void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1377 
1378  Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1379  void setKind(Kind K) { Pair.setInt(K); }
1380  };
1381 
1383  : public llvm::FastFoldingSetNode,
1385  public:
1386  SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1387  : FastFoldingSetNode(ID)
1388  {}
1389  };
1390 
1391  /// A cache of special member function overload resolution results
1392  /// for C++ records.
1393  llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1394 
1395  /// A cache of the flags available in enumerations with the flag_bits
1396  /// attribute.
1397  mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1398 
1399  /// The kind of translation unit we are processing.
1400  ///
1401  /// When we're processing a complete translation unit, Sema will perform
1402  /// end-of-translation-unit semantic tasks (such as creating
1403  /// initializers for tentative definitions in C) once parsing has
1404  /// completed. Modules and precompiled headers perform different kinds of
1405  /// checks.
1407 
1408  llvm::BumpPtrAllocator BumpAlloc;
1409 
1410  /// The number of SFINAE diagnostics that have been trapped.
1412 
1413  typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1415 
1416  /// A mapping from parameters with unparsed default arguments to the
1417  /// set of instantiations of each parameter.
1418  ///
1419  /// This mapping is a temporary data structure used when parsing
1420  /// nested class templates or nested classes of class templates,
1421  /// where we might end up instantiating an inner class before the
1422  /// default arguments of its methods have been parsed.
1424 
1425  // Contains the locations of the beginning of unparsed default
1426  // argument locations.
1427  llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1428 
1429  /// UndefinedInternals - all the used, undefined objects which require a
1430  /// definition in this translation unit.
1431  llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1432 
1433  /// Determine if VD, which must be a variable or function, is an external
1434  /// symbol that nonetheless can't be referenced from outside this translation
1435  /// unit because its type has no linkage and it's not extern "C".
1437 
1438  /// Obtain a sorted list of functions that are undefined but ODR-used.
1439  void getUndefinedButUsed(
1440  SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1441 
1442  /// Retrieves list of suspicious delete-expressions that will be checked at
1443  /// the end of translation unit.
1444  const llvm::MapVector<FieldDecl *, DeleteLocs> &
1446 
1448  public:
1449  using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1450  using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1451  iterator begin() { return Methods.begin(); }
1452  iterator end() { return Methods.end(); }
1453  iterator find(Selector Sel) { return Methods.find(Sel); }
1454  std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1455  return Methods.insert(Val);
1456  }
1457  int count(Selector Sel) const { return Methods.count(Sel); }
1458  bool empty() const { return Methods.empty(); }
1459 
1460  private:
1461  llvm::DenseMap<Selector, Lists> Methods;
1462  };
1463 
1464  /// Method Pool - allows efficient lookup when typechecking messages to "id".
1465  /// We need to maintain a list, since selectors can have differing signatures
1466  /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1467  /// of selectors are "overloaded").
1468  /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1469  /// methods inside categories with a particular selector.
1471 
1472  /// Method selectors used in a \@selector expression. Used for implementation
1473  /// of -Wselector.
1474  llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1475 
1476  /// List of SourceLocations where 'self' is implicitly retained inside a
1477  /// block.
1480 
1481  /// Kinds of C++ special members.
1490  };
1491 
1492  typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1494 
1495  /// The C++ special members which we are currently in the process of
1496  /// declaring. If this process recursively triggers the declaration of the
1497  /// same special member, we should act as if it is not yet declared.
1499 
1500  /// Kinds of defaulted comparison operator functions.
1501  enum class DefaultedComparisonKind : unsigned char {
1502  /// This is not a defaultable comparison operator.
1503  None,
1504  /// This is an operator== that should be implemented as a series of
1505  /// subobject comparisons.
1506  Equal,
1507  /// This is an operator<=> that should be implemented as a series of
1508  /// subobject comparisons.
1509  ThreeWay,
1510  /// This is an operator!= that should be implemented as a rewrite in terms
1511  /// of a == comparison.
1512  NotEqual,
1513  /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1514  /// terms of a <=> comparison.
1515  Relational,
1516  };
1517 
1518  /// The function definitions which were renamed as part of typo-correction
1519  /// to match their respective declarations. We want to keep track of them
1520  /// to ensure that we don't emit a "redefinition" error if we encounter a
1521  /// correctly named definition after the renamed definition.
1523 
1524  /// Stack of types that correspond to the parameter entities that are
1525  /// currently being copy-initialized. Can be empty.
1527 
1528  void ReadMethodPool(Selector Sel);
1530 
1531  /// Private Helper predicate to check for 'self'.
1532  bool isSelfExpr(Expr *RExpr);
1533  bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1534 
1535  /// Cause the active diagnostic on the DiagosticsEngine to be
1536  /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1537  /// should not be used elsewhere.
1538  void EmitCurrentDiagnostic(unsigned DiagID);
1539 
1540  /// Records and restores the CurFPFeatures state on entry/exit of compound
1541  /// statements.
1543  public:
1544  FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) {
1545  OldOverrides = S.FpPragmaStack.CurrentValue;
1546  }
1548  S.CurFPFeatures = OldFPFeaturesState;
1549  S.FpPragmaStack.CurrentValue = OldOverrides;
1550  }
1551  FPOptionsOverride getOverrides() { return OldOverrides; }
1552 
1553  private:
1554  Sema& S;
1555  FPOptions OldFPFeaturesState;
1556  FPOptionsOverride OldOverrides;
1557  };
1558 
1559  void addImplicitTypedef(StringRef Name, QualType T);
1560 
1561  bool WarnedStackExhausted = false;
1562 
1563  /// Increment when we find a reference; decrement when we find an ignored
1564  /// assignment. Ultimately the value is 0 if every reference is an ignored
1565  /// assignment.
1566  llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1567 
1568 private:
1569  Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1570 
1571  bool WarnedDarwinSDKInfoMissing = false;
1572 
1573 public:
1574  Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1576  CodeCompleteConsumer *CompletionConsumer = nullptr);
1577  ~Sema();
1578 
1579  /// Perform initialization that occurs after the parser has been
1580  /// initialized but before it parses anything.
1581  void Initialize();
1582 
1583  /// This virtual key function only exists to limit the emission of debug info
1584  /// describing the Sema class. GCC and Clang only emit debug info for a class
1585  /// with a vtable when the vtable is emitted. Sema is final and not
1586  /// polymorphic, but the debug info size savings are so significant that it is
1587  /// worth adding a vtable just to take advantage of this optimization.
1588  virtual void anchor();
1589 
1590  const LangOptions &getLangOpts() const { return LangOpts; }
1593 
1596  Preprocessor &getPreprocessor() const { return PP; }
1597  ASTContext &getASTContext() const { return Context; }
1598  ASTConsumer &getASTConsumer() const { return Consumer; }
1600  ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1601 
1603  StringRef Platform);
1605 
1606  ///Registers an external source. If an external source already exists,
1607  /// creates a multiplex external source and appends to it.
1608  ///
1609  ///\param[in] E - A non-null external sema source.
1610  ///
1612 
1613  void PrintStats() const;
1614 
1615  /// Warn that the stack is nearly exhausted.
1617 
1618  /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1619  /// guaranteed). Produces a warning if we're low on stack space and allocates
1620  /// more in that case. Use this in code that may recurse deeply (for example,
1621  /// in template instantiation) to avoid stack overflow.
1623  llvm::function_ref<void()> Fn);
1624 
1625  /// Helper class that creates diagnostics with optional
1626  /// template instantiation stacks.
1627  ///
1628  /// This class provides a wrapper around the basic DiagnosticBuilder
1629  /// class that emits diagnostics. ImmediateDiagBuilder is
1630  /// responsible for emitting the diagnostic (as DiagnosticBuilder
1631  /// does) and, if the diagnostic comes from inside a template
1632  /// instantiation, printing the template instantiation stack as
1633  /// well.
1635  Sema &SemaRef;
1636  unsigned DiagID;
1637 
1638  public:
1639  ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1640  : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1641  ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1642  : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1643 
1644  // This is a cunning lie. DiagnosticBuilder actually performs move
1645  // construction in its copy constructor (but due to varied uses, it's not
1646  // possible to conveniently express this as actual move construction). So
1647  // the default copy ctor here is fine, because the base class disables the
1648  // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1649  // in that case anwyay.
1650  ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1651 
1653  // If we aren't active, there is nothing to do.
1654  if (!isActive()) return;
1655 
1656  // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1657  // builder itself so it won't emit the diagnostic in its own destructor.
1658  //
1659  // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1660  // do its own needless checks to see if the diagnostic needs to be
1661  // emitted. However, because we take care to ensure that the builder
1662  // objects never escape, a sufficiently smart compiler will be able to
1663  // eliminate that code.
1664  Clear();
1665 
1666  // Dispatch to Sema to emit the diagnostic.
1667  SemaRef.EmitCurrentDiagnostic(DiagID);
1668  }
1669 
1670  /// Teach operator<< to produce an object of the correct type.
1671  template <typename T>
1672  friend const ImmediateDiagBuilder &
1674  const DiagnosticBuilder &BaseDiag = Diag;
1675  BaseDiag << Value;
1676  return Diag;
1677  }
1678 
1679  // It is necessary to limit this to rvalue reference to avoid calling this
1680  // function with a bitfield lvalue argument since non-const reference to
1681  // bitfield is not allowed.
1682  template <typename T, typename = typename std::enable_if<
1683  !std::is_lvalue_reference<T>::value>::type>
1684  const ImmediateDiagBuilder &operator<<(T &&V) const {
1685  const DiagnosticBuilder &BaseDiag = *this;
1686  BaseDiag << std::move(V);
1687  return *this;
1688  }
1689  };
1690 
1691  /// A generic diagnostic builder for errors which may or may not be deferred.
1692  ///
1693  /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1694  /// which are not allowed to appear inside __device__ functions and are
1695  /// allowed to appear in __host__ __device__ functions only if the host+device
1696  /// function is never codegen'ed.
1697  ///
1698  /// To handle this, we use the notion of "deferred diagnostics", where we
1699  /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1700  ///
1701  /// This class lets you emit either a regular diagnostic, a deferred
1702  /// diagnostic, or no diagnostic at all, according to an argument you pass to
1703  /// its constructor, thus simplifying the process of creating these "maybe
1704  /// deferred" diagnostics.
1706  public:
1707  enum Kind {
1708  /// Emit no diagnostics.
1710  /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1712  /// Emit the diagnostic immediately, and, if it's a warning or error, also
1713  /// emit a call stack showing how this function can be reached by an a
1714  /// priori known-emitted function.
1716  /// Create a deferred diagnostic, which is emitted only if the function
1717  /// it's attached to is codegen'ed. Also emit a call stack as with
1718  /// K_ImmediateWithCallStack.
1720  };
1721 
1722  SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1723  FunctionDecl *Fn, Sema &S);
1725  SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1727 
1728  bool isImmediate() const { return ImmediateDiag.hasValue(); }
1729 
1730  /// Convertible to bool: True if we immediately emitted an error, false if
1731  /// we didn't emit an error or we created a deferred error.
1732  ///
1733  /// Example usage:
1734  ///
1735  /// if (SemaDiagnosticBuilder(...) << foo << bar)
1736  /// return ExprError();
1737  ///
1738  /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1739  /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1740  operator bool() const { return isImmediate(); }
1741 
1742  template <typename T>
1743  friend const SemaDiagnosticBuilder &
1745  if (Diag.ImmediateDiag.hasValue())
1746  *Diag.ImmediateDiag << Value;
1747  else if (Diag.PartialDiagId.hasValue())
1748  Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1749  << Value;
1750  return Diag;
1751  }
1752 
1753  // It is necessary to limit this to rvalue reference to avoid calling this
1754  // function with a bitfield lvalue argument since non-const reference to
1755  // bitfield is not allowed.
1756  template <typename T, typename = typename std::enable_if<
1757  !std::is_lvalue_reference<T>::value>::type>
1758  const SemaDiagnosticBuilder &operator<<(T &&V) const {
1759  if (ImmediateDiag.hasValue())
1760  *ImmediateDiag << std::move(V);
1761  else if (PartialDiagId.hasValue())
1762  S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1763  return *this;
1764  }
1765 
1766  friend const SemaDiagnosticBuilder &
1768  if (Diag.ImmediateDiag.hasValue())
1769  PD.Emit(*Diag.ImmediateDiag);
1770  else if (Diag.PartialDiagId.hasValue())
1771  Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1772  return Diag;
1773  }
1774 
1775  void AddFixItHint(const FixItHint &Hint) const {
1776  if (ImmediateDiag.hasValue())
1777  ImmediateDiag->AddFixItHint(Hint);
1778  else if (PartialDiagId.hasValue())
1779  S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1780  }
1781 
1783  return ExprError();
1784  }
1786  return StmtError();
1787  }
1788  operator ExprResult() const { return ExprError(); }
1789  operator StmtResult() const { return StmtError(); }
1790  operator TypeResult() const { return TypeError(); }
1791  operator DeclResult() const { return DeclResult(true); }
1792  operator MemInitResult() const { return MemInitResult(true); }
1793 
1794  private:
1795  Sema &S;
1796  SourceLocation Loc;
1797  unsigned DiagID;
1798  FunctionDecl *Fn;
1799  bool ShowCallStack;
1800 
1801  // Invariant: At most one of these Optionals has a value.
1802  // FIXME: Switch these to a Variant once that exists.
1804  llvm::Optional<unsigned> PartialDiagId;
1805  };
1806 
1807  /// Is the last error level diagnostic immediate. This is used to determined
1808  /// whether the next info diagnostic should be immediate.
1810 
1811  /// Emit a diagnostic.
1812  SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1813  bool DeferHint = false);
1814 
1815  /// Emit a partial diagnostic.
1817  bool DeferHint = false);
1818 
1819  /// Build a partial diagnostic.
1820  PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1821 
1822  /// Whether deferrable diagnostics should be deferred.
1823  bool DeferDiags = false;
1824 
1825  /// RAII class to control scope of DeferDiags.
1827  Sema &S;
1828  bool SavedDeferDiags = false;
1829 
1830  public:
1832  : S(S), SavedDeferDiags(S.DeferDiags) {
1833  S.DeferDiags = DeferDiags;
1834  }
1835  ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1836  };
1837 
1838  /// Whether uncompilable error has occurred. This includes error happens
1839  /// in deferred diagnostics.
1840  bool hasUncompilableErrorOccurred() const;
1841 
1842  bool findMacroSpelling(SourceLocation &loc, StringRef name);
1843 
1844  /// Get a string to suggest for zero-initialization of a type.
1845  std::string
1848 
1849  /// Calls \c Lexer::getLocForEndOfToken()
1851 
1852  /// Retrieve the module loader associated with the preprocessor.
1853  ModuleLoader &getModuleLoader() const;
1854 
1855  /// Invent a new identifier for parameters of abbreviated templates.
1856  IdentifierInfo *
1858  unsigned Index);
1859 
1861 
1862  private:
1863  /// Function or variable declarations to be checked for whether the deferred
1864  /// diagnostics should be emitted.
1865  llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1866 
1867  public:
1868  // Emit all deferred diagnostics.
1869  void emitDeferredDiags();
1870 
1872  /// The global module fragment, between 'module;' and a module-declaration.
1874  /// A normal translation unit fragment. For a non-module unit, this is the
1875  /// entire translation unit. Otherwise, it runs from the module-declaration
1876  /// to the private-module-fragment (if any) or the end of the TU (if not).
1878  /// The private module fragment, between 'module :private;' and the end of
1879  /// the translation unit.
1881  };
1882 
1886 
1888 
1890 
1891  void PushFunctionScope();
1892  void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1894 
1895  /// This is used to inform Sema what the current TemplateParameterDepth
1896  /// is during Parsing. Currently it is used to pass on the depth
1897  /// when parsing generic lambda 'auto' parameters.
1899 
1900  void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1902  unsigned OpenMPCaptureLevel = 0);
1903 
1904  /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1905  /// time after they've been popped.
1907  Sema *Self;
1908 
1909  public:
1910  explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1912  };
1913 
1914  using PoppedFunctionScopePtr =
1915  std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1916 
1919  const Decl *D = nullptr,
1920  QualType BlockType = QualType());
1921 
1923  return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1924  }
1925 
1927 
1931  void setFunctionHasMustTail();
1932 
1933  void PushCompoundScope(bool IsStmtExpr);
1934  void PopCompoundScope();
1935 
1937 
1939 
1940  /// Retrieve the current block, if any.
1942 
1943  /// Get the innermost lambda enclosing the current location, if any. This
1944  /// looks through intervening non-lambda scopes such as local functions and
1945  /// blocks.
1947 
1948  /// Retrieve the current lambda scope info, if any.
1949  /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1950  /// lambda scope info ignoring all inner capturing scopes that are not
1951  /// lambda scopes.
1953  getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1954 
1955  /// Retrieve the current generic lambda info, if any.
1957 
1958  /// Retrieve the current captured region, if any.
1960 
1961  /// Retrieve the current function, if any, that should be analyzed for
1962  /// potential availability violations.
1964 
1965  /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1967 
1968  /// Called before parsing a function declarator belonging to a function
1969  /// declaration.
1971  unsigned TemplateParameterDepth);
1972 
1973  /// Called after parsing a function declarator belonging to a function
1974  /// declaration.
1976 
1977  void ActOnComment(SourceRange Comment);
1978 
1979  //===--------------------------------------------------------------------===//
1980  // Type Analysis / Processing: SemaType.cpp.
1981  //
1982 
1984  const DeclSpec *DS = nullptr);
1985  QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1986  const DeclSpec *DS = nullptr);
1988  SourceLocation Loc, DeclarationName Entity);
1989  QualType BuildReferenceType(QualType T, bool LValueRef,
1990  SourceLocation Loc, DeclarationName Entity);
1992  Expr *ArraySize, unsigned Quals,
1993  SourceRange Brackets, DeclarationName Entity);
1994  QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1995  QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1996  SourceLocation AttrLoc);
1997  QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
1998  SourceLocation AttrLoc);
1999 
2000  QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
2001  SourceLocation AttrLoc);
2002 
2003  /// Same as above, but constructs the AddressSpace index if not provided.
2005  SourceLocation AttrLoc);
2006 
2008 
2010 
2011  /// Build a function type.
2012  ///
2013  /// This routine checks the function type according to C++ rules and
2014  /// under the assumption that the result type and parameter types have
2015  /// just been instantiated from a template. It therefore duplicates
2016  /// some of the behavior of GetTypeForDeclarator, but in a much
2017  /// simpler form that is only suitable for this narrow use case.
2018  ///
2019  /// \param T The return type of the function.
2020  ///
2021  /// \param ParamTypes The parameter types of the function. This array
2022  /// will be modified to account for adjustments to the types of the
2023  /// function parameters.
2024  ///
2025  /// \param Loc The location of the entity whose type involves this
2026  /// function type or, if there is no such entity, the location of the
2027  /// type that will have function type.
2028  ///
2029  /// \param Entity The name of the entity that involves the function
2030  /// type, if known.
2031  ///
2032  /// \param EPI Extra information about the function type. Usually this will
2033  /// be taken from an existing function with the same prototype.
2034  ///
2035  /// \returns A suitable function type, if there are no errors. The
2036  /// unqualified type will always be a FunctionProtoType.
2037  /// Otherwise, returns a NULL type.
2039  MutableArrayRef<QualType> ParamTypes,
2040  SourceLocation Loc, DeclarationName Entity,
2041  const FunctionProtoType::ExtProtoInfo &EPI);
2042 
2044  SourceLocation Loc,
2045  DeclarationName Entity);
2047  SourceLocation Loc, DeclarationName Entity);
2051  SourceLocation Loc);
2053  SourceLocation Loc);
2054  QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2055 
2058 
2059  /// Package the given type and TSI into a ParsedType.
2064  TypeSourceInfo **TInfo = nullptr);
2065  CanThrowResult canThrow(const Stmt *E);
2066  /// Determine whether the callee of a particular function call can throw.
2067  /// E, D and Loc are all optional.
2068  static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2069  SourceLocation Loc = SourceLocation());
2071  const FunctionProtoType *FPT);
2078  const FunctionProtoType *Old, SourceLocation OldLoc,
2079  const FunctionProtoType *New, SourceLocation NewLoc);
2081  const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2082  const FunctionProtoType *Old, SourceLocation OldLoc,
2083  const FunctionProtoType *New, SourceLocation NewLoc);
2084  bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2085  bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2086  const PartialDiagnostic &NestedDiagID,
2087  const PartialDiagnostic &NoteID,
2088  const PartialDiagnostic &NoThrowDiagID,
2089  const FunctionProtoType *Superset,
2090  SourceLocation SuperLoc,
2091  const FunctionProtoType *Subset,
2092  SourceLocation SubLoc);
2093  bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2094  const PartialDiagnostic &NoteID,
2095  const FunctionProtoType *Target,
2096  SourceLocation TargetLoc,
2097  const FunctionProtoType *Source,
2098  SourceLocation SourceLoc);
2099 
2101 
2102  /// The parser has parsed the context-sensitive type 'instancetype'
2103  /// in an Objective-C message declaration. Return the appropriate type.
2105 
2106  /// Abstract class used to diagnose incomplete types.
2107  struct TypeDiagnoser {
2109 
2110  virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2111  virtual ~TypeDiagnoser() {}
2112  };
2113 
2114  static int getPrintable(int I) { return I; }
2115  static unsigned getPrintable(unsigned I) { return I; }
2116  static bool getPrintable(bool B) { return B; }
2117  static const char * getPrintable(const char *S) { return S; }
2118  static StringRef getPrintable(StringRef S) { return S; }
2119  static const std::string &getPrintable(const std::string &S) { return S; }
2120  static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2121  return II;
2122  }
2124  static QualType getPrintable(QualType T) { return T; }
2125  static SourceRange getPrintable(SourceRange R) { return R; }
2126  static SourceRange getPrintable(SourceLocation L) { return L; }
2127  static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2128  static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2129 
2130  template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2131  protected:
2132  unsigned DiagID;
2133  std::tuple<const Ts &...> Args;
2134 
2135  template <std::size_t... Is>
2136  void emit(const SemaDiagnosticBuilder &DB,
2137  std::index_sequence<Is...>) const {
2138  // Apply all tuple elements to the builder in order.
2139  bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2140  (void)Dummy;
2141  }
2142 
2143  public:
2144  BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2145  : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2146  assert(DiagID != 0 && "no diagnostic for type diagnoser");
2147  }
2148 
2149  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2150  const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2151  emit(DB, std::index_sequence_for<Ts...>());
2152  DB << T;
2153  }
2154  };
2155 
2156  /// Do a check to make sure \p Name looks like a legal argument for the
2157  /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
2158  /// is invalid for the given declaration.
2159  ///
2160  /// \p AL is used to provide caret diagnostics in case of a malformed name.
2161  ///
2162  /// \returns true if the name is a valid swift name for \p D, false otherwise.
2163  bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2164  const ParsedAttr &AL, bool IsAsync);
2165 
2166  /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2167  /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2168  /// For example, a diagnostic with no other parameters would generally have
2169  /// the form "...%select{incomplete|sizeless}0 type %1...".
2170  template <typename... Ts>
2172  public:
2173  SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2174  : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2175 
2176  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2177  const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2178  this->emit(DB, std::index_sequence_for<Ts...>());
2179  DB << T->isSizelessType() << T;
2180  }
2181  };
2182 
2183  enum class CompleteTypeKind {
2184  /// Apply the normal rules for complete types. In particular,
2185  /// treat all sizeless types as incomplete.
2186  Normal,
2187 
2188  /// Relax the normal rules for complete types so that they include
2189  /// sizeless built-in types.
2191 
2192  // FIXME: Eventually we should flip the default to Normal and opt in
2193  // to AcceptSizeless rather than opt out of it.
2195  };
2196 
2197 private:
2198  /// Methods for marking which expressions involve dereferencing a pointer
2199  /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2200  /// they are parsed, meaning that a noderef pointer may not be accessed. For
2201  /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2202  /// `*p`, but need to check that `address of` is called on it. This requires
2203  /// keeping a container of all pending expressions and checking if the address
2204  /// of them are eventually taken.
2205  void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2206  void CheckAddressOfNoDeref(const Expr *E);
2207  void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2208 
2209  bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2210  CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2211 
2212  struct ModuleScope {
2213  SourceLocation BeginLoc;
2214  clang::Module *Module = nullptr;
2215  bool ModuleInterface = false;
2216  bool ImplicitGlobalModuleFragment = false;
2217  VisibleModuleSet OuterVisibleModules;
2218  };
2219  /// The modules we're currently parsing.
2221 
2222  /// Namespace definitions that we will export when they finish.
2223  llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2224 
2225  /// Get the module whose scope we are currently within.
2226  Module *getCurrentModule() const {
2227  return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2228  }
2229 
2230  /// Helper function to judge if we are in module purview.
2231  /// Return false if we are not in a module.
2232  bool isCurrentModulePurview() const {
2233  return getCurrentModule() ? getCurrentModule()->isModulePurview() : false;
2234  }
2235 
2236  /// Enter the scope of the global module.
2237  Module *PushGlobalModuleFragment(SourceLocation BeginLoc, bool IsImplicit);
2238  /// Leave the scope of the global module.
2239  void PopGlobalModuleFragment();
2240 
2241  VisibleModuleSet VisibleModules;
2242 
2243 public:
2244  /// Get the module owning an entity.
2245  Module *getOwningModule(const Decl *Entity) {
2246  return Entity->getOwningModule();
2247  }
2248 
2249  /// Make a merged definition of an existing hidden definition \p ND
2250  /// visible at the specified location.
2252 
2253  bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2254 
2255  // When loading a non-modular PCH files, this is used to restore module
2256  // visibility.
2257  void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2258  VisibleModules.setVisible(Mod, ImportLoc);
2259  }
2260 
2261  /// Determine whether a declaration is visible to name lookup.
2262  bool isVisible(const NamedDecl *D) {
2263  return D->isUnconditionallyVisible() || isVisibleSlow(D);
2264  }
2265 
2266  /// Determine whether any declaration of an entity is visible.
2267  bool
2269  llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2270  return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2271  }
2272  bool hasVisibleDeclarationSlow(const NamedDecl *D,
2274 
2277 
2278  /// Determine if \p D and \p Suggested have a structurally compatible
2279  /// layout as described in C11 6.2.7/1.
2280  bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2281 
2282  /// Determine if \p D has a visible definition. If not, suggest a declaration
2283  /// that should be made visible to expose the definition.
2284  bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2285  bool OnlyNeedComplete = false);
2287  NamedDecl *Hidden;
2288  return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2289  }
2290 
2291  /// Determine if the template parameter \p D has a visible default argument.
2292  bool
2294  llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2295 
2296  /// Determine if there is a visible declaration of \p D that is an explicit
2297  /// specialization declaration for a specialization of a template. (For a
2298  /// member specialization, use hasVisibleMemberSpecialization.)
2300  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2301 
2302  /// Determine if there is a visible declaration of \p D that is a member
2303  /// specialization declaration (as opposed to an instantiated declaration).
2305  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2306 
2307  /// Determine if \p A and \p B are equivalent internal linkage declarations
2308  /// from different modules, and thus an ambiguity error can be downgraded to
2309  /// an extension warning.
2311  const NamedDecl *B);
2313  SourceLocation Loc, const NamedDecl *D,
2315 
2317 
2320  return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2321  }
2323  CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2325  CompleteTypeKind Kind, unsigned DiagID);
2326 
2328  TypeDiagnoser &Diagnoser) {
2329  return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2330  }
2331  bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2332  return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2333  }
2334 
2335  template <typename... Ts>
2336  bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2337  const Ts &...Args) {
2338  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2339  return RequireCompleteType(Loc, T, Diagnoser);
2340  }
2341 
2342  template <typename... Ts>
2343  bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2344  const Ts &... Args) {
2345  SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2346  return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2347  }
2348 
2349  /// Get the type of expression E, triggering instantiation to complete the
2350  /// type if necessary -- that is, if the expression refers to a templated
2351  /// static data member of incomplete array type.
2352  ///
2353  /// May still return an incomplete type if instantiation was not possible or
2354  /// if the type is incomplete for a different reason. Use
2355  /// RequireCompleteExprType instead if a diagnostic is expected for an
2356  /// incomplete expression type.
2358 
2359  void completeExprArrayBound(Expr *E);
2361  TypeDiagnoser &Diagnoser);
2362  bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2363 
2364  template <typename... Ts>
2365  bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2366  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2367  return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2368  }
2369 
2370  template <typename... Ts>
2371  bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2372  const Ts &... Args) {
2373  SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2374  return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2375  }
2376 
2378  TypeDiagnoser &Diagnoser);
2379  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2380 
2381  template <typename... Ts>
2382  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2383  const Ts &...Args) {
2384  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2385  return RequireLiteralType(Loc, T, Diagnoser);
2386  }
2387 
2389  const CXXScopeSpec &SS, QualType T,
2390  TagDecl *OwnedTagDecl = nullptr);
2391 
2392  // Returns the underlying type of a decltype with the given expression.
2394 
2396  /// If AsUnevaluated is false, E is treated as though it were an evaluated
2397  /// context, such as when building a type for decltype(auto).
2398  QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
2401  SourceLocation Loc);
2402 
2403  //===--------------------------------------------------------------------===//
2404  // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2405  //
2406 
2407  struct SkipBodyInfo {
2410  New(nullptr) {}
2415  };
2416 
2417  DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2418 
2420 
2422 
2424  Scope *S, CXXScopeSpec *SS = nullptr,
2425  bool isClassName = false, bool HasTrailingDot = false,
2426  ParsedType ObjectType = nullptr,
2427  bool IsCtorOrDtorName = false,
2428  bool WantNontrivialTypeSourceInfo = false,
2429  bool IsClassTemplateDeductionContext = true,
2430  IdentifierInfo **CorrectedII = nullptr);
2432  bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2434  SourceLocation IILoc,
2435  Scope *S,
2436  CXXScopeSpec *SS,
2437  ParsedType &SuggestedType,
2438  bool IsTemplateName = false);
2439 
2440  /// Attempt to behave like MSVC in situations where lookup of an unqualified
2441  /// type name has failed in a dependent context. In these situations, we
2442  /// automatically form a DependentTypeName that will retry lookup in a related
2443  /// scope during instantiation.
2445  SourceLocation NameLoc,
2446  bool IsTemplateTypeArg);
2447 
2448  /// Describes the result of the name lookup and resolution performed
2449  /// by \c ClassifyName().
2451  /// This name is not a type or template in this context, but might be
2452  /// something else.
2454  /// Classification failed; an error has been produced.
2456  /// The name has been typo-corrected to a keyword.
2458  /// The name was classified as a type.
2460  /// The name was classified as a specific non-type, non-template
2461  /// declaration. ActOnNameClassifiedAsNonType should be called to
2462  /// convert the declaration to an expression.
2464  /// The name was classified as an ADL-only function name.
2465  /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2466  /// result to an expression.
2468  /// The name denotes a member of a dependent type that could not be
2469  /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2470  /// convert the result to an expression.
2472  /// The name was classified as an overload set, and an expression
2473  /// representing that overload set has been formed.
2474  /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2475  /// expression referencing the overload set.
2477  /// The name was classified as a template whose specializations are types.
2479  /// The name was classified as a variable template name.
2481  /// The name was classified as a function template name.
2483  /// The name was classified as an ADL-only function template name.
2485  /// The name was classified as a concept name.
2487  };
2488 
2491  union {
2496  };
2497 
2498  explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2499 
2500  public:
2502 
2503  NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2504 
2506  return NameClassification(NC_Error);
2507  }
2508 
2511  }
2512 
2515  Result.Expr = E;
2516  return Result;
2517  }
2518 
2521  Result.NonTypeDecl = D;
2522  return Result;
2523  }
2524 
2527  }
2528 
2531  }
2532 
2535  Result.Template = Name;
2536  return Result;
2537  }
2538 
2541  Result.Template = Name;
2542  return Result;
2543  }
2544 
2547  Result.Template = Name;
2548  return Result;
2549  }
2550 
2553  Result.Template = Name;
2554  return Result;
2555  }
2556 
2559  Result.Template = Name;
2560  return Result;
2561  }
2562 
2563  NameClassificationKind getKind() const { return Kind; }
2564 
2566  assert(Kind == NC_OverloadSet);
2567  return Expr;
2568  }
2569 
2571  assert(Kind == NC_Type);
2572  return Type;
2573  }
2574 
2576  assert(Kind == NC_NonType);
2577  return NonTypeDecl;
2578  }
2579 
2581  assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2582  Kind == NC_VarTemplate || Kind == NC_Concept ||
2583  Kind == NC_UndeclaredTemplate);
2584  return Template;
2585  }
2586 
2588  switch (Kind) {
2589  case NC_TypeTemplate:
2590  return TNK_Type_template;
2591  case NC_FunctionTemplate:
2592  return TNK_Function_template;
2593  case NC_VarTemplate:
2594  return TNK_Var_template;
2595  case NC_Concept:
2596  return TNK_Concept_template;
2597  case NC_UndeclaredTemplate:
2598  return TNK_Undeclared_template;
2599  default:
2600  llvm_unreachable("unsupported name classification.");
2601  }
2602  }
2603  };
2604 
2605  /// Perform name lookup on the given name, classifying it based on
2606  /// the results of name lookup and the following token.
2607  ///
2608  /// This routine is used by the parser to resolve identifiers and help direct
2609  /// parsing. When the identifier cannot be found, this routine will attempt
2610  /// to correct the typo and classify based on the resulting name.
2611  ///
2612  /// \param S The scope in which we're performing name lookup.
2613  ///
2614  /// \param SS The nested-name-specifier that precedes the name.
2615  ///
2616  /// \param Name The identifier. If typo correction finds an alternative name,
2617  /// this pointer parameter will be updated accordingly.
2618  ///
2619  /// \param NameLoc The location of the identifier.
2620  ///
2621  /// \param NextToken The token following the identifier. Used to help
2622  /// disambiguate the name.
2623  ///
2624  /// \param CCC The correction callback, if typo correction is desired.
2625  NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2626  IdentifierInfo *&Name, SourceLocation NameLoc,
2627  const Token &NextToken,
2628  CorrectionCandidateCallback *CCC = nullptr);
2629 
2630  /// Act on the result of classifying a name as an undeclared (ADL-only)
2631  /// non-type declaration.
2633  SourceLocation NameLoc);
2634  /// Act on the result of classifying a name as an undeclared member of a
2635  /// dependent base class.
2637  IdentifierInfo *Name,
2638  SourceLocation NameLoc,
2639  bool IsAddressOfOperand);
2640  /// Act on the result of classifying a name as a specific non-type
2641  /// declaration.
2643  NamedDecl *Found,
2644  SourceLocation NameLoc,
2645  const Token &NextToken);
2646  /// Act on the result of classifying a name as an overload set.
2648 
2649  /// Describes the detailed kind of a template name. Used in diagnostics.
2651  ClassTemplate,
2653  VarTemplate,
2654  AliasTemplate,
2656  Concept,
2658  };
2661 
2662  /// Determine whether it's plausible that E was intended to be a
2663  /// template-name.
2664  bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2665  if (!getLangOpts().CPlusPlus || E.isInvalid())
2666  return false;
2667  Dependent = false;
2668  if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2669  return !DRE->hasExplicitTemplateArgs();
2670  if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2671  return !ME->hasExplicitTemplateArgs();
2672  Dependent = true;
2673  if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2674  return !DSDRE->hasExplicitTemplateArgs();
2675  if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2676  return !DSME->hasExplicitTemplateArgs();
2677  // Any additional cases recognized here should also be handled by
2678  // diagnoseExprIntendedAsTemplateName.
2679  return false;
2680  }
2682  SourceLocation Less,
2683  SourceLocation Greater);
2684 
2685  void warnOnReservedIdentifier(const NamedDecl *D);
2686 
2688 
2690  MultiTemplateParamsArg TemplateParameterLists);
2692  QualType &T, SourceLocation Loc,
2693  unsigned FailedFoldDiagID);
2697  DeclarationName Name, SourceLocation Loc,
2698  bool IsTemplateId);
2699  void
2700  diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2701  SourceLocation FallbackLoc,
2702  SourceLocation ConstQualLoc = SourceLocation(),
2703  SourceLocation VolatileQualLoc = SourceLocation(),
2704  SourceLocation RestrictQualLoc = SourceLocation(),
2705  SourceLocation AtomicQualLoc = SourceLocation(),
2706  SourceLocation UnalignedQualLoc = SourceLocation());
2707 
2708  static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2709  void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2711  const LookupResult &R);
2714  const LookupResult &R);
2715  void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2716  const LookupResult &R);
2717  void CheckShadow(Scope *S, VarDecl *D);
2718 
2719  /// Warn if 'E', which is an expression that is about to be modified, refers
2720  /// to a shadowing declaration.
2722 
2724 
2725 private:
2726  /// Map of current shadowing declarations to shadowed declarations. Warn if
2727  /// it looks like the user is trying to modify the shadowing declaration.
2728  llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2729 
2730 public:
2731  void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2732  void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2733  void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2734  TypedefNameDecl *NewTD);
2737  TypeSourceInfo *TInfo,
2740  LookupResult &Previous, bool &Redeclaration);
2742  TypeSourceInfo *TInfo,
2744  MultiTemplateParamsArg TemplateParamLists,
2745  bool &AddToScope,
2747  NamedDecl *
2749  MultiTemplateParamsArg TemplateParamLists);
2750  // Returns true if the variable declaration is a redeclaration
2753  bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2754  Expr *Init);
2758 
2760  TypeSourceInfo *TInfo,
2762  MultiTemplateParamsArg TemplateParamLists,
2763  bool &AddToScope);
2765 
2766  enum class CheckConstexprKind {
2767  /// Diagnose issues that are non-constant or that are extensions.
2768  Diagnose,
2769  /// Identify whether this function satisfies the formal rules for constexpr
2770  /// functions in the current lanugage mode (with no extensions).
2771  CheckValid
2772  };
2773 
2776 
2779  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2781  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2782  // Returns true if the function declaration is a redeclaration
2785  bool IsMemberSpecialization);
2786  bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2788  QualType NewT, QualType OldT);
2789  void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2792  bool IsDefinition);
2796  SourceLocation Loc,
2797  QualType T);
2799  SourceLocation NameLoc, IdentifierInfo *Name,
2800  QualType T, TypeSourceInfo *TSInfo,
2801  StorageClass SC);
2802  void ActOnParamDefaultArgument(Decl *param,
2803  SourceLocation EqualLoc,
2804  Expr *defarg);
2806  SourceLocation ArgLoc);
2807  void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2809  SourceLocation EqualLoc);
2810  void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2811  SourceLocation EqualLoc);
2812 
2813  // Contexts where using non-trivial C union types can be disallowed. This is
2814  // passed to err_non_trivial_c_union_in_invalid_context.
2816  // Function parameter.
2818  // Function return.
2820  // Default-initialized object.
2822  // Variable with automatic storage duration.
2824  // Initializer expression that might copy from another object.
2826  // Assignment.
2828  // Compound literal.
2830  // Block capture.
2832  // lvalue-to-rvalue conversion of volatile type.
2834  };
2835 
2836  /// Emit diagnostics if the initializer or any of its explicit or
2837  /// implicitly-generated subexpressions require copying or
2838  /// default-initializing a type that is or contains a C union type that is
2839  /// non-trivial to copy or default-initialize.
2841 
2842  // These flags are passed to checkNonTrivialCUnion.
2844  NTCUK_Init = 0x1,
2846  NTCUK_Copy = 0x4,
2847  };
2848 
2849  /// Emit diagnostics if a non-trivial C union type or a struct that contains
2850  /// a non-trivial C union is used in an invalid context.
2852  NonTrivialCUnionContext UseContext,
2853  unsigned NonTrivialKind);
2854 
2855  void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2856  void ActOnUninitializedDecl(Decl *dcl);
2857  void ActOnInitializerError(Decl *Dcl);
2858 
2859  void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2860  void ActOnCXXForRangeDecl(Decl *D);
2862  IdentifierInfo *Ident,
2863  ParsedAttributes &Attrs,
2864  SourceLocation AttrEnd);
2865  void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2866  void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2868  void FinalizeDeclaration(Decl *D);
2872 
2873  /// Should be called on all declarations that might have attached
2874  /// documentation comments.
2875  void ActOnDocumentableDecl(Decl *D);
2877 
2879  SourceLocation LocAfterDecls);
2881  FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2882  SkipBodyInfo *SkipBody = nullptr);
2884  MultiTemplateParamsArg TemplateParamLists,
2885  SkipBodyInfo *SkipBody = nullptr);
2887  SkipBodyInfo *SkipBody = nullptr);
2890  ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
2891  void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2893  return D && isa<ObjCMethodDecl>(D);
2894  }
2895 
2896  /// Determine whether we can delay parsing the body of a function or
2897  /// function template until it is used, assuming we don't care about emitting
2898  /// code for that function.
2899  ///
2900  /// This will be \c false if we may need the body of the function in the
2901  /// middle of parsing an expression (where it's impractical to switch to
2902  /// parsing a different function), for instance, if it's constexpr in C++11
2903  /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2904  bool canDelayFunctionBody(const Declarator &D);
2905 
2906  /// Determine whether we can skip parsing the body of a function
2907  /// definition, assuming we don't care about analyzing its body or emitting
2908  /// code for that function.
2909  ///
2910  /// This will be \c false only if we may need the body of the function in
2911  /// order to parse the rest of the program (for instance, if it is
2912  /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2913  bool canSkipFunctionBody(Decl *D);
2914 
2917  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2920 
2921  /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2922  /// attribute for which parsing is delayed.
2924 
2925  /// Diagnose any unused parameters in the given sequence of
2926  /// ParmVarDecl pointers.
2928 
2929  /// Diagnose whether the size of parameters or return value of a
2930  /// function or obj-c method definition is pass-by-value and larger than a
2931  /// specified threshold.
2932  void
2934  QualType ReturnTy, NamedDecl *D);
2935 
2936  void DiagnoseInvalidJumps(Stmt *Body);
2938  SourceLocation AsmLoc,
2939  SourceLocation RParenLoc);
2940 
2941  /// Handle a C++11 empty-declaration and attribute-declaration.
2943  SourceLocation SemiLoc);
2944 
2945  enum class ModuleDeclKind {
2946  Interface, ///< 'export module X;'
2947  Implementation, ///< 'module X;'
2948  };
2949 
2950  /// The parser has processed a module-declaration that begins the definition
2951  /// of a module interface or implementation.
2953  SourceLocation ModuleLoc, ModuleDeclKind MDK,
2954  ModuleIdPath Path, bool IsFirstDecl);
2955 
2956  /// The parser has processed a global-module-fragment declaration that begins
2957  /// the definition of the global module fragment of the current module unit.
2958  /// \param ModuleLoc The location of the 'module' keyword.
2960 
2961  /// The parser has processed a private-module-fragment declaration that begins
2962  /// the definition of the private module fragment of the current module unit.
2963  /// \param ModuleLoc The location of the 'module' keyword.
2964  /// \param PrivateLoc The location of the 'private' keyword.
2966  SourceLocation PrivateLoc);
2967 
2968  /// The parser has processed a module import declaration.
2969  ///
2970  /// \param StartLoc The location of the first token in the declaration. This
2971  /// could be the location of an '@', 'export', or 'import'.
2972  /// \param ExportLoc The location of the 'export' keyword, if any.
2973  /// \param ImportLoc The location of the 'import' keyword.
2974  /// \param Path The module access path.
2976  SourceLocation ExportLoc,
2977  SourceLocation ImportLoc, ModuleIdPath Path);
2979  SourceLocation ExportLoc,
2980  SourceLocation ImportLoc, Module *M,
2981  ModuleIdPath Path = {});
2982 
2983  /// The parser has processed a module import translated from a
2984  /// #include or similar preprocessing directive.
2985  void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2986  void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2987 
2988  /// The parsed has entered a submodule.
2989  void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2990  /// The parser has left a submodule.
2991  void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2992 
2993  /// Create an implicit import of the given module at the given
2994  /// source location, for error recovery, if possible.
2995  ///
2996  /// This routine is typically used when an entity found by name lookup
2997  /// is actually hidden within a module that we know about but the user
2998  /// has forgotten to import.
2999  void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
3000  Module *Mod);
3001 
3002  /// Kinds of missing import. Note, the values of these enumerators correspond
3003  /// to %select values in diagnostics.
3004  enum class MissingImportKind {
3005  Declaration,
3006  Definition,
3010  };
3011 
3012  /// Diagnose that the specified declaration needs to be visible but
3013  /// isn't, and suggest a module import that would resolve the problem.
3015  MissingImportKind MIK, bool Recover = true);
3017  SourceLocation DeclLoc, ArrayRef<Module *> Modules,
3018  MissingImportKind MIK, bool Recover);
3019 
3021  SourceLocation LBraceLoc);
3023  SourceLocation RBraceLoc);
3024 
3025  /// We've found a use of a templated declaration that would trigger an
3026  /// implicit instantiation. Check that any relevant explicit specializations
3027  /// and partial specializations are visible, and diagnose if not.
3029 
3030  /// Retrieve a suitable printing policy for diagnostics.
3032  return getPrintingPolicy(Context, PP);
3033  }
3034 
3035  /// Retrieve a suitable printing policy for diagnostics.
3036  static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
3037  const Preprocessor &PP);
3038 
3039  /// Scope actions.
3040  void ActOnPopScope(SourceLocation Loc, Scope *S);
3042 
3044  RecordDecl *&AnonRecord);
3046  MultiTemplateParamsArg TemplateParams,
3047  bool IsExplicitInstantiation,
3048  RecordDecl *&AnonRecord);
3049 
3051  AccessSpecifier AS,
3052  RecordDecl *Record,
3053  const PrintingPolicy &Policy);
3054 
3056  RecordDecl *Record);
3057 
3058  /// Common ways to introduce type names without a tag for use in diagnostics.
3059  /// Keep in sync with err_tag_reference_non_tag.
3060  enum NonTagKind {
3070  };
3071 
3072  /// Given a non-tag type declaration, returns an enum useful for indicating
3073  /// what kind of non-tag type this is.
3075 
3077  TagTypeKind NewTag, bool isDefinition,
3078  SourceLocation NewTagLoc,
3079  const IdentifierInfo *Name);
3080 
3081  enum TagUseKind {
3082  TUK_Reference, // Reference to a tag: 'struct foo *X;'
3083  TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
3084  TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
3085  TUK_Friend // Friend declaration: 'friend struct foo;'
3086  };
3087 
3088  Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3089  SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
3090  SourceLocation NameLoc, const ParsedAttributesView &Attr,
3091  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
3092  MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
3093  bool &IsDependent, SourceLocation ScopedEnumKWLoc,
3094  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3095  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3096  SkipBodyInfo *SkipBody = nullptr);
3097 
3099  unsigned TagSpec, SourceLocation TagLoc,
3100  CXXScopeSpec &SS, IdentifierInfo *Name,
3101  SourceLocation NameLoc,
3102  const ParsedAttributesView &Attr,
3103  MultiTemplateParamsArg TempParamLists);
3104 
3106  unsigned TagSpec,
3107  TagUseKind TUK,
3108  const CXXScopeSpec &SS,
3109  IdentifierInfo *Name,
3110  SourceLocation TagLoc,
3111  SourceLocation NameLoc);
3112 
3113  void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3114  IdentifierInfo *ClassName,
3115  SmallVectorImpl<Decl *> &Decls);
3116  Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3117  Declarator &D, Expr *BitfieldWidth);
3118 
3119  FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3120  Declarator &D, Expr *BitfieldWidth,
3121  InClassInitStyle InitStyle,
3122  AccessSpecifier AS);
3124  SourceLocation DeclStart, Declarator &D,
3125  Expr *BitfieldWidth,
3126  InClassInitStyle InitStyle,
3127  AccessSpecifier AS,
3128  const ParsedAttr &MSPropertyAttr);
3129 
3131  TypeSourceInfo *TInfo,
3132  RecordDecl *Record, SourceLocation Loc,
3133  bool Mutable, Expr *BitfieldWidth,
3134  InClassInitStyle InitStyle,
3135  SourceLocation TSSL,
3136  AccessSpecifier AS, NamedDecl *PrevDecl,
3137  Declarator *D = nullptr);
3138 
3139  bool CheckNontrivialField(FieldDecl *FD);
3140  void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3141 
3143  /// The triviality of a method unaffected by "trivial_abi".
3145 
3146  /// The triviality of a method affected by "trivial_abi".
3148  };
3149 
3152  bool Diagnose = false);
3153 
3154  /// For a defaulted function, the kind of defaulted function that it is.
3156  CXXSpecialMember SpecialMember : 8;
3157  DefaultedComparisonKind Comparison : 8;
3158 
3159  public:
3161  : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3162  }
3164  : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3166  : SpecialMember(CXXInvalid), Comparison(Comp) {}
3167 
3168  bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3169  bool isComparison() const {
3170  return Comparison != DefaultedComparisonKind::None;
3171  }
3172 
3173  explicit operator bool() const {
3174  return isSpecialMember() || isComparison();
3175  }
3176 
3177  CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3178  DefaultedComparisonKind asComparison() const { return Comparison; }
3179 
3180  /// Get the index of this function kind for use in diagnostics.
3181  unsigned getDiagnosticIndex() const {
3182  static_assert(CXXInvalid > CXXDestructor,
3183  "invalid should have highest index");
3184  static_assert((unsigned)DefaultedComparisonKind::None == 0,
3185  "none should be equal to zero");
3186  return SpecialMember + (unsigned)Comparison;
3187  }
3188  };
3189 
3190  DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3191 
3194  }
3197  }
3198 
3199  void ActOnLastBitfield(SourceLocation DeclStart,
3200  SmallVectorImpl<Decl *> &AllIvarDecls);
3201  Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3202  Declarator &D, Expr *BitfieldWidth,
3203  tok::ObjCKeywordKind visibility);
3204 
3205  // This is used for both record definitions and ObjC interface declarations.
3206  void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3207  ArrayRef<Decl *> Fields, SourceLocation LBrac,
3208  SourceLocation RBrac, const ParsedAttributesView &AttrList);
3209 
3210  /// ActOnTagStartDefinition - Invoked when we have entered the
3211  /// scope of a tag's definition (e.g., for an enumeration, class,
3212  /// struct, or union).
3214 
3215  /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3216  /// Differently from C++, actually parse the body and reject / error out
3217  /// in case of a structural mismatch.
3218  bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
3219  SkipBodyInfo &SkipBody);
3220 
3222 
3223  /// Invoked when we enter a tag definition that we're skipping.
3225 
3227 
3228  /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3229  /// C++ record definition's base-specifiers clause and are starting its
3230  /// member declarations.
3232  SourceLocation FinalLoc,
3233  bool IsFinalSpelledSealed,
3234  bool IsAbstract,
3235  SourceLocation LBraceLoc);
3236 
3237  /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3238  /// the definition of a tag (enumeration, class, struct, or union).
3240  SourceRange BraceRange);
3241 
3243 
3245 
3246  /// Invoked when we must temporarily exit the objective-c container
3247  /// scope for parsing/looking-up C constructs.
3248  ///
3249  /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3252 
3253  /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3254  /// error parsing the definition of a tag.
3256 
3258  EnumConstantDecl *LastEnumConst,
3259  SourceLocation IdLoc,
3260  IdentifierInfo *Id,
3261  Expr *val);
3263  bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3264  QualType EnumUnderlyingTy, bool IsFixed,
3265  const EnumDecl *Prev);
3266 
3267  /// Determine whether the body of an anonymous enumeration should be skipped.
3268  /// \param II The name of the first enumerator.
3270  SourceLocation IILoc);
3271 
3272  Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3274  const ParsedAttributesView &Attrs,
3275  SourceLocation EqualLoc, Expr *Val);
3276  void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3277  Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3278  const ParsedAttributesView &Attr);
3279 
3280  /// Set the current declaration context until it gets popped.
3281  void PushDeclContext(Scope *S, DeclContext *DC);
3282  void PopDeclContext();
3283 
3284  /// EnterDeclaratorContext - Used when we must lookup names in the context
3285  /// of a declarator's nested name specifier.
3287  void ExitDeclaratorContext(Scope *S);
3288 
3289  /// Enter a template parameter scope, after it's been associated with a particular
3290  /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3291  /// in the correct order.
3292  void EnterTemplatedContext(Scope *S, DeclContext *DC);
3293 
3294  /// Push the parameters of D, which must be a function, into scope.
3295  void ActOnReenterFunctionContext(Scope* S, Decl* D);
3296  void ActOnExitFunctionContext();
3297 
3299 
3300  /// getCurFunctionDecl - If inside of a function body, this returns a pointer
3301  /// to the function decl for the function being parsed. If we're currently
3302  /// in a 'block', this returns the containing context.
3304 
3305  /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3306  /// the method decl for the method being parsed. If we're currently
3307  /// in a 'block', this returns the containing context.
3309 
3310  /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3311  /// or C function we're in, otherwise return null. If we're currently
3312  /// in a 'block', this returns the containing context.
3314 
3315  /// Add this decl to the scope shadowed decl chains.
3316  void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3317 
3318  /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3319  /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3320  /// true if 'D' belongs to the given declaration context.
3321  ///
3322  /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3323  /// enclosing namespace set of the context, rather than contained
3324  /// directly within it.
3325  bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3326  bool AllowInlineNamespace = false);
3327 
3328  /// Finds the scope corresponding to the given decl context, if it
3329  /// happens to be an enclosing scope. Otherwise return NULL.
3330  static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3331 
3332  /// Subroutines of ActOnDeclarator().
3334  TypeSourceInfo *TInfo);
3336 
3337  /// Describes the kind of merge to perform for availability
3338  /// attributes (including "deprecated", "unavailable", and "availability").
3340  /// Don't merge availability attributes at all.
3342  /// Merge availability attributes for a redeclaration, which requires
3343  /// an exact match.
3345  /// Merge availability attributes for an override, which requires
3346  /// an exact match or a weakening of constraints.
3348  /// Merge availability attributes for an implementation of
3349  /// a protocol requirement.
3351  /// Merge availability attributes for an implementation of
3352  /// an optional protocol requirement.
3354  };
3355 
3356  /// Describes the kind of priority given to an availability attribute.
3357  ///
3358  /// The sum of priorities deteremines the final priority of the attribute.
3359  /// The final priority determines how the attribute will be merged.
3360  /// An attribute with a lower priority will always remove higher priority
3361  /// attributes for the specified platform when it is being applied. An
3362  /// attribute with a higher priority will not be applied if the declaration
3363  /// already has an availability attribute with a lower priority for the
3364  /// specified platform. The final prirority values are not expected to match
3365  /// the values in this enumeration, but instead should be treated as a plain
3366  /// integer value. This enumeration just names the priority weights that are
3367  /// used to calculate that final vaue.
3369  /// The availability attribute was specified explicitly next to the
3370  /// declaration.
3372 
3373  /// The availability attribute was applied using '#pragma clang attribute'.
3375 
3376  /// The availability attribute for a specific platform was inferred from
3377  /// an availability attribute for another platform.
3379  };
3380 
3381  /// Attribute merging methods. Return true if a new attribute was added.
3382  AvailabilityAttr *
3384  IdentifierInfo *Platform, bool Implicit,
3385  VersionTuple Introduced, VersionTuple Deprecated,
3386  VersionTuple Obsoleted, bool IsUnavailable,
3387  StringRef Message, bool IsStrict, StringRef Replacement,
3388  AvailabilityMergeKind AMK, int Priority);
3389  TypeVisibilityAttr *
3391  TypeVisibilityAttr::VisibilityType Vis);
3392  VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3393  VisibilityAttr::VisibilityType Vis);
3394  UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3395  StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3396  DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3397  DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3398  MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3399  const AttributeCommonInfo &CI,
3400  bool BestCase,
3401  MSInheritanceModel Model);
3402  ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3403  StringRef NewUserDiagnostic);
3404  FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3405  IdentifierInfo *Format, int FormatIdx,
3406  int FirstArg);
3407  SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3408  StringRef Name);
3409  CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3410  StringRef Name);
3411  AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3412  const AttributeCommonInfo &CI,
3413  const IdentifierInfo *Ident);
3414  MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3415  SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3416  StringRef Name);
3417  OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3418  const AttributeCommonInfo &CI);
3419  InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3420  InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3421  const InternalLinkageAttr &AL);
3422  WebAssemblyImportNameAttr *mergeImportNameAttr(
3423  Decl *D, const WebAssemblyImportNameAttr &AL);
3424  WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3425  Decl *D, const WebAssemblyImportModuleAttr &AL);
3426  EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3427  EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3428  const EnforceTCBLeafAttr &AL);
3429  BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
3430 
3431  void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3434  LookupResult &OldDecls);
3435  bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3436  bool MergeTypeWithOld);
3438  Scope *S, bool MergeTypeWithOld);
3441  void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3442  void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3443  bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3444  void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3445  bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3446 
3447  // AssignmentAction - This is used by all the assignment diagnostic functions
3448  // to represent what is actually causing the operation
3458  };
3459 
3460  /// C++ Overloading.
3462  /// This is a legitimate overload: the existing declarations are
3463  /// functions or function templates with different signatures.
3465 
3466  /// This is not an overload because the signature exactly matches
3467  /// an existing declaration.
3469 
3470  /// This is not an overload because the lookup results contain a
3471  /// non-function.
3473  };
3475  FunctionDecl *New,
3476  const LookupResult &OldDecls,
3477  NamedDecl *&OldDecl,
3478  bool IsForUsingDecl);
3479  bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
3480  bool ConsiderCudaAttrs = true,
3481  bool ConsiderRequiresClauses = true);
3482 
3483  enum class AllowedExplicit {
3484  /// Allow no explicit functions to be used.
3485  None,
3486  /// Allow explicit conversion functions but not explicit constructors.
3487  Conversions,
3488  /// Allow both explicit conversion functions and explicit constructors.
3489  All
3490  };
3491 
3493  TryImplicitConversion(Expr *From, QualType ToType,
3494  bool SuppressUserConversions,
3495  AllowedExplicit AllowExplicit,
3496  bool InOverloadResolution,
3497  bool CStyle,
3498  bool AllowObjCWritebackConversion);
3499 
3500  bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3501  bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3502  bool IsComplexPromotion(QualType FromType, QualType ToType);
3503  bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3504  bool InOverloadResolution,
3505  QualType& ConvertedType, bool &IncompatibleObjC);
3506  bool isObjCPointerConversion(QualType FromType, QualType ToType,
3507  QualType& ConvertedType, bool &IncompatibleObjC);
3508  bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3509  QualType &ConvertedType);
3510  bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3511  QualType& ConvertedType);
3512  bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3513  const FunctionProtoType *NewType,
3514  unsigned *ArgPos = nullptr);
3516  QualType FromType, QualType ToType);
3517 
3520  bool CheckPointerConversion(Expr *From, QualType ToType,
3521  CastKind &Kind,
3522  CXXCastPath& BasePath,
3523  bool IgnoreBaseAccess,
3524  bool Diagnose = true);
3525  bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3526  bool InOverloadResolution,
3527  QualType &ConvertedType);
3528  bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3529  CastKind &Kind,
3530  CXXCastPath &BasePath,
3531  bool IgnoreBaseAccess);
3532  bool IsQualificationConversion(QualType FromType, QualType ToType,
3533  bool CStyle, bool &ObjCLifetimeConversion);
3534  bool IsFunctionConversion(QualType FromType, QualType ToType,
3535  QualType &ResultTy);
3538 
3540  const InitializedEntity &Entity, InitListExpr *From);
3541 
3542  bool IsStringInit(Expr *Init, const ArrayType *AT);
3543 
3545  ExprResult Init);
3547  SourceLocation EqualLoc,
3548  ExprResult Init,
3549  bool TopLevelOfInitList = false,
3550  bool AllowExplicit = false);
3552  NestedNameSpecifier *Qualifier,
3553  NamedDecl *FoundDecl,
3554  CXXMethodDecl *Method);
3555 
3556  /// Check that the lifetime of the initializer (and its subobjects) is
3557  /// sufficient for initializing the entity, and perform lifetime extension
3558  /// (when permitted) if not.
3559  void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3560 
3563 
3564  /// Contexts in which a converted constant expression is required.
3565  enum CCEKind {
3566  CCEK_CaseValue, ///< Expression in a case label.
3567  CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
3568  CCEK_TemplateArg, ///< Value of a non-type template parameter.
3569  CCEK_ArrayBound, ///< Array bound in array declarator or new-expression.
3570  CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier.
3571  CCEK_Noexcept ///< Condition in a noexcept(bool) specifier.
3572  };
3574  llvm::APSInt &Value, CCEKind CCE);
3576  APValue &Value, CCEKind CCE,
3577  NamedDecl *Dest = nullptr);
3578 
3579  /// Abstract base class used to perform a contextual implicit
3580  /// conversion from an expression to any type passing a filter.
3582  public:
3583  bool Suppress;
3585 
3587  bool SuppressConversion = false)
3589 
3590  /// Determine whether the specified type is a valid destination type
3591  /// for this conversion.
3592  virtual bool match(QualType T) = 0;
3593 
3594  /// Emits a diagnostic complaining that the expression does not have
3595  /// integral or enumeration type.
3596  virtual SemaDiagnosticBuilder
3597  diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3598 
3599  /// Emits a diagnostic when the expression has incomplete class type.
3600  virtual SemaDiagnosticBuilder
3602 
3603  /// Emits a diagnostic when the only matching conversion function
3604  /// is explicit.
3606  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3607 
3608  /// Emits a note for the explicit conversion function.
3609  virtual SemaDiagnosticBuilder
3610  noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3611 
3612  /// Emits a diagnostic when there are multiple possible conversion
3613  /// functions.
3614  virtual SemaDiagnosticBuilder
3616 
3617  /// Emits a note for one of the candidate conversions.
3618  virtual SemaDiagnosticBuilder
3619  noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3620 
3621  /// Emits a diagnostic when we picked a conversion function
3622  /// (for cases when we are not allowed to pick a conversion function).
3624  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3625 
3627  };
3628 
3630  bool AllowScopedEnumerations;
3631 
3632  public:
3633  ICEConvertDiagnoser(bool AllowScopedEnumerations,
3634  bool Suppress, bool SuppressConversion)
3636  AllowScopedEnumerations(AllowScopedEnumerations) {}
3637 
3638  /// Match an integral or (possibly scoped) enumeration type.
3639  bool match(QualType T) override;
3640 
3643  return diagnoseNotInt(S, Loc, T);
3644  }
3645 
3646  /// Emits a diagnostic complaining that the expression does not have
3647  /// integral or enumeration type.
3648  virtual SemaDiagnosticBuilder
3649  diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3650  };
3651 
3652  /// Perform a contextual implicit conversion.
3654  SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3655 
3656 
3661  };
3663 
3664  // Note that LK_String is intentionally after the other literals, as
3665  // this is used for diagnostics logic.
3674  };
3676 
3678  NestedNameSpecifier *Qualifier,
3679  NamedDecl *FoundDecl,
3680  NamedDecl *Member);
3681 
3682  // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3683  // TODO: make this is a typesafe union.
3686 
3688 
3689  void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3690  ArrayRef<Expr *> Args,
3691  OverloadCandidateSet &CandidateSet,
3692  bool SuppressUserConversions = false,
3693  bool PartialOverloading = false,
3694  bool AllowExplicit = true,
3695  bool AllowExplicitConversion = false,
3696  ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3697  ConversionSequenceList EarlyConversions = None,
3698  OverloadCandidateParamOrder PO = {});
3699  void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3700  ArrayRef<Expr *> Args,
3701  OverloadCandidateSet &CandidateSet,
3702  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3703  bool SuppressUserConversions = false,
3704  bool PartialOverloading = false,
3705  bool FirstArgumentIsBase = false);
3706  void AddMethodCandidate(DeclAccessPair FoundDecl,
3707  QualType ObjectType,
3708  Expr::Classification ObjectClassification,
3709  ArrayRef<Expr *> Args,
3710  OverloadCandidateSet& CandidateSet,
3711  bool SuppressUserConversion = false,
3712  OverloadCandidateParamOrder PO = {});
3713  void AddMethodCandidate(CXXMethodDecl *Method,
3714  DeclAccessPair FoundDecl,
3715  CXXRecordDecl *ActingContext, QualType ObjectType,
3716  Expr::Classification ObjectClassification,
3717  ArrayRef<Expr *> Args,
3718  OverloadCandidateSet& CandidateSet,
3719  bool SuppressUserConversions = false,
3720  bool PartialOverloading = false,
3721  ConversionSequenceList EarlyConversions = None,
3722  OverloadCandidateParamOrder PO = {});
3723  void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3724  DeclAccessPair FoundDecl,
3725  CXXRecordDecl *ActingContext,
3726  TemplateArgumentListInfo *ExplicitTemplateArgs,
3727  QualType ObjectType,
3728  Expr::Classification ObjectClassification,
3729  ArrayRef<Expr *> Args,
3730  OverloadCandidateSet& CandidateSet,
3731  bool SuppressUserConversions = false,
3732  bool PartialOverloading = false,
3733  OverloadCandidateParamOrder PO = {});
3735  FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3736  TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3737  OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3738  bool PartialOverloading = false, bool AllowExplicit = true,
3739  ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3740  OverloadCandidateParamOrder PO = {});
3742  FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3743  ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3744  ConversionSequenceList &Conversions, bool SuppressUserConversions,
3745  CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3746  Expr::Classification ObjectClassification = {},
3747  OverloadCandidateParamOrder PO = {});
3749  CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3750  CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3751  OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3752  bool AllowExplicit, bool AllowResultConversion = true);
3754  FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3755  CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3756  OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3757  bool AllowExplicit, bool AllowResultConversion = true);
3758  void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3759  DeclAccessPair FoundDecl,
3760  CXXRecordDecl *ActingContext,
3761  const FunctionProtoType *Proto,
3762  Expr *Object, ArrayRef<Expr *> Args,
3763  OverloadCandidateSet& CandidateSet);
3765  const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3766  OverloadCandidateSet &CandidateSet,
3767  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3769  SourceLocation OpLoc, ArrayRef<Expr *> Args,
3770  OverloadCandidateSet &CandidateSet,
3771  OverloadCandidateParamOrder PO = {});
3772  void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3773  OverloadCandidateSet& CandidateSet,
3774  bool IsAssignmentOperator = false,
3775  unsigned NumContextualBoolArguments = 0);
3777  SourceLocation OpLoc, ArrayRef<Expr *> Args,
3778  OverloadCandidateSet& CandidateSet);
3779  void AddArgumentDependentLookupCandidates(DeclarationName Name,
3780  SourceLocation Loc,
3781  ArrayRef<Expr *> Args,
3782  TemplateArgumentListInfo *ExplicitTemplateArgs,
3783  OverloadCandidateSet& CandidateSet,
3784  bool PartialOverloading = false);
3785 
3786  // Emit as a 'note' the specific overload candidate
3787  void NoteOverloadCandidate(
3788  NamedDecl *Found, FunctionDecl *Fn,
3790  QualType DestType = QualType(), bool TakingAddress = false);
3791 
3792  // Emit as a series of 'note's all template and non-templates identified by
3793  // the expression Expr
3794  void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3795  bool TakingAddress = false);
3796 
3797  /// Check the enable_if expressions on the given function. Returns the first
3798  /// failing attribute, or NULL if they were all successful.
3799  EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
3800  ArrayRef<Expr *> Args,
3801  bool MissingImplicitThis = false);
3802 
3803  /// Find the failed Boolean condition within a given Boolean
3804  /// constant expression, and describe it with a string.
3805  std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3806 
3807  /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3808  /// non-ArgDependent DiagnoseIfAttrs.
3809  ///
3810  /// Argument-dependent diagnose_if attributes should be checked each time a
3811  /// function is used as a direct callee of a function call.
3812  ///
3813  /// Returns true if any errors were emitted.
3814  bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3815  const Expr *ThisArg,
3816  ArrayRef<const Expr *> Args,
3817  SourceLocation Loc);
3818 
3819  /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3820  /// ArgDependent DiagnoseIfAttrs.
3821  ///
3822  /// Argument-independent diagnose_if attributes should be checked on every use
3823  /// of a function.
3824  ///
3825  /// Returns true if any errors were emitted.
3826  bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3827  SourceLocation Loc);
3828 
3829  /// Returns whether the given function's address can be taken or not,
3830  /// optionally emitting a diagnostic if the address can't be taken.
3831  ///
3832  /// Returns false if taking the address of the function is illegal.
3833  bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3834  bool Complain = false,
3835  SourceLocation Loc = SourceLocation());
3836 
3837  // [PossiblyAFunctionType] --> [Return]
3838  // NonFunctionType --> NonFunctionType
3839  // R (A) --> R(A)
3840  // R (*)(A) --> R (A)
3841  // R (&)(A) --> R (A)
3842  // R (S::*)(A) --> R (A)
3843  QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3844 
3845  FunctionDecl *
3846  ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3847  QualType TargetType,
3848  bool Complain,
3849  DeclAccessPair &Found,
3850  bool *pHadMultipleCandidates = nullptr);
3851 
3852  FunctionDecl *
3853  resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
3854 
3856  ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3857 
3858  FunctionDecl *
3860  bool Complain = false,
3861  DeclAccessPair *Found = nullptr);
3862 
3864  ExprResult &SrcExpr,
3865  bool DoFunctionPointerConverion = false,
3866  bool Complain = false,
3867  SourceRange OpRangeForComplaining = SourceRange(),
3868  QualType DestTypeForComplaining = QualType(),
3869  unsigned DiagIDForComplaining = 0);
3870 
3871 
3872  Expr *FixOverloadedFunctionReference(Expr *E,
3873  DeclAccessPair FoundDecl,
3874  FunctionDecl *Fn);
3876  DeclAccessPair FoundDecl,
3877  FunctionDecl *Fn);
3878 
3879  void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3880  ArrayRef<Expr *> Args,
3881  OverloadCandidateSet &CandidateSet,
3882  bool PartialOverloading = false);
3884  LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
3885  ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
3886 
3887  // An enum used to represent the different possible results of building a
3888  // range-based for loop.
3893  };
3894 
3896  SourceLocation RangeLoc,
3897  const DeclarationNameInfo &NameInfo,
3898  LookupResult &MemberLookup,
3899  OverloadCandidateSet *CandidateSet,
3900  Expr *Range, ExprResult *CallExpr);
3901 
3903  UnresolvedLookupExpr *ULE,
3904  SourceLocation LParenLoc,
3905  MultiExprArg Args,
3906  SourceLocation RParenLoc,
3907  Expr *ExecConfig,
3908  bool AllowTypoCorrection=true,
3909  bool CalleesAddressIsTaken=false);
3910 
3912  MultiExprArg Args, SourceLocation RParenLoc,
3913  OverloadCandidateSet *CandidateSet,
3914  ExprResult *Result);
3915 
3917  NestedNameSpecifierLoc NNSLoc,
3918  DeclarationNameInfo DNI,
3919  const UnresolvedSetImpl &Fns,
3920  bool PerformADL = true);
3921 
3923  UnaryOperatorKind Opc,
3924  const UnresolvedSetImpl &Fns,
3925  Expr *input, bool RequiresADL = true);
3926 
3927  void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
3929  const UnresolvedSetImpl &Fns,
3930  ArrayRef<Expr *> Args, bool RequiresADL = true);
3932  BinaryOperatorKind Opc,
3933  const UnresolvedSetImpl &Fns,
3934  Expr *LHS, Expr *RHS,
3935  bool RequiresADL = true,
3936  bool AllowRewrittenCandidates = true,
3937  FunctionDecl *DefaultedFn = nullptr);
3939  const UnresolvedSetImpl &Fns,
3940  Expr *LHS, Expr *RHS,
3941  FunctionDecl *DefaultedFn);
3942 
3944  SourceLocation RLoc,
3945  Expr *Base,Expr *Idx);
3946 
3948  SourceLocation LParenLoc,
3949  MultiExprArg Args,
3950  SourceLocation RParenLoc,
3951  Expr *ExecConfig = nullptr,
3952  bool IsExecConfig = false,
3953  bool AllowRecovery = false);
3954  ExprResult
3955  BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3956  MultiExprArg Args,
3957  SourceLocation RParenLoc);
3958 
3960  SourceLocation OpLoc,
3961  bool *NoArrowOperatorFound = nullptr);
3962 
3963  /// CheckCallReturnType - Checks that a call expression's return type is
3964  /// complete. Returns true on failure. The location passed in is the location
3965  /// that best represents the call.
3966  bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3967  CallExpr *CE, FunctionDecl *FD);
3968 
3969  /// Helpers for dealing with blocks and functions.
3971  bool CheckParameterNames);
3975 
3976  /// \name Name lookup
3977  ///
3978  /// These routines provide name lookup that is used during semantic
3979  /// analysis to resolve the various kinds of names (identifiers,
3980  /// overloaded operator names, constructor names, etc.) into zero or
3981  /// more declarations within a particular scope. The major entry
3982  /// points are LookupName, which performs unqualified name lookup,
3983  /// and LookupQualifiedName, which performs qualified name lookup.
3984  ///
3985  /// All name lookup is performed based on some specific criteria,
3986  /// which specify what names will be visible to name lookup and how
3987  /// far name lookup should work. These criteria are important both
3988  /// for capturing language semantics (certain lookups will ignore
3989  /// certain names, for example) and for performance, since name
3990  /// lookup is often a bottleneck in the compilation of C++. Name
3991  /// lookup criteria is specified via the LookupCriteria enumeration.
3992  ///
3993  /// The results of name lookup can vary based on the kind of name
3994  /// lookup performed, the current language, and the translation
3995  /// unit. In C, for example, name lookup will either return nothing
3996  /// (no entity found) or a single declaration. In C++, name lookup
3997  /// can additionally refer to a set of overloaded functions or
3998  /// result in an ambiguity. All of the possible results of name
3999  /// lookup are captured by the LookupResult class, which provides
4000  /// the ability to distinguish among them.
4001  //@{
4002 
4003  /// Describes the kind of name lookup to perform.
4005  /// Ordinary name lookup, which finds ordinary names (functions,
4006  /// variables, typedefs, etc.) in C and most kinds of names
4007  /// (functions, variables, members, types, etc.) in C++.
4009  /// Tag name lookup, which finds the names of enums, classes,
4010  /// structs, and unions.
4012  /// Label name lookup.
4014  /// Member name lookup, which finds the names of
4015  /// class/struct/union members.
4017  /// Look up of an operator name (e.g., operator+) for use with
4018  /// operator overloading. This lookup is similar to ordinary name
4019  /// lookup, but will ignore any declarations that are class members.
4021  /// Look up a name following ~ in a destructor name. This is an ordinary
4022  /// lookup, but prefers tags to typedefs.
4024  /// Look up of a name that precedes the '::' scope resolution
4025  /// operator in C++. This lookup completely ignores operator, object,
4026  /// function, and enumerator names (C++ [basic.lookup.qual]p1).
4028  /// Look up a namespace name within a C++ using directive or
4029  /// namespace alias definition, ignoring non-namespace names (C++
4030  /// [basic.lookup.udir]p1).
4032  /// Look up all declarations in a scope with the given name,
4033  /// including resolved using declarations. This is appropriate
4034  /// for checking redeclarations for a using declaration.
4036  /// Look up an ordinary name that is going to be redeclared as a
4037  /// name with linkage. This lookup ignores any declarations that
4038  /// are outside of the current scope unless they have linkage. See
4039  /// C99 6.2.2p4-5 and C++ [basic.link]p6.
4041  /// Look up a friend of a local class. This lookup does not look
4042  /// outside the innermost non-class scope. See C++11 [class.friend]p11.
4044  /// Look up the name of an Objective-C protocol.
4046  /// Look up implicit 'self' parameter of an objective-c method.
4048  /// Look up the name of an OpenMP user-defined reduction operation.
4050  /// Look up the name of an OpenMP user-defined mapper.
4052  /// Look up any declaration with any name.
4054  };
4055 
4056  /// Specifies whether (or how) name lookup is being performed for a
4057  /// redeclaration (vs. a reference).
4059  /// The lookup is a reference to this name that is not for the
4060  /// purpose of redeclaring the name.
4062  /// The lookup results will be used for redeclaration of a name,
4063  /// if an entity by that name already exists and is visible.
4065  /// The lookup results will be used for redeclaration of a name
4066  /// with external linkage; non-visible lookup results with external linkage
4067  /// may also be found.
4069  };
4070 
4072  // A declaration with an owning module for linkage can never link against
4073  // anything that is not visible. We don't need to check linkage here; if
4074  // the context has internal linkage, redeclaration lookup won't find things
4075  // from other TUs, and we can't safely compute linkage yet in general.
4076  if (cast<Decl>(CurContext)
4077  ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
4078  return ForVisibleRedeclaration;
4079  return ForExternalRedeclaration;
4080  }
4081 
4082  /// The possible outcomes of name lookup for a literal operator.
4084  /// The lookup resulted in an error.
4086  /// The lookup found no match but no diagnostic was issued.
4088  /// The lookup found a single 'cooked' literal operator, which
4089  /// expects a normal literal to be built and passed to it.
4091  /// The lookup found a single 'raw' literal operator, which expects
4092  /// a string literal containing the spelling of the literal token.
4094  /// The lookup found an overload set of literal operator templates,
4095  /// which expect the characters of the spelling of the literal token to be
4096  /// passed as a non-type template argument pack.
4098  /// The lookup found an overload set of literal operator templates,
4099  /// which expect the character type and characters of the spelling of the
4100  /// string literal token to be passed as template arguments.
4102  };
4103 
4104  SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
4106  bool ConstArg,
4107  bool VolatileArg,
4108  bool RValueThis,
4109  bool ConstThis,
4110  bool VolatileThis);
4111 
4112  typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
4113  typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
4115 
4116 private:
4117  bool CppLookupName(LookupResult &R, Scope *S);
4118 
4119  struct TypoExprState {
4120  std::unique_ptr<TypoCorrectionConsumer> Consumer;
4121  TypoDiagnosticGenerator DiagHandler;
4122  TypoRecoveryCallback RecoveryHandler;
4123  TypoExprState();
4124  TypoExprState(TypoExprState &&other) noexcept;
4125  TypoExprState &operator=(TypoExprState &&other) noexcept;
4126  };
4127 
4128  /// The set of unhandled TypoExprs and their associated state.
4129  llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
4130 
4131  /// Creates a new TypoExpr AST node.
4132  TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4134  TypoRecoveryCallback TRC, SourceLocation TypoLoc);
4135 
4136  // The set of known/encountered (unique, canonicalized) NamespaceDecls.
4137  //
4138  // The boolean value will be true to indicate that the namespace was loaded
4139  // from an AST/PCH file, or false otherwise.
4140  llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
4141 
4142  /// Whether we have already loaded known namespaces from an extenal
4143  /// source.
4144  bool LoadedExternalKnownNamespaces;
4145 
4146  /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
4147  /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
4148  /// should be skipped entirely.
4149  std::unique_ptr<TypoCorrectionConsumer>
4150  makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
4151  Sema::LookupNameKind LookupKind, Scope *S,
4152  CXXScopeSpec *SS,
4154  DeclContext *MemberContext, bool EnteringContext,
4155  const ObjCObjectPointerType *OPT,
4156  bool ErrorRecovery);
4157 
4158 public:
4159  const TypoExprState &getTypoExprState(TypoExpr *TE) const;
4160 
4161  /// Clears the state of the given TypoExpr.
4162  void clearDelayedTypo(TypoExpr *TE);
4163 
4164  /// Look up a name, looking for a single declaration. Return
4165  /// null if the results were absent, ambiguous, or overloaded.
4166  ///
4167  /// It is preferable to use the elaborated form and explicitly handle
4168  /// ambiguity and overloaded.
4170  SourceLocation Loc,
4171  LookupNameKind NameKind,
4172  RedeclarationKind Redecl
4174  bool LookupBuiltin(LookupResult &R);
4175  void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
4176  bool LookupName(LookupResult &R, Scope *S,
4177  bool AllowBuiltinCreation = false);
4178  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4179  bool InUnqualifiedLookup = false);
4180  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4181  CXXScopeSpec &SS);
4183  bool AllowBuiltinCreation = false,
4184  bool EnteringContext = false);
4186  RedeclarationKind Redecl
4188  bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
4189 
4191  UnresolvedSetImpl &Functions);
4192 
4194  SourceLocation GnuLabelLoc = SourceLocation());
4195 
4199  unsigned Quals);
4200  CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
4201  bool RValueThis, unsigned ThisQuals);
4203  unsigned Quals);
4204  CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
4205  bool RValueThis, unsigned ThisQuals);
4207 
4208  bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
4209  bool IsUDSuffix);
4212  bool AllowRaw, bool AllowTemplate,
4213  bool AllowStringTemplate, bool DiagnoseMissing,
4214  StringLiteral *StringLit = nullptr);
4215  bool isKnownName(StringRef name);
4216 
4217  /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4219  Emitted,
4220  CUDADiscarded, // Discarded due to CUDA/HIP hostness
4221  OMPDiscarded, // Discarded due to OpenMP hostness
4222  TemplateDiscarded, // Discarded due to uninstantiated templates
4223  Unknown,
4224  };
4226  bool Final = false);
4227 
4228  // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4230 
4232  ArrayRef<Expr *> Args, ADLResult &Functions);
4233 
4236  bool IncludeGlobalScope = true,
4237  bool LoadExternal = true);
4240  bool IncludeGlobalScope = true,
4241  bool IncludeDependentBases = false,
4242  bool LoadExternal = true);
4243 
4245  CTK_NonError, // CorrectTypo used in a non error recovery situation.
4246  CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
4247  };
4248 
4250  Sema::LookupNameKind LookupKind,
4251  Scope *S, CXXScopeSpec *SS,
4253  CorrectTypoKind Mode,
4254  DeclContext *MemberContext = nullptr,
4255  bool EnteringContext = false,
4256  const ObjCObjectPointerType *OPT = nullptr,
4257  bool RecordFailure = true);
4258 
4260  Sema::LookupNameKind LookupKind, Scope *S,
4261  CXXScopeSpec *SS,
4265  DeclContext *MemberContext = nullptr,
4266  bool EnteringContext = false,
4267  const ObjCObjectPointerType *OPT = nullptr);
4268 
4269  /// Process any TypoExprs in the given Expr and its children,
4270  /// generating diagnostics as appropriate and returning a new Expr if there
4271  /// were typos that were all successfully corrected and ExprError if one or
4272  /// more typos could not be corrected.
4273  ///
4274  /// \param E The Expr to check for TypoExprs.
4275  ///
4276  /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
4277  /// initializer.
4278  ///
4279  /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
4280  /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
4281  ///
4282  /// \param Filter A function applied to a newly rebuilt Expr to determine if
4283  /// it is an acceptable/usable result from a single combination of typo
4284  /// corrections. As long as the filter returns ExprError, different
4285  /// combinations of corrections will be tried until all are exhausted.
4287  Expr *E, VarDecl *InitDecl = nullptr,
4288  bool RecoverUncorrectedTypos = false,
4289  llvm::function_ref<ExprResult(Expr *)> Filter =
4290  [](Expr *E) -> ExprResult { return E; });
4291 
4293  ExprResult ER, VarDecl *InitDecl = nullptr,
4294  bool RecoverUncorrectedTypos = false,
4295  llvm::function_ref<ExprResult(Expr *)> Filter =
4296  [](Expr *E) -> ExprResult { return E; }) {
4297  return ER.isInvalid()
4298  ? ER
4299  : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
4300  RecoverUncorrectedTypos, Filter);
4301  }
4302 
4303  void diagnoseTypo(const TypoCorrection &Correction,
4304  const PartialDiagnostic &TypoDiag,
4305  bool ErrorRecovery = true);
4306 
4307  void diagnoseTypo(const TypoCorrection &Correction,
4308  const PartialDiagnostic &TypoDiag,
4309  const PartialDiagnostic &PrevNote,
4310  bool ErrorRecovery = true);
4311 
4312  void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4313 
4314  void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
4315  ArrayRef<Expr *> Args,
4316  AssociatedNamespaceSet &AssociatedNamespaces,
4317  AssociatedClassSet &AssociatedClasses);
4318 
4319  void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4320  bool ConsiderLinkage, bool AllowInlineNamespace);
4321 
4322  bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4323 
4324  void DiagnoseAmbiguousLookup(LookupResult &Result);
4325  //@}
4326 
4327  /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
4328  ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
4329  ArrayRef<Expr *> SubExprs,
4330  QualType T = QualType());
4331 
4332  ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
4333  SourceLocation IdLoc,
4334  bool TypoCorrection = false);
4335  FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4336  SourceLocation Loc);
4337  NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
4338  Scope *S, bool ForRedeclaration,
4339  SourceLocation Loc);
4340  NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4341  Scope *S);
4343  FunctionDecl *FD);
4344  void AddKnownFunctionAttributes(FunctionDecl *FD);
4345 
4346  // More parsing and symbol table subroutines.
4347 
4348  void ProcessPragmaWeak(Scope *S, Decl *D);
4349  // Decl attributes - this routine is the top level dispatcher.
4350  void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
4351  // Helper for delayed processing of attributes.
4352  void ProcessDeclAttributeDelayed(Decl *D,
4353  const ParsedAttributesView &AttrList);
4354  void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
4355  bool IncludeCXX11Attributes = true);
4356  bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4357  const ParsedAttributesView &AttrList);
4358 
4359  void checkUnusedDeclAttributes(Declarator &D);
4360 
4361  /// Handles semantic checking for features that are common to all attributes,
4362  /// such as checking whether a parameter was properly specified, or the
4363  /// correct number of arguments were passed, etc. Returns true if the
4364  /// attribute has been diagnosed.
4365  bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A);
4366  bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A);
4367 
4368  /// Determine if type T is a valid subject for a nonnull and similar
4369  /// attributes. By default, we look through references (the behavior used by
4370  /// nonnull), but if the second parameter is true, then we treat a reference
4371  /// type as valid.
4372  bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4373 
4374  bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4375  bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
4376  const FunctionDecl *FD = nullptr);
4377  bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4378  bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4379  bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4380  StringRef &Str,
4381  SourceLocation *ArgLocation = nullptr);
4382  llvm::Error isValidSectionSpecifier(StringRef Str);
4383  bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4384  bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4385  bool checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str,
4386  const StringLiteral *Literal,
4387  bool &HasDefault, bool &HasCommas,
4388  SmallVectorImpl<StringRef> &Strings);
4390  CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4391  MSInheritanceModel SemanticSpelling);
4392 
4393  void CheckAlignasUnderalignment(Decl *D);
4394 
4395  /// Adjust the calling convention of a method to be the ABI default if it
4396  /// wasn't specified explicitly. This handles method types formed from
4397  /// function type typedefs and typename template arguments.
4398  void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
4399  SourceLocation Loc);
4400 
4401  // Check if there is an explicit attribute, but only look through parens.
4402  // The intent is to look for an attribute on the current declarator, but not
4403  // one that came from a typedef.
4404  bool hasExplicitCallingConv(QualType T);
4405 
4406  /// Get the outermost AttributedType node that sets a calling convention.
4407  /// Valid types should not have multiple attributes with different CCs.
4408  const AttributedType *getCallingConvAttributedType(QualType T) const;
4409 
4410  /// Process the attributes before creating an attributed statement. Returns
4411  /// the semantic attributes that have been processed.
4412  void ProcessStmtAttributes(Stmt *Stmt,
4413  const ParsedAttributesWithRange &InAttrs,
4414  SmallVectorImpl<const Attr *> &OutAttrs);
4415 
4416  void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
4417  ObjCMethodDecl *MethodDecl,
4418  bool IsProtocolMethodDecl);
4419 
4420  void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
4421  ObjCMethodDecl *Overridden,
4422  bool IsProtocolMethodDecl);
4423 
4424  /// WarnExactTypedMethods - This routine issues a warning if method
4425  /// implementation declaration matches exactly that of its declaration.
4426  void WarnExactTypedMethods(ObjCMethodDecl *Method,
4427  ObjCMethodDecl *MethodDecl,
4428  bool IsProtocolMethodDecl);
4429 
4431 
4432  /// CheckImplementationIvars - This routine checks if the instance variables
4433  /// listed in the implelementation match those listed in the interface.
4435  ObjCIvarDecl **Fields, unsigned nIvars,
4436  SourceLocation Loc);
4437 
4438  /// ImplMethodsVsClassMethods - This is main routine to warn if any method
4439  /// remains unimplemented in the class or category \@implementation.
4440  void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
4441  ObjCContainerDecl* IDecl,
4442  bool IncompleteImpl = false);
4443 
4444  /// DiagnoseUnimplementedProperties - This routine warns on those properties
4445  /// which must be implemented by this implementation.
4447  ObjCContainerDecl *CDecl,
4448  bool SynthesizeProperties);
4449 
4450  /// Diagnose any null-resettable synthesized setters.
4452 
4453  /// DefaultSynthesizeProperties - This routine default synthesizes all
4454  /// properties which must be synthesized in the class's \@implementation.
4456  ObjCInterfaceDecl *IDecl,
4457  SourceLocation AtEnd);
4459 
4460  /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
4461  /// an ivar synthesized for 'Method' and 'Method' is a property accessor
4462  /// declared in class 'IFace'.
4464  ObjCMethodDecl *Method, ObjCIvarDecl *IV);
4465 
4466  /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
4467  /// backs the property is not used in the property's accessor.
4469  const ObjCImplementationDecl *ImplD);
4470 
4471  /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
4472  /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
4473  /// It also returns ivar's property on success.
4475  const ObjCPropertyDecl *&PDecl) const;
4476 
4477  /// Called by ActOnProperty to handle \@property declarations in
4478  /// class extensions.
4480  SourceLocation AtLoc,
4481  SourceLocation LParenLoc,
4482  FieldDeclarator &FD,
4483  Selector GetterSel,
4484  SourceLocation GetterNameLoc,
4485  Selector SetterSel,
4486  SourceLocation SetterNameLoc,
4487  const bool isReadWrite,
4488  unsigned &Attributes,
4489  const unsigned AttributesAsWritten,
4490  QualType T,
4491  TypeSourceInfo *TSI,
4492  tok::ObjCKeywordKind MethodImplKind);
4493 
4494  /// Called by ActOnProperty and HandlePropertyInClassExtension to
4495  /// handle creating the ObjcPropertyDecl for a category or \@interface.
4497  ObjCContainerDecl *CDecl,
4498  SourceLocation AtLoc,
4499  SourceLocation LParenLoc,
4500  FieldDeclarator &FD,
4501  Selector GetterSel,
4502  SourceLocation GetterNameLoc,
4503  Selector SetterSel,
4504  SourceLocation SetterNameLoc,
4505  const bool isReadWrite,
4506  const unsigned Attributes,
4507  const unsigned AttributesAsWritten,
4508  QualType T,
4509  TypeSourceInfo *TSI,
4510  tok::ObjCKeywordKind MethodImplKind,
4511  DeclContext *lexicalDC = nullptr);
4512 
4513  /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
4514  /// warning) when atomic property has one but not the other user-declared
4515  /// setter or getter.
4517  ObjCInterfaceDecl* IDecl);
4518 
4520 
4522  const ObjCImplementationDecl *ImplD,
4523  const ObjCInterfaceDecl *IFD);
4524 
4526 
4530  };
4531 
4532  /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
4533  /// true, or false, accordingly.
4534  bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
4535  const ObjCMethodDecl *PrevMethod,
4536  MethodMatchStrategy strategy = MMS_strict);
4537 
4538  /// MatchAllMethodDeclarations - Check methods declaraed in interface or
4539  /// or protocol against those declared in their implementations.
4540  void MatchAllMethodDeclarations(const SelectorSet &InsMap,
4541  const SelectorSet &ClsMap,
4542  SelectorSet &InsMapSeen,
4543  SelectorSet &ClsMapSeen,
4544  ObjCImplDecl* IMPDecl,
4545  ObjCContainerDecl* IDecl,
4546  bool &IncompleteImpl,
4547  bool ImmediateClass,
4548  bool WarnCategoryMethodImpl=false);
4549 
4550  /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
4551  /// category matches with those implemented in its primary class and
4552  /// warns each time an exact match is found.
4554 
4555  /// Add the given method to the list of globally-known methods.
4557 
4558  /// Returns default addr space for method qualifiers.
4560 
4561 private:
4562  /// AddMethodToGlobalPool - Add an instance or factory method to the global
4563  /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
4564  void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
4565 
4566  /// LookupMethodInGlobalPool - Returns the instance or factory method and
4567  /// optionally warns if there are multiple signatures.
4568  ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4569  bool receiverIdOrClass,
4570  bool instance);
4571 
4572 public:
4573  /// - Returns instance or factory methods in global method pool for
4574  /// given selector. It checks the desired kind first, if none is found, and
4575  /// parameter checkTheOther is set, it then checks the other kind. If no such
4576  /// method or only one method is found, function returns false; otherwise, it
4577  /// returns true.
4578  bool
4581  bool InstanceFirst, bool CheckTheOther,
4582  const ObjCObjectType *TypeBound = nullptr);
4583 
4584  bool
4586  SourceRange R, bool receiverIdOrClass,
4588 
4589  void
4591  Selector Sel, SourceRange R,
4592  bool receiverIdOrClass);
4593 
4594 private:
4595  /// - Returns a selector which best matches given argument list or
4596  /// nullptr if none could be found
4597  ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4598  bool IsInstance,
4600 
4601 
4602  /// Record the typo correction failure and return an empty correction.
4603  TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4604  bool RecordFailure = true) {
4605  if (RecordFailure)
4606  TypoCorrectionFailures[Typo].insert(TypoLoc);
4607  return TypoCorrection();
4608  }
4609 
4610 public:
4611  /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4612  /// unit are added to a global pool. This allows us to efficiently associate
4613  /// a selector with a method declaraation for purposes of typechecking
4614  /// messages sent to "id" (where the class of the object is unknown).
4615  void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4616  AddMethodToGlobalPool(Method, impl, /*instance*/true);
4617  }
4618 
4619  /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4620  void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4621  AddMethodToGlobalPool(Method, impl, /*instance*/false);
4622  }
4623 
4624  /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
4625  /// pool.
4626  void AddAnyMethodToGlobalPool(Decl *D);
4627 
4628  /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
4629  /// there are multiple signatures.
4631  bool receiverIdOrClass=false) {
4632  return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4633  /*instance*/true);
4634  }
4635 
4636  /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4637  /// there are multiple signatures.
4639  bool receiverIdOrClass=false) {
4640  return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4641  /*instance*/false);
4642  }
4643 
4645  QualType ObjectType=QualType());
4646  /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4647  /// implementation.
4649 
4650  /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4651  /// initialization.
4654 
4655  //===--------------------------------------------------------------------===//
4656  // Statement Parsing Callbacks: SemaStmt.cpp.
4657 public:
4658  class FullExprArg {
4659  public: