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