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