clang  10.0.0svn
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/Attr.h"
18 #include "clang/AST/Availability.h"
20 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/LocInfoType.h"
28 #include "clang/AST/NSAPI.h"
30 #include "clang/AST/StmtCXX.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/AST/TypeOrdering.h"
34 #include "clang/Basic/Module.h"
37 #include "clang/Basic/Specifiers.h"
39 #include "clang/Basic/TypeTraits.h"
41 #include "clang/Sema/CleanupInfo.h"
42 #include "clang/Sema/DeclSpec.h"
46 #include "clang/Sema/Ownership.h"
47 #include "clang/Sema/Scope.h"
49 #include "clang/Sema/Weak.h"
50 #include "llvm/ADT/ArrayRef.h"
51 #include "llvm/ADT/Optional.h"
52 #include "llvm/ADT/SetVector.h"
53 #include "llvm/ADT/SmallBitVector.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/TinyPtrVector.h"
57 #include <deque>
58 #include <memory>
59 #include <string>
60 #include <tuple>
61 #include <vector>
62 
63 namespace llvm {
64  class APSInt;
65  template <typename ValueT> struct DenseMapInfo;
66  template <typename ValueT, typename ValueInfoT> class DenseSet;
67  class SmallBitVector;
68  struct InlineAsmIdentifierInfo;
69 }
70 
71 namespace clang {
72  class ADLResult;
73  class ASTConsumer;
74  class ASTContext;
75  class ASTMutationListener;
76  class ASTReader;
77  class ASTWriter;
78  class ArrayType;
79  class ParsedAttr;
80  class BindingDecl;
81  class BlockDecl;
82  class CapturedDecl;
83  class CXXBasePath;
84  class CXXBasePaths;
85  class CXXBindTemporaryExpr;
87  class CXXConstructorDecl;
88  class CXXConversionDecl;
89  class CXXDeleteExpr;
90  class CXXDestructorDecl;
91  class CXXFieldCollector;
92  class CXXMemberCallExpr;
93  class CXXMethodDecl;
94  class CXXScopeSpec;
95  class CXXTemporary;
96  class CXXTryStmt;
97  class CallExpr;
98  class ClassTemplateDecl;
99  class ClassTemplatePartialSpecializationDecl;
100  class ClassTemplateSpecializationDecl;
101  class VarTemplatePartialSpecializationDecl;
102  class CodeCompleteConsumer;
103  class CodeCompletionAllocator;
104  class CodeCompletionTUInfo;
105  class CodeCompletionResult;
106  class CoroutineBodyStmt;
107  class Decl;
108  class DeclAccessPair;
109  class DeclContext;
110  class DeclRefExpr;
111  class DeclaratorDecl;
112  class DeducedTemplateArgument;
113  class DependentDiagnostic;
114  class DesignatedInitExpr;
115  class Designation;
116  class EnableIfAttr;
117  class EnumConstantDecl;
118  class Expr;
119  class ExtVectorType;
120  class FormatAttr;
121  class FriendDecl;
122  class FunctionDecl;
123  class FunctionProtoType;
124  class FunctionTemplateDecl;
125  class ImplicitConversionSequence;
127  class InitListExpr;
128  class InitializationKind;
129  class InitializationSequence;
130  class InitializedEntity;
131  class IntegerLiteral;
132  class LabelStmt;
133  class LambdaExpr;
134  class LangOptions;
135  class LocalInstantiationScope;
136  class LookupResult;
137  class MacroInfo;
139  class ModuleLoader;
140  class MultiLevelTemplateArgumentList;
141  class NamedDecl;
142  class ObjCCategoryDecl;
143  class ObjCCategoryImplDecl;
144  class ObjCCompatibleAliasDecl;
145  class ObjCContainerDecl;
146  class ObjCImplDecl;
147  class ObjCImplementationDecl;
148  class ObjCInterfaceDecl;
149  class ObjCIvarDecl;
150  template <class T> class ObjCList;
151  class ObjCMessageExpr;
152  class ObjCMethodDecl;
153  class ObjCPropertyDecl;
154  class ObjCProtocolDecl;
155  class OMPThreadPrivateDecl;
156  class OMPRequiresDecl;
157  class OMPDeclareReductionDecl;
158  class OMPDeclareSimdDecl;
159  class OMPClause;
160  struct OMPVarListLocTy;
161  struct OverloadCandidate;
162  enum class OverloadCandidateParamOrder : char;
163  enum OverloadCandidateRewriteKind : unsigned;
164  class OverloadCandidateSet;
165  class OverloadExpr;
166  class ParenListExpr;
167  class ParmVarDecl;
168  class Preprocessor;
169  class PseudoDestructorTypeStorage;
170  class PseudoObjectExpr;
171  class QualType;
172  class StandardConversionSequence;
173  class Stmt;
174  class StringLiteral;
175  class SwitchStmt;
176  class TemplateArgument;
177  class TemplateArgumentList;
178  class TemplateArgumentLoc;
179  class TemplateDecl;
180  class TemplateInstantiationCallback;
181  class TemplateParameterList;
182  class TemplatePartialOrderingContext;
183  class TemplateTemplateParmDecl;
184  class Token;
185  class TypeAliasDecl;
186  class TypedefDecl;
187  class TypedefNameDecl;
188  class TypeLoc;
189  class TypoCorrectionConsumer;
190  class UnqualifiedId;
191  class UnresolvedLookupExpr;
192  class UnresolvedMemberExpr;
193  class UnresolvedSetImpl;
194  class UnresolvedSetIterator;
195  class UsingDecl;
196  class UsingShadowDecl;
197  class ValueDecl;
198  class VarDecl;
199  class VarTemplateSpecializationDecl;
200  class VisibilityAttr;
201  class VisibleDeclConsumer;
202  class IndirectFieldDecl;
203  struct DeductionFailureInfo;
204  class TemplateSpecCandidateSet;
205 
206 namespace sema {
207  class AccessedEntity;
208  class BlockScopeInfo;
209  class Capture;
210  class CapturedRegionScopeInfo;
211  class CapturingScopeInfo;
212  class CompoundScopeInfo;
213  class DelayedDiagnostic;
214  class DelayedDiagnosticPool;
215  class FunctionScopeInfo;
216  class LambdaScopeInfo;
217  class PossiblyUnreachableDiag;
218  class SemaPPCallbacks;
219  class TemplateDeductionInfo;
220 }
221 
222 namespace threadSafety {
223  class BeforeSet;
224  void threadSafetyCleanup(BeforeSet* Cache);
225 }
226 
227 // FIXME: No way to easily map from TemplateTypeParmTypes to
228 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
229 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
231 
232 /// Describes whether we've seen any nullability information for the given
233 /// file.
235  /// The first pointer declarator (of any pointer kind) in the file that does
236  /// not have a corresponding nullability annotation.
238 
239  /// The end location for the first pointer declarator in the file. Used for
240  /// placing fix-its.
242 
243  /// Which kind of pointer declarator we saw.
244  uint8_t PointerKind;
245 
246  /// Whether we saw any type nullability annotations in the given file.
247  bool SawTypeNullability = false;
248 };
249 
250 /// A mapping from file IDs to a record of whether we've seen nullability
251 /// information in that file.
253  /// A mapping from file IDs to the nullability information for each file ID.
254  llvm::DenseMap<FileID, FileNullability> Map;
255 
256  /// A single-element cache based on the file ID.
257  struct {
260  } Cache;
261 
262 public:
264  // Check the single-element cache.
265  if (file == Cache.File)
266  return Cache.Nullability;
267 
268  // It's not in the single-element cache; flush the cache if we have one.
269  if (!Cache.File.isInvalid()) {
270  Map[Cache.File] = Cache.Nullability;
271  }
272 
273  // Pull this entry into the cache.
274  Cache.File = file;
275  Cache.Nullability = Map[file];
276  return Cache.Nullability;
277  }
278 };
279 
280 /// Keeps track of expected type during expression parsing. The type is tied to
281 /// a particular token, all functions that update or consume the type take a
282 /// start location of the token they are looking at as a parameter. This allows
283 /// to avoid updating the type on hot paths in the parser.
285 public:
286  PreferredTypeBuilder() = default;
287  explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
288 
289  void enterCondition(Sema &S, SourceLocation Tok);
290  void enterReturn(Sema &S, SourceLocation Tok);
291  void enterVariableInit(SourceLocation Tok, Decl *D);
292  /// Computing a type for the function argument may require running
293  /// overloading, so we postpone its computation until it is actually needed.
294  ///
295  /// Clients should be very careful when using this funciton, as it stores a
296  /// function_ref, clients should make sure all calls to get() with the same
297  /// location happen while function_ref is alive.
298  void enterFunctionArgument(SourceLocation Tok,
299  llvm::function_ref<QualType()> ComputeType);
300 
301  void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
302  void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
303  SourceLocation OpLoc);
304  void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
305  void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
306  void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
307  /// Handles all type casts, including C-style cast, C++ casts, etc.
308  void enterTypeCast(SourceLocation Tok, QualType CastType);
309 
311  if (Tok != ExpectedLoc)
312  return QualType();
313  if (!Type.isNull())
314  return Type;
315  if (ComputeType)
316  return ComputeType();
317  return QualType();
318  }
319 
320 private:
321  /// Start position of a token for which we store expected type.
322  SourceLocation ExpectedLoc;
323  /// Expected type for a token starting at ExpectedLoc.
324  QualType Type;
325  /// A function to compute expected type at ExpectedLoc. It is only considered
326  /// if Type is null.
327  llvm::function_ref<QualType()> ComputeType;
328 };
329 
330 /// Sema - This implements semantic analysis and AST building for C.
331 class Sema {
332  Sema(const Sema &) = delete;
333  void operator=(const Sema &) = delete;
334 
335  ///Source of additional semantic information.
336  ExternalSemaSource *ExternalSource;
337 
338  ///Whether Sema has generated a multiplexer and has to delete it.
339  bool isMultiplexExternalSource;
340 
341  static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
342 
343  bool isVisibleSlow(const NamedDecl *D);
344 
345  /// Determine whether two declarations should be linked together, given that
346  /// the old declaration might not be visible and the new declaration might
347  /// not have external linkage.
348  bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
349  const NamedDecl *New) {
350  if (isVisible(Old))
351  return true;
352  // See comment in below overload for why it's safe to compute the linkage
353  // of the new declaration here.
354  if (New->isExternallyDeclarable()) {
355  assert(Old->isExternallyDeclarable() &&
356  "should not have found a non-externally-declarable previous decl");
357  return true;
358  }
359  return false;
360  }
361  bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
362 
363  void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
364  QualType ResultTy,
365  ArrayRef<QualType> Args);
366 
367 public:
371 
374 
381 
382  /// Flag indicating whether or not to collect detailed statistics.
384 
385  /// Code-completion consumer.
387 
388  /// CurContext - This is the current declaration context of parsing.
390 
391  /// Generally null except when we temporarily switch decl contexts,
392  /// like in \see ActOnObjCTemporaryExitContainerContext.
394 
395  /// VAListTagName - The declaration name corresponding to __va_list_tag.
396  /// This is used as part of a hack to omit that class from ADL results.
398 
399  bool MSStructPragmaOn; // True when \#pragma ms_struct on
400 
401  /// Controls member pointer representation format under the MS ABI.
404 
405  /// Stack of active SEH __finally scopes. Can be empty.
407 
408  /// Source location for newly created implicit MSInheritanceAttrs
410 
411  /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
412  /// `TransformTypos` in order to keep track of any TypoExprs that are created
413  /// recursively during typo correction and wipe them away if the correction
414  /// fails.
416 
417  /// pragma clang section kind
419  PCSK_Invalid = 0,
420  PCSK_BSS = 1,
421  PCSK_Data = 2,
422  PCSK_Rodata = 3,
423  PCSK_Text = 4,
424  PCSK_Relro = 5
425  };
426 
428  PCSA_Set = 0,
429  PCSA_Clear = 1
430  };
431 
433  std::string SectionName;
434  bool Valid = false;
436 
437  void Act(SourceLocation PragmaLocation,
439  StringLiteral* Name);
440  };
441 
447 
449  PSK_Reset = 0x0, // #pragma ()
450  PSK_Set = 0x1, // #pragma (value)
451  PSK_Push = 0x2, // #pragma (push[, id])
452  PSK_Pop = 0x4, // #pragma (pop[, id])
453  PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
454  PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
455  PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
456  };
457 
458  template<typename ValueType>
459  struct PragmaStack {
460  struct Slot {
461  llvm::StringRef StackSlotLabel;
462  ValueType Value;
465  Slot(llvm::StringRef StackSlotLabel, ValueType Value,
466  SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
467  : StackSlotLabel(StackSlotLabel), Value(Value),
468  PragmaLocation(PragmaLocation),
469  PragmaPushLocation(PragmaPushLocation) {}
470  };
471  void Act(SourceLocation PragmaLocation,
472  PragmaMsStackAction Action,
473  llvm::StringRef StackSlotLabel,
474  ValueType Value);
475 
476  // MSVC seems to add artificial slots to #pragma stacks on entering a C++
477  // method body to restore the stacks on exit, so it works like this:
478  //
479  // struct S {
480  // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
481  // void Method {}
482  // #pragma <name>(pop, InternalPragmaSlot)
483  // };
484  //
485  // It works even with #pragma vtordisp, although MSVC doesn't support
486  // #pragma vtordisp(push [, id], n)
487  // syntax.
488  //
489  // Push / pop a named sentinel slot.
490  void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
491  assert((Action == PSK_Push || Action == PSK_Pop) &&
492  "Can only push / pop #pragma stack sentinels!");
493  Act(CurrentPragmaLocation, Action, Label, CurrentValue);
494  }
495 
496  // Constructors.
497  explicit PragmaStack(const ValueType &Default)
498  : DefaultValue(Default), CurrentValue(Default) {}
499 
500  bool hasValue() const { return CurrentValue != DefaultValue; }
501 
503  ValueType DefaultValue; // Value used for PSK_Reset action.
504  ValueType CurrentValue;
506  };
507  // FIXME: We should serialize / deserialize these if they occur in a PCH (but
508  // we shouldn't do so if they're in a module).
509 
510  /// Whether to insert vtordisps prior to virtual bases in the Microsoft
511  /// C++ ABI. Possible values are 0, 1, and 2, which mean:
512  ///
513  /// 0: Suppress all vtordisps
514  /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
515  /// structors
516  /// 2: Always insert vtordisps to support RTTI on partially constructed
517  /// objects
519  // #pragma pack.
520  // Sentinel to represent when the stack is set to mac68k alignment.
521  static const unsigned kMac68kAlignmentSentinel = ~0U;
523  // The current #pragma pack values and locations at each #include.
525  unsigned CurrentValue;
527  bool HasNonDefaultValue, ShouldWarnOnInclude;
528  };
530  // Segment #pragmas.
535 
536  // RAII object to push / pop sentinel slots for all MS #pragma stacks.
537  // Actions should be performed only if we enter / exit a C++ method body.
539  public:
540  PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
542 
543  private:
544  Sema &S;
545  StringRef SlotLabel;
546  bool ShouldAct;
547  };
548 
549  /// A mapping that describes the nullability we've seen in each header file.
551 
552  /// Last section used with #pragma init_seg.
555 
556  /// VisContext - Manages the stack for \#pragma GCC visibility.
557  void *VisContext; // Really a "PragmaVisStack*"
558 
559  /// This an attribute introduced by \#pragma clang attribute.
564  bool IsUsed;
565  };
566 
567  /// A push'd group of PragmaAttributeEntries.
569  /// The location of the push attribute.
571  /// The namespace of this push group.
574  };
575 
577 
578  /// The declaration that is currently receiving an attribute from the
579  /// #pragma attribute stack.
581 
582  /// This represents the last location of a "#pragma clang optimize off"
583  /// directive if such a directive has not been closed by an "on" yet. If
584  /// optimizations are currently "on", this is set to an invalid location.
586 
587  /// Flag indicating if Sema is building a recovery call expression.
588  ///
589  /// This flag is used to avoid building recovery call expressions
590  /// if Sema is already doing so, which would cause infinite recursions.
592 
593  /// Used to control the generation of ExprWithCleanups.
595 
596  /// ExprCleanupObjects - This is the stack of objects requiring
597  /// cleanup that are created by the current full expression. The
598  /// element type here is ExprWithCleanups::Object.
600 
601  /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
602  /// to a variable (constant) that may or may not be odr-used in this Expr, and
603  /// we won't know until all lvalue-to-rvalue and discarded value conversions
604  /// have been applied to all subexpressions of the enclosing full expression.
605  /// This is cleared at the end of each full expression.
606  using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
608 
609  std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
610 
611  /// Stack containing information about each of the nested
612  /// function, block, and method scopes that are currently active.
614 
616  &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
618 
619  /// ExtVectorDecls - This is a list all the extended vector types. This allows
620  /// us to associate a raw vector type with one of the ext_vector type names.
621  /// This is only necessary for issuing pretty diagnostics.
623 
624  /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
625  std::unique_ptr<CXXFieldCollector> FieldCollector;
626 
628 
629  /// Set containing all declared private fields that are not used.
630  NamedDeclSetType UnusedPrivateFields;
631 
632  /// Set containing all typedefs that are likely unused.
635 
636  /// Delete-expressions to be analyzed at the end of translation unit
637  ///
638  /// This list contains class members, and locations of delete-expressions
639  /// that could not be proven as to whether they mismatch with new-expression
640  /// used in initializer of the field.
641  typedef std::pair<SourceLocation, bool> DeleteExprLoc;
643  llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
644 
645  typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
646 
647  /// PureVirtualClassDiagSet - a set of class declarations which we have
648  /// emitted a list of pure virtual functions. Used to prevent emitting the
649  /// same list more than once.
650  std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
651 
652  /// ParsingInitForAutoVars - a set of declarations with auto types for which
653  /// we are currently parsing the initializer.
654  llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
655 
656  /// Look for a locally scoped extern "C" declaration by the given name.
657  NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
658 
659  typedef LazyVector<VarDecl *, ExternalSemaSource,
660  &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
662 
663  /// All the tentative definitions encountered in the TU.
665 
666  typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
667  &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
669 
670  /// The set of file scoped decls seen so far that have not been used
671  /// and must warn if not used. Only contains the first declaration.
673 
674  typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
675  &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
677 
678  /// All the delegating constructors seen so far in the file, used for
679  /// cycle detection at the end of the TU.
681 
682  /// All the overriding functions seen during a class definition
683  /// that had their exception spec checks delayed, plus the overridden
684  /// function.
687 
688  /// All the function redeclarations seen during a class definition that had
689  /// their exception spec checks delayed, plus the prior declaration they
690  /// should be checked against. Except during error recovery, the new decl
691  /// should always be a friend declaration, as that's the only valid way to
692  /// redeclare a special member before its class is complete.
695 
696  typedef llvm::MapVector<const FunctionDecl *,
697  std::unique_ptr<LateParsedTemplate>>
700 
701  /// Callback to the parser to parse templated functions when needed.
702  typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
703  typedef void LateTemplateParserCleanupCB(void *P);
704  LateTemplateParserCB *LateTemplateParser;
705  LateTemplateParserCleanupCB *LateTemplateParserCleanup;
707 
708  void SetLateTemplateParser(LateTemplateParserCB *LTP,
709  LateTemplateParserCleanupCB *LTPCleanup,
710  void *P) {
711  LateTemplateParser = LTP;
712  LateTemplateParserCleanup = LTPCleanup;
713  OpaqueParser = P;
714  }
715 
716  class DelayedDiagnostics;
717 
719  sema::DelayedDiagnosticPool *SavedPool;
721  };
724 
725  /// A class which encapsulates the logic for delaying diagnostics
726  /// during parsing and other processing.
728  /// The current pool of diagnostics into which delayed
729  /// diagnostics should go.
731 
732  public:
733  DelayedDiagnostics() : CurPool(nullptr) {}
734 
735  /// Adds a delayed diagnostic.
736  void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
737 
738  /// Determines whether diagnostics should be delayed.
739  bool shouldDelayDiagnostics() { return CurPool != nullptr; }
740 
741  /// Returns the current delayed-diagnostics pool.
743  return CurPool;
744  }
745 
746  /// Enter a new scope. Access and deprecation diagnostics will be
747  /// collected in this pool.
750  state.SavedPool = CurPool;
751  CurPool = &pool;
752  return state;
753  }
754 
755  /// Leave a delayed-diagnostic state that was previously pushed.
756  /// Do not emit any of the diagnostics. This is performed as part
757  /// of the bookkeeping of popping a pool "properly".
759  CurPool = state.SavedPool;
760  }
761 
762  /// Enter a new scope where access and deprecation diagnostics are
763  /// not delayed.
766  state.SavedPool = CurPool;
767  CurPool = nullptr;
768  return state;
769  }
770 
771  /// Undo a previous pushUndelayed().
773  assert(CurPool == nullptr);
774  CurPool = state.SavedPool;
775  }
777 
778  /// A RAII object to temporarily push a declaration context.
779  class ContextRAII {
780  private:
781  Sema &S;
782  DeclContext *SavedContext;
783  ProcessingContextState SavedContextState;
784  QualType SavedCXXThisTypeOverride;
785 
786  public:
787  ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
788  : S(S), SavedContext(S.CurContext),
789  SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
790  SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
791  {
792  assert(ContextToPush && "pushing null context");
793  S.CurContext = ContextToPush;
794  if (NewThisContext)
796  }
797 
798  void pop() {
799  if (!SavedContext) return;
800  S.CurContext = SavedContext;
801  S.DelayedDiagnostics.popUndelayed(SavedContextState);
802  S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
803  SavedContext = nullptr;
804  }
805 
807  pop();
808  }
809  };
810 
811  /// Used to change context to isConstantEvaluated without pushing a heavy
812  /// ExpressionEvaluationContextRecord object.
814 
816  return ExprEvalContexts.back().isConstantEvaluated() ||
817  isConstantEvaluatedOverride;
818  }
819 
820  /// RAII object to handle the state changes required to synthesize
821  /// a function body.
823  Sema &S;
824  Sema::ContextRAII SavedContext;
825  bool PushedCodeSynthesisContext = false;
826 
827  public:
829  : S(S), SavedContext(S, DC) {
830  S.PushFunctionScope();
832  Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
833  if (auto *FD = dyn_cast<FunctionDecl>(DC))
834  FD->setWillHaveBody(true);
835  else
836  assert(isa<ObjCMethodDecl>(DC));
837  }
838 
840  assert(!PushedCodeSynthesisContext);
841 
843  Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
844  Ctx.PointOfInstantiation = UseLoc;
845  Ctx.Entity = cast<Decl>(S.CurContext);
847 
848  PushedCodeSynthesisContext = true;
849  }
850 
852  if (PushedCodeSynthesisContext)
854  if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
855  FD->setWillHaveBody(false);
858  }
859  };
860 
861  /// WeakUndeclaredIdentifiers - Identifiers contained in
862  /// \#pragma weak before declared. rare. may alias another
863  /// identifier, declared or undeclared
864  llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
865 
866  /// ExtnameUndeclaredIdentifiers - Identifiers contained in
867  /// \#pragma redefine_extname before declared. Used in Solaris system headers
868  /// to define functions that occur in multiple standards to call the version
869  /// in the currently selected standard.
870  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
871 
872 
873  /// Load weak undeclared identifiers from the external source.
874  void LoadExternalWeakUndeclaredIdentifiers();
875 
876  /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
877  /// \#pragma weak during processing of other Decls.
878  /// I couldn't figure out a clean way to generate these in-line, so
879  /// we store them here and handle separately -- which is a hack.
880  /// It would be best to refactor this.
882 
884 
885  /// Translation Unit Scope - useful to Objective-C actions that need
886  /// to lookup file scope declarations in the "ordinary" C decl namespace.
887  /// For example, user-defined classes, built-in "id" type, etc.
889 
890  /// The C++ "std" namespace, where the standard library resides.
892 
893  /// The C++ "std::bad_alloc" class, which is defined by the C++
894  /// standard library.
896 
897  /// The C++ "std::align_val_t" enum class, which is defined by the C++
898  /// standard library.
900 
901  /// The C++ "std::experimental" namespace, where the experimental parts
902  /// of the standard library resides.
904 
905  /// The C++ "std::initializer_list" template, which is defined in
906  /// <initializer_list>.
908 
909  /// The C++ "std::coroutine_traits" template, which is defined in
910  /// <coroutine_traits>
912 
913  /// The C++ "type_info" declaration, which is defined in <typeinfo>.
915 
916  /// The MSVC "_GUID" struct, which is defined in MSVC header files.
918 
919  /// Caches identifiers/selectors for NSFoundation APIs.
920  std::unique_ptr<NSAPI> NSAPIObj;
921 
922  /// The declaration of the Objective-C NSNumber class.
924 
925  /// The declaration of the Objective-C NSValue class.
927 
928  /// Pointer to NSNumber type (NSNumber *).
930 
931  /// Pointer to NSValue type (NSValue *).
933 
934  /// The Objective-C NSNumber methods used to create NSNumber literals.
935  ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
936 
937  /// The declaration of the Objective-C NSString class.
939 
940  /// Pointer to NSString type (NSString *).
942 
943  /// The declaration of the stringWithUTF8String: method.
945 
946  /// The declaration of the valueWithBytes:objCType: method.
948 
949  /// The declaration of the Objective-C NSArray class.
951 
952  /// The declaration of the arrayWithObjects:count: method.
954 
955  /// The declaration of the Objective-C NSDictionary class.
957 
958  /// The declaration of the dictionaryWithObjects:forKeys:count: method.
960 
961  /// id<NSCopying> type.
963 
964  /// will hold 'respondsToSelector:'
966 
967  /// A flag to remember whether the implicit forms of operator new and delete
968  /// have been declared.
970 
971  /// A flag to indicate that we're in a context that permits abstract
972  /// references to fields. This is really a
974 
975  /// Describes how the expressions currently being parsed are
976  /// evaluated at run-time, if at all.
978  /// The current expression and its subexpressions occur within an
979  /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
980  /// \c sizeof, where the type of the expression may be significant but
981  /// no code will be generated to evaluate the value of the expression at
982  /// run time.
983  Unevaluated,
984 
985  /// The current expression occurs within a braced-init-list within
986  /// an unevaluated operand. This is mostly like a regular unevaluated
987  /// context, except that we still instantiate constexpr functions that are
988  /// referenced here so that we can perform narrowing checks correctly.
989  UnevaluatedList,
990 
991  /// The current expression occurs within a discarded statement.
992  /// This behaves largely similarly to an unevaluated operand in preventing
993  /// definitions from being required, but not in other ways.
994  DiscardedStatement,
995 
996  /// The current expression occurs within an unevaluated
997  /// operand that unconditionally permits abstract references to
998  /// fields, such as a SIZE operator in MS-style inline assembly.
999  UnevaluatedAbstract,
1000 
1001  /// The current context is "potentially evaluated" in C++11 terms,
1002  /// but the expression is evaluated at compile-time (like the values of
1003  /// cases in a switch statement).
1004  ConstantEvaluated,
1005 
1006  /// The current expression is potentially evaluated at run time,
1007  /// which means that code may be generated to evaluate the value of the
1008  /// expression at run time.
1009  PotentiallyEvaluated,
1010 
1011  /// The current expression is potentially evaluated, but any
1012  /// declarations referenced inside that expression are only used if
1013  /// in fact the current expression is used.
1014  ///
1015  /// This value is used when parsing default function arguments, for which
1016  /// we would like to provide diagnostics (e.g., passing non-POD arguments
1017  /// through varargs) but do not want to mark declarations as "referenced"
1018  /// until the default argument is used.
1019  PotentiallyEvaluatedIfUsed
1020  };
1021 
1022  /// Data structure used to record current or nested
1023  /// expression evaluation contexts.
1025  /// The expression evaluation context.
1027 
1028  /// Whether the enclosing context needed a cleanup.
1030 
1031  /// Whether we are in a decltype expression.
1033 
1034  /// The number of active cleanup objects when we entered
1035  /// this expression evaluation context.
1037 
1038  /// The number of typos encountered during this expression evaluation
1039  /// context (i.e. the number of TypoExprs created).
1040  unsigned NumTypos;
1041 
1043 
1044  /// The lambdas that are present within this context, if it
1045  /// is indeed an unevaluated context.
1047 
1048  /// The declaration that provides context for lambda expressions
1049  /// and block literals if the normal declaration context does not
1050  /// suffice, e.g., in a default function argument.
1052 
1053  /// If we are processing a decltype type, a set of call expressions
1054  /// for which we have deferred checking the completeness of the return type.
1056 
1057  /// If we are processing a decltype type, a set of temporary binding
1058  /// expressions for which we have deferred checking the destructor.
1060 
1061  llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1062 
1063  /// Expressions appearing as the LHS of a volatile assignment in this
1064  /// context. We produce a warning for these when popping the context if
1065  /// they are not discarded-value expressions nor unevaluated operands.
1067 
1068  /// \brief Describes whether we are in an expression constext which we have
1069  /// to handle differently.
1071  EK_Decltype, EK_TemplateArgument, EK_Other
1072  } ExprContext;
1073 
1075  unsigned NumCleanupObjects,
1076  CleanupInfo ParentCleanup,
1077  Decl *ManglingContextDecl,
1078  ExpressionKind ExprContext)
1079  : Context(Context), ParentCleanup(ParentCleanup),
1080  NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1081  ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1082 
1083  bool isUnevaluated() const {
1084  return Context == ExpressionEvaluationContext::Unevaluated ||
1085  Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1086  Context == ExpressionEvaluationContext::UnevaluatedList;
1087  }
1088  bool isConstantEvaluated() const {
1089  return Context == ExpressionEvaluationContext::ConstantEvaluated;
1090  }
1091  };
1092 
1093  /// A stack of expression evaluation contexts.
1095 
1096  /// Emit a warning for all pending noderef expressions that we recorded.
1097  void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1098 
1099  /// Compute the mangling number context for a lambda expression or
1100  /// block literal. Also return the extra mangling decl if any.
1101  ///
1102  /// \param DC - The DeclContext containing the lambda expression or
1103  /// block literal.
1104  std::tuple<MangleNumberingContext *, Decl *>
1105  getCurrentMangleNumberContext(const DeclContext *DC);
1106 
1107 
1108  /// SpecialMemberOverloadResult - The overloading result for a special member
1109  /// function.
1110  ///
1111  /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1112  /// integer are used to determine whether overload resolution succeeded.
1114  public:
1115  enum Kind {
1118  Success
1119  };
1120 
1121  private:
1122  llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1123 
1124  public:
1127  : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1128 
1129  CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1130  void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1131 
1132  Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1133  void setKind(Kind K) { Pair.setInt(K); }
1134  };
1135 
1137  : public llvm::FastFoldingSetNode,
1139  public:
1140  SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1141  : FastFoldingSetNode(ID)
1142  {}
1143  };
1144 
1145  /// A cache of special member function overload resolution results
1146  /// for C++ records.
1147  llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1148 
1149  /// A cache of the flags available in enumerations with the flag_bits
1150  /// attribute.
1151  mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1152 
1153  /// The kind of translation unit we are processing.
1154  ///
1155  /// When we're processing a complete translation unit, Sema will perform
1156  /// end-of-translation-unit semantic tasks (such as creating
1157  /// initializers for tentative definitions in C) once parsing has
1158  /// completed. Modules and precompiled headers perform different kinds of
1159  /// checks.
1161 
1162  llvm::BumpPtrAllocator BumpAlloc;
1163 
1164  /// The number of SFINAE diagnostics that have been trapped.
1166 
1167  typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1169 
1170  /// A mapping from parameters with unparsed default arguments to the
1171  /// set of instantiations of each parameter.
1172  ///
1173  /// This mapping is a temporary data structure used when parsing
1174  /// nested class templates or nested classes of class templates,
1175  /// where we might end up instantiating an inner class before the
1176  /// default arguments of its methods have been parsed.
1178 
1179  // Contains the locations of the beginning of unparsed default
1180  // argument locations.
1181  llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1182 
1183  /// UndefinedInternals - all the used, undefined objects which require a
1184  /// definition in this translation unit.
1185  llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1186 
1187  /// Determine if VD, which must be a variable or function, is an external
1188  /// symbol that nonetheless can't be referenced from outside this translation
1189  /// unit because its type has no linkage and it's not extern "C".
1190  bool isExternalWithNoLinkageType(ValueDecl *VD);
1191 
1192  /// Obtain a sorted list of functions that are undefined but ODR-used.
1193  void getUndefinedButUsed(
1194  SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1195 
1196  /// Retrieves list of suspicious delete-expressions that will be checked at
1197  /// the end of translation unit.
1198  const llvm::MapVector<FieldDecl *, DeleteLocs> &
1199  getMismatchingDeleteExpressions() const;
1200 
1201  typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1202  typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1203 
1204  /// Method Pool - allows efficient lookup when typechecking messages to "id".
1205  /// We need to maintain a list, since selectors can have differing signatures
1206  /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1207  /// of selectors are "overloaded").
1208  /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1209  /// methods inside categories with a particular selector.
1210  GlobalMethodPool MethodPool;
1211 
1212  /// Method selectors used in a \@selector expression. Used for implementation
1213  /// of -Wselector.
1214  llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1215 
1216  /// List of SourceLocations where 'self' is implicitly retained inside a
1217  /// block.
1220 
1221  /// Kinds of C++ special members.
1229  CXXInvalid
1230  };
1231 
1232  typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1234 
1235  /// The C++ special members which we are currently in the process of
1236  /// declaring. If this process recursively triggers the declaration of the
1237  /// same special member, we should act as if it is not yet declared.
1238  llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1239 
1240  /// The function definitions which were renamed as part of typo-correction
1241  /// to match their respective declarations. We want to keep track of them
1242  /// to ensure that we don't emit a "redefinition" error if we encounter a
1243  /// correctly named definition after the renamed definition.
1244  llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1245 
1246  /// Stack of types that correspond to the parameter entities that are
1247  /// currently being copy-initialized. Can be empty.
1249 
1250  void ReadMethodPool(Selector Sel);
1251  void updateOutOfDateSelector(Selector Sel);
1252 
1253  /// Private Helper predicate to check for 'self'.
1254  bool isSelfExpr(Expr *RExpr);
1255  bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1256 
1257  /// Cause the active diagnostic on the DiagosticsEngine to be
1258  /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1259  /// should not be used elsewhere.
1260  void EmitCurrentDiagnostic(unsigned DiagID);
1261 
1262  /// Records and restores the FP_CONTRACT state on entry/exit of compound
1263  /// statements.
1265  public:
1266  FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1267  ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1268 
1269  private:
1270  Sema& S;
1271  FPOptions OldFPFeaturesState;
1272  };
1273 
1274  void addImplicitTypedef(StringRef Name, QualType T);
1275 
1276  bool WarnedStackExhausted = false;
1277 
1278 public:
1279  Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1281  CodeCompleteConsumer *CompletionConsumer = nullptr);
1282  ~Sema();
1283 
1284  /// Perform initialization that occurs after the parser has been
1285  /// initialized but before it parses anything.
1286  void Initialize();
1287 
1288  const LangOptions &getLangOpts() const { return LangOpts; }
1289  OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1290  FPOptions &getFPOptions() { return FPFeatures; }
1291 
1292  DiagnosticsEngine &getDiagnostics() const { return Diags; }
1293  SourceManager &getSourceManager() const { return SourceMgr; }
1294  Preprocessor &getPreprocessor() const { return PP; }
1295  ASTContext &getASTContext() const { return Context; }
1296  ASTConsumer &getASTConsumer() const { return Consumer; }
1297  ASTMutationListener *getASTMutationListener() const;
1298  ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1299 
1300  ///Registers an external source. If an external source already exists,
1301  /// creates a multiplex external source and appends to it.
1302  ///
1303  ///\param[in] E - A non-null external sema source.
1304  ///
1305  void addExternalSource(ExternalSemaSource *E);
1306 
1307  void PrintStats() const;
1308 
1309  /// Warn that the stack is nearly exhausted.
1310  void warnStackExhausted(SourceLocation Loc);
1311 
1312  /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1313  /// guaranteed). Produces a warning if we're low on stack space and allocates
1314  /// more in that case. Use this in code that may recurse deeply (for example,
1315  /// in template instantiation) to avoid stack overflow.
1317  llvm::function_ref<void()> Fn);
1318 
1319  /// Helper class that creates diagnostics with optional
1320  /// template instantiation stacks.
1321  ///
1322  /// This class provides a wrapper around the basic DiagnosticBuilder
1323  /// class that emits diagnostics. SemaDiagnosticBuilder is
1324  /// responsible for emitting the diagnostic (as DiagnosticBuilder
1325  /// does) and, if the diagnostic comes from inside a template
1326  /// instantiation, printing the template instantiation stack as
1327  /// well.
1329  Sema &SemaRef;
1330  unsigned DiagID;
1331 
1332  public:
1333  SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1334  : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1335 
1336  // This is a cunning lie. DiagnosticBuilder actually performs move
1337  // construction in its copy constructor (but due to varied uses, it's not
1338  // possible to conveniently express this as actual move construction). So
1339  // the default copy ctor here is fine, because the base class disables the
1340  // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1341  // in that case anwyay.
1342  SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1343 
1345  // If we aren't active, there is nothing to do.
1346  if (!isActive()) return;
1347 
1348  // Otherwise, we need to emit the diagnostic. First flush the underlying
1349  // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1350  // won't emit the diagnostic in its own destructor.
1351  //
1352  // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1353  // do its own needless checks to see if the diagnostic needs to be
1354  // emitted. However, because we take care to ensure that the builder
1355  // objects never escape, a sufficiently smart compiler will be able to
1356  // eliminate that code.
1357  FlushCounts();
1358  Clear();
1359 
1360  // Dispatch to Sema to emit the diagnostic.
1361  SemaRef.EmitCurrentDiagnostic(DiagID);
1362  }
1363 
1364  /// Teach operator<< to produce an object of the correct type.
1365  template<typename T>
1367  const SemaDiagnosticBuilder &Diag, const T &Value) {
1368  const DiagnosticBuilder &BaseDiag = Diag;
1369  BaseDiag << Value;
1370  return Diag;
1371  }
1372  };
1373 
1374  /// Emit a diagnostic.
1376  DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1377  return SemaDiagnosticBuilder(DB, *this, DiagID);
1378  }
1379 
1380  /// Emit a partial diagnostic.
1382 
1383  /// Build a partial diagnostic.
1384  PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1385 
1386  bool findMacroSpelling(SourceLocation &loc, StringRef name);
1387 
1388  /// Get a string to suggest for zero-initialization of a type.
1389  std::string
1390  getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1391  std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1392 
1393  /// Calls \c Lexer::getLocForEndOfToken()
1394  SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1395 
1396  /// Retrieve the module loader associated with the preprocessor.
1397  ModuleLoader &getModuleLoader() const;
1398 
1399  void emitAndClearUnusedLocalTypedefWarnings();
1400 
1402  /// The global module fragment, between 'module;' and a module-declaration.
1404  /// A normal translation unit fragment. For a non-module unit, this is the
1405  /// entire translation unit. Otherwise, it runs from the module-declaration
1406  /// to the private-module-fragment (if any) or the end of the TU (if not).
1408  /// The private module fragment, between 'module :private;' and the end of
1409  /// the translation unit.
1410  Private
1411  };
1412 
1413  void ActOnStartOfTranslationUnit();
1414  void ActOnEndOfTranslationUnit();
1415  void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1416 
1417  void CheckDelegatingCtorCycles();
1418 
1419  Scope *getScopeForContext(DeclContext *Ctx);
1420 
1421  void PushFunctionScope();
1422  void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1423  sema::LambdaScopeInfo *PushLambdaScope();
1424 
1425  /// This is used to inform Sema what the current TemplateParameterDepth
1426  /// is during Parsing. Currently it is used to pass on the depth
1427  /// when parsing generic lambda 'auto' parameters.
1428  void RecordParsingTemplateParameterDepth(unsigned Depth);
1429 
1430  void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1432  unsigned OpenMPCaptureLevel = 0);
1433 
1434  /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1435  /// time after they've been popped.
1437  Sema *Self;
1438 
1439  public:
1440  explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1441  void operator()(sema::FunctionScopeInfo *Scope) const;
1442  };
1443 
1444  using PoppedFunctionScopePtr =
1445  std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1446 
1448  PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1449  const Decl *D = nullptr,
1450  QualType BlockType = QualType());
1451 
1453  return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1454  }
1455 
1456  sema::FunctionScopeInfo *getEnclosingFunction() const;
1457 
1458  void setFunctionHasBranchIntoScope();
1459  void setFunctionHasBranchProtectedScope();
1460  void setFunctionHasIndirectGoto();
1461 
1462  void PushCompoundScope(bool IsStmtExpr);
1463  void PopCompoundScope();
1464 
1465  sema::CompoundScopeInfo &getCurCompoundScope() const;
1466 
1467  bool hasAnyUnrecoverableErrorsInThisFunction() const;
1468 
1469  /// Retrieve the current block, if any.
1470  sema::BlockScopeInfo *getCurBlock();
1471 
1472  /// Get the innermost lambda enclosing the current location, if any. This
1473  /// looks through intervening non-lambda scopes such as local functions and
1474  /// blocks.
1475  sema::LambdaScopeInfo *getEnclosingLambda() const;
1476 
1477  /// Retrieve the current lambda scope info, if any.
1478  /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1479  /// lambda scope info ignoring all inner capturing scopes that are not
1480  /// lambda scopes.
1482  getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1483 
1484  /// Retrieve the current generic lambda info, if any.
1485  sema::LambdaScopeInfo *getCurGenericLambda();
1486 
1487  /// Retrieve the current captured region, if any.
1488  sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1489 
1490  /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1491  SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1492 
1493  void ActOnComment(SourceRange Comment);
1494 
1495  //===--------------------------------------------------------------------===//
1496  // Type Analysis / Processing: SemaType.cpp.
1497  //
1498 
1499  QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1500  const DeclSpec *DS = nullptr);
1501  QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1502  const DeclSpec *DS = nullptr);
1503  QualType BuildPointerType(QualType T,
1504  SourceLocation Loc, DeclarationName Entity);
1505  QualType BuildReferenceType(QualType T, bool LValueRef,
1506  SourceLocation Loc, DeclarationName Entity);
1507  QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1508  Expr *ArraySize, unsigned Quals,
1509  SourceRange Brackets, DeclarationName Entity);
1510  QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1511  QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1512  SourceLocation AttrLoc);
1513  QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1514  SourceLocation AttrLoc);
1515 
1516  /// Same as above, but constructs the AddressSpace index if not provided.
1517  QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1518  SourceLocation AttrLoc);
1519 
1520  bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1521 
1522  bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1523 
1524  /// Build a function type.
1525  ///
1526  /// This routine checks the function type according to C++ rules and
1527  /// under the assumption that the result type and parameter types have
1528  /// just been instantiated from a template. It therefore duplicates
1529  /// some of the behavior of GetTypeForDeclarator, but in a much
1530  /// simpler form that is only suitable for this narrow use case.
1531  ///
1532  /// \param T The return type of the function.
1533  ///
1534  /// \param ParamTypes The parameter types of the function. This array
1535  /// will be modified to account for adjustments to the types of the
1536  /// function parameters.
1537  ///
1538  /// \param Loc The location of the entity whose type involves this
1539  /// function type or, if there is no such entity, the location of the
1540  /// type that will have function type.
1541  ///
1542  /// \param Entity The name of the entity that involves the function
1543  /// type, if known.
1544  ///
1545  /// \param EPI Extra information about the function type. Usually this will
1546  /// be taken from an existing function with the same prototype.
1547  ///
1548  /// \returns A suitable function type, if there are no errors. The
1549  /// unqualified type will always be a FunctionProtoType.
1550  /// Otherwise, returns a NULL type.
1551  QualType BuildFunctionType(QualType T,
1552  MutableArrayRef<QualType> ParamTypes,
1553  SourceLocation Loc, DeclarationName Entity,
1554  const FunctionProtoType::ExtProtoInfo &EPI);
1555 
1556  QualType BuildMemberPointerType(QualType T, QualType Class,
1557  SourceLocation Loc,
1558  DeclarationName Entity);
1559  QualType BuildBlockPointerType(QualType T,
1560  SourceLocation Loc, DeclarationName Entity);
1561  QualType BuildParenType(QualType T);
1562  QualType BuildAtomicType(QualType T, SourceLocation Loc);
1563  QualType BuildReadPipeType(QualType T,
1564  SourceLocation Loc);
1565  QualType BuildWritePipeType(QualType T,
1566  SourceLocation Loc);
1567 
1568  TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1569  TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1570 
1571  /// Package the given type and TSI into a ParsedType.
1572  ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1573  DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1574  DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1575  static QualType GetTypeFromParser(ParsedType Ty,
1576  TypeSourceInfo **TInfo = nullptr);
1577  CanThrowResult canThrow(const Expr *E);
1578  const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1579  const FunctionProtoType *FPT);
1580  void UpdateExceptionSpec(FunctionDecl *FD,
1582  bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1583  bool CheckDistantExceptionSpec(QualType T);
1584  bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1585  bool CheckEquivalentExceptionSpec(
1586  const FunctionProtoType *Old, SourceLocation OldLoc,
1587  const FunctionProtoType *New, SourceLocation NewLoc);
1588  bool CheckEquivalentExceptionSpec(
1589  const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1590  const FunctionProtoType *Old, SourceLocation OldLoc,
1591  const FunctionProtoType *New, SourceLocation NewLoc);
1592  bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1593  bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1594  const PartialDiagnostic &NestedDiagID,
1595  const PartialDiagnostic &NoteID,
1596  const PartialDiagnostic &NoThrowDiagID,
1597  const FunctionProtoType *Superset,
1598  SourceLocation SuperLoc,
1599  const FunctionProtoType *Subset,
1600  SourceLocation SubLoc);
1601  bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1602  const PartialDiagnostic &NoteID,
1603  const FunctionProtoType *Target,
1604  SourceLocation TargetLoc,
1605  const FunctionProtoType *Source,
1606  SourceLocation SourceLoc);
1607 
1608  TypeResult ActOnTypeName(Scope *S, Declarator &D);
1609 
1610  /// The parser has parsed the context-sensitive type 'instancetype'
1611  /// in an Objective-C message declaration. Return the appropriate type.
1612  ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1613 
1614  /// Abstract class used to diagnose incomplete types.
1615  struct TypeDiagnoser {
1617 
1618  virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1619  virtual ~TypeDiagnoser() {}
1620  };
1621 
1622  static int getPrintable(int I) { return I; }
1623  static unsigned getPrintable(unsigned I) { return I; }
1624  static bool getPrintable(bool B) { return B; }
1625  static const char * getPrintable(const char *S) { return S; }
1626  static StringRef getPrintable(StringRef S) { return S; }
1627  static const std::string &getPrintable(const std::string &S) { return S; }
1628  static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1629  return II;
1630  }
1632  static QualType getPrintable(QualType T) { return T; }
1633  static SourceRange getPrintable(SourceRange R) { return R; }
1634  static SourceRange getPrintable(SourceLocation L) { return L; }
1635  static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1636  static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1637 
1638  template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1639  unsigned DiagID;
1640  std::tuple<const Ts &...> Args;
1641 
1642  template <std::size_t... Is>
1643  void emit(const SemaDiagnosticBuilder &DB,
1644  std::index_sequence<Is...>) const {
1645  // Apply all tuple elements to the builder in order.
1646  bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1647  (void)Dummy;
1648  }
1649 
1650  public:
1651  BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1652  : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1653  assert(DiagID != 0 && "no diagnostic for type diagnoser");
1654  }
1655 
1656  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1657  const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1658  emit(DB, std::index_sequence_for<Ts...>());
1659  DB << T;
1660  }
1661  };
1662 
1663 private:
1664  /// Methods for marking which expressions involve dereferencing a pointer
1665  /// marked with the 'noderef' attribute. Expressions are checked bottom up as
1666  /// they are parsed, meaning that a noderef pointer may not be accessed. For
1667  /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
1668  /// `*p`, but need to check that `address of` is called on it. This requires
1669  /// keeping a container of all pending expressions and checking if the address
1670  /// of them are eventually taken.
1671  void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
1672  void CheckAddressOfNoDeref(const Expr *E);
1673  void CheckMemberAccessOfNoDeref(const MemberExpr *E);
1674 
1675  bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1676  TypeDiagnoser *Diagnoser);
1677 
1678  struct ModuleScope {
1679  SourceLocation BeginLoc;
1680  clang::Module *Module = nullptr;
1681  bool ModuleInterface = false;
1682  bool ImplicitGlobalModuleFragment = false;
1683  VisibleModuleSet OuterVisibleModules;
1684  };
1685  /// The modules we're currently parsing.
1687 
1688  /// Namespace definitions that we will export when they finish.
1689  llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
1690 
1691  /// Get the module whose scope we are currently within.
1692  Module *getCurrentModule() const {
1693  return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1694  }
1695 
1696  VisibleModuleSet VisibleModules;
1697 
1698 public:
1699  /// Get the module owning an entity.
1700  Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1701 
1702  /// Make a merged definition of an existing hidden definition \p ND
1703  /// visible at the specified location.
1704  void makeMergedDefinitionVisible(NamedDecl *ND);
1705 
1706  bool isModuleVisible(const Module *M, bool ModulePrivate = false);
1707 
1708  /// Determine whether a declaration is visible to name lookup.
1709  bool isVisible(const NamedDecl *D) {
1710  return !D->isHidden() || isVisibleSlow(D);
1711  }
1712 
1713  /// Determine whether any declaration of an entity is visible.
1714  bool
1716  llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1717  return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1718  }
1719  bool hasVisibleDeclarationSlow(const NamedDecl *D,
1721 
1722  bool hasVisibleMergedDefinition(NamedDecl *Def);
1723  bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1724 
1725  /// Determine if \p D and \p Suggested have a structurally compatible
1726  /// layout as described in C11 6.2.7/1.
1727  bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1728 
1729  /// Determine if \p D has a visible definition. If not, suggest a declaration
1730  /// that should be made visible to expose the definition.
1731  bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1732  bool OnlyNeedComplete = false);
1734  NamedDecl *Hidden;
1735  return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1736  }
1737 
1738  /// Determine if the template parameter \p D has a visible default argument.
1739  bool
1741  llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1742 
1743  /// Determine if there is a visible declaration of \p D that is an explicit
1744  /// specialization declaration for a specialization of a template. (For a
1745  /// member specialization, use hasVisibleMemberSpecialization.)
1746  bool hasVisibleExplicitSpecialization(
1747  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1748 
1749  /// Determine if there is a visible declaration of \p D that is a member
1750  /// specialization declaration (as opposed to an instantiated declaration).
1751  bool hasVisibleMemberSpecialization(
1752  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1753 
1754  /// Determine if \p A and \p B are equivalent internal linkage declarations
1755  /// from different modules, and thus an ambiguity error can be downgraded to
1756  /// an extension warning.
1757  bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1758  const NamedDecl *B);
1759  void diagnoseEquivalentInternalLinkageDeclarations(
1760  SourceLocation Loc, const NamedDecl *D,
1762 
1763  bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
1764 
1766  return !RequireCompleteTypeImpl(Loc, T, nullptr);
1767  }
1768  bool RequireCompleteType(SourceLocation Loc, QualType T,
1769  TypeDiagnoser &Diagnoser);
1770  bool RequireCompleteType(SourceLocation Loc, QualType T,
1771  unsigned DiagID);
1772 
1773  template <typename... Ts>
1774  bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1775  const Ts &...Args) {
1776  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1777  return RequireCompleteType(Loc, T, Diagnoser);
1778  }
1779 
1780  void completeExprArrayBound(Expr *E);
1781  bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1782  bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1783 
1784  template <typename... Ts>
1785  bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1786  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1787  return RequireCompleteExprType(E, Diagnoser);
1788  }
1789 
1790  bool RequireLiteralType(SourceLocation Loc, QualType T,
1791  TypeDiagnoser &Diagnoser);
1792  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1793 
1794  template <typename... Ts>
1795  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1796  const Ts &...Args) {
1797  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1798  return RequireLiteralType(Loc, T, Diagnoser);
1799  }
1800 
1801  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1802  const CXXScopeSpec &SS, QualType T,
1803  TagDecl *OwnedTagDecl = nullptr);
1804 
1805  QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1806  /// If AsUnevaluated is false, E is treated as though it were an evaluated
1807  /// context, such as when building a type for decltype(auto).
1808  QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1809  bool AsUnevaluated = true);
1810  QualType BuildUnaryTransformType(QualType BaseType,
1812  SourceLocation Loc);
1813 
1814  //===--------------------------------------------------------------------===//
1815  // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1816  //
1817 
1818  struct SkipBodyInfo {
1820  : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1821  New(nullptr) {}
1826  };
1827 
1828  DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1829 
1830  void DiagnoseUseOfUnimplementedSelectors();
1831 
1832  bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1833 
1835  Scope *S, CXXScopeSpec *SS = nullptr,
1836  bool isClassName = false, bool HasTrailingDot = false,
1837  ParsedType ObjectType = nullptr,
1838  bool IsCtorOrDtorName = false,
1839  bool WantNontrivialTypeSourceInfo = false,
1840  bool IsClassTemplateDeductionContext = true,
1841  IdentifierInfo **CorrectedII = nullptr);
1842  TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1843  bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1844  void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1845  SourceLocation IILoc,
1846  Scope *S,
1847  CXXScopeSpec *SS,
1848  ParsedType &SuggestedType,
1849  bool IsTemplateName = false);
1850 
1851  /// Attempt to behave like MSVC in situations where lookup of an unqualified
1852  /// type name has failed in a dependent context. In these situations, we
1853  /// automatically form a DependentTypeName that will retry lookup in a related
1854  /// scope during instantiation.
1855  ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1856  SourceLocation NameLoc,
1857  bool IsTemplateTypeArg);
1858 
1859  /// Describes the result of the name lookup and resolution performed
1860  /// by \c ClassifyName().
1862  /// This name is not a type or template in this context, but might be
1863  /// something else.
1865  /// Classification failed; an error has been produced.
1867  /// The name has been typo-corrected to a keyword.
1869  /// The name was classified as a type.
1871  /// The name was classified as a specific non-type, non-template
1872  /// declaration. ActOnNameClassifiedAsNonType should be called to
1873  /// convert the declaration to an expression.
1875  /// The name was classified as an ADL-only function name.
1876  /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
1877  /// result to an expression.
1879  /// The name denotes a member of a dependent type that could not be
1880  /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
1881  /// convert the result to an expression.
1883  /// The name was classified as a non-type, and an expression representing
1884  /// that name has been formed.
1886  /// The name was classified as a template whose specializations are types.
1888  /// The name was classified as a variable template name.
1890  /// The name was classified as a function template name.
1892  /// The name was classified as an ADL-only function template name.
1894  };
1895 
1898  union {
1903  };
1904 
1905  explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1906 
1907  public:
1908  NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1909 
1910  NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1911 
1913  return NameClassification(NC_Error);
1914  }
1915 
1917  return NameClassification(NC_Unknown);
1918  }
1919 
1921  NameClassification Result(NC_ContextIndependentExpr);
1922  Result.Expr = E;
1923  return Result;
1924  }
1925 
1927  NameClassification Result(NC_NonType);
1928  Result.NonTypeDecl = D;
1929  return Result;
1930  }
1931 
1933  return NameClassification(NC_UndeclaredNonType);
1934  }
1935 
1937  return NameClassification(NC_DependentNonType);
1938  }
1939 
1941  NameClassification Result(NC_TypeTemplate);
1942  Result.Template = Name;
1943  return Result;
1944  }
1945 
1947  NameClassification Result(NC_VarTemplate);
1948  Result.Template = Name;
1949  return Result;
1950  }
1951 
1953  NameClassification Result(NC_FunctionTemplate);
1954  Result.Template = Name;
1955  return Result;
1956  }
1957 
1959  NameClassification Result(NC_UndeclaredTemplate);
1960  Result.Template = Name;
1961  return Result;
1962  }
1963 
1965 
1967  assert(Kind == NC_ContextIndependentExpr);
1968  return Expr;
1969  }
1970 
1972  assert(Kind == NC_Type);
1973  return Type;
1974  }
1975 
1977  assert(Kind == NC_NonType);
1978  return NonTypeDecl;
1979  }
1980 
1982  assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1983  Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate);
1984  return Template;
1985  }
1986 
1988  switch (Kind) {
1989  case NC_TypeTemplate:
1990  return TNK_Type_template;
1991  case NC_FunctionTemplate:
1992  return TNK_Function_template;
1993  case NC_VarTemplate:
1994  return TNK_Var_template;
1995  case NC_UndeclaredTemplate:
1996  return TNK_Undeclared_template;
1997  default:
1998  llvm_unreachable("unsupported name classification.");
1999  }
2000  }
2001  };
2002 
2003  /// Perform name lookup on the given name, classifying it based on
2004  /// the results of name lookup and the following token.
2005  ///
2006  /// This routine is used by the parser to resolve identifiers and help direct
2007  /// parsing. When the identifier cannot be found, this routine will attempt
2008  /// to correct the typo and classify based on the resulting name.
2009  ///
2010  /// \param S The scope in which we're performing name lookup.
2011  ///
2012  /// \param SS The nested-name-specifier that precedes the name.
2013  ///
2014  /// \param Name The identifier. If typo correction finds an alternative name,
2015  /// this pointer parameter will be updated accordingly.
2016  ///
2017  /// \param NameLoc The location of the identifier.
2018  ///
2019  /// \param NextToken The token following the identifier. Used to help
2020  /// disambiguate the name.
2021  ///
2022  /// \param CCC The correction callback, if typo correction is desired.
2023  NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2024  IdentifierInfo *&Name, SourceLocation NameLoc,
2025  const Token &NextToken,
2026  CorrectionCandidateCallback *CCC = nullptr);
2027 
2028  /// Act on the result of classifying a name as an undeclared (ADL-only)
2029  /// non-type declaration.
2030  ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2031  SourceLocation NameLoc);
2032  /// Act on the result of classifying a name as an undeclared member of a
2033  /// dependent base class.
2034  ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2035  IdentifierInfo *Name,
2036  SourceLocation NameLoc,
2037  bool IsAddressOfOperand);
2038  /// Act on the result of classifying a name as a specific non-type
2039  /// declaration.
2040  ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2041  NamedDecl *Found,
2042  SourceLocation NameLoc,
2043  const Token &NextToken);
2044 
2045  /// Describes the detailed kind of a template name. Used in diagnostics.
2047  ClassTemplate,
2048  FunctionTemplate,
2049  VarTemplate,
2050  AliasTemplate,
2051  TemplateTemplateParam,
2052  Concept,
2053  DependentTemplate
2054  };
2056  getTemplateNameKindForDiagnostics(TemplateName Name);
2057 
2058  /// Determine whether it's plausible that E was intended to be a
2059  /// template-name.
2060  bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2061  if (!getLangOpts().CPlusPlus || E.isInvalid())
2062  return false;
2063  Dependent = false;
2064  if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2065  return !DRE->hasExplicitTemplateArgs();
2066  if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2067  return !ME->hasExplicitTemplateArgs();
2068  Dependent = true;
2069  if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2070  return !DSDRE->hasExplicitTemplateArgs();
2071  if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2072  return !DSME->hasExplicitTemplateArgs();
2073  // Any additional cases recognized here should also be handled by
2074  // diagnoseExprIntendedAsTemplateName.
2075  return false;
2076  }
2077  void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2080 
2081  Decl *ActOnDeclarator(Scope *S, Declarator &D);
2082 
2083  NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2084  MultiTemplateParamsArg TemplateParameterLists);
2085  void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2086  bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2087  bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2088  DeclarationName Name, SourceLocation Loc,
2089  bool IsTemplateId);
2090  void
2091  diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2092  SourceLocation FallbackLoc,
2093  SourceLocation ConstQualLoc = SourceLocation(),
2094  SourceLocation VolatileQualLoc = SourceLocation(),
2095  SourceLocation RestrictQualLoc = SourceLocation(),
2096  SourceLocation AtomicQualLoc = SourceLocation(),
2097  SourceLocation UnalignedQualLoc = SourceLocation());
2098 
2099  static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2100  void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2101  NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2102  const LookupResult &R);
2103  NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2104  void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2105  const LookupResult &R);
2106  void CheckShadow(Scope *S, VarDecl *D);
2107 
2108  /// Warn if 'E', which is an expression that is about to be modified, refers
2109  /// to a shadowing declaration.
2110  void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2111 
2112  void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2113 
2114 private:
2115  /// Map of current shadowing declarations to shadowed declarations. Warn if
2116  /// it looks like the user is trying to modify the shadowing declaration.
2117  llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2118 
2119 public:
2120  void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2121  void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2122  void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2123  TypedefNameDecl *NewTD);
2124  void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2125  NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2126  TypeSourceInfo *TInfo,
2128  NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2129  LookupResult &Previous, bool &Redeclaration);
2130  NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2131  TypeSourceInfo *TInfo,
2132  LookupResult &Previous,
2133  MultiTemplateParamsArg TemplateParamLists,
2134  bool &AddToScope,
2135  ArrayRef<BindingDecl *> Bindings = None);
2136  NamedDecl *
2137  ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2138  MultiTemplateParamsArg TemplateParamLists);
2139  // Returns true if the variable declaration is a redeclaration
2140  bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2141  void CheckVariableDeclarationType(VarDecl *NewVD);
2142  bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2143  Expr *Init);
2144  void CheckCompleteVariableDeclaration(VarDecl *VD);
2145  void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2146  void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2147 
2148  NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2149  TypeSourceInfo *TInfo,
2150  LookupResult &Previous,
2151  MultiTemplateParamsArg TemplateParamLists,
2152  bool &AddToScope);
2153  bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2154 
2155  enum class CheckConstexprKind {
2156  /// Diagnose issues that are non-constant or that are extensions.
2157  Diagnose,
2158  /// Identify whether this function satisfies the formal rules for constexpr
2159  /// functions in the current lanugage mode (with no extensions).
2160  CheckValid
2161  };
2162 
2163  bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2165 
2166  void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2167  void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2168  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2169  void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2170  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2171  // Returns true if the function declaration is a redeclaration
2172  bool CheckFunctionDeclaration(Scope *S,
2173  FunctionDecl *NewFD, LookupResult &Previous,
2174  bool IsMemberSpecialization);
2175  bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2176  bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2177  QualType NewT, QualType OldT);
2178  void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2179  void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2180  Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2181  bool IsDefinition);
2182  void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2183  Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2184  ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2185  SourceLocation Loc,
2186  QualType T);
2187  ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2188  SourceLocation NameLoc, IdentifierInfo *Name,
2189  QualType T, TypeSourceInfo *TSInfo,
2190  StorageClass SC);
2191  void ActOnParamDefaultArgument(Decl *param,
2192  SourceLocation EqualLoc,
2193  Expr *defarg);
2194  void ActOnParamUnparsedDefaultArgument(Decl *param,
2195  SourceLocation EqualLoc,
2196  SourceLocation ArgLoc);
2197  void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2198  bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2199  SourceLocation EqualLoc);
2200 
2201  // Contexts where using non-trivial C union types can be disallowed. This is
2202  // passed to err_non_trivial_c_union_in_invalid_context.
2204  // Function parameter.
2206  // Function return.
2208  // Default-initialized object.
2210  // Variable with automatic storage duration.
2212  // Initializer expression that might copy from another object.
2214  // Assignment.
2216  // Compound literal.
2218  // Block capture.
2220  // lvalue-to-rvalue conversion of volatile type.
2222  };
2223 
2224  /// Emit diagnostics if the initializer or any of its explicit or
2225  /// implicitly-generated subexpressions require copying or
2226  /// default-initializing a type that is or contains a C union type that is
2227  /// non-trivial to copy or default-initialize.
2228  void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2229 
2230  // These flags are passed to checkNonTrivialCUnion.
2232  NTCUK_Init = 0x1,
2233  NTCUK_Destruct = 0x2,
2234  NTCUK_Copy = 0x4,
2235  };
2236 
2237  /// Emit diagnostics if a non-trivial C union type or a struct that contains
2238  /// a non-trivial C union is used in an invalid context.
2239  void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2240  NonTrivialCUnionContext UseContext,
2241  unsigned NonTrivialKind);
2242 
2243  void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2244  void ActOnUninitializedDecl(Decl *dcl);
2245  void ActOnInitializerError(Decl *Dcl);
2246 
2247  void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2248  void ActOnCXXForRangeDecl(Decl *D);
2249  StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2250  IdentifierInfo *Ident,
2251  ParsedAttributes &Attrs,
2252  SourceLocation AttrEnd);
2253  void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2254  void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2255  void CheckStaticLocalForDllExport(VarDecl *VD);
2256  void FinalizeDeclaration(Decl *D);
2257  DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2258  ArrayRef<Decl *> Group);
2259  DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2260 
2261  /// Should be called on all declarations that might have attached
2262  /// documentation comments.
2263  void ActOnDocumentableDecl(Decl *D);
2264  void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2265 
2266  void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2267  SourceLocation LocAfterDecls);
2268  void CheckForFunctionRedefinition(
2269  FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2270  SkipBodyInfo *SkipBody = nullptr);
2271  Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2272  MultiTemplateParamsArg TemplateParamLists,
2273  SkipBodyInfo *SkipBody = nullptr);
2274  Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2275  SkipBodyInfo *SkipBody = nullptr);
2276  void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2278  return D && isa<ObjCMethodDecl>(D);
2279  }
2280 
2281  /// Determine whether we can delay parsing the body of a function or
2282  /// function template until it is used, assuming we don't care about emitting
2283  /// code for that function.
2284  ///
2285  /// This will be \c false if we may need the body of the function in the
2286  /// middle of parsing an expression (where it's impractical to switch to
2287  /// parsing a different function), for instance, if it's constexpr in C++11
2288  /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2289  bool canDelayFunctionBody(const Declarator &D);
2290 
2291  /// Determine whether we can skip parsing the body of a function
2292  /// definition, assuming we don't care about analyzing its body or emitting
2293  /// code for that function.
2294  ///
2295  /// This will be \c false only if we may need the body of the function in
2296  /// order to parse the rest of the program (for instance, if it is
2297  /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2298  bool canSkipFunctionBody(Decl *D);
2299 
2300  void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2301  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2302  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2303  Decl *ActOnSkippedFunctionBody(Decl *Decl);
2304  void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2305 
2306  /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2307  /// attribute for which parsing is delayed.
2308  void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2309 
2310  /// Diagnose any unused parameters in the given sequence of
2311  /// ParmVarDecl pointers.
2312  void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2313 
2314  /// Diagnose whether the size of parameters or return value of a
2315  /// function or obj-c method definition is pass-by-value and larger than a
2316  /// specified threshold.
2317  void
2318  DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2319  QualType ReturnTy, NamedDecl *D);
2320 
2321  void DiagnoseInvalidJumps(Stmt *Body);
2322  Decl *ActOnFileScopeAsmDecl(Expr *expr,
2323  SourceLocation AsmLoc,
2324  SourceLocation RParenLoc);
2325 
2326  /// Handle a C++11 empty-declaration and attribute-declaration.
2327  Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2328  SourceLocation SemiLoc);
2329 
2330  enum class ModuleDeclKind {
2331  Interface, ///< 'export module X;'
2332  Implementation, ///< 'module X;'
2333  };
2334 
2335  /// The parser has processed a module-declaration that begins the definition
2336  /// of a module interface or implementation.
2337  DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2338  SourceLocation ModuleLoc, ModuleDeclKind MDK,
2339  ModuleIdPath Path, bool IsFirstDecl);
2340 
2341  /// The parser has processed a global-module-fragment declaration that begins
2342  /// the definition of the global module fragment of the current module unit.
2343  /// \param ModuleLoc The location of the 'module' keyword.
2344  DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2345 
2346  /// The parser has processed a private-module-fragment declaration that begins
2347  /// the definition of the private module fragment of the current module unit.
2348  /// \param ModuleLoc The location of the 'module' keyword.
2349  /// \param PrivateLoc The location of the 'private' keyword.
2350  DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2351  SourceLocation PrivateLoc);
2352 
2353  /// The parser has processed a module import declaration.
2354  ///
2355  /// \param StartLoc The location of the first token in the declaration. This
2356  /// could be the location of an '@', 'export', or 'import'.
2357  /// \param ExportLoc The location of the 'export' keyword, if any.
2358  /// \param ImportLoc The location of the 'import' keyword.
2359  /// \param Path The module access path.
2360  DeclResult ActOnModuleImport(SourceLocation StartLoc,
2361  SourceLocation ExportLoc,
2362  SourceLocation ImportLoc, ModuleIdPath Path);
2363  DeclResult ActOnModuleImport(SourceLocation StartLoc,
2364  SourceLocation ExportLoc,
2365  SourceLocation ImportLoc, Module *M,
2366  ModuleIdPath Path = {});
2367 
2368  /// The parser has processed a module import translated from a
2369  /// #include or similar preprocessing directive.
2370  void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2371  void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2372 
2373  /// The parsed has entered a submodule.
2374  void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2375  /// The parser has left a submodule.
2376  void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2377 
2378  /// Create an implicit import of the given module at the given
2379  /// source location, for error recovery, if possible.
2380  ///
2381  /// This routine is typically used when an entity found by name lookup
2382  /// is actually hidden within a module that we know about but the user
2383  /// has forgotten to import.
2384  void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2385  Module *Mod);
2386 
2387  /// Kinds of missing import. Note, the values of these enumerators correspond
2388  /// to %select values in diagnostics.
2389  enum class MissingImportKind {
2390  Declaration,
2391  Definition,
2392  DefaultArgument,
2393  ExplicitSpecialization,
2394  PartialSpecialization
2395  };
2396 
2397  /// Diagnose that the specified declaration needs to be visible but
2398  /// isn't, and suggest a module import that would resolve the problem.
2399  void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2400  MissingImportKind MIK, bool Recover = true);
2401  void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2402  SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2403  MissingImportKind MIK, bool Recover);
2404 
2405  Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2406  SourceLocation LBraceLoc);
2407  Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2408  SourceLocation RBraceLoc);
2409 
2410  /// We've found a use of a templated declaration that would trigger an
2411  /// implicit instantiation. Check that any relevant explicit specializations
2412  /// and partial specializations are visible, and diagnose if not.
2413  void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2414 
2415  /// We've found a use of a template specialization that would select a
2416  /// partial specialization. Check that the partial specialization is visible,
2417  /// and diagnose if not.
2418  void checkPartialSpecializationVisibility(SourceLocation Loc,
2419  NamedDecl *Spec);
2420 
2421  /// Retrieve a suitable printing policy for diagnostics.
2423  return getPrintingPolicy(Context, PP);
2424  }
2425 
2426  /// Retrieve a suitable printing policy for diagnostics.
2427  static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2428  const Preprocessor &PP);
2429 
2430  /// Scope actions.
2431  void ActOnPopScope(SourceLocation Loc, Scope *S);
2432  void ActOnTranslationUnitScope(Scope *S);
2433 
2434  Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2435  RecordDecl *&AnonRecord);
2436  Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2437  MultiTemplateParamsArg TemplateParams,
2438  bool IsExplicitInstantiation,
2439  RecordDecl *&AnonRecord);
2440 
2441  Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2442  AccessSpecifier AS,
2443  RecordDecl *Record,
2444  const PrintingPolicy &Policy);
2445 
2446  Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2447  RecordDecl *Record);
2448 
2449  /// Common ways to introduce type names without a tag for use in diagnostics.
2450  /// Keep in sync with err_tag_reference_non_tag.
2451  enum NonTagKind {
2461  };
2462 
2463  /// Given a non-tag type declaration, returns an enum useful for indicating
2464  /// what kind of non-tag type this is.
2465  NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2466 
2467  bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2468  TagTypeKind NewTag, bool isDefinition,
2469  SourceLocation NewTagLoc,
2470  const IdentifierInfo *Name);
2471 
2472  enum TagUseKind {
2473  TUK_Reference, // Reference to a tag: 'struct foo *X;'
2474  TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2475  TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2476  TUK_Friend // Friend declaration: 'friend struct foo;'
2477  };
2478 
2479  Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2480  SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2481  SourceLocation NameLoc, const ParsedAttributesView &Attr,
2482  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2483  MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2484  bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2485  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2486  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2487  SkipBodyInfo *SkipBody = nullptr);
2488 
2489  Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2490  unsigned TagSpec, SourceLocation TagLoc,
2491  CXXScopeSpec &SS, IdentifierInfo *Name,
2492  SourceLocation NameLoc,
2493  const ParsedAttributesView &Attr,
2494  MultiTemplateParamsArg TempParamLists);
2495 
2496  TypeResult ActOnDependentTag(Scope *S,
2497  unsigned TagSpec,
2498  TagUseKind TUK,
2499  const CXXScopeSpec &SS,
2500  IdentifierInfo *Name,
2501  SourceLocation TagLoc,
2502  SourceLocation NameLoc);
2503 
2504  void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2505  IdentifierInfo *ClassName,
2506  SmallVectorImpl<Decl *> &Decls);
2507  Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2508  Declarator &D, Expr *BitfieldWidth);
2509 
2510  FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2511  Declarator &D, Expr *BitfieldWidth,
2512  InClassInitStyle InitStyle,
2513  AccessSpecifier AS);
2514  MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2515  SourceLocation DeclStart, Declarator &D,
2516  Expr *BitfieldWidth,
2517  InClassInitStyle InitStyle,
2518  AccessSpecifier AS,
2519  const ParsedAttr &MSPropertyAttr);
2520 
2521  FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2522  TypeSourceInfo *TInfo,
2523  RecordDecl *Record, SourceLocation Loc,
2524  bool Mutable, Expr *BitfieldWidth,
2525  InClassInitStyle InitStyle,
2526  SourceLocation TSSL,
2527  AccessSpecifier AS, NamedDecl *PrevDecl,
2528  Declarator *D = nullptr);
2529 
2530  bool CheckNontrivialField(FieldDecl *FD);
2531  void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2532 
2534  /// The triviality of a method unaffected by "trivial_abi".
2536 
2537  /// The triviality of a method affected by "trivial_abi".
2538  TAH_ConsiderTrivialABI
2539  };
2540 
2541  bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2542  TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2543  bool Diagnose = false);
2544  CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2545  void ActOnLastBitfield(SourceLocation DeclStart,
2546  SmallVectorImpl<Decl *> &AllIvarDecls);
2547  Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2548  Declarator &D, Expr *BitfieldWidth,
2549  tok::ObjCKeywordKind visibility);
2550 
2551  // This is used for both record definitions and ObjC interface declarations.
2552  void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
2553  ArrayRef<Decl *> Fields, SourceLocation LBrac,
2554  SourceLocation RBrac, const ParsedAttributesView &AttrList);
2555 
2556  /// ActOnTagStartDefinition - Invoked when we have entered the
2557  /// scope of a tag's definition (e.g., for an enumeration, class,
2558  /// struct, or union).
2559  void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2560 
2561  /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2562  /// Differently from C++, actually parse the body and reject / error out
2563  /// in case of a structural mismatch.
2564  bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2565  SkipBodyInfo &SkipBody);
2566 
2568 
2569  /// Invoked when we enter a tag definition that we're skipping.
2570  SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2571 
2572  Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2573 
2574  /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2575  /// C++ record definition's base-specifiers clause and are starting its
2576  /// member declarations.
2577  void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2578  SourceLocation FinalLoc,
2579  bool IsFinalSpelledSealed,
2580  SourceLocation LBraceLoc);
2581 
2582  /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2583  /// the definition of a tag (enumeration, class, struct, or union).
2584  void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2585  SourceRange BraceRange);
2586 
2587  void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2588 
2589  void ActOnObjCContainerFinishDefinition();
2590 
2591  /// Invoked when we must temporarily exit the objective-c container
2592  /// scope for parsing/looking-up C constructs.
2593  ///
2594  /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2595  void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2596  void ActOnObjCReenterContainerContext(DeclContext *DC);
2597 
2598  /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2599  /// error parsing the definition of a tag.
2600  void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2601 
2602  EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2603  EnumConstantDecl *LastEnumConst,
2604  SourceLocation IdLoc,
2605  IdentifierInfo *Id,
2606  Expr *val);
2607  bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2608  bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2609  QualType EnumUnderlyingTy, bool IsFixed,
2610  const EnumDecl *Prev);
2611 
2612  /// Determine whether the body of an anonymous enumeration should be skipped.
2613  /// \param II The name of the first enumerator.
2614  SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2615  SourceLocation IILoc);
2616 
2617  Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2619  const ParsedAttributesView &Attrs,
2620  SourceLocation EqualLoc, Expr *Val);
2621  void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2622  Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
2623  const ParsedAttributesView &Attr);
2624 
2625  DeclContext *getContainingDC(DeclContext *DC);
2626 
2627  /// Set the current declaration context until it gets popped.
2628  void PushDeclContext(Scope *S, DeclContext *DC);
2629  void PopDeclContext();
2630 
2631  /// EnterDeclaratorContext - Used when we must lookup names in the context
2632  /// of a declarator's nested name specifier.
2633  void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2634  void ExitDeclaratorContext(Scope *S);
2635 
2636  /// Push the parameters of D, which must be a function, into scope.
2637  void ActOnReenterFunctionContext(Scope* S, Decl* D);
2638  void ActOnExitFunctionContext();
2639 
2640  DeclContext *getFunctionLevelDeclContext();
2641 
2642  /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2643  /// to the function decl for the function being parsed. If we're currently
2644  /// in a 'block', this returns the containing context.
2645  FunctionDecl *getCurFunctionDecl();
2646 
2647  /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2648  /// the method decl for the method being parsed. If we're currently
2649  /// in a 'block', this returns the containing context.
2650  ObjCMethodDecl *getCurMethodDecl();
2651 
2652  /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2653  /// or C function we're in, otherwise return null. If we're currently
2654  /// in a 'block', this returns the containing context.
2655  NamedDecl *getCurFunctionOrMethodDecl();
2656 
2657  /// Add this decl to the scope shadowed decl chains.
2658  void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2659 
2660  /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2661  /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2662  /// true if 'D' belongs to the given declaration context.
2663  ///
2664  /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2665  /// enclosing namespace set of the context, rather than contained
2666  /// directly within it.
2667  bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2668  bool AllowInlineNamespace = false);
2669 
2670  /// Finds the scope corresponding to the given decl context, if it
2671  /// happens to be an enclosing scope. Otherwise return NULL.
2672  static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2673 
2674  /// Subroutines of ActOnDeclarator().
2675  TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2676  TypeSourceInfo *TInfo);
2677  bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2678 
2679  /// Describes the kind of merge to perform for availability
2680  /// attributes (including "deprecated", "unavailable", and "availability").
2682  /// Don't merge availability attributes at all.
2684  /// Merge availability attributes for a redeclaration, which requires
2685  /// an exact match.
2687  /// Merge availability attributes for an override, which requires
2688  /// an exact match or a weakening of constraints.
2690  /// Merge availability attributes for an implementation of
2691  /// a protocol requirement.
2693  };
2694 
2695  /// Describes the kind of priority given to an availability attribute.
2696  ///
2697  /// The sum of priorities deteremines the final priority of the attribute.
2698  /// The final priority determines how the attribute will be merged.
2699  /// An attribute with a lower priority will always remove higher priority
2700  /// attributes for the specified platform when it is being applied. An
2701  /// attribute with a higher priority will not be applied if the declaration
2702  /// already has an availability attribute with a lower priority for the
2703  /// specified platform. The final prirority values are not expected to match
2704  /// the values in this enumeration, but instead should be treated as a plain
2705  /// integer value. This enumeration just names the priority weights that are
2706  /// used to calculate that final vaue.
2708  /// The availability attribute was specified explicitly next to the
2709  /// declaration.
2710  AP_Explicit = 0,
2711 
2712  /// The availability attribute was applied using '#pragma clang attribute'.
2713  AP_PragmaClangAttribute = 1,
2714 
2715  /// The availability attribute for a specific platform was inferred from
2716  /// an availability attribute for another platform.
2717  AP_InferredFromOtherPlatform = 2
2718  };
2719 
2720  /// Attribute merging methods. Return true if a new attribute was added.
2721  AvailabilityAttr *
2722  mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
2723  IdentifierInfo *Platform, bool Implicit,
2724  VersionTuple Introduced, VersionTuple Deprecated,
2725  VersionTuple Obsoleted, bool IsUnavailable,
2726  StringRef Message, bool IsStrict, StringRef Replacement,
2727  AvailabilityMergeKind AMK, int Priority);
2728  TypeVisibilityAttr *
2729  mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2730  TypeVisibilityAttr::VisibilityType Vis);
2731  VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2732  VisibilityAttr::VisibilityType Vis);
2733  UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
2734  StringRef Uuid);
2735  DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
2736  DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
2737  MSInheritanceAttr *
2738  mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase,
2739  MSInheritanceAttr::Spelling SemanticSpelling);
2740  FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
2741  IdentifierInfo *Format, int FormatIdx,
2742  int FirstArg);
2743  SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
2744  StringRef Name);
2745  CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
2746  StringRef Name);
2747  AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
2748  const AttributeCommonInfo &CI,
2749  const IdentifierInfo *Ident);
2750  MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
2751  NoSpeculativeLoadHardeningAttr *
2752  mergeNoSpeculativeLoadHardeningAttr(Decl *D,
2753  const NoSpeculativeLoadHardeningAttr &AL);
2754  SpeculativeLoadHardeningAttr *
2755  mergeSpeculativeLoadHardeningAttr(Decl *D,
2756  const SpeculativeLoadHardeningAttr &AL);
2757  OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
2758  const AttributeCommonInfo &CI);
2759  InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
2760  InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
2761  const InternalLinkageAttr &AL);
2762  CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
2763  CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
2764 
2765  void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2766  AvailabilityMergeKind AMK = AMK_Redeclaration);
2767  void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2768  LookupResult &OldDecls);
2769  bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2770  bool MergeTypeWithOld);
2771  bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2772  Scope *S, bool MergeTypeWithOld);
2773  void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2774  void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2775  void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2776  void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2777  bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2778  void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2779  bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2780 
2781  // AssignmentAction - This is used by all the assignment diagnostic functions
2782  // to represent what is actually causing the operation
2791  AA_Passing_CFAudited
2792  };
2793 
2794  /// C++ Overloading.
2796  /// This is a legitimate overload: the existing declarations are
2797  /// functions or function templates with different signatures.
2799 
2800  /// This is not an overload because the signature exactly matches
2801  /// an existing declaration.
2803 
2804  /// This is not an overload because the lookup results contain a
2805  /// non-function.
2806  Ovl_NonFunction
2807  };
2808  OverloadKind CheckOverload(Scope *S,
2809  FunctionDecl *New,
2810  const LookupResult &OldDecls,
2811  NamedDecl *&OldDecl,
2812  bool IsForUsingDecl);
2813  bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2814  bool ConsiderCudaAttrs = true);
2815 
2817  TryImplicitConversion(Expr *From, QualType ToType,
2818  bool SuppressUserConversions,
2819  bool AllowExplicit,
2820  bool InOverloadResolution,
2821  bool CStyle,
2822  bool AllowObjCWritebackConversion);
2823 
2824  bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2825  bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2826  bool IsComplexPromotion(QualType FromType, QualType ToType);
2827  bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2828  bool InOverloadResolution,
2829  QualType& ConvertedType, bool &IncompatibleObjC);
2830  bool isObjCPointerConversion(QualType FromType, QualType ToType,
2831  QualType& ConvertedType, bool &IncompatibleObjC);
2832  bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2833  QualType &ConvertedType);
2834  bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2835  QualType& ConvertedType);
2836  bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2837  const FunctionProtoType *NewType,
2838  unsigned *ArgPos = nullptr);
2839  void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2840  QualType FromType, QualType ToType);
2841 
2842  void maybeExtendBlockObject(ExprResult &E);
2843  CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2844  bool CheckPointerConversion(Expr *From, QualType ToType,
2845  CastKind &Kind,
2846  CXXCastPath& BasePath,
2847  bool IgnoreBaseAccess,
2848  bool Diagnose = true);
2849  bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2850  bool InOverloadResolution,
2851  QualType &ConvertedType);
2852  bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2853  CastKind &Kind,
2854  CXXCastPath &BasePath,
2855  bool IgnoreBaseAccess);
2856  bool IsQualificationConversion(QualType FromType, QualType ToType,
2857  bool CStyle, bool &ObjCLifetimeConversion);
2858  bool IsFunctionConversion(QualType FromType, QualType ToType,
2859  QualType &ResultTy);
2860  bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2861  bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2862 
2863  ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2864  const VarDecl *NRVOCandidate,
2865  QualType ResultType,
2866  Expr *Value,
2867  bool AllowNRVO = true);
2868 
2869  bool CanPerformAggregateInitializationForOverloadResolution(
2870  const InitializedEntity &Entity, InitListExpr *From);
2871 
2872  bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2873  ExprResult Init);
2874  ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2875  SourceLocation EqualLoc,
2876  ExprResult Init,
2877  bool TopLevelOfInitList = false,
2878  bool AllowExplicit = false);
2879  ExprResult PerformObjectArgumentInitialization(Expr *From,
2880  NestedNameSpecifier *Qualifier,
2881  NamedDecl *FoundDecl,
2882  CXXMethodDecl *Method);
2883 
2884  /// Check that the lifetime of the initializer (and its subobjects) is
2885  /// sufficient for initializing the entity, and perform lifetime extension
2886  /// (when permitted) if not.
2887  void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
2888 
2889  ExprResult PerformContextuallyConvertToBool(Expr *From);
2890  ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2891 
2892  /// Contexts in which a converted constant expression is required.
2893  enum CCEKind {
2894  CCEK_CaseValue, ///< Expression in a case label.
2895  CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2896  CCEK_TemplateArg, ///< Value of a non-type template parameter.
2897  CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2898  CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
2899  CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
2900  };
2902  llvm::APSInt &Value, CCEKind CCE);
2904  APValue &Value, CCEKind CCE);
2905 
2906  /// Abstract base class used to perform a contextual implicit
2907  /// conversion from an expression to any type passing a filter.
2909  public:
2910  bool Suppress;
2912 
2913  ContextualImplicitConverter(bool Suppress = false,
2914  bool SuppressConversion = false)
2915  : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2916 
2917  /// Determine whether the specified type is a valid destination type
2918  /// for this conversion.
2919  virtual bool match(QualType T) = 0;
2920 
2921  /// Emits a diagnostic complaining that the expression does not have
2922  /// integral or enumeration type.
2923  virtual SemaDiagnosticBuilder
2924  diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2925 
2926  /// Emits a diagnostic when the expression has incomplete class type.
2927  virtual SemaDiagnosticBuilder
2928  diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2929 
2930  /// Emits a diagnostic when the only matching conversion function
2931  /// is explicit.
2932  virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2933  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2934 
2935  /// Emits a note for the explicit conversion function.
2936  virtual SemaDiagnosticBuilder
2937  noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2938 
2939  /// Emits a diagnostic when there are multiple possible conversion
2940  /// functions.
2941  virtual SemaDiagnosticBuilder
2942  diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2943 
2944  /// Emits a note for one of the candidate conversions.
2945  virtual SemaDiagnosticBuilder
2946  noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2947 
2948  /// Emits a diagnostic when we picked a conversion function
2949  /// (for cases when we are not allowed to pick a conversion function).
2950  virtual SemaDiagnosticBuilder diagnoseConversion(
2951  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2952 
2954  };
2955 
2957  bool AllowScopedEnumerations;
2958 
2959  public:
2960  ICEConvertDiagnoser(bool AllowScopedEnumerations,
2961  bool Suppress, bool SuppressConversion)
2962  : ContextualImplicitConverter(Suppress, SuppressConversion),
2963  AllowScopedEnumerations(AllowScopedEnumerations) {}
2964 
2965  /// Match an integral or (possibly scoped) enumeration type.
2966  bool match(QualType T) override;
2967 
2970  return diagnoseNotInt(S, Loc, T);
2971  }
2972 
2973  /// Emits a diagnostic complaining that the expression does not have
2974  /// integral or enumeration type.
2975  virtual SemaDiagnosticBuilder
2976  diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2977  };
2978 
2979  /// Perform a contextual implicit conversion.
2980  ExprResult PerformContextualImplicitConversion(
2981  SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2982 
2983 
2987  OS_Error
2988  };
2989  ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2990 
2991  // Note that LK_String is intentionally after the other literals, as
2992  // this is used for diagnostics logic.
3000  LK_None
3001  };
3002  ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3003 
3004  ExprResult PerformObjectMemberConversion(Expr *From,
3005  NestedNameSpecifier *Qualifier,
3006  NamedDecl *FoundDecl,
3007  NamedDecl *Member);
3008 
3009  // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3010  // TODO: make this is a typesafe union.
3013 
3015 
3016  void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3017  ArrayRef<Expr *> Args,
3018  OverloadCandidateSet &CandidateSet,
3019  bool SuppressUserConversions = false,
3020  bool PartialOverloading = false,
3021  bool AllowExplicit = true,
3022  bool AllowExplicitConversion = false,
3023  ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3024  ConversionSequenceList EarlyConversions = None,
3025  OverloadCandidateParamOrder PO = {});
3026  void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3027  ArrayRef<Expr *> Args,
3028  OverloadCandidateSet &CandidateSet,
3029  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3030  bool SuppressUserConversions = false,
3031  bool PartialOverloading = false,
3032  bool FirstArgumentIsBase = false);
3033  void AddMethodCandidate(DeclAccessPair FoundDecl,
3034  QualType ObjectType,
3035  Expr::Classification ObjectClassification,
3036  ArrayRef<Expr *> Args,
3037  OverloadCandidateSet& CandidateSet,
3038  bool SuppressUserConversion = false,
3039  OverloadCandidateParamOrder PO = {});
3040  void AddMethodCandidate(CXXMethodDecl *Method,
3041  DeclAccessPair FoundDecl,
3042  CXXRecordDecl *ActingContext, QualType ObjectType,
3043  Expr::Classification ObjectClassification,
3044  ArrayRef<Expr *> Args,
3045  OverloadCandidateSet& CandidateSet,
3046  bool SuppressUserConversions = false,
3047  bool PartialOverloading = false,
3048  ConversionSequenceList EarlyConversions = None,
3049  OverloadCandidateParamOrder PO = {});
3050  void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3051  DeclAccessPair FoundDecl,
3052  CXXRecordDecl *ActingContext,
3053  TemplateArgumentListInfo *ExplicitTemplateArgs,
3054  QualType ObjectType,
3055  Expr::Classification ObjectClassification,
3056  ArrayRef<Expr *> Args,
3057  OverloadCandidateSet& CandidateSet,
3058  bool SuppressUserConversions = false,
3059  bool PartialOverloading = false,
3060  OverloadCandidateParamOrder PO = {});
3061  void AddTemplateOverloadCandidate(
3062  FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3063  TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3064  OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3065  bool PartialOverloading = false, bool AllowExplicit = true,
3066  ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3067  OverloadCandidateParamOrder PO = {});
3068  bool CheckNonDependentConversions(
3069  FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3070  ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3071  ConversionSequenceList &Conversions, bool SuppressUserConversions,
3072  CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3073  Expr::Classification ObjectClassification = {},
3074  OverloadCandidateParamOrder PO = {});
3075  void AddConversionCandidate(
3076  CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3077  CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3078  OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3079  bool AllowExplicit, bool AllowResultConversion = true);
3080  void AddTemplateConversionCandidate(
3081  FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3082  CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3083  OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3084  bool AllowExplicit, bool AllowResultConversion = true);
3085  void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3086  DeclAccessPair FoundDecl,
3087  CXXRecordDecl *ActingContext,
3088  const FunctionProtoType *Proto,
3089  Expr *Object, ArrayRef<Expr *> Args,
3090  OverloadCandidateSet& CandidateSet);
3091  void AddNonMemberOperatorCandidates(
3092  const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3093  OverloadCandidateSet &CandidateSet,
3094  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3095  void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3096  SourceLocation OpLoc, ArrayRef<Expr *> Args,
3097  OverloadCandidateSet &CandidateSet,
3098  OverloadCandidateParamOrder PO = {});
3099  void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3100  OverloadCandidateSet& CandidateSet,
3101  bool IsAssignmentOperator = false,
3102  unsigned NumContextualBoolArguments = 0);
3103  void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3104  SourceLocation OpLoc, ArrayRef<Expr *> Args,
3105  OverloadCandidateSet& CandidateSet);
3106  void AddArgumentDependentLookupCandidates(DeclarationName Name,
3107  SourceLocation Loc,
3108  ArrayRef<Expr *> Args,
3109  TemplateArgumentListInfo *ExplicitTemplateArgs,
3110  OverloadCandidateSet& CandidateSet,
3111  bool PartialOverloading = false);
3112 
3113  // Emit as a 'note' the specific overload candidate
3114  void NoteOverloadCandidate(
3115  NamedDecl *Found, FunctionDecl *Fn,
3117  QualType DestType = QualType(), bool TakingAddress = false);
3118 
3119  // Emit as a series of 'note's all template and non-templates identified by
3120  // the expression Expr
3121  void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3122  bool TakingAddress = false);
3123 
3124  /// Check the enable_if expressions on the given function. Returns the first
3125  /// failing attribute, or NULL if they were all successful.
3126  EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
3127  bool MissingImplicitThis = false);
3128 
3129  /// Find the failed Boolean condition within a given Boolean
3130  /// constant expression, and describe it with a string.
3131  std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3132 
3133  /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3134  /// non-ArgDependent DiagnoseIfAttrs.
3135  ///
3136  /// Argument-dependent diagnose_if attributes should be checked each time a
3137  /// function is used as a direct callee of a function call.
3138  ///
3139  /// Returns true if any errors were emitted.
3140  bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3141  const Expr *ThisArg,
3143  SourceLocation Loc);
3144 
3145  /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3146  /// ArgDependent DiagnoseIfAttrs.
3147  ///
3148  /// Argument-independent diagnose_if attributes should be checked on every use
3149  /// of a function.
3150  ///
3151  /// Returns true if any errors were emitted.
3152  bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3153  SourceLocation Loc);
3154 
3155  /// Returns whether the given function's address can be taken or not,
3156  /// optionally emitting a diagnostic if the address can't be taken.
3157  ///
3158  /// Returns false if taking the address of the function is illegal.
3159  bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3160  bool Complain = false,
3161  SourceLocation Loc = SourceLocation());
3162 
3163  // [PossiblyAFunctionType] --> [Return]
3164  // NonFunctionType --> NonFunctionType
3165  // R (A) --> R(A)
3166  // R (*)(A) --> R (A)
3167  // R (&)(A) --> R (A)
3168  // R (S::*)(A) --> R (A)
3169  QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3170 
3171  FunctionDecl *
3172  ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3173  QualType TargetType,
3174  bool Complain,
3175  DeclAccessPair &Found,
3176  bool *pHadMultipleCandidates = nullptr);
3177 
3178  FunctionDecl *
3179  resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
3180  DeclAccessPair &FoundResult);
3181 
3182  bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
3183  ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3184 
3185  FunctionDecl *
3186  ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3187  bool Complain = false,
3188  DeclAccessPair *Found = nullptr);
3189 
3190  bool ResolveAndFixSingleFunctionTemplateSpecialization(
3191  ExprResult &SrcExpr,
3192  bool DoFunctionPointerConverion = false,
3193  bool Complain = false,
3194  SourceRange OpRangeForComplaining = SourceRange(),
3195  QualType DestTypeForComplaining = QualType(),
3196  unsigned DiagIDForComplaining = 0);
3197 
3198 
3199  Expr *FixOverloadedFunctionReference(Expr *E,
3200  DeclAccessPair FoundDecl,
3201  FunctionDecl *Fn);
3202  ExprResult FixOverloadedFunctionReference(ExprResult,
3203  DeclAccessPair FoundDecl,
3204  FunctionDecl *Fn);
3205 
3206  void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3207  ArrayRef<Expr *> Args,
3208  OverloadCandidateSet &CandidateSet,
3209  bool PartialOverloading = false);
3210 
3211  // An enum used to represent the different possible results of building a
3212  // range-based for loop.
3216  FRS_DiagnosticIssued
3217  };
3218 
3219  ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3220  SourceLocation RangeLoc,
3221  const DeclarationNameInfo &NameInfo,
3222  LookupResult &MemberLookup,
3223  OverloadCandidateSet *CandidateSet,
3224  Expr *Range, ExprResult *CallExpr);
3225 
3226  ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3227  UnresolvedLookupExpr *ULE,
3228  SourceLocation LParenLoc,
3229  MultiExprArg Args,
3230  SourceLocation RParenLoc,
3231  Expr *ExecConfig,
3232  bool AllowTypoCorrection=true,
3233  bool CalleesAddressIsTaken=false);
3234 
3235  bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3236  MultiExprArg Args, SourceLocation RParenLoc,
3237  OverloadCandidateSet *CandidateSet,
3238  ExprResult *Result);
3239 
3240  ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
3241  UnaryOperatorKind Opc,
3242  const UnresolvedSetImpl &Fns,
3243  Expr *input, bool RequiresADL = true);
3244 
3245  ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
3246  BinaryOperatorKind Opc,
3247  const UnresolvedSetImpl &Fns,
3248  Expr *LHS, Expr *RHS,
3249  bool RequiresADL = true,
3250  bool AllowRewrittenCandidates = true);
3251 
3252  ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
3253  SourceLocation RLoc,
3254  Expr *Base,Expr *Idx);
3255 
3256  ExprResult
3257  BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
3258  SourceLocation LParenLoc,
3259  MultiExprArg Args,
3260  SourceLocation RParenLoc);
3261  ExprResult
3262  BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3263  MultiExprArg Args,
3264  SourceLocation RParenLoc);
3265 
3266  ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
3267  SourceLocation OpLoc,
3268  bool *NoArrowOperatorFound = nullptr);
3269 
3270  /// CheckCallReturnType - Checks that a call expression's return type is
3271  /// complete. Returns true on failure. The location passed in is the location
3272  /// that best represents the call.
3273  bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3274  CallExpr *CE, FunctionDecl *FD);
3275 
3276  /// Helpers for dealing with blocks and functions.
3277  bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
3278  bool CheckParameterNames);
3279  void CheckCXXDefaultArguments(FunctionDecl *FD);
3280  void CheckExtraCXXDefaultArguments(Declarator &D);
3281  Scope *getNonFieldDeclScope(Scope *S);
3282 
3283  /// \name Name lookup
3284  ///
3285  /// These routines provide name lookup that is used during semantic
3286  /// analysis to resolve the various kinds of names (identifiers,
3287  /// overloaded operator names, constructor names, etc.) into zero or
3288  /// more declarations within a particular scope. The major entry
3289  /// points are LookupName, which performs unqualified name lookup,
3290  /// and LookupQualifiedName, which performs qualified name lookup.
3291  ///
3292  /// All name lookup is performed based on some specific criteria,
3293  /// which specify what names will be visible to name lookup and how
3294  /// far name lookup should work. These criteria are important both
3295  /// for capturing language semantics (certain lookups will ignore
3296  /// certain names, for example) and for performance, since name
3297  /// lookup is often a bottleneck in the compilation of C++. Name
3298  /// lookup criteria is specified via the LookupCriteria enumeration.
3299  ///
3300  /// The results of name lookup can vary based on the kind of name
3301  /// lookup performed, the current language, and the translation
3302  /// unit. In C, for example, name lookup will either return nothing
3303  /// (no entity found) or a single declaration. In C++, name lookup
3304  /// can additionally refer to a set of overloaded functions or
3305  /// result in an ambiguity. All of the possible results of name
3306  /// lookup are captured by the LookupResult class, which provides
3307  /// the ability to distinguish among them.
3308  //@{
3309 
3310  /// Describes the kind of name lookup to perform.
3312  /// Ordinary name lookup, which finds ordinary names (functions,
3313  /// variables, typedefs, etc.) in C and most kinds of names
3314  /// (functions, variables, members, types, etc.) in C++.
3315  LookupOrdinaryName = 0,
3316  /// Tag name lookup, which finds the names of enums, classes,
3317  /// structs, and unions.
3319  /// Label name lookup.
3321  /// Member name lookup, which finds the names of
3322  /// class/struct/union members.
3324  /// Look up of an operator name (e.g., operator+) for use with
3325  /// operator overloading. This lookup is similar to ordinary name
3326  /// lookup, but will ignore any declarations that are class members.
3328  /// Look up of a name that precedes the '::' scope resolution
3329  /// operator in C++. This lookup completely ignores operator, object,
3330  /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3332  /// Look up a namespace name within a C++ using directive or
3333  /// namespace alias definition, ignoring non-namespace names (C++
3334  /// [basic.lookup.udir]p1).
3336  /// Look up all declarations in a scope with the given name,
3337  /// including resolved using declarations. This is appropriate
3338  /// for checking redeclarations for a using declaration.
3340  /// Look up an ordinary name that is going to be redeclared as a
3341  /// name with linkage. This lookup ignores any declarations that
3342  /// are outside of the current scope unless they have linkage. See
3343  /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3345  /// Look up a friend of a local class. This lookup does not look
3346  /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3348  /// Look up the name of an Objective-C protocol.
3350  /// Look up implicit 'self' parameter of an objective-c method.
3352  /// Look up the name of an OpenMP user-defined reduction operation.
3354  /// Look up the name of an OpenMP user-defined mapper.
3356  /// Look up any declaration with any name.
3357  LookupAnyName
3358  };
3359 
3360  /// Specifies whether (or how) name lookup is being performed for a
3361  /// redeclaration (vs. a reference).
3363  /// The lookup is a reference to this name that is not for the
3364  /// purpose of redeclaring the name.
3365  NotForRedeclaration = 0,
3366  /// The lookup results will be used for redeclaration of a name,
3367  /// if an entity by that name already exists and is visible.
3369  /// The lookup results will be used for redeclaration of a name
3370  /// with external linkage; non-visible lookup results with external linkage
3371  /// may also be found.
3372  ForExternalRedeclaration
3373  };
3374 
3376  // A declaration with an owning module for linkage can never link against
3377  // anything that is not visible. We don't need to check linkage here; if
3378  // the context has internal linkage, redeclaration lookup won't find things
3379  // from other TUs, and we can't safely compute linkage yet in general.
3380  if (cast<Decl>(CurContext)
3381  ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3382  return ForVisibleRedeclaration;
3383  return ForExternalRedeclaration;
3384  }
3385 
3386  /// The possible outcomes of name lookup for a literal operator.
3388  /// The lookup resulted in an error.
3390  /// The lookup found no match but no diagnostic was issued.
3392  /// The lookup found a single 'cooked' literal operator, which
3393  /// expects a normal literal to be built and passed to it.
3395  /// The lookup found a single 'raw' literal operator, which expects
3396  /// a string literal containing the spelling of the literal token.
3398  /// The lookup found an overload set of literal operator templates,
3399  /// which expect the characters of the spelling of the literal token to be
3400  /// passed as a non-type template argument pack.
3402  /// The lookup found an overload set of literal operator templates,
3403  /// which expect the character type and characters of the spelling of the
3404  /// string literal token to be passed as template arguments.
3405  LOLR_StringTemplate
3406  };
3407 
3408  SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3410  bool ConstArg,
3411  bool VolatileArg,
3412  bool RValueThis,
3413  bool ConstThis,
3414  bool VolatileThis);
3415 
3416  typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3417  typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3419 
3420 private:
3421  bool CppLookupName(LookupResult &R, Scope *S);
3422 
3423  struct TypoExprState {
3424  std::unique_ptr<TypoCorrectionConsumer> Consumer;
3425  TypoDiagnosticGenerator DiagHandler;
3426  TypoRecoveryCallback RecoveryHandler;
3427  TypoExprState();
3428  TypoExprState(TypoExprState &&other) noexcept;
3429  TypoExprState &operator=(TypoExprState &&other) noexcept;
3430  };
3431 
3432  /// The set of unhandled TypoExprs and their associated state.
3433  llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3434 
3435  /// Creates a new TypoExpr AST node.
3436  TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3437  TypoDiagnosticGenerator TDG,
3438  TypoRecoveryCallback TRC);
3439 
3440  // The set of known/encountered (unique, canonicalized) NamespaceDecls.
3441  //
3442  // The boolean value will be true to indicate that the namespace was loaded
3443  // from an AST/PCH file, or false otherwise.
3444  llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3445 
3446  /// Whether we have already loaded known namespaces from an extenal
3447  /// source.
3448  bool LoadedExternalKnownNamespaces;
3449 
3450  /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
3451  /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3452  /// should be skipped entirely.
3453  std::unique_ptr<TypoCorrectionConsumer>
3454  makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3455  Sema::LookupNameKind LookupKind, Scope *S,
3456  CXXScopeSpec *SS,
3458  DeclContext *MemberContext, bool EnteringContext,
3459  const ObjCObjectPointerType *OPT,
3460  bool ErrorRecovery);
3461 
3462 public:
3463  const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3464 
3465  /// Clears the state of the given TypoExpr.
3466  void clearDelayedTypo(TypoExpr *TE);
3467 
3468  /// Look up a name, looking for a single declaration. Return
3469  /// null if the results were absent, ambiguous, or overloaded.
3470  ///
3471  /// It is preferable to use the elaborated form and explicitly handle
3472  /// ambiguity and overloaded.
3473  NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3474  SourceLocation Loc,
3475  LookupNameKind NameKind,
3476  RedeclarationKind Redecl
3477  = NotForRedeclaration);
3478  bool LookupBuiltin(LookupResult &R);
3479  bool LookupName(LookupResult &R, Scope *S,
3480  bool AllowBuiltinCreation = false);
3481  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3482  bool InUnqualifiedLookup = false);
3483  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3484  CXXScopeSpec &SS);
3485  bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3486  bool AllowBuiltinCreation = false,
3487  bool EnteringContext = false);
3488  ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3489  RedeclarationKind Redecl
3490  = NotForRedeclaration);
3491  bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3492 
3493  void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3494  QualType T1, QualType T2,
3495  UnresolvedSetImpl &Functions);
3496 
3497  LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3498  SourceLocation GnuLabelLoc = SourceLocation());
3499 
3500  DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3501  CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3502  CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3503  unsigned Quals);
3504  CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3505  bool RValueThis, unsigned ThisQuals);
3506  CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3507  unsigned Quals);
3508  CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3509  bool RValueThis, unsigned ThisQuals);
3510  CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3511 
3512  bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3513  LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3514  ArrayRef<QualType> ArgTys,
3515  bool AllowRaw,
3516  bool AllowTemplate,
3517  bool AllowStringTemplate,
3518  bool DiagnoseMissing);
3519  bool isKnownName(StringRef name);
3520 
3521  /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
3523  Emitted,
3524  CUDADiscarded, // Discarded due to CUDA/HIP hostness
3525  OMPDiscarded, // Discarded due to OpenMP hostness
3526  TemplateDiscarded, // Discarded due to uninstantiated templates
3527  Unknown,
3528  };
3529  FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl);
3530 
3531  // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
3532  bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
3533 
3534  void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3535  ArrayRef<Expr *> Args, ADLResult &Functions);
3536 
3537  void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3538  VisibleDeclConsumer &Consumer,
3539  bool IncludeGlobalScope = true,
3540  bool LoadExternal = true);
3541  void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3542  VisibleDeclConsumer &Consumer,
3543  bool IncludeGlobalScope = true,
3544  bool IncludeDependentBases = false,
3545  bool LoadExternal = true);
3546 
3548  CTK_NonError, // CorrectTypo used in a non error recovery situation.
3549  CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3550  };
3551 
3552  TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3553  Sema::LookupNameKind LookupKind,
3554  Scope *S, CXXScopeSpec *SS,
3556  CorrectTypoKind Mode,
3557  DeclContext *MemberContext = nullptr,
3558  bool EnteringContext = false,
3559  const ObjCObjectPointerType *OPT = nullptr,
3560  bool RecordFailure = true);
3561 
3562  TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3563  Sema::LookupNameKind LookupKind, Scope *S,
3564  CXXScopeSpec *SS,
3566  TypoDiagnosticGenerator TDG,
3568  DeclContext *MemberContext = nullptr,
3569  bool EnteringContext = false,
3570  const ObjCObjectPointerType *OPT = nullptr);
3571 
3572  /// Process any TypoExprs in the given Expr and its children,
3573  /// generating diagnostics as appropriate and returning a new Expr if there
3574  /// were typos that were all successfully corrected and ExprError if one or
3575  /// more typos could not be corrected.
3576  ///
3577  /// \param E The Expr to check for TypoExprs.
3578  ///
3579  /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3580  /// initializer.
3581  ///
3582  /// \param Filter A function applied to a newly rebuilt Expr to determine if
3583  /// it is an acceptable/usable result from a single combination of typo
3584  /// corrections. As long as the filter returns ExprError, different
3585  /// combinations of corrections will be tried until all are exhausted.
3586  ExprResult
3587  CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3588  llvm::function_ref<ExprResult(Expr *)> Filter =
3589  [](Expr *E) -> ExprResult { return E; });
3590 
3591  ExprResult
3593  llvm::function_ref<ExprResult(Expr *)> Filter) {
3594  return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3595  }
3596 
3597  ExprResult
3598  CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3599  llvm::function_ref<ExprResult(Expr *)> Filter =
3600  [](Expr *E) -> ExprResult { return E; }) {
3601  return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3602  }
3603 
3604  ExprResult
3606  llvm::function_ref<ExprResult(Expr *)> Filter) {
3607  return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3608  }
3609 
3610  void diagnoseTypo(const TypoCorrection &Correction,
3611  const PartialDiagnostic &TypoDiag,
3612  bool ErrorRecovery = true);
3613 
3614  void diagnoseTypo(const TypoCorrection &Correction,
3615  const PartialDiagnostic &TypoDiag,
3616  const PartialDiagnostic &PrevNote,
3617  bool ErrorRecovery = true);
3618 
3619  void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3620 
3621  void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3622  ArrayRef<Expr *> Args,
3623  AssociatedNamespaceSet &AssociatedNamespaces,
3624  AssociatedClassSet &AssociatedClasses);
3625 
3626  void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3627  bool ConsiderLinkage, bool AllowInlineNamespace);
3628 
3629  bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3630 
3631  void DiagnoseAmbiguousLookup(LookupResult &Result);
3632  //@}
3633 
3634  ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3635  SourceLocation IdLoc,
3636  bool TypoCorrection = false);
3637  NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3638  Scope *S, bool ForRedeclaration,
3639  SourceLocation Loc);
3640  NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3641  Scope *S);
3642  void AddKnownFunctionAttributes(FunctionDecl *FD);
3643 
3644  // More parsing and symbol table subroutines.
3645 
3646  void ProcessPragmaWeak(Scope *S, Decl *D);
3647  // Decl attributes - this routine is the top level dispatcher.
3648  void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3649  // Helper for delayed processing of attributes.
3650  void ProcessDeclAttributeDelayed(Decl *D,
3651  const ParsedAttributesView &AttrList);
3652  void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
3653  bool IncludeCXX11Attributes = true);
3654  bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3655  const ParsedAttributesView &AttrList);
3656 
3657  void checkUnusedDeclAttributes(Declarator &D);
3658 
3659  /// Determine if type T is a valid subject for a nonnull and similar
3660  /// attributes. By default, we look through references (the behavior used by
3661  /// nonnull), but if the second parameter is true, then we treat a reference
3662  /// type as valid.
3663  bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3664 
3665  bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
3666  bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
3667  const FunctionDecl *FD = nullptr);
3668  bool CheckAttrTarget(const ParsedAttr &CurrAttr);
3669  bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
3670  bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
3671  StringRef &Str,
3672  SourceLocation *ArgLocation = nullptr);
3673  bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3674  bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3675  bool checkMSInheritanceAttrOnDefinition(
3676  CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3677  MSInheritanceAttr::Spelling SemanticSpelling);
3678 
3679  void CheckAlignasUnderalignment(Decl *D);
3680 
3681  /// Adjust the calling convention of a method to be the ABI default if it
3682  /// wasn't specified explicitly. This handles method types formed from
3683  /// function type typedefs and typename template arguments.
3684  void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3685  SourceLocation Loc);
3686 
3687  // Check if there is an explicit attribute, but only look through parens.
3688  // The intent is to look for an attribute on the current declarator, but not
3689  // one that came from a typedef.
3690  bool hasExplicitCallingConv(QualType T);
3691 
3692  /// Get the outermost AttributedType node that sets a calling convention.
3693  /// Valid types should not have multiple attributes with different CCs.
3694  const AttributedType *getCallingConvAttributedType(QualType T) const;
3695 
3696  /// Stmt attributes - this routine is the top level dispatcher.
3697  StmtResult ProcessStmtAttributes(Stmt *Stmt,
3698  const ParsedAttributesView &Attrs,
3699  SourceRange Range);
3700 
3701  void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3702  ObjCMethodDecl *MethodDecl,
3703  bool IsProtocolMethodDecl);
3704 
3705  void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3706  ObjCMethodDecl *Overridden,
3707  bool IsProtocolMethodDecl);
3708 
3709  /// WarnExactTypedMethods - This routine issues a warning if method
3710  /// implementation declaration matches exactly that of its declaration.
3711  void WarnExactTypedMethods(ObjCMethodDecl *Method,
3712  ObjCMethodDecl *MethodDecl,
3713  bool IsProtocolMethodDecl);
3714 
3715  typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3716 
3717  /// CheckImplementationIvars - This routine checks if the instance variables
3718  /// listed in the implelementation match those listed in the interface.
3719  void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3720  ObjCIvarDecl **Fields, unsigned nIvars,
3721  SourceLocation Loc);
3722 
3723  /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3724  /// remains unimplemented in the class or category \@implementation.
3725  void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3726  ObjCContainerDecl* IDecl,
3727  bool IncompleteImpl = false);
3728 
3729  /// DiagnoseUnimplementedProperties - This routine warns on those properties
3730  /// which must be implemented by this implementation.
3731  void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3732  ObjCContainerDecl *CDecl,
3733  bool SynthesizeProperties);
3734 
3735  /// Diagnose any null-resettable synthesized setters.
3736  void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3737 
3738  /// DefaultSynthesizeProperties - This routine default synthesizes all
3739  /// properties which must be synthesized in the class's \@implementation.
3740  void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
3741  ObjCInterfaceDecl *IDecl,
3742  SourceLocation AtEnd);
3743  void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
3744 
3745  /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3746  /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3747  /// declared in class 'IFace'.
3748  bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3749  ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3750 
3751  /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3752  /// backs the property is not used in the property's accessor.
3753  void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3754  const ObjCImplementationDecl *ImplD);
3755 
3756  /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3757  /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3758  /// It also returns ivar's property on success.
3759  ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3760  const ObjCPropertyDecl *&PDecl) const;
3761 
3762  /// Called by ActOnProperty to handle \@property declarations in
3763  /// class extensions.
3764  ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3765  SourceLocation AtLoc,
3766  SourceLocation LParenLoc,
3767  FieldDeclarator &FD,
3768  Selector GetterSel,
3769  SourceLocation GetterNameLoc,
3770  Selector SetterSel,
3771  SourceLocation SetterNameLoc,
3772  const bool isReadWrite,
3773  unsigned &Attributes,
3774  const unsigned AttributesAsWritten,
3775  QualType T,
3776  TypeSourceInfo *TSI,
3777  tok::ObjCKeywordKind MethodImplKind);
3778 
3779  /// Called by ActOnProperty and HandlePropertyInClassExtension to
3780  /// handle creating the ObjcPropertyDecl for a category or \@interface.
3781  ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3782  ObjCContainerDecl *CDecl,
3783  SourceLocation AtLoc,
3784  SourceLocation LParenLoc,
3785  FieldDeclarator &FD,
3786  Selector GetterSel,
3787  SourceLocation GetterNameLoc,
3788  Selector SetterSel,
3789  SourceLocation SetterNameLoc,
3790  const bool isReadWrite,
3791  const unsigned Attributes,
3792  const unsigned AttributesAsWritten,
3793  QualType T,
3794  TypeSourceInfo *TSI,
3795  tok::ObjCKeywordKind MethodImplKind,
3796  DeclContext *lexicalDC = nullptr);
3797 
3798  /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3799  /// warning) when atomic property has one but not the other user-declared
3800  /// setter or getter.
3801  void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3802  ObjCInterfaceDecl* IDecl);
3803 
3804  void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3805 
3806  void DiagnoseMissingDesignatedInitOverrides(
3807  const ObjCImplementationDecl *ImplD,
3808  const ObjCInterfaceDecl *IFD);
3809 
3810  void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3811 
3814  MMS_strict
3815  };
3816 
3817  /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3818  /// true, or false, accordingly.
3819  bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3820  const ObjCMethodDecl *PrevMethod,
3821  MethodMatchStrategy strategy = MMS_strict);
3822 
3823  /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3824  /// or protocol against those declared in their implementations.
3825  void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3826  const SelectorSet &ClsMap,
3827  SelectorSet &InsMapSeen,
3828  SelectorSet &ClsMapSeen,
3829  ObjCImplDecl* IMPDecl,
3830  ObjCContainerDecl* IDecl,
3831  bool &IncompleteImpl,
3832  bool ImmediateClass,
3833  bool WarnCategoryMethodImpl=false);
3834 
3835  /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3836  /// category matches with those implemented in its primary class and
3837  /// warns each time an exact match is found.
3838  void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3839 
3840  /// Add the given method to the list of globally-known methods.
3841  void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3842 
3843 private:
3844  /// AddMethodToGlobalPool - Add an instance or factory method to the global
3845  /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3846  void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3847 
3848  /// LookupMethodInGlobalPool - Returns the instance or factory method and
3849  /// optionally warns if there are multiple signatures.
3850  ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3851  bool receiverIdOrClass,
3852  bool instance);
3853 
3854 public:
3855  /// - Returns instance or factory methods in global method pool for
3856  /// given selector. It checks the desired kind first, if none is found, and
3857  /// parameter checkTheOther is set, it then checks the other kind. If no such
3858  /// method or only one method is found, function returns false; otherwise, it
3859  /// returns true.
3860  bool
3861  CollectMultipleMethodsInGlobalPool(Selector Sel,
3863  bool InstanceFirst, bool CheckTheOther,
3864  const ObjCObjectType *TypeBound = nullptr);
3865 
3866  bool
3867  AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3868  SourceRange R, bool receiverIdOrClass,
3870 
3871  void
3872  DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3873  Selector Sel, SourceRange R,
3874  bool receiverIdOrClass);
3875 
3876 private:
3877  /// - Returns a selector which best matches given argument list or
3878  /// nullptr if none could be found
3879  ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3880  bool IsInstance,
3882 
3883 
3884  /// Record the typo correction failure and return an empty correction.
3885  TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3886  bool RecordFailure = true) {
3887  if (RecordFailure)
3888  TypoCorrectionFailures[Typo].insert(TypoLoc);
3889  return TypoCorrection();
3890  }
3891 
3892 public:
3893  /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3894  /// unit are added to a global pool. This allows us to efficiently associate
3895  /// a selector with a method declaraation for purposes of typechecking
3896  /// messages sent to "id" (where the class of the object is unknown).
3897  void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3898  AddMethodToGlobalPool(Method, impl, /*instance*/true);
3899  }
3900 
3901  /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3902  void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3903  AddMethodToGlobalPool(Method, impl, /*instance*/false);
3904  }
3905 
3906  /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3907  /// pool.
3908  void AddAnyMethodToGlobalPool(Decl *D);
3909 
3910  /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3911  /// there are multiple signatures.
3913  bool receiverIdOrClass=false) {
3914  return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3915  /*instance*/true);
3916  }
3917 
3918  /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3919  /// there are multiple signatures.
3921  bool receiverIdOrClass=false) {
3922  return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3923  /*instance*/false);
3924  }
3925 
3926  const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3927  QualType ObjectType=QualType());
3928  /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3929  /// implementation.
3930  ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3931 
3932  /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3933  /// initialization.
3934  void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3936 
3937  //===--------------------------------------------------------------------===//
3938  // Statement Parsing Callbacks: SemaStmt.cpp.
3939 public:
3940  class FullExprArg {
3941  public:
3942  FullExprArg() : E(nullptr) { }
3943  FullExprArg(Sema &actions) : E(nullptr) { }
3944 
3946  return E;
3947  }
3948 
3949  Expr *get() const { return E; }
3950 
3952  return E;
3953  }
3954 
3955  private:
3956  // FIXME: No need to make the entire Sema class a friend when it's just
3957  // Sema::MakeFullExpr that needs access to the constructor below.
3958  friend class Sema;
3959 
3960  explicit FullExprArg(Expr *expr) : E(expr) {}
3961 
3962  Expr *E;
3963  };
3964 
3966  return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3967  }
3969  return FullExprArg(
3970  ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
3971  }
3973  ExprResult FE =
3974  ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3975  /*DiscardedValue*/ true);
3976  return FullExprArg(FE.get());
3977  }
3978 
3979  StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
3980  StmtResult ActOnExprStmtError();
3981 
3982  StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3983  bool HasLeadingEmptyMacro = false);
3984 
3985  void ActOnStartOfCompoundStmt(bool IsStmtExpr);
3986  void ActOnFinishOfCompoundStmt();
3987  StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3988  ArrayRef<Stmt *> Elts, bool isStmtExpr);
3989 
3990  /// A RAII object to enter scope of a compound statement.
3992  public:
3993  CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
3994  S.ActOnStartOfCompoundStmt(IsStmtExpr);
3995  }
3996 
3998  S.ActOnFinishOfCompoundStmt();
3999  }
4000 
4001  private:
4002  Sema &S;
4003  };
4004 
4005  /// An RAII helper that pops function a function scope on exit.
4008  bool Active;
4009  FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
4011  if (Active)
4013  }
4014  void disable() { Active = false; }
4015  };
4016 
4017  StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4018  SourceLocation StartLoc,
4019  SourceLocation EndLoc);
4020  void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4021  StmtResult ActOnForEachLValueExpr(Expr *E);
4022  ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4023  StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4024  SourceLocation DotDotDotLoc, ExprResult RHS,
4026  void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4027 
4028  StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4029  SourceLocation ColonLoc,
4030  Stmt *SubStmt, Scope *CurScope);
4031  StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4032  SourceLocation ColonLoc, Stmt *SubStmt);
4033 
4034  StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
4035  ArrayRef<const Attr*> Attrs,
4036  Stmt *SubStmt);
4037 
4038  class ConditionResult;
4039  StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4040  Stmt *InitStmt,
4041  ConditionResult Cond, Stmt *ThenVal,
4042  SourceLocation ElseLoc, Stmt *ElseVal);
4043  StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4044  Stmt *InitStmt,
4045  ConditionResult Cond, Stmt *ThenVal,
4046  SourceLocation ElseLoc, Stmt *ElseVal);
4047  StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4048  Stmt *InitStmt,
4049  ConditionResult Cond);
4050  StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4051  Stmt *Switch, Stmt *Body);
4052  StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
4053  Stmt *Body);
4054  StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4055  SourceLocation WhileLoc, SourceLocation CondLParen,
4056  Expr *Cond, SourceLocation CondRParen);
4057 
4058  StmtResult ActOnForStmt(SourceLocation ForLoc,
4059  SourceLocation LParenLoc,
4060  Stmt *First,
4061  ConditionResult Second,
4062  FullExprArg Third,
4063  SourceLocation RParenLoc,
4064  Stmt *Body);
4065  ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4066  Expr *collection);
4067  StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4068  Stmt *First, Expr *collection,
4069  SourceLocation RParenLoc);
4070  StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4071 
4073  /// Initial building of a for-range statement.
4075  /// Instantiation or recovery rebuild of a for-range statement. Don't
4076  /// attempt any typo-correction.
4078  /// Determining whether a for-range statement could be built. Avoid any
4079  /// unnecessary or irreversible actions.
4080  BFRK_Check
4081  };
4082 
4083  StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
4084  SourceLocation CoawaitLoc,
4085  Stmt *InitStmt,
4086  Stmt *LoopVar,
4087  SourceLocation ColonLoc, Expr *Collection,
4088  SourceLocation RParenLoc,
4089  BuildForRangeKind Kind);
4090  StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
4091  SourceLocation CoawaitLoc,
4092  Stmt *InitStmt,
4093  SourceLocation ColonLoc,
4094  Stmt *RangeDecl, Stmt *Begin, Stmt *End,
4095  Expr *Cond, Expr *Inc,
4096  Stmt *LoopVarDecl,
4097  SourceLocation RParenLoc,
4098  BuildForRangeKind Kind);
4099  StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
4100 
4101  StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
4102  SourceLocation LabelLoc,
4103  LabelDecl *TheDecl);
4104  StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
4105  SourceLocation StarLoc,
4106  Expr *DestExp);
4107  StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
4108  StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
4109 
4110  void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4111  CapturedRegionKind Kind, unsigned NumParams);
4112  typedef std::pair<StringRef, QualType> CapturedParamNameType;
4113  void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4114  CapturedRegionKind Kind,
4116  unsigned OpenMPCaptureLevel = 0);
4117  StmtResult ActOnCapturedRegionEnd(Stmt *S);
4118  void ActOnCapturedRegionError();
4119  RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
4120  SourceLocation Loc,
4121  unsigned NumParams);
4122 
4124  CES_Strict = 0,
4125  CES_AllowParameters = 1,
4126  CES_AllowDifferentTypes = 2,
4127  CES_AllowExceptionVariables = 4,
4128  CES_FormerDefault = (CES_AllowParameters),
4129  CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
4130  CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
4131  CES_AllowExceptionVariables),
4132  };
4133 
4134  VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
4136  bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
4138 
4139  StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4140  Scope *CurScope);
4141  StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4142  StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4143 
4144  StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
4145  bool IsVolatile, unsigned NumOutputs,
4146  unsigned NumInputs, IdentifierInfo **Names,
4147  MultiExprArg Constraints, MultiExprArg Exprs,
4148  Expr *AsmString, MultiExprArg Clobbers,
4149  unsigned NumLabels,
4150  SourceLocation RParenLoc);
4151 
4152  void FillInlineAsmIdentifierInfo(Expr *Res,
4153  llvm::InlineAsmIdentifierInfo &Info);
4154  ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
4155  SourceLocation TemplateKWLoc,
4156  UnqualifiedId &Id,
4157  bool IsUnevaluatedContext);
4158  bool LookupInlineAsmField(StringRef Base, StringRef Member,
4159  unsigned &Offset, SourceLocation AsmLoc);
4160  ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
4161  SourceLocation AsmLoc);
4162  StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
4163  ArrayRef<Token> AsmToks,
4164  StringRef AsmString,
4165  unsigned NumOutputs, unsigned NumInputs,
4166  ArrayRef<StringRef> Constraints,
4167  ArrayRef<StringRef> Clobbers,
4168  ArrayRef<Expr*> Exprs,
4169  SourceLocation EndLoc);
4170  LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
4171  SourceLocation Location,
4172  bool AlwaysCreate);
4173 
4174  VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4175  SourceLocation StartLoc,
4176  SourceLocation IdLoc, IdentifierInfo *Id,
4177  bool Invalid = false);
4178 
4179  Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4180 
4181  StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4182  Decl *Parm, Stmt *Body);
4183 
4184  StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
4185 
4186  StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4187  MultiStmtArg Catch, Stmt *Finally);
4188 
4189  StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
4190  StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4191  Scope *CurScope);
4192  ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
4193  Expr *operand);
4194  StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
4195  Expr *SynchExpr,
4196  Stmt *SynchBody);
4197 
4198  StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
4199 
4200  VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
4201  SourceLocation StartLoc,
4202  SourceLocation IdLoc,
4203  IdentifierInfo *Id);
4204 
4205  Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
4206 
4207  StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
4208  Decl *ExDecl, Stmt *HandlerBlock);
4209  StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4210  ArrayRef<Stmt *> Handlers);
4211 
4212  StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
4213  SourceLocation TryLoc, Stmt *TryBlock,
4214  Stmt *Handler);
4215  StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
4216  Expr *FilterExpr,
4217  Stmt *Block);
4218  void ActOnStartSEHFinallyBlock();
4219  void ActOnAbortSEHFinallyBlock();
4220  StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
4221  StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
4222 
4223  void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
4224 
4225  bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4226 
4227  /// If it's a file scoped decl that must warn if not used, keep track
4228  /// of it.
4229  void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4230 
4231  /// DiagnoseUnusedExprResult - If the statement passed in is an expression
4232  /// whose result is unused, warn.
4233  void DiagnoseUnusedExprResult(const Stmt *S);
4234  void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4235  void DiagnoseUnusedDecl(const NamedDecl *ND);
4236 
4237  /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
4238  /// statement as a \p Body, and it is located on the same line.
4239  ///
4240  /// This helps prevent bugs due to typos, such as:
4241  /// if (condition);
4242  /// do_stuff();
4243  void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4244  const Stmt *Body,
4245  unsigned DiagID);
4246 
4247  /// Warn if a for/while loop statement \p S, which is followed by
4248  /// \p PossibleBody, has a suspicious null statement as a body.
4249  void DiagnoseEmptyLoopBody(const Stmt *S,
4250  const Stmt *PossibleBody);
4251 
4252  /// Warn if a value is moved to itself.
4253  void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
4254  SourceLocation OpLoc);
4255 
4256  /// Warn if we're implicitly casting from a _Nullable pointer type to a
4257  /// _Nonnull one.
4258  void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
4259  SourceLocation Loc);
4260 
4261  /// Warn when implicitly casting 0 to nullptr.
4262  void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
4263 
4265  return DelayedDiagnostics.push(pool);
4266  }
4267  void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
4268 
4269  typedef ProcessingContextState ParsingClassState;
4270  ParsingClassState PushParsingClass() {
4272  }
4273  void PopParsingClass(ParsingClassState state) {
4275  }
4276 
4277  void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
4278 
4279  void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4280  const ObjCInterfaceDecl *UnknownObjCClass,
4281  bool ObjCPropertyAccess,
4282  bool AvoidPartialAvailabilityChecks = false,
4283  ObjCInterfaceDecl *ClassReceiver = nullptr);
4284 
4285  bool makeUnavailableInSystemHeader(SourceLocation loc,
4286  UnavailableAttr::ImplicitReason reason);
4287 
4288  /// Issue any -Wunguarded-availability warnings in \c FD
4289  void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
4290 
4291  //===--------------------------------------------------------------------===//
4292  // Expression Parsing Callbacks: SemaExpr.cpp.
4293 
4294  bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
4295  bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4296  const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
4297  bool ObjCPropertyAccess = false,
4298  bool AvoidPartialAvailabilityChecks = false,
4299  ObjCInterfaceDecl *ClassReciever = nullptr);
4300  void NoteDeletedFunction(FunctionDecl *FD);
4301  void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
4302  bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
4303  ObjCMethodDecl *Getter,
4304  SourceLocation Loc);
4305  void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
4306  ArrayRef<Expr *> Args);
4307 
4308  void PushExpressionEvaluationContext(
4309  ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
4311  ExpressionEvaluationContextRecord::EK_Other);
4312  enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
4313  void PushExpressionEvaluationContext(
4316  ExpressionEvaluationContextRecord::EK_Other);
4317  void PopExpressionEvaluationContext();
4318 
4319  void DiscardCleanupsInEvaluationContext();
4320 
4321  ExprResult TransformToPotentiallyEvaluated(Expr *E);
4322  ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
4323 
4324  ExprResult CheckUnevaluatedOperand(Expr *E);
4325  void CheckUnusedVolatileAssignment(Expr *E);
4326 
4327  ExprResult ActOnConstantExpression(ExprResult Res);
4328 
4329  // Functions for marking a declaration referenced. These functions also
4330  // contain the relevant logic for marking if a reference to a function or
4331  // variable is an odr-use (in the C++11 sense). There are separate variants
4332  // for expressions referring to a decl; these exist because odr-use marking
4333  // needs to be delayed for some constant variables when we build one of the
4334  // named expressions.
4335  //
4336  // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4337  // should usually be true. This only needs to be set to false if the lack of
4338  // odr-use cannot be determined from the current context (for instance,
4339  // because the name denotes a virtual function and was written without an
4340  // explicit nested-name-specifier).
4341  void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4342  void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4343  bool MightBeOdrUse = true);
4344  void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4345  void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4346  void MarkMemberReferenced(MemberExpr *E);
4347  void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
4348  void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
4349  unsigned CapturingScopeIndex);
4350 
4351  ExprResult CheckLValueToRValueConversionOperand(Expr *E);
4352  void CleanupVarDeclMarking();
4353 
4355  TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4356  };
4357 
4358  /// Try to capture the given variable.
4359  ///
4360  /// \param Var The variable to capture.
4361  ///
4362  /// \param Loc The location at which the capture occurs.
4363  ///
4364  /// \param Kind The kind of capture, which may be implicit (for either a
4365  /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4366  ///
4367  /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4368  /// an explicit lambda capture.
4369  ///
4370  /// \param BuildAndDiagnose Whether we are actually supposed to add the
4371  /// captures or diagnose errors. If false, this routine merely check whether
4372  /// the capture can occur without performing the capture itself or complaining
4373  /// if the variable cannot be captured.
4374  ///
4375  /// \param CaptureType Will be set to the type of the field used to capture
4376  /// this variable in the innermost block or lambda. Only valid when the
4377  /// variable can be captured.
4378  ///
4379  /// \param DeclRefType Will be set to the type of a reference to the capture
4380  /// from within the current scope. Only valid when the variable can be
4381  /// captured.
4382  ///
4383  /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4384  /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4385  /// This is useful when enclosing lambdas must speculatively capture
4386  /// variables that may or may not be used in certain specializations of
4387  /// a nested generic lambda.
4388  ///
4389  /// \returns true if an error occurred (i.e., the variable cannot be
4390  /// captured) and false if the capture succeeded.
4391  bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4392  SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4393  QualType &CaptureType,
4394  QualType &DeclRefType,
4395  const unsigned *const FunctionScopeIndexToStopAt);
4396 
4397  /// Try to capture the given variable.
4398  bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4399  TryCaptureKind Kind = TryCapture_Implicit,
4400  SourceLocation EllipsisLoc = SourceLocation());
4401 
4402  /// Checks if the variable must be captured.
4403  bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4404 
4405  /// Given a variable, determine the type that a reference to that
4406  /// variable will have in the given scope.
4407  QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4408 
4409  /// Mark all of the declarations referenced within a particular AST node as
4410  /// referenced. Used when template instantiation instantiates a non-dependent
4411  /// type -- entities referenced by the type are now referenced.
4412  void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4413  void MarkDeclarationsReferencedInExpr(Expr *E,
4414  bool SkipLocalVariables = false);
4415 
4416  /// Try to recover by turning the given expression into a
4417  /// call. Returns true if recovery was attempted or an error was
4418  /// emitted; this may also leave the ExprResult invalid.
4419  bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4420  bool ForceComplain = false,
4421  bool (*IsPlausibleResult)(QualType) = nullptr);
4422 
4423  /// Figure out if an expression could be turned into a call.
4424  bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4425  UnresolvedSetImpl &NonTemplateOverloads);
4426 
4427  /// Conditionally issue a diagnostic based on the current
4428  /// evaluation context.
4429  ///
4430  /// \param Statement If Statement is non-null, delay reporting the
4431  /// diagnostic until the function body is parsed, and then do a basic
4432  /// reachability analysis to determine if the statement is reachable.
4433  /// If it is unreachable, the diagnostic will not be emitted.
4434  bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4435  const PartialDiagnostic &PD);
4436  /// Similar, but diagnostic is only produced if all the specified statements
4437  /// are reachable.
4438  bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
4439  const PartialDiagnostic &PD);
4440 
4441  // Primary Expressions.
4442  SourceRange getExprRange(Expr *E) const;
4443 
4444  ExprResult ActOnIdExpression(
4445  Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4446  UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4447  CorrectionCandidateCallback *CCC = nullptr,
4448  bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4449 
4450  void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4451  TemplateArgumentListInfo &Buffer,
4452  DeclarationNameInfo &NameInfo,
4453  const TemplateArgumentListInfo *&TemplateArgs);
4454 
4455  bool
4456  DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4458  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4459  ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4460 
4461  DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
4462  IdentifierInfo *II);
4463  ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
4464 
4465  ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4466  IdentifierInfo *II,
4467  bool AllowBuiltinCreation=false);
4468 
4469  ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4470  SourceLocation TemplateKWLoc,
4471  const DeclarationNameInfo &NameInfo,
4472  bool isAddressOfOperand,
4473  const TemplateArgumentListInfo *TemplateArgs);
4474 
4475  /// If \p D cannot be odr-used in the current expression evaluation context,
4476  /// return a reason explaining why. Otherwise, return NOUR_None.
4477  NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
4478 
4479  DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4480  SourceLocation Loc,
4481  const CXXScopeSpec *SS = nullptr);
4482  DeclRefExpr *
4483  BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4484  const DeclarationNameInfo &NameInfo,
4485  const CXXScopeSpec *SS = nullptr,
4486  NamedDecl *FoundD = nullptr,
4487  SourceLocation TemplateKWLoc = SourceLocation(),
4488  const TemplateArgumentListInfo *TemplateArgs = nullptr);
4489  DeclRefExpr *
4490  BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4491  const DeclarationNameInfo &NameInfo,
4493  NamedDecl *FoundD = nullptr,
4494  SourceLocation TemplateKWLoc = SourceLocation(),
4495  const TemplateArgumentListInfo *TemplateArgs = nullptr);
4496 
4497  ExprResult
4498  BuildAnonymousStructUnionMemberReference(
4499  const CXXScopeSpec &SS,
4500  SourceLocation nameLoc,
4501  IndirectFieldDecl *indirectField,
4502  DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4503  Expr *baseObjectExpr = nullptr,
4504  SourceLocation opLoc = SourceLocation());
4505 
4506  ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4507  SourceLocation TemplateKWLoc,
4508  LookupResult &R,
4509  const TemplateArgumentListInfo *TemplateArgs,
4510  const Scope *S);
4511  ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4512  SourceLocation TemplateKWLoc,
4513  LookupResult &R,
4514  const TemplateArgumentListInfo *TemplateArgs,
4515  bool IsDefiniteInstance,
4516  const Scope *S);
4517  bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4518  const LookupResult &R,
4519  bool HasTrailingLParen);
4520 
4521  ExprResult
4522  BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4523  const DeclarationNameInfo &NameInfo,
4524  bool IsAddressOfOperand, const Scope *S,
4525  TypeSourceInfo **RecoveryTSI = nullptr);
4526 
4527  ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4528  SourceLocation TemplateKWLoc,
4529  const DeclarationNameInfo &NameInfo,
4530  const TemplateArgumentListInfo *TemplateArgs);
4531 
4532  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4533  LookupResult &R,
4534  bool NeedsADL,
4535  bool AcceptInvalidDecl = false);
4536  ExprResult BuildDeclarationNameExpr(
4537  const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4538  NamedDecl *FoundD = nullptr,
4539  const TemplateArgumentListInfo *TemplateArgs = nullptr,
4540  bool AcceptInvalidDecl = false);
4541 
4542  ExprResult BuildLiteralOperatorCall(LookupResult &R,
4543  DeclarationNameInfo &SuffixInfo,
4544  ArrayRef<Expr *> Args,
4545  SourceLocation LitEndLoc,
4546  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4547 
4548  ExprResult BuildPredefinedExpr(SourceLocation Loc,
4550  ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4551  ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4552 
4553  bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4554 
4555  ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4556  ExprResult ActOnCharacterConstant(const Token &Tok,
4557  Scope *UDLScope = nullptr);
4558  ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4559  ExprResult ActOnParenListExpr(SourceLocation L,
4560  SourceLocation R,
4561  MultiExprArg Val);
4562 
4563  /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4564  /// fragments (e.g. "foo" "bar" L"baz").
4565  ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4566  Scope *UDLScope = nullptr);
4567 
4568  ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4569  SourceLocation DefaultLoc,
4570  SourceLocation RParenLoc,
4571  Expr *ControllingExpr,
4572  ArrayRef<ParsedType> ArgTypes,
4573  ArrayRef<Expr *> ArgExprs);
4574  ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4575  SourceLocation DefaultLoc,
4576  SourceLocation RParenLoc,
4577  Expr *ControllingExpr,
4579  ArrayRef<Expr *> Exprs);
4580 
4581  // Binary/Unary Operators. 'Tok' is the token for the operator.
4582  ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4583  Expr *InputExpr);
4584  ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4585  UnaryOperatorKind Opc, Expr *Input);
4586  ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4587  tok::TokenKind Op, Expr *Input);
4588 
4589  bool isQualifiedMemberAccess(Expr *E);
4590  QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4591 
4592  ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4593  SourceLocation OpLoc,
4594  UnaryExprOrTypeTrait ExprKind,
4595  SourceRange R);
4596  ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4597  UnaryExprOrTypeTrait ExprKind);
4598  ExprResult
4599  ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4600  UnaryExprOrTypeTrait ExprKind,
4601  bool IsType, void *TyOrEx,
4602  SourceRange ArgRange);
4603 
4604  ExprResult CheckPlaceholderExpr(Expr *E);
4605  bool CheckVecStepExpr(Expr *E);
4606 
4607  bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4608  bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4609  SourceRange ExprRange,
4610  UnaryExprOrTypeTrait ExprKind);
4611  ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4612  SourceLocation OpLoc,
4613  IdentifierInfo &Name,
4614  SourceLocation NameLoc,
4615  SourceLocation RParenLoc);
4616  ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4617  tok::TokenKind Kind, Expr *Input);
4618 
4619  ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4620  Expr *Idx, SourceLocation RLoc);
4621  ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4622  Expr *Idx, SourceLocation RLoc);
4623  ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4624  Expr *LowerBound, SourceLocation ColonLoc,
4625  Expr *Length, SourceLocation RBLoc);
4626 
4627  // This struct is for use by ActOnMemberAccess to allow
4628  // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4629  // changing the access operator from a '.' to a '->' (to see if that is the
4630  // change needed to fix an error about an unknown member, e.g. when the class
4631  // defines a custom operator->).
4633  Scope *S;
4636  };
4637 
4638  ExprResult BuildMemberReferenceExpr(
4639  Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4640  CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4641  NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4642  const TemplateArgumentListInfo *TemplateArgs,
4643  const Scope *S,
4644  ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4645 
4646  ExprResult
4647  BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4648  bool IsArrow, const CXXScopeSpec &SS,
4649  SourceLocation TemplateKWLoc,
4650  NamedDecl *FirstQualifierInScope, LookupResult &R,
4651  const TemplateArgumentListInfo *TemplateArgs,
4652  const Scope *S,
4653  bool SuppressQualifierCheck = false,
4654  ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4655 
4656  ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4657  SourceLocation OpLoc,
4658  const CXXScopeSpec &SS, FieldDecl *Field,
4659  DeclAccessPair FoundDecl,
4660  const DeclarationNameInfo &MemberNameInfo);
4661 
4662  ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4663 
4664  bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4665  const CXXScopeSpec &SS,
4666  const LookupResult &R);
4667 
4668  ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4669  bool IsArrow, SourceLocation OpLoc,
4670  const CXXScopeSpec &SS,
4671  SourceLocation TemplateKWLoc,
4672  NamedDecl *FirstQualifierInScope,
4673  const DeclarationNameInfo &NameInfo,
4674  const TemplateArgumentListInfo *TemplateArgs);
4675 
4676  ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4677  SourceLocation OpLoc,
4678  tok::TokenKind OpKind,
4679  CXXScopeSpec &SS,
4680  SourceLocation TemplateKWLoc,
4681  UnqualifiedId &Member,
4682  Decl *ObjCImpDecl);
4683 
4684  MemberExpr *
4685  BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4686  const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
4687  ValueDecl *Member, DeclAccessPair FoundDecl,
4688  bool HadMultipleCandidates,
4689  const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4691  const TemplateArgumentListInfo *TemplateArgs = nullptr);
4692  MemberExpr *
4693  BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4694  NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
4695  ValueDecl *Member, DeclAccessPair FoundDecl,
4696  bool HadMultipleCandidates,
4697  const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4699  const TemplateArgumentListInfo *TemplateArgs = nullptr);
4700 
4701  void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4702  bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4703  FunctionDecl *FDecl,
4704  const FunctionProtoType *Proto,
4705  ArrayRef<Expr *> Args,
4706  SourceLocation RParenLoc,
4707  bool ExecConfig = false);
4708  void CheckStaticArrayArgument(SourceLocation CallLoc,
4709  ParmVarDecl *Param,
4710  const Expr *ArgExpr);
4711 
4712  /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4713  /// This provides the location of the left/right parens and a list of comma
4714  /// locations.
4715  ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4716  MultiExprArg ArgExprs, SourceLocation RParenLoc,
4717  Expr *ExecConfig = nullptr);
4718  ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4719  MultiExprArg ArgExprs, SourceLocation RParenLoc,
4720  Expr *ExecConfig = nullptr,
4721  bool IsExecConfig = false);
4722  enum class AtomicArgumentOrder { API, AST };
4723  ExprResult
4724  BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4725  SourceLocation RParenLoc, MultiExprArg Args,
4727  AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
4728  ExprResult
4729  BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
4730  ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
4731  Expr *Config = nullptr, bool IsExecConfig = false,
4732  ADLCallKind UsesADL = ADLCallKind::NotADL);
4733 
4734  ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4735  MultiExprArg ExecConfig,
4736  SourceLocation GGGLoc);
4737 
4738  ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4739  Declarator &D, ParsedType &Ty,
4740  SourceLocation RParenLoc, Expr *CastExpr);
4741  ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4742  TypeSourceInfo *Ty,
4743  SourceLocation RParenLoc,
4744  Expr *Op);
4745  CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4746 
4747  /// Build an altivec or OpenCL literal.
4748  ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4749  SourceLocation RParenLoc, Expr *E,
4750  TypeSourceInfo *TInfo);
4751 
4752  ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4753 
4754  ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4755  ParsedType Ty,
4756  SourceLocation RParenLoc,
4757  Expr *InitExpr);
4758 
4759  ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4760  TypeSourceInfo *TInfo,
4761  SourceLocation RParenLoc,
4762  Expr *LiteralExpr);
4763 
4764  ExprResult ActOnInitList(SourceLocation LBraceLoc,
4765  MultiExprArg InitArgList,
4766  SourceLocation RBraceLoc);
4767 
4768  ExprResult BuildInitList(SourceLocation LBraceLoc,
4769  MultiExprArg InitArgList,
4770  SourceLocation RBraceLoc);
4771 
4772  ExprResult ActOnDesignatedInitializer(Designation &Desig,
4773  SourceLocation EqualOrColonLoc,
4774  bool GNUSyntax,
4775  ExprResult Init);
4776 
4777 private:
4778  static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4779 
4780 public:
4781  ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4782  tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4783  ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4784  BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4785  ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4786  Expr *LHSExpr, Expr *RHSExpr);
4787 
4788  void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4789 
4790  /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4791  /// in the case of a the GNU conditional expr extension.
4792  ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4793  SourceLocation ColonLoc,
4794  Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4795 
4796  /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4797  ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4798  LabelDecl *TheDecl);
4799 
4800  void ActOnStartStmtExpr();
4801  ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4802  SourceLocation RPLoc); // "({..})"
4803  // Handle the final expression in a statement expression.
4804  ExprResult ActOnStmtExprResult(ExprResult E);
4805  void ActOnStmtExprError();
4806 
4807  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4810  bool isBrackets; // true if [expr], false if .ident
4811  union {
4814  } U;
4815  };
4816 
4817  /// __builtin_offsetof(type, a.b[123][456].c)
4818  ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4819  TypeSourceInfo *TInfo,
4820  ArrayRef<OffsetOfComponent> Components,
4821  SourceLocation RParenLoc);
4822  ExprResult ActOnBuiltinOffsetOf(Scope *S,
4823  SourceLocation BuiltinLoc,
4825  ParsedType ParsedArgTy,
4826  ArrayRef<OffsetOfComponent> Components,
4827  SourceLocation RParenLoc);
4828 
4829  // __builtin_choose_expr(constExpr, expr1, expr2)
4830  ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4831  Expr *CondExpr, Expr *LHSExpr,
4832  Expr *RHSExpr, SourceLocation RPLoc);
4833 
4834  // __builtin_va_arg(expr, type)
4835  ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4836  SourceLocation RPLoc);
4837  ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4838  TypeSourceInfo *TInfo, SourceLocation RPLoc);
4839 
4840  // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
4841  // __builtin_COLUMN()
4842  ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
4843  SourceLocation BuiltinLoc,
4844  SourceLocation RPLoc);
4845 
4846  // Build a potentially resolved SourceLocExpr.
4847  ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
4848  SourceLocation BuiltinLoc, SourceLocation RPLoc,
4849  DeclContext *ParentContext);
4850 
4851  // __null
4852  ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4853 
4854  bool CheckCaseExpression(Expr *E);
4855 
4856  /// Describes the result of an "if-exists" condition check.
4858  /// The symbol exists.
4860 
4861  /// The symbol does not exist.
4863 
4864  /// The name is a dependent name, so the results will differ
4865  /// from one instantiation to the next.
4867 
4868  /// An error occurred.
4869  IER_Error
4870  };
4871 
4873  CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4874  const DeclarationNameInfo &TargetNameInfo);
4875 
4877  CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4878  bool IsIfExists, CXXScopeSpec &SS,
4879  UnqualifiedId &Name);
4880 
4881  StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4882  bool IsIfExists,
4883  NestedNameSpecifierLoc QualifierLoc,
4884  DeclarationNameInfo NameInfo,
4885  Stmt *Nested);
4886  StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4887  bool IsIfExists,
4888  CXXScopeSpec &SS, UnqualifiedId &Name,
4889  Stmt *Nested);
4890 
4891  //===------------------------- "Block" Extension ------------------------===//
4892 
4893  /// ActOnBlockStart - This callback is invoked when a block literal is
4894  /// started.
4895  void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4896 
4897  /// ActOnBlockArguments - This callback allows processing of block arguments.
4898  /// If there are no arguments, this is still invoked.
4899  void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4900  Scope *CurScope);
4901 
4902  /// ActOnBlockError - If there is an error parsing a block, this callback
4903  /// is invoked to pop the information about the block from the action impl.
4904  void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4905 
4906  /// ActOnBlockStmtExpr - This is called when the body of a block statement
4907  /// literal was successfully completed. ^(int x){...}
4908  ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4909  Scope *CurScope);
4910 
4911  //===---------------------------- Clang Extensions ----------------------===//
4912 
4913  /// __builtin_convertvector(...)
4914  ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4915  SourceLocation BuiltinLoc,
4916  SourceLocation RParenLoc);
4917 
4918  //===---------------------------- OpenCL Features -----------------------===//
4919 
4920  /// __builtin_astype(...)
4921  ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4922  SourceLocation BuiltinLoc,
4923  SourceLocation RParenLoc);
4924 
4925  //===---------------------------- C++ Features --------------------------===//
4926 
4927  // Act on C++ namespaces
4928  Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4929  SourceLocation NamespaceLoc,
4930  SourceLocation IdentLoc, IdentifierInfo *Ident,
4931  SourceLocation LBrace,
4932  const ParsedAttributesView &AttrList,
4934  void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4935 
4936  NamespaceDecl *getStdNamespace() const;
4937  NamespaceDecl *getOrCreateStdNamespace();
4938 
4939  NamespaceDecl *lookupStdExperimentalNamespace();
4940 
4941  CXXRecordDecl *getStdBadAlloc() const;
4942  EnumDecl *getStdAlignValT() const;
4943 
4944 private:
4945  // A cache representing if we've fully checked the various comparison category
4946  // types stored in ASTContext. The bit-index corresponds to the integer value
4947  // of a ComparisonCategoryType enumerator.
4948  llvm::SmallBitVector FullyCheckedComparisonCategories;
4949 
4950  ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4951  CXXScopeSpec &SS,
4952  ParsedType TemplateTypeTy,
4953  IdentifierInfo *MemberOrBase);
4954 
4955 public:
4956  /// Lookup the specified comparison category types in the standard
4957  /// library, an check the VarDecls possibly returned by the operator<=>
4958  /// builtins for that type.
4959  ///
4960  /// \return The type of the comparison category type corresponding to the
4961  /// specified Kind, or a null type if an error occurs
4962  QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
4963  SourceLocation Loc);
4964 
4965  /// Tests whether Ty is an instance of std::initializer_list and, if
4966  /// it is and Element is not NULL, assigns the element type to Element.
4967  bool isStdInitializerList(QualType Ty, QualType *Element);
4968 
4969  /// Looks for the std::initializer_list template and instantiates it
4970  /// with Element, or emits an error if it's not found.
4971  ///
4972  /// \returns The instantiated template, or null on error.
4973  QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4974 
4975  /// Determine whether Ctor is an initializer-list constructor, as
4976  /// defined in [dcl.init.list]p2.
4977  bool isInitListConstructor(const FunctionDecl *Ctor);
4978 
4979  Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
4980  SourceLocation NamespcLoc, CXXScopeSpec &SS,
4981  SourceLocation IdentLoc,
4982  IdentifierInfo *NamespcName,
4983  const ParsedAttributesView &AttrList);
4984 
4985  void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4986 
4987  Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4988  SourceLocation NamespaceLoc,
4989  SourceLocation AliasLoc,
4990  IdentifierInfo *Alias,
4991  CXXScopeSpec &SS,
4992  SourceLocation IdentLoc,
4993  IdentifierInfo *Ident);
4994 
4995  void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4996  bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4997  const LookupResult &PreviousDecls,
4998  UsingShadowDecl *&PrevShadow);
4999  UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
5000  NamedDecl *Target,
5001  UsingShadowDecl *PrevDecl);
5002 
5003  bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5004  bool HasTypenameKeyword,
5005  const CXXScopeSpec &SS,
5006  SourceLocation NameLoc,
5007  const LookupResult &Previous);
5008  bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
5009  bool HasTypename,
5010  const CXXScopeSpec &SS,
5011  const DeclarationNameInfo &NameInfo,
5012  SourceLocation NameLoc);
5013 
5014  NamedDecl *BuildUsingDeclaration(
5015  Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
5016  bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
5017  DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
5018  const ParsedAttributesView &AttrList, bool IsInstantiation);
5019  NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5020  ArrayRef<NamedDecl *> Expansions);
5021 
5022  bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5023 
5024  /// Given a derived-class using shadow declaration for a constructor and the
5025  /// correspnding base class constructor, find or create the implicit
5026  /// synthesized derived class constructor to use for this initialization.
5027  CXXConstructorDecl *
5028  findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5029  ConstructorUsingShadowDecl *DerivedShadow);
5030 
5031  Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5032  SourceLocation UsingLoc,
5033  SourceLocation TypenameLoc, CXXScopeSpec &SS,
5034  UnqualifiedId &Name, SourceLocation EllipsisLoc,
5035  const ParsedAttributesView &AttrList);
5036  Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5037  MultiTemplateParamsArg TemplateParams,
5038  SourceLocation UsingLoc, UnqualifiedId &Name,
5039  const ParsedAttributesView &AttrList,
5040  TypeResult Type, Decl *DeclFromDeclSpec);
5041 
5042  /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5043  /// including handling of its default argument expressions.
5044  ///
5045  /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5046  ExprResult
5047  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5048  NamedDecl *FoundDecl,
5049  CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5050  bool HadMultipleCandidates, bool IsListInitialization,
5051  bool IsStdInitListInitialization,
5052  bool RequiresZeroInit, unsigned ConstructKind,
5053  SourceRange ParenRange);
5054 
5055  /// Build a CXXConstructExpr whose constructor has already been resolved if
5056  /// it denotes an inherited constructor.
5057  ExprResult
5058  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5059  CXXConstructorDecl *Constructor, bool Elidable,
5060  MultiExprArg Exprs,
5061  bool HadMultipleCandidates, bool IsListInitialization,
5062  bool IsStdInitListInitialization,
5063  bool RequiresZeroInit, unsigned ConstructKind,
5064  SourceRange ParenRange);
5065 
5066  // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5067  // the constructor can be elidable?
5068  ExprResult
5069  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5070  NamedDecl *FoundDecl,
5071  CXXConstructorDecl *Constructor, bool Elidable,
5072  MultiExprArg Exprs, bool HadMultipleCandidates,
5073  bool IsListInitialization,
5074  bool IsStdInitListInitialization, bool RequiresZeroInit,
5075  unsigned ConstructKind, SourceRange ParenRange);
5076 
5077  ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
5078 
5079 
5080  /// Instantiate or parse a C++ default argument expression as necessary.
5081  /// Return true on error.
5082  bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5083  ParmVarDecl *Param);
5084 
5085  /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
5086  /// the default expr if needed.
5087  ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5088  FunctionDecl *FD,
5089  ParmVarDecl *Param);
5090 
5091  /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5092  /// constructed variable.
5093  void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
5094 
5095  /// Helper class that collects exception specifications for
5096  /// implicitly-declared special member functions.
5098  // Pointer to allow copying
5099  Sema *Self;
5100  // We order exception specifications thus:
5101  // noexcept is the most restrictive, but is only used in C++11.
5102  // throw() comes next.
5103  // Then a throw(collected exceptions)
5104  // Finally no specification, which is expressed as noexcept(false).
5105  // throw(...) is used instead if any called function uses it.
5106  ExceptionSpecificationType ComputedEST;
5107  llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5108  SmallVector<QualType, 4> Exceptions;
5109 
5110  void ClearExceptions() {
5111  ExceptionsSeen.clear();
5112  Exceptions.clear();
5113  }
5114 
5115  public:
5117  : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5118  if (!Self.