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