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